当前位置:   article > 正文

对接kimi,打造聊天机器人,生成文档摘要_kimi接口

kimi接口

Kimi,是月之暗面于2023年10月推出的一款智能助手,主要应用场景为专业学术论文的翻译和理解、辅助分析法律问题、快速理解API开发文档等,是全球首个支持输入20万汉字的智能助手产品

1.登录,获取API Key

打开网址Moonshot AI - 开放平台 ,可以看到官网比较简洁,有两部分构成,api文档和用户中心

点击用户中心,可以用微信登录,然后在API Key管理中新建一个key,记录下来

2.引入依赖 

由于跟kimi对接需要用到SSE(Server Send Event),我们使用okhttp库

  1. <dependency>
  2. <groupId>cn.hutool</groupId>
  3. <artifactId>hutool-all</artifactId>
  4. <version>5.8.25</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.squareup.okhttp3</groupId>
  8. <artifactId>okhttp</artifactId>
  9. <version>4.10.0</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.squareup.okhttp3</groupId>
  13. <artifactId>okhttp-sse</artifactId>
  14. <version>4.10.0</version>
  15. </dependency>

3.实现简单的对话

  1. @NoArgsConstructor
  2. @AllArgsConstructor
  3. @Data
  4. @Builder
  5. public class Message {
  6. private String role;
  7. private String content;
  8. }
  1. public enum RoleEnum {
  2. system,
  3. user,
  4. assistant;
  5. }

  1. public class MoonshotAiUtils {
  2. private static final String API_KEY = "api key";
  3. private static final String MODELS_URL = "https://api.moonshot.cn/v1/models";
  4. private static final String FILES_URL = "https://api.moonshot.cn/v1/files";
  5. private static final String ESTIMATE_TOKEN_COUNT_URL = "https://api.moonshot.cn/v1/tokenizers/estimate-token-count";
  6. private static final String CHAT_COMPLETION_URL = "https://api.moonshot.cn/v1/chat/completions";
  7. public static String getModelList() {
  8. return getCommonRequest(MODELS_URL)
  9. .execute()
  10. .body();
  11. }
  12. public static String uploadFile(@NonNull File file) {
  13. return getCommonRequest(FILES_URL)
  14. .method(Method.POST)
  15. .header("purpose", "file-extract")
  16. .form("file", file)
  17. .execute()
  18. .body();
  19. }
  20. public static String getFileList() {
  21. return getCommonRequest(FILES_URL)
  22. .execute()
  23. .body();
  24. }
  25. public static String deleteFile(@NonNull String fileId) {
  26. return getCommonRequest(FILES_URL + "/" + fileId)
  27. .method(Method.DELETE)
  28. .execute()
  29. .body();
  30. }
  31. public static String getFileDetail(@NonNull String fileId) {
  32. return getCommonRequest(FILES_URL + "/" + fileId)
  33. .execute()
  34. .body();
  35. }
  36. public static String getFileContent(@NonNull String fileId) {
  37. return getCommonRequest(FILES_URL + "/" + fileId + "/content")
  38. .execute()
  39. .body();
  40. }
  41. public static String estimateTokenCount(@NonNull String model, @NonNull List<Message> messages) {
  42. String requestBody = new JSONObject()
  43. .putOpt("model", model)
  44. .putOpt("messages", messages)
  45. .toString();
  46. return getCommonRequest(ESTIMATE_TOKEN_COUNT_URL)
  47. .method(Method.POST)
  48. .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
  49. .body(requestBody)
  50. .execute()
  51. .body();
  52. }
  53. @SneakyThrows
  54. public static String chat(@NonNull String model, @NonNull List<Message> messages) {
  55. StringBuilder sb = new StringBuilder();
  56. String requestBody = new JSONObject()
  57. .putOpt("model", model)
  58. .putOpt("messages", messages)
  59. .putOpt("stream", true)
  60. .toString();
  61. Request okhttpRequest = new Request.Builder()
  62. .url(CHAT_COMPLETION_URL)
  63. .post(RequestBody.create(requestBody, MediaType.get(ContentType.JSON.getValue())))
  64. .addHeader("Authorization", "Bearer " + API_KEY)
  65. .build();
  66. Call call = new OkHttpClient().newCall(okhttpRequest);
  67. Response okhttpResponse = call.execute();
  68. BufferedReader reader = new BufferedReader(okhttpResponse.body().charStream());
  69. try {
  70. String line;
  71. while ((line = reader.readLine()) != null) {
  72. if (StrUtil.isBlank(line)) {
  73. continue;
  74. }
  75. if (JSONUtil.isTypeJSON(line)) {
  76. Optional.of(JSONUtil.parseObj(line))
  77. .map(x -> x.getJSONObject("error"))
  78. .map(x -> x.getStr("message"))
  79. .ifPresent(x -> System.out.println("error: " + x));
  80. JSONObject jsonObject = JSONUtil.parseObj(line);
  81. throw new ServiceFailException(jsonObject.getJSONObject("error").getStr("message"));
  82. }
  83. line = StrUtil.replace(line, "data: ", StrUtil.EMPTY);
  84. if (StrUtil.equals("[DONE]", line) || !JSONUtil.isTypeJSON(line)) {
  85. return sb.toString();
  86. }
  87. Optional.of(JSONUtil.parseObj(line))
  88. .map(x -> x.getJSONArray("choices"))
  89. .filter(CollUtil::isNotEmpty)
  90. .map(x -> (JSONObject) x.get(0))
  91. .map(x -> x.getJSONObject("delta"))
  92. .map(x -> x.getStr("content"))
  93. .ifPresent(x -> sb.append(x));
  94. }
  95. return sb.toString();
  96. } finally {
  97. IoUtil.close(reader);
  98. }
  99. }
  100. private static HttpRequest getCommonRequest(@NonNull String url) {
  101. return HttpRequest.of(url).header(Header.AUTHORIZATION, "Bearer " + API_KEY);
  102. }
  103. }

  1. @RestController
  2. @RequestMapping("/kimi")
  3. @Tag(name = "kimi管理")
  4. public class KimiController extends BaseController {
  5. // 演示用,实际要存入用户session
  6. private List<Message> messages = new ArrayList<>();
  7. @Operation(summary = "聊天")
  8. @GetMapping("chat")
  9. public Result chat(String content) {
  10. Message message = new Message(RoleEnum.user.name(), content);
  11. messages.add(message);
  12. // 模型列表 https://platform.moonshot.cn/docs/intro#%E6%A8%A1%E5%9E%8B%E5%88%97%E8%A1%A8
  13. String result = MoonshotAiUtils.chat("moonshot-v1-8k", messages);
  14. return resultOk(result);
  15. }
  16. }

代码都挺简单的,需要注意的是用户的多次问答需要放到一个list中一起发送给kimi,这样kimi才能根据上下文回答问题

4.提取文档摘要 

提取文档摘要我们先要把文档上传到kimi获取一个content,再调用聊天接口给提示词就行了

  1. @Operation(summary = "提取文档摘要")
  2. @GetMapping("docSummary")
  3. public Result docSummary() {
  4. String hint = "请简要描述文档中的内容";
  5. String content = MoonshotAiUtils.uploadFile(new File("d:/read.docx"));
  6. List<Message> messages = CollUtil.newArrayList(
  7. new Message(RoleEnum.system.name(), content),
  8. new Message(RoleEnum.user.name(), hint)
  9. );
  10. String result = MoonshotAiUtils.chat("moonshot-v1-32k", messages);
  11. return resultOk(result);
  12. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/733998
推荐阅读
相关标签
  

闽ICP备14008679号