基于微软云第一个大模型程序Java和python实现

1 注册一个微软云账号

按照提示一步一步注册,注册过程中,注册微软云账号需要visa卡。可以在某宝花钱30元买下。

2 部署模型

搜索openAI

创建资源组

部署一个模型

这个后面代码会使用

3 Java 实现

pom 依赖

java 复制代码
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-ai-openai</artifactId>
            <version>1.0.0-beta.12</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.53</version>
        </dependency>
java 复制代码
package org.example;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.ai.openai.models.ChatChoice;
import com.azure.ai.openai.models.ChatCompletions;
import com.azure.ai.openai.models.ChatCompletionsOptions;
import com.azure.ai.openai.models.ChatRequestMessage;
import com.azure.ai.openai.models.ChatRequestSystemMessage;
import com.azure.ai.openai.models.ChatRequestUserMessage;
import com.azure.ai.openai.models.ChatResponseMessage;
import com.azure.ai.openai.models.CompletionsUsage;
import com.azure.core.credential.AzureKeyCredential;

import java.util.ArrayList;
import java.util.List;

//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
    public static void main(String[] args) {
        String azureOpenaiKey = "上面截图密钥";
        String endpoint = "上面截图的目标url";
        String deploymentOrModelId = "gpt-4";

        OpenAIClient client = new OpenAIClientBuilder()
                .endpoint(endpoint)
                .credential(new AzureKeyCredential(azureOpenaiKey))
                .buildClient();

        List<ChatRequestMessage> chatMessages = new ArrayList<>();
        // 角色信息
        chatMessages.add(new ChatRequestSystemMessage("你是一个AI助理"));
        chatMessages.add(new ChatRequestUserMessage("你好,hello word?"));

        // 对话
        ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, new ChatCompletionsOptions(chatMessages));

        System.out.printf("Model ID=%s is created at %s.%n", chatCompletions.getId(), chatCompletions.getCreatedAt());
        for (ChatChoice choice : chatCompletions.getChoices()) {
            ChatResponseMessage message = choice.getMessage();
            System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole());
            System.out.println("Message:");
            System.out.println(message.getContent());
        }
        System.out.println(JSON.toJSONString(chatCompletions, SerializerFeature.DisableCircularReferenceDetect));
    }
}

返回结果

bash 复制代码
{
	"choices": [{
	// 返回结果检查
		"contentFilterResults": {
			"hate": {
				"filtered": false,
				"severity": {
					"value": "safe"
				}
			},
			"selfHarm": {
				"filtered": false,
				"severity": {
					"value": "safe"
				}
			},
			"sexual": {
				"filtered": false,
				"severity": {
					"value": "safe"
				}
			},
			"violence": {
				"filtered": false,
				"severity": {
					"value": "safe"
				}
			}
		},
		"finishReason": {
			"value": "stop"
		},
		"index": 0,
		"message": {
			"content": "你好!看来你可能想说 \"Hello World\"?如果你有任何问题或需要帮助,请告诉我!",
			"role": {
				"value": "assistant"
			}
		}
	}],
	"createdAt": "2024-12-02T15:52:49Z",
	"id": "chatcmpl-Aa317pSTYUtdpy2RjvZxmBXRTtlZi",
	"model": "gpt-4-turbo-2024-04-09",
	// 提示词检查
	"promptFilterResults": [{
		"contentFilterResults": {
			"hate": {
				"filtered": false,
				"severity": {
					"value": "safe"
				}
			},
			"jailbreak": {
				"detected": false,
				"filtered": false
			},
			"selfHarm": {
				"filtered": false,
				"severity": {
					"value": "safe"
				}
			},
			"sexual": {
				"filtered": false,
				"severity": {
					"value": "safe"
				}
			},
			"violence": {
				"filtered": false,
				"severity": {
					"value": "safe"
				}
			}
		},
		"promptIndex": 0
	}],
	"systemFingerprint": "fp_5603ee5e2e",
	"usage": {
		"completionTokens": 33,
		"promptTokens": 24,
		"totalTokens": 57
	}
}
4 python

安装python环境,安装依赖:pip install openai

python 复制代码
from openai import AzureOpenAI


azureOpenaiKey = "上面截图密钥";
endpoint = "上面截图目标url";
deploymentOrModelId = "gpt-4";
client = AzureOpenAI(
  azure_endpoint =endpoint,
  api_key=azureOpenaiKey,
  api_version="2024-02-01"
)

response = client.chat.completions.create(
    model=deploymentOrModelId,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "hello gpt"}
    ]
)

print(response.choices[0].message.content)

参考文献

【1】https://learn.microsoft.com/zh-cn/azure/ai-services/openai/whisper-quickstart?tabs=command-line%2Cpython-new%2Cjavascript-keyless%2Ctypescript-keyless\&pivots=programming-language-python

【2】https://learn.microsoft.com/zh-tw/azure/ai-services/openai/how-to/migration?tabs=python-new%2Cdalle-fix

相关推荐
_GR1 小时前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
轲乐夹欣糖20 小时前
word中对插入的图片修改背景色
microsoft
西电研梦2 天前
2025考研国家线首次全面下降,涵盖与24年对比分析!
人工智能·经验分享·考研·microsoft·西电·西安电子科技大学
黄昏难掩秋色23153 天前
SpringMVC的基本使用
linux·windows·microsoft
广拓科技3 天前
Figure自研模型Helix发布,人形机器人迈向新纪元?
microsoft·机器人
微软技术栈3 天前
赛前启航 | 三场重磅直播集结,予力微软 AI 开发者挑战赛!
人工智能·microsoft
张鹏993 天前
【Microsoft® PowerPoint for Mac】MAC一键导出PPT备注
microsoft·macos·powerpoint
张鹏993 天前
【Microsoft PowerPoint for Mac】2分钟配置-MAC一键删除PPT中的所有备注
microsoft·macos·powerpoint
alden_ygq4 天前
Ollama 模型交互
microsoft·交互
提拉米苏不吃肉4 天前
跨平台公式兼容性大模型提示词模板(飞书 + CSDN + Microsoft Word)
microsoft·word·飞书