SpringBoot?Java通過API的方式調(diào)用騰訊智能體(騰訊元寶)代碼示例
引言
我發(fā)現(xiàn)官網(wǎng)只有Python的調(diào)用代碼示例,在網(wǎng)上也沒找到有人分享Java的例子,因此就有了這篇文章,前人栽樹后人乘涼(如果你只想看代碼部分可跳到文章后半部分)。
一、獲取調(diào)用API所需要的參數(shù)信息:
首先我們進(jìn)入騰訊元器獲取調(diào)用API所需要的參數(shù)信息;鏈接:https://yuanqi.tencent.com/
點擊【我的創(chuàng)建】,找到自己想要API調(diào)用的智能體,點擊【更多】,點擊【調(diào)用API】。

我們會得到調(diào)用所需要的信息:url、assistant_id、token等。

調(diào)用信息的具體意義可參考官網(wǎng)文檔:?https://docs.qq.com/aio/p/scxmsn78nzsuj64?p=unUU8C3HBocfQSOGAh2BYuC
請求參數(shù)(其中紅框為必填項):

二、代碼實現(xiàn):
【代碼1】:
主要是對請求參數(shù)的處理;官方給的參數(shù)例子格式是:
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" +
"}";但是我們一般情況下不能這樣寫死,所以需要動態(tài)處理請求參數(shù),如下:
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】:
上面調(diào)用的accessRetailApi.doPostJson5(url,json,token)方法的代碼內(nèi)容:
//API方式調(diào)用騰訊智能體(元寶)
public List doPostJson5(String apiurl, String jsonInput,String auth) throws IOException {
// API 的 URL
String url = apiurl;
// 請求頭
String authorizationToken = auth; // 替換為實際的Token
String jsonInputString = jsonInput;
// 創(chuàng)建URL對象
URL obj = new URL(url);
// 打開連接
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
// 設(shè)置請求方法為 POST
connection.setRequestMethod("POST");
// 設(shè)置請求頭
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);
}
// 獲取響應(yīng)狀態(tài)碼;為200即成功
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
List result = new ArrayList();
// 讀取響應(yīng)內(nèi)容
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類型字符串轉(zhuǎn)換成List<Map>
public static List strToList(String liststr, String path) throws Exception{
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(liststr);
// 訪問路徑的數(shù)組
JsonNode datasNode = rootNode.path(path);
// 創(chuàng)建一個List來存儲Map
List<Map<String, Object>> datasList = new ArrayList<>();
// 遍歷數(shù)組中的每個元素(JsonNode),并將其轉(zhuǎn)換為Map
for (JsonNode dataNode : datasNode) {
Map<String, Object> dataMap = new HashMap<>();
dataNode.fields().forEachRemaining(entry -> {
// 注意:這里簡單地將所有值都視為Object類型
// 對于更復(fù)雜的類型(如嵌套對象或數(shù)組),你可能需要進(jìn)一步的邏輯來處理它們
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轉(zhuǎn)換為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方法,這個方法是把調(diào)用成功返回的字符串結(jié)果轉(zhuǎn)換成數(shù)組;
例如:獲得的resultstr是這樣一段字符串:

通過 strToList(resultstr,"choices")方法把“choices”路徑下提取成數(shù)組List,方便后續(xù)處理:

【代碼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;
總結(jié)
到此這篇關(guān)于SpringBoot Java通過API的方式調(diào)用騰訊智能體(騰訊元寶)的文章就介紹到這了,更多相關(guān)Java API調(diào)用騰訊元寶內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot?整合?ElasticSearch操作各種高級查詢搜索
這篇文章主要介紹了SpringBoot?整合?ES?進(jìn)行各種高級查詢搜索的實踐記錄,本文主要圍繞?SpringBoot?整合?ElasticSearch?進(jìn)行各種高級查詢的介紹,需要的朋友可以參考下2022-06-06
SpringBoot中配置Web靜態(tài)資源路徑的方法
這篇文章主要介紹了SpringBoot中配置Web靜態(tài)資源路徑的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
在IntelliJ IDEA中.idea文件是什么可以刪除嗎
相信有很多小伙伴,在用idea寫java代碼的時候,創(chuàng)建工程總是會出現(xiàn).idea文件,該文件也從來沒去打開使用過,那么它在我們項目里面,扮演什么角色,到底能不能刪除它呢?這篇文章主要介紹了在IntelliJ IDEA中.idea文件是什么可以刪除嗎,需要的朋友可以參考下2024-01-01
一文看懂springboot實現(xiàn)短信服務(wù)功能
項目中的短信服務(wù)基本上上都會用到,簡單的注冊驗證碼,消息通知等等都會用到。這篇文章主要介紹了springboot 實現(xiàn)短信服務(wù)功能,需要的朋友可以參考下2019-10-10
對象存儲服務(wù)MinIO快速入門(集成項目的詳細(xì)過程)
MinIO是一個開源的對象存儲服務(wù),支持多種操作系統(tǒng),配置簡單且性能高,它使用糾刪碼進(jìn)行數(shù)據(jù)保護,可以容忍硬件故障,MinIO支持多種語言的SDK和豐富的API,本文介紹對象存儲服務(wù)MinIO快速入門,感興趣的朋友一起看看吧2025-03-03
SpringCloud Gateway加載斷言predicates與過濾器filters的源碼分析
這篇文章主要介紹了SpringCloud Gateway加載斷言predicates與過濾器filters的詳細(xì)過程,本文通過源碼給大家解析的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05

