基于微软云第一个大模型程序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

相关推荐
AdSet聚合广告7 小时前
APP、小程序对接聚合广告平台,有哪些广告变现策略?
大数据·人工智能·microsoft·小程序·个人开发
番茄电脑全能王1 天前
电脑运行时提示“0x80240037”错误,提示安装ie插件或其他微软程序时,报错提示“未指定的错误”是什么原因?以及要怎么解决和预防?
经验分享·microsoft·电脑
獨枭3 天前
MFC 自定义静态文本控件:增强型标签控件
c++·microsoft·mfc
港股研究社3 天前
同道猎聘Q3营收降利润增,AI或成估值重塑关键词
人工智能·microsoft
hola1738414393 天前
什么是多模态和模态
前端·microsoft·qt6.3
哥谭居民00014 天前
Connection对象,Statement对象和ResultSet对象的依赖关系 JDBC
数据库·microsoft·oracle
喜欢猪猪4 天前
Spring面试题---Spring DAO:简化数据访问的利器
数据库·microsoft·oracle
我不是程序猿儿5 天前
【C#】GridControl 和 GridView
开发语言·microsoft·c#