目前ai时代,本次分享下通过java怎么使用kimi完成智能会话
首先你要去kimi官网注册账号,获取apikey,这个很重要,新人会有15块钱的免费额度,足够练习使用了
接下来获取apikey
官网地址:https://platform.moonshot.cn/
点击用户中心,如图
点击APIKey管理,然后右边新建,这样就获取一个key了,这个key自己保存好。
接下来点击左边的使命认证,个人认证通过即可。
最后在下面可以看到如图 有15元的余额
接下来进入编码阶段:
首先创建一个springboot项目,在这里就不演示了。
pom.xml文件:
xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cjc</groupId>
<artifactId>demo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo1</name>
<description>demo1</description>
<url/>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<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>4.10.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp-sse</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
工具类:有三个
java
package com.cjc.util;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class Message {
private String role;
private String content;
}
java
package com.cjc.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.NonNull;
import lombok.SneakyThrows;
import okhttp3.*;
import java.io.BufferedReader;
import java.io.File;
import java.util.List;
import java.util.Optional;
public class MoonshotAiUtils {
private static final String API_KEY = "自己的APIKey";
private static final String MODELS_URL = "https://api.moonshot.cn/v1/models";
private static final String FILES_URL = "https://api.moonshot.cn/v1/files";
private static final String ESTIMATE_TOKEN_COUNT_URL = "https://api.moonshot.cn/v1/tokenizers/estimate-token-count";
private static final String CHAT_COMPLETION_URL = "https://api.moonshot.cn/v1/chat/completions";
public static String getModelList() {
return getCommonRequest(MODELS_URL)
.execute()
.body();
}
public static String uploadFile(@NonNull File file) {
return getCommonRequest(FILES_URL)
.method(Method.POST)
.header("purpose", "file-extract")
.form("file", file)
.execute()
.body();
}
public static String getFileList() {
return getCommonRequest(FILES_URL)
.execute()
.body();
}
public static String deleteFile(@NonNull String fileId) {
return getCommonRequest(FILES_URL + "/" + fileId)
.method(Method.DELETE)
.execute()
.body();
}
public static String getFileDetail(@NonNull String fileId) {
return getCommonRequest(FILES_URL + "/" + fileId)
.execute()
.body();
}
public static String getFileContent(@NonNull String fileId) {
return getCommonRequest(FILES_URL + "/" + fileId + "/content")
.execute()
.body();
}
public static String estimateTokenCount(@NonNull String model, @NonNull List<Message> messages) {
String requestBody = new JSONObject()
.putOpt("model", model)
.putOpt("messages", messages)
.toString();
return getCommonRequest(ESTIMATE_TOKEN_COUNT_URL)
.method(Method.POST)
.header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
.body(requestBody)
.execute()
.body();
}
@SneakyThrows
public static void chat(@NonNull String model, @NonNull List<Message> messages) {
String requestBody = new JSONObject()
.putOpt("model", model)
.putOpt("messages", messages)
.putOpt("stream", true)
.toString();
Request okhttpRequest = new Request.Builder()
.url(CHAT_COMPLETION_URL)
.post(RequestBody.create(requestBody, MediaType.get(ContentType.JSON.getValue())))
.addHeader("Authorization", "Bearer " + API_KEY)
.build();
Call call = new OkHttpClient().newCall(okhttpRequest);
Response okhttpResponse = call.execute();
BufferedReader reader = new BufferedReader(okhttpResponse.body().charStream());
String line;
while ((line = reader.readLine()) != null) {
if (StrUtil.isBlank(line)) {
continue;
}
if (JSONUtil.isTypeJSON(line)) {
Optional.of(JSONUtil.parseObj(line))
.map(x -> x.getJSONObject("error"))
.map(x -> x.getStr("message"))
.ifPresent(x -> System.out.println("error: " + x));
return;
}
line = StrUtil.replace(line, "data: ", StrUtil.EMPTY);
if (StrUtil.equals("[DONE]", line) || !JSONUtil.isTypeJSON(line)) {
return;
}
Optional.of(JSONUtil.parseObj(line))
.map(x -> x.getJSONArray("choices"))
.filter(CollUtil::isNotEmpty)
.map(x -> (JSONObject) x.get(0))
.map(x -> x.getJSONObject("delta"))
.map(x -> x.getStr("content"))
.ifPresent(x -> System.out.print(x));
}
}
private static HttpRequest getCommonRequest(@NonNull String url) {
return HttpRequest.of(url).header(Header.AUTHORIZATION, "Bearer " + API_KEY);
}
@SneakyThrows
public static String chat2(@NonNull String model, @NonNull List<Message> messages) {
String requestBody = new JSONObject()
.putOpt("model", model)
.putOpt("messages", messages)
.putOpt("stream", true)
.toString();
Request okhttpRequest = new Request.Builder()
.url(CHAT_COMPLETION_URL)
.post(RequestBody.create(requestBody, MediaType.get(ContentType.JSON.getValue())))
.addHeader("Authorization", "Bearer " + API_KEY)
.build();
Call call = new OkHttpClient().newCall(okhttpRequest);
Response okhttpResponse = call.execute();
BufferedReader reader = new BufferedReader(okhttpResponse.body().charStream());
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (StrUtil.isBlank(line)) {
continue;
}
if (JSONUtil.isTypeJSON(line)) {
Optional.of(JSONUtil.parseObj(line))
.map(x -> x.getJSONObject("error"))
.map(x -> x.getStr("message"))
.ifPresent(x -> {
System.out.println("error: " + x);
result.append("error: ").append(x).append("\n");
});
return result.toString();
}
line = StrUtil.replace(line, "data: ", StrUtil.EMPTY);
if (StrUtil.equals("[DONE]", line) || !JSONUtil.isTypeJSON(line)) {
return result.toString();
}
Optional.of(JSONUtil.parseObj(line))
.map(x -> x.getJSONArray("choices"))
.filter(CollUtil::isNotEmpty)
.map(x -> (JSONObject) x.get(0))
.map(x -> x.getJSONObject("delta"))
.map(x -> x.getStr("content"))
.ifPresent(result::append);
}
return result.toString();
}
}
java
package com.cjc.util;
public enum RoleEnum {
system,
user,
assistant;
}
然后编写controller
java
package com.cjc.controller;
import cn.hutool.core.collection.CollUtil;
import com.cjc.util.Message;
import com.cjc.util.MoonshotAiUtils;
import com.cjc.util.RoleEnum;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/kimi")
public class TestController {
@RequestMapping("/chat")
public String chat(@RequestParam("msg") String msg){
List<Message> messages = CollUtil.newArrayList(
new Message(RoleEnum.system.name(), "你是kimi AI"),
new Message(RoleEnum.user.name(), msg)
);
return MoonshotAiUtils.chat2("moonshot-v1-8k",messages);
}
}
通过浏览器访问一下
这样就成功的通过java代码完成kimi的智能会话了。
完结,撒花!求赞求关注威:c_-j_-c