gpt4 book ai didi

openai-api - 如何使用 Java 中的 CHATGPT 聊天完成 API 检索新问题中先前的上下文并获得相应的结果?

转载 作者:行者123 更新时间:2023-12-02 22:48:24 25 4
gpt4 key购买 nike

我必须使用Java中的CHATGPT聊天完成API来检索新问题中以前的上下文(请查看所有以前的上下文并提供其摘要。)并获得相应的结果。为此我正在使用:

API:

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": "user", "content": "Hello!"}]
}'
  • 使用了聊天完成 API
  • 使用了编辑API

回应:

{
"id": "chatcmpl-76eCdoZ4qHySmqBTsX0e97NqTOLgs",
"object": "chat.completion",
"created": 1681818863,
"model": "gpt-3.5-turbo-0301",
"usage": {
"prompt_tokens": 16,
"completion_tokens": 29,
"total_tokens": 45
},
"choices": [
{
"message": {
"role": "assistant",
"content": "**As an AI language model, I cannot check the clauses without specific context. Please provide more information or context so that I can assist you accurately.**"
},
"finish_reason": "stop",
"index": 0
}
]
}

最佳答案

需要通过添加响应中收到的消息对象来递归调用 API 请求。根据documentation ,每个响应都会包含一个 finish_reason(stop,length,content_filter,null)。在下面的代码中,如果原因是“length”,它将附加在响应(chatResp)中收到的最后一个消息对象,并且这将被递归调用,直到完成原因是“stop”。

ChatRequest request = new ChatRequest(model,temperature);


do{
HttpResponse<String> response = callAi(request);
if(response!=null ) {
if(response.getStatus()==200) {
try {
chatResp = new ObjectMapper().readValue(response.getBody().toString(), ChatResponse.class);
} catch (Exception e) {
e.printStackTrace();
}
if(chatResp!=null) {
// Use the response as required
}
// if 'length' is the finish reason
if(chatResp.getChoices().get(0).getFinish_reason().equals("length")) {
request.messages.add(chatResp.getChoices().get(0).getMessage());
}
}
}
}while(chatResp!=null && !chatResp.getChoices().get(0).getFinish_reason().equals("stop"));

关于openai-api - 如何使用 Java 中的 CHATGPT 聊天完成 API 检索新问题中先前的上下文并获得相应的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76044299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com