当前位置:   article > 正文

对接MiniMax知识库,实现FAQRobot_代码中调用minimax接口

代码中调用minimax接口

我们在逛淘宝拼多多的时候,看到一个喜欢的商品,就会像客服问很多问题,这些问题有很多重复的,如果客服每次都回答,会浪费很多时间和人力,这个时候就可以整理成FAQ(Frequently Asked Questions,经常问到的问题),客户当然不会费劲去看这些FAQ,他们只关心自己提问的问题,这时就需要用到自然语言处理和知识库了。

MiniMax官网: MiniMax-与用户共创智能

MiniMax开发平台: MiniMax-与用户共创智能

准备groupID和秘钥

账户信息中查看groupID

接口秘钥中新建秘钥

创建知识库 

以下代码使用了Hutool工具类

第一步先创建知识库,保存返回的knowledgeId,后面会用到

  1. public void createKnowledge() {
  2. String url = buildMiniMaxUrl("embedding/create_knowledge_base");
  3. JSONObject data = new JSONObject();
  4. data.putOpt("operator_id", System.currentTimeMillis());
  5. data.putOpt("name", "我的知识库test");
  6. data.putOpt("embedding_model", "kbq-001");
  7. String result = buildMiniMaxHeader(HttpRequest.post(url))
  8. .body(data.toString())
  9. .execute().body();
  10. validMiniMaxResult(result);
  11. JSONObject resp = new JSONObject(result);
  12. long knowledgeBaseId = resp.getLong("knowledge_base_id");
  13. System.out.println(resp);
  14. }
  15. private String buildMiniMaxUrl(String url) {
  16. StringBuilder sb = new StringBuilder("https://api.minimax.chat/v1/");
  17. sb.append(url);
  18. sb.append(url.indexOf("?") == -1 ? "?" : "&");
  19. sb.append("GroupId=" + groupId);
  20. return sb.toString();
  21. }
  22. private HttpRequest buildMiniMaxHeader(HttpRequest request) {
  23. request.header("content-type", "application/json");
  24. request.header("Authorization", "Bearer " + secretKey);
  25. return request;
  26. }
  27. private void validMiniMaxResult(String result) {
  28. JSONObject json = new JSONObject(result);
  29. JSONObject baseResp = json.getJSONObject("base_resp");
  30. if (baseResp.getInt("status_code") != 0) {
  31. log.error("调用miniMax接口错误: {}", result);
  32. throw new ServiceFailException(baseResp.getStr("status_msg"));
  33. }
  34. }

上传文档

上传文档保存返回的file_id

  1. public void filesUpload() {
  2. String url = buildMiniMaxUrl("files/upload");
  3. Map params = new HashMap();
  4. params.put("purpose", "retrieval");
  5. params.put("file", new File("d:/C中心.docx"));
  6. String result = buildMiniMaxHeader(HttpRequest.post(url))
  7. .form(params)
  8. .execute().body();
  9. validMiniMaxResult(result);
  10. JSONObject resp = new JSONObject(result);
  11. long fileId = resp.getJSONObject("file").getLong("file_id");
  12. System.out.println(result);
  13. }

添加文档到知识库

  1. public void addDocument() {
  2. String url = buildMiniMaxUrl("embedding/add_document");
  3. JSONObject data = new JSONObject();
  4. data.putOpt("operator_id", System.currentTimeMillis());
  5. data.putOpt("knowledge_base_id", knowledge_base_id);
  6. data.putOpt("file_id", file_id);
  7. data.putOpt("doc_params", new JSONObject()
  8. .putOpt("chunk_size", 1000)
  9. .putOpt("chunk_overlap", 100));
  10. String result = buildMiniMaxHeader(HttpRequest.post(url))
  11. .body(data.toString())
  12. .execute().body();
  13. validMiniMaxResult(result);
  14. JSONObject resp = new JSONObject(result);
  15. System.out.println(result);
  16. }

检索知识库

