KIMI接口收费情况:
限速标准:
限速概念:
简单api调用:
1)引入pom依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.25</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.8</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp-sse</artifactId>
<version>4.10.0</version>
</dependency>
2)设置角色枚举类
public enum RoleEnum {
system,
user,
assistant;
}
3)设置消息实体类
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class Message {
private String role;
private String content;
}
4)设置聊天代码
public void chat() {
OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();
try {
// 设置密钥--在kimi个人中心新建密钥即可获得
String apiKey = "";
// moonshot开发的访问api
String apiUrl = "https://api.moonshot.cn/v1/chat/completions";
// 三种访问标准 标准不同收费不同:moonshot-v1-8k、moonshot-v1-32k、moonshot-v1-128k
String model = "moonshot-v1-8k";
// 设置请求头
Map<String, String> header = new HashMap<String, String>();
header.put("Authorization", "Bearer " + apiKey);
header.put("Content-Type", "application/json");
// 设置提问信息
List<Message> messages = CollUtil.newArrayList(
new Message(RoleEnum.system.name(), "你是kimi AI"),
new Message(RoleEnum.user.name(), "你是谁")
);
String requestBody = new cn.hutool.json.JSONObject()
.putOpt("model", model)
.putOpt("messages", messages)
.toString();
Request request = new Request.Builder()
.url(apiUrl)
.headers(Headers.of(header))
.method("POST", okhttp3.RequestBody.create(MediaType.parse("application/json"),
requestBody))
.build();
try (Response response = client.newCall(request).execute()) {
String str=checkResponse(response);
System.out.println("答复:"+str);
}
} catch (Exception e) {
throw new RuntimeException("Unknown err", e);
}
}
private String checkResponse(Response response) {
if (response.isSuccessful()) {
if(response.body()==null){
throw new RuntimeException("Response body is null");
}else{
try(ResponseBody body = response.body()){
return body.string();
}catch (Exception e){
throw new RuntimeException("Error reading response body",e);
}
}
} else if(response.code()==401) {
throw new RuntimeException("Unauthorized");
} else if (response.code() == 400) {
throw new RuntimeException("Bad request");
} else if (response.code() == 429) {
throw new RuntimeException("Too many requests");
} else{
throw new RuntimeException("Error response code: "+response.code());
}
}