目录
任务:优化接口代码 实现聊天功能
导入依赖
用了三个包,分别是:fastjson gson okhttp
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.0</version>
</dependency>
定义传输信息类
class ChatMsg {
private String role;
private String content;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
设置时间限制
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(5, TimeUnit.SECONDS) // 连接超时设置为20秒
.writeTimeout(15, TimeUnit.SECONDS) // 写入超时设置为30秒
.readTimeout(20, TimeUnit.SECONDS) // 读取超时设置为30秒
.build();
static Gson gson = new Gson();
进行语音的传输和聊天
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String msg=sc.next();
while(!msg.equals("EOF"))
{
String accessToken = "df4dfce285458e3f20b95d6ac9da24ebff6d28b6";
String url = "https://o1v0n08ck756f9ae.aistudio-hub.baidu.com/chat/completions";
// 结合prompt增强的当前待发送信息
ChatMsg chatMsg = new ChatMsg();
chatMsg.setRole("user");
chatMsg.setContent(msg);
// 当前发送消息数组
List<ChatMsg> messages = new ArrayList<ChatMsg>();
messages.add(chatMsg);
String messagesJson = gson.toJson(messages);
String content = "{\"messages\":" + messagesJson + "}";
long start = System.currentTimeMillis();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, content);
//System.out.println(content);
Request request = new Request.Builder().url(url).method("POST", body)
.addHeader("Content-Type", "application/json").addHeader("Authorization", "df4dfce285458e3f20b95d6ac9da24ebff6d28b6").build();
Response response = HTTP_CLIENT.newCall(request).execute();
String responseText = response.body().string();
//System.out.println("response返回: \n" + responseText);
long end = System.currentTimeMillis();
//System.out.println("该回答花费时间为:" + (end - start) / 1000.0 + "秒");
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(responseText);
String answer = rootNode.get("result").asText();
System.out.println(answer);
msg=sc.next();
}