SpringBoot Java 通过API的方式调用腾讯智能体(腾讯元宝)

我发现官网只有Python的调用代码示例,在网上也没找到有人分享Java的例子,因此就有了这篇文章,前人栽树后人乘凉(如果你只想看代码部分可跳到文章后半部分)。

一、获取调用API所需要的参数信息:

首先我们进入腾讯元器获取调用API所需要的参数信息;链接:https://yuanqi.tencent.com/

点击【我的创建】,找到自己想要API调用的智能体,点击【更多】,点击【调用API】。

我们会得到调用所需要的信息:url、assistant_id、token等。

调用信息的具体意义可参考官网文档:https://docs.qq.com/aio/p/scxmsn78nzsuj64?p=unUU8C3HBocfQSOGAh2BYuC

请求参数(其中红框为必填项): 


二、代码实现:

【代码1】:

 主要是对请求参数的处理;官方给的参数例子格式是:

String jsonInputString = "{\n" +
                "  \"assistant_id\": \"你的assistant_id\",\n" +
                "  \"user_id\": \"username\",\n" +
                "  \"stream\": false,\n" +
                "  \"messages\": [\n" +
                "    {\n" +
                "      \"role\": \"user\",\n" +
                "      \"content\": [\n" +
                "        {\n" +
                "          \"type\": \"text\",\n" +
                "          \"text\": \"开始\"\n" +
                "        }\n" +
                "      ]\n" +
                "    }\n" +
                "  ]\n" +
                "}";

但是我们一般情况下不能这样写死,所以需要动态处理请求参数,如下: 

String url = 你的url";
String token = "你的token";
try {
            Map m = new HashMap();
            m.put("assistant_id","你的assistant_id");
            m.put("user_id","username");
            m.put("stream",false);
            List mesg = new ArrayList();
            Map m2 = new HashMap();
            m2.put("role","user");
            Map m3 = new HashMap();
            m3.put("type","text");
            m3.put("text","开始");
            List content = new ArrayList();
            content.add(m3);
            m2.put("content",content);
            mesg.add(m2);
            m.put("messages",mesg);
            Gson gson = new Gson();
            String json = gson.toJson(m);
            List list = accessRetailApi.doPostJson5(url,json,token);
        }catch (Exception e){
            e.printStackTrace();
        }

【代码1】所引用的包参考:

import com.google.gson.Gson;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

【代码2】:

上面调用的accessRetailApi.doPostJson5(url,json,token)方法的代码内容:

//API方式调用腾讯智能体(元宝)
    public List doPostJson5(String apiurl, String jsonInput,String auth) throws IOException {
        // API 的 URL
        String url = apiurl;

        // 请求头
        String authorizationToken = auth; // 替换为实际的Token

        String jsonInputString = jsonInput;
        // 创建URL对象
        URL obj = new URL(url);

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为 POST
        connection.setRequestMethod("POST");

        // 设置请求头
        connection.setRequestProperty("X-Source", "openapi");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + authorizationToken);

        // 启用输入输出流
        connection.setDoOutput(true);

        // 将请求体写入输出流
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 获取响应状态码;为200即成功
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        List result = new ArrayList();
        // 读取响应内容
        try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            String resultstr = response.toString();
            System.out.println("Response: " + response.toString());
            result = strToList(resultstr,"choices");
            System.out.println("result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //把JSON类型字符串转换成List<Map>
    public static List strToList(String liststr, String path) throws Exception{
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(liststr);
        // 访问路径的数组
        JsonNode datasNode = rootNode.path(path);
        // 创建一个List来存储Map
        List<Map<String, Object>> datasList = new ArrayList<>();

        // 遍历数组中的每个元素(JsonNode),并将其转换为Map
        for (JsonNode dataNode : datasNode) {
            Map<String, Object> dataMap = new HashMap<>();
            dataNode.fields().forEachRemaining(entry -> {
                // 注意:这里简单地将所有值都视为Object类型
                // 对于更复杂的类型(如嵌套对象或数组),你可能需要进一步的逻辑来处理它们
                dataMap.put(entry.getKey(), entry.getValue().asText());
                if(entry.getKey().equals("message")) {
                    ObjectMapper objectMapper = new ObjectMapper();
                    Map<String, Object> resultMap = new HashMap<>();
                    try {
                        // 首先,将整个JSON字符串解析为JsonNode
                        JsonNode rootNode2 = objectMapper.readTree(entry.getValue().toString());
                        // 将JsonNode转换为Map<String, Object>
                        resultMap = objectMapper.convertValue(rootNode2, Map.class);
                        dataMap.replace("message", resultMap);
                    } catch (JsonMappingException e) {
                        e.printStackTrace();
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
            });
            datasList.add(dataMap);
        }
        return datasList;
    }

 其中特意要讲解一下的是strToList方法,这个方法是把调用成功返回的字符串结果转换成数组;

例如:获得的resultstr是这样一段字符串:

通过 strToList(resultstr,"choices")方法把“choices”路径下提取成数组List,方便后续处理:

【代码2】所引用的包参考:

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值