使用AnythingLLM的api调用

使用AnythingLLM的api调用

目标

AnythingLLM是一个图形化的工具,想要在项目中使用,就必须使用API调用。

好在AnythingLLM提供了这样的工具。

官方文档

API Access and Keys | AnythingLLM by Mintplex Labs

申请API-KEY

创建新的API-KEY

访问Swagger

访问本地的http://localhost:3001/api/docs/ 可以查询到官方的文档。

测试API

点击左上角的Authorize进行认证,API key是作为请求头传入的。

找到工作空间的进行POST的Chat

得到了这样的响应:

可以看到成功发挥了AnythingLLM的查询文档功能。

{
  "id": "63dd7a4b-45f9-4b29-84be-74a0119f85e6",
  "type": "textResponse",
  "close": true,
  "error": null,
  "chatId": 17,
  "textResponse": "ECharts is a powerful, open-source JavaScript visualization library that offers flexible chart types, robust rendering engines, and professional data analysis capabilities. It allows developers to create dynamic, interactive visualizations for web applications using various charts such as line charts, bar charts, scatter plots, pie charts, and more. ECharts supports customization in terms of appearance, layout, and interactivity, making it suitable for a wide range of uses from simple dashboards to complex data analysis tools.",
  "sources": [
    {
      "id": "5be5be5f-a394-41b0-a47e-1db35c9fc8ce",
      "url": "file://C:\\Users\\81067\\AppData\\Roaming\\anythingllm-desktop\\storage\\hotdir\\echarts使用 英文文档.docx",
      "title": "echarts使用 英文文档.docx",
      "docAuthor": "no author found",
      "description": "No description found.",
      "docSource": "pdf file uploaded by the user.",
      "chunkSource": "",
      "published": "2024/6/23 12:24:49",
      "wordCount": 871,
      "token_count_estimate": 904,
      "text": "<document_metadata>\nsourceDocument: echarts使用 英文文档.docx\npublished: 2024/6/23 12:24:49\n</document_metadata>\n\nECharts is a powerful, open-source JavaScript visualization library that provides flexible chart types, powerful rendering engines, and professional data analysis capabilities. Here is a comprehensive guide on how to use ECharts:\n\nGetting Started with ECharts\n\n1. Installation\n\nYou can include ECharts in your project by downloading it from the Apache ECharts website or by using a CDN like jsDelivr. To quickly set it up:\n\nDownload from CDN:\n\nhtml\n\n复制代码\n\n<script src=\"https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js\"></script>\n\nInclude in HTML:\n\nhtml\n\n复制代码\n\n<script src=\"echarts.js\"></script>\n\n2. Basic Setup\n\nCreate a simple HTML file and include the ECharts library. Set up a container where the chart will be rendered:\n\nhtml\n\n复制代码\n\n<!DOCTYPE html>\n\n<html>\n\n<head>\n\n    <meta charset=\"utf-8\">\n\n    <script src=\"echarts.js\"></script>\n\n</head>\n\n<body>\n\n    <div id=\"main\" style=\"width: 600px;height:400px;\"></div>\n\n    <script type=\"text/javascript\">",
      "_distance": 0.4381682872772217,
      "score": 0.5618317127227783
    },
    {
      "id": "2880ba79-f81b-4b72-ad93-2951bebe55b3",
      "url": "file://C:\\Users\\81067\\AppData\\Roaming\\anythingllm-desktop\\storage\\hotdir\\echarts使用 英文文档.docx",
      "title": "echarts使用 英文文档.docx",
      "docAuthor": "no author found",
      "description": "No description found.",
      "docSource": "pdf file uploaded by the user.",
      "chunkSource": "",
      "published": "2024/6/23 12:24:49",
      "wordCount": 871,
      "token_count_estimate": 904,
      "text": "<document_metadata>\nsourceDocument: echarts使用 英文文档.docx\npublished: 2024/6/23 12:24:49\n</document_metadata>\n\nboundaryGap: false,\n\n        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n\n    },\n\n    yAxis: {\n\n        type: 'value'\n\n    },\n\n    series: [\n\n        {\n\n            name: 'Email',\n\n            type: 'line',\n\n            stack: 'Total',\n\n            data: [120, 132, 101, 134, 90, 230, 210]\n\n        }\n\n    ]\n\n};\n\nResources\n\nFor more detailed guides and examples, you can refer to the official ECharts documentation and the ECharts handbook which cover everything from basic setup to advanced usage and best practices.\n\nThese resources will help you leverage ECharts' full potential to create engaging and informative visualizations for your web applications.",
      "_distance": 0.4401152729988098,
      "score": 0.5598847270011902
    },
    {
      "id": "6f5ed6cf-124c-4871-88cc-231a50217b44",
      "url": "file://C:\\Users\\81067\\AppData\\Roaming\\anythingllm-desktop\\storage\\hotdir\\echarts使用 英文文档.docx",
      "title": "echarts使用 英文文档.docx",
      "docAuthor": "no author found",
      "description": "No description found.",
      "docSource": "pdf file uploaded by the user.",
      "chunkSource": "",
      "published": "2024/6/23 12:24:49",
      "wordCount": 871,
      "token_count_estimate": 904,
      "text": "<document_metadata>\nsourceDocument: echarts使用 英文文档.docx\npublished: 2024/6/23 12:24:49\n</document_metadata>\n\n},\n\n    series: [{\n\n        data: [120, 200, 150, 80, 70, 110, 130],\n\n        type: 'bar'\n\n    }]\n\n};\n\nLine Chart:\n\njavascript\n\n复制代码\n\nvar option = {\n\n    xAxis: {\n\n        type: 'category',\n\n        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n\n    },\n\n    yAxis: {\n\n        type: 'value'\n\n    },\n\n    series: [{\n\n        data: [150, 230, 224, 218, 135, 147, 260],\n\n        type: 'line'\n\n    }]\n\n};\n\n4. Advanced Features\n\nECharts provides advanced features like dynamic data, rich text labels, animations, and interactions:\n\nDynamic Data:\n\njavascript\n\n复制代码\n\nsetInterval(function () {\n\n    var data = option.series[0].data;\n\n    data.shift();\n\n    data.push(Math.round(Math.random() * 1000));\n\n    myChart.setOption(option);\n\n}, 2000);\n\nRich Text:\n\njavascript\n\n复制代码\n\nvar option = {\n\n    title: {\n\n        text: 'ECharts Entry Example',\n\n        subtext: 'Purely Fictitious'\n\n    },\n\n    tooltip: {\n\n        trigger: 'axis'\n\n    },\n\n    xAxis: {\n\n        type: 'category',",
      "_distance": 0.45500361919403076,
      "score": 0.5449963808059692
    },
    {
      "id": "4919bd52-1962-40f2-ba3f-2b869f12f606",
      "url": "file://C:\\Users\\81067\\AppData\\Roaming\\anythingllm-desktop\\storage\\hotdir\\echarts使用 英文文档.docx",
      "title": "echarts使用 英文文档.docx",
      "docAuthor": "no author found",
      "description": "No description found.",
      "docSource": "pdf file uploaded by the user.",
      "chunkSource": "",
      "published": "2024/6/23 12:24:49",
      "wordCount": 871,
      "token_count_estimate": 904,
      "text": "<document_metadata>\nsourceDocument: echarts使用 英文文档.docx\npublished: 2024/6/23 12:24:49\n</document_metadata>\n\nvar myChart = echarts.init(document.getElementById('main'));\n\n        var option = {\n\n            title: {\n\n                text: 'ECharts Example'\n\n            },\n\n            tooltip: {},\n\n            legend: {\n\n                data: ['sales']\n\n            },\n\n            xAxis: {\n\n                data: ['Shirts', 'Cardigans', 'Chiffons', 'Pants', 'Heels', 'Socks']\n\n            },\n\n            yAxis: {},\n\n            series: [{\n\n                name: 'sales',\n\n                type: 'bar',\n\n                data: [5, 20, 36, 10, 10, 20]\n\n            }]\n\n        };\n\n        myChart.setOption(option);\n\n    </script>\n\n</body>\n\n</html>\n\n3. Chart Types\n\nECharts supports a variety of chart types, including bar, line, pie, scatter, and more. Each chart type can be customized extensively:\n\nBar Chart:\n\njavascript\n\n复制代码\n\nvar option = {\n\n    xAxis: {\n\n        type: 'category',\n\n        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n\n    },\n\n    yAxis: {\n\n        type: 'value'",
      "_distance": 0.5417587757110596,
      "score": 0.45824122428894043
    }
  ]
}

