Java如何调用ChatGPT

前置条件

一个OpenAI的API KEYS

网络畅通,能访问ChatGPT

官方API

OpenAI提供的API可通过http调用,官方API文档,提供了很多接口,下面是一个对话模型的调用示例

示例请求,system为提示语,user为具体问题

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "system", "content": "你是一个翻译器,我输入中文,你翻译成英文"},{"role": "user", "content": "今天天气真好啊"}],
     "temperature": 0.0,
     "top_p": 1
   }'

响应,content字段为回答内容

{
    
    
	"id": "chatcmpl-7DZFY2pLRRhg6ZabTrjrPA8EJpwCr",
	"object": "chat.completion",
	"created": 1683468120,
	"model": "gpt-3.5-turbo-0301",
	"usage": {
    
    
		"prompt_tokens": 46,
		"completion_tokens": 7,
		"total_tokens": 53
	},
	"choices": [{
    
    
		"message": {
    
    
			"role": "assistant",
			"content": "The weather is really nice today."
		},
		"finish_reason": "stop",
		"index": 0
	}]
}

依赖引入

上述API可以自己写Java代码进行调用,不过目前有很多已封装好的Java包可直接使用,这里选择openai-gpt3-javaGitHub地址

pom.xml中引入依赖

<dependency>
    <groupId>com.theokanning.openai-gpt3-java</groupId>
    <artifactId>service</artifactId>
    <version>0.12.0</version>
</dependency>

使用

    /**
     * localhost:8080/chatgpt/chat?question=今天天气真好啊
     *
     * @param question 给chatgpt的问题
     * @return chatgpt的回答
     */
    @RequestMapping("/chat")
    public String chat(String question) {
    
    
        // 对于chat 类模型,prompt是一个对话列表
        ChatMessage[] prompt = {
    
    
                new ChatMessage(ChatMessageRole.SYSTEM.value(), "你是一个翻译器,我输入中文,你翻译成英文"),
                new ChatMessage(ChatMessageRole.USER.value(), question)
        };

        ChatCompletionResult result = createChatCompletion(
                Arrays.asList(prompt)
        );

        String resp = result.getChoices().get(0).getMessage().getContent();
        System.out.println(resp);
        return resp;
    }

    public ChatCompletionResult createChatCompletion(List<ChatMessage> messages) {
    
    
        // 需要申请ApiKey
        OpenAiService service = new OpenAiService("sk-xxx");

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                // 模型名称
                .model("gpt-3.5-turbo")
                // 下面两项数值控制模型输出的随机性,对回答的稳定性要求高时,可设置随机性为最低
                .temperature(0.0D)
                .topP(1.0)
                .messages(messages)
                .build();
        return service.createChatCompletion(chatCompletionRequest);
    }

测试

调用接口 localhost:8080/chatgpt/chat?question=今天天气真好啊,得到回答 The weather is really nice today.

猜你喜欢

转载自blog.csdn.net/yaorongke/article/details/130549180