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 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 datasList = new ArrayList(); // 遍历数组中的每个元素(JsonNode),并将其转换为Map for (JsonNode dataNode : datasNode) { Map 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 resultMap = new HashMap(); try { // 首先,将整个JSON字符串解析为JsonNode JsonNode rootNode2 = objectMapper.readTree(entry.getValue().toString()); // 将JsonNode转换为Map 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方法,这个方法是把调用成功返回的字符串结果转换成数组;
通过 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;
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。