Swagger也给出了Curl命令

curl -X 'POST' \
  'http://localhost:3001/api/v1/workspace/echarts/chat' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer SHCJ9M8-CD6M1P1-P8GMHE9-CFHK12E' \
  -H 'Content-Type: application/json' \
  -d '{
  "message": "What is echarts?",
  "mode": "chat"
}'

编写代码

根据Swagger给出的Curl命令,编写Java代码

curl -X 'POST' \
  'http://localhost:3001/api/v1/workspace/echarts/chat' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer SHCJ9M8-CD6M1P1-P8GMHE9-CFHK12E' \
  -H 'Content-Type: application/json' \
  -d '{
  "message": "What is echarts?",
  "mode": "chat"
}'

编写一个askLocalAnythingLLM方法,传入message参数,将授权信息等传入请求头中,得到返回的JSON处理后作为String类型传回。

public static String askLocalAnythingLLM(String message) {
    final String TARGET_URL = "http://localhost:3001/api/v1/workspace/echarts/chat";
    final String ACCEPT_HEADER = "application/json";
    final String AUTHORIZATION_HEADER = "Bearer Y78TPJ6-5PJMMHB-Q07KE5B-07308GT";
    final String CONTENT_TYPE_HEADER = "application/json";
    StringBuilder response = new StringBuilder();
    try {
        // 创建URL对象
        URL url = new URL(TARGET_URL);
​
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
​
        // 设置请求方法为POST
        connection.setRequestMethod("POST");
​
        // 设置请求头
        connection.setRequestProperty("accept", ACCEPT_HEADER);
        connection.setRequestProperty("Authorization", AUTHORIZATION_HEADER);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_HEADER);
​
        // 允许向连接中写入数据
        connection.setDoOutput(true);
​
        // 创建JSON请求体
        String jsonInputString = String.format("{ \"message\": \"%s\", \"mode\": \"query\" }", message);
​
        // 向连接中写入数据
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }
​
        int responseCode = connection.getResponseCode();
        System.out.println("POST Response Code :: " + responseCode);
​
        // 读取响应内容
        try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
​
    // 创建JSONObject对象
    JSONObject jsonObject = new JSONObject(response.toString());
    // 提取textResponse字段
    String textResponse = jsonObject.getString("textResponse");
​
    return textResponse;
}
  • 27
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值