实现人工智能简单交互

发布时间 2023-12-06 18:11:09作者: xiaobaibao

1.首先引入依赖:

<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>client</artifactId>
<version>0.9.0</version>
</dependency>

2.尽量在yml里配置好相关secret等参数:

openai.secretKey=
openai.model=text-davinci-003
openai.prompt=
openai.temperature=0
openai.max_tokens=1024
openai.stream=true

3.方法实现:

public String createCompletion(String message) {
if (StrUtil.isEmptyIfStr(this.key1)|| ObjectUtil.isNull(this.openAiService)){
return "请先设置key!";
}
log.info("me--->"+message);
// 将用户的文本信息发送之后,openai会将回答们封装在 CompletionRequest 里面,里面包含了很多 choice
CompletionRequest completionRequest = this.buildCompletionRequest(message);
return this.createCompletion(completionRequest);
}

建立请求方法实现:

private CompletionRequest buildCompletionRequest(String message) {
return CompletionRequest.builder().prompt(message) // 本层封装用户文本
.model(this.openAi.getModel()) // 模型:给予并返回生成的文本一个模型
.maxTokens(this.openAi.getMax_tokens()) // 请求中生成文本的最大标记数,对文本的准确性有的要求
.build();
}

发送请求并接受信息返回给前台方法实现:

protected String createCompletion(CompletionRequest completionRequest) {
// 响应封装在字符串里面
StringBuilder response = new StringBuilder();
// 发送请求并接收响应
CompletionResult completion = this.openAiService.createCompletion(completionRequest);
// openai会生成多个选项,一般来说第一个选项就是最优解
List<CompletionChoice> choices = completion.getChoices();
// 在每次迭代中,Lambda 表达式会获取当前迭代的 choice 对象,并调用其 getText() 方法来获取该选项的文本内容。然后,将该文本内容附加到 response 对象的末尾,使用 append 方法
choices.forEach(choice -> response.append(choice.getText()));
//去掉响应文本开头的\n\n,这时候的 response 包含了全部的choice
String res = StrUtil.replaceFirst(response.toString(), "\n\n", "");
log.info("chatGPT--->"+"正在效应");
return res;
}