由于检索知识库用到了流式返回,所以需要用到okhttp库

  1. <dependency>
  2. <groupId>com.squareup.okhttp3</groupId>
  3. <artifactId>okhttp</artifactId>
  4. <version>4.10.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.squareup.okhttp3</groupId>
  8. <artifactId>okhttp-sse</artifactId>
  9. <version>4.10.0</version>
  10. </dependency>
  1. public void chatcompletion() throws IOException {
  2. StringBuilder sb = new StringBuilder();
  3. BufferedReader reader = null;
  4. String url = buildMiniMaxUrl("text/chatcompletion_pro");
  5. JSONObject data = new JSONObject()
  6. .putOpt("bot_setting", new JSONArray()
  7. .set(new JSONObject()
  8. .putOpt("bot_name", "MM智能助理")
  9. .putOpt("content", "MM智能助理是一款由MiniMax自研的,没有调用其他产品的接口的大型语言模型。MiniMax是一家中国科技公司,一直致力于进行大模型相关的研究。")))
  10. .putOpt("model", "abab6.5s-chat")
  11. .putOpt("mask_sensitive_info", false)
  12. .putOpt("stream", true)
  13. .putOpt("reply_constraints"
  14. , new JSONObject()
  15. .putOpt("sender_type", "BOT")
  16. .putOpt("sender_name", "MM智能助理"))
  17. .putOpt("messages", new JSONArray()
  18. .set(new JSONObject()
  19. .putOpt("sender_type", "USER")
  20. .putOpt("sender_name", "用户")
  21. .putOpt("text", "卖家直送物流目前可以支持配送到哪些地区")))
  22. .putOpt("knowledge_base_param", new JSONObject()
  23. .putOpt("knowledge_base_id", knowledge_base_id));
  24. //System.out.println(data.toString());
  25. Request okhttpRequest = new Request.Builder()
  26. .url(url)
  27. .post(RequestBody.create(data.toString(), MediaType.get(ContentType.JSON.getValue())))
  28. .addHeader("Authorization", "Bearer " + secretKey)
  29. .build();
  30. Call call = new OkHttpClient.Builder()
  31. .connectTimeout(10, TimeUnit.SECONDS)
  32. .writeTimeout(60, TimeUnit.SECONDS)
  33. .readTimeout(120, TimeUnit.SECONDS)
  34. .build()
  35. .newCall(okhttpRequest);
  36. Response okhttpResponse = call.execute();
  37. reader = new BufferedReader(okhttpResponse.body().charStream());
  38. String line;
  39. int totalToken = 0;
  40. while ((line = reader.readLine()) != null) {
  41. if (cn.hutool.core.util.StrUtil.isBlank(line)) {
  42. continue;
  43. }
  44. System.out.println(line);
  45. if (JSONUtil.isTypeJSON(line)) {
  46. JSONObject json = new JSONObject(line);
  47. JSONObject baseResp = json.getJSONObject("base_resp");
  48. if (baseResp.getInt("status_code") != 0) {
  49. throw new RuntimeException(baseResp.getStr("status_msg"));
  50. }
  51. }
  52. line = cn.hutool.core.util.StrUtil.replace(line, "data: ", cn.hutool.core.util.StrUtil.EMPTY);
  53. if (StrUtil.equals("[DONE]", line) || !JSONUtil.isTypeJSON(line)) {
  54. System.out.println(sb.toString());
  55. }
  56. JSONObject lineObj = JSONUtil.parseObj(line);
  57. if (lineObj != null && lineObj.getJSONObject("usage") != null) {
  58. totalToken = lineObj.getJSONObject("usage").getInt("total_tokens");
  59. }
  60. Optional.of(lineObj)
  61. .map(x -> x.getJSONArray("choices"))
  62. .filter(CollUtil::isNotEmpty)
  63. .map(x -> (JSONObject) x.get(0))
  64. .filter(object -> !"stop".equals(object.getStr("finish_reason")))
  65. .map(x -> x.getJSONArray("messages"))
  66. .filter(CollUtil::isNotEmpty)
  67. .map(x -> (JSONObject) x.get(0))
  68. .ifPresent(x -> {
  69. sb.append(x.getStr("text"));
  70. });
  71. }
  72. System.out.println(totalToken);
  73. System.out.println(sb.toString());
  74. }

我们把卖家直送FAQ转成txt上传到知识库看看效果FAQ

 

 以上是FAQ内容,我们看看知识库的问答

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

闽ICP备14008679号