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

相关推荐
公子小六3 天前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms
Nerd(BUG版)3 天前
鸿蒙API18~26新增V2组件全解析
microsoft·华为·harmonyos
解决问题no解决代码问题7 天前
日志脱敏双链路统一优化:从两套枚举到单一规则源,兼顾安全与可维护性
microsoft
Dovis(誓平步青云)8 天前
启元 T1 Pro 人机相声搭档:语音-触摸双通道的启元机器人节奏引擎设计
开发语言·前端·javascript·microsoft·交互
宝桥南山8 天前
.NET 11 - 尝试一下Blazor中的新特性SupplyParameterFromTempData
microsoft·微软·c#·asp.net·.net·.netcore
Liangwei Lin9 天前
Exchange Server 2019 部署手册
microsoft
ms365copilot9 天前
Microsoft 365 Copilot跨工作资料整理
microsoft·copilot
中二骚年10 天前
Windows 安全中心 / 防火墙故障,calc和Microsoft Store,终端(管理员)无法正常打开。 原因 + 修复方案
windows·安全·microsoft
kk_net889910 天前
微软常用运行库合集免费下载安装教程(附运行库安装包)微软运行库安装图文教程
其他·microsoft
GlobalInfo10 天前
2026年全球机器人用超平执行器市场研究报告:市场规模达7.51亿美元,人形机器人商业化与轻量化运动控制需求推动行业增长
大数据·人工智能·数码相机·microsoft·机器人