當前位置: 妍妍網 > 碼農

手把手教你 Java 呼叫通義千問的 API,快速入門 AI 開發

2024-05-15碼農

就在上周,阿裏雲釋出了一則重磅訊息:釋出通義千問大模型2.5版本,能力全面升級,中文效能趕超GPT-4!為了讓更多人享受到AI帶來的便利與創新,他們已向全網使用者無償開放1000萬字的長文件處理功能。

本篇文章我將手把手教你如何透過Java呼叫通義千問API,完成一個小案例的開發,入門AIGC。

註冊開通

進入網站 https://dashscope.console.aliyun.com/overview

然後使用支付寶、釘釘或手機號 註冊一個阿裏雲帳號 ,註冊完成後登入

點選 未開通 按鈕

然後點選 立即開通

開通完成後 前往控制台

獲取API-KEY

進入 https://dashscope.console.aliyun.com/apiKey

根據截圖操作 獲取API-KEY

關閉彈窗後無法再次檢視API-KEY,如果忘了可以重新生成一個

實戰

開啟IDEA新建一個SpringBoot計畫

添加要用的依賴,我這裏先添加了Web依賴和Lombok

添加hutool工具包依賴

<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.27</version>
</dependency>

建立ChatController類,用於前端處理請求

package cn.unclecode.dashscope.controller;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import cn.unclecode.dashscope.request.ChatRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public classChatController{
@PostMapping("/chat")
public String chat(String q){
String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
String ApiKey = "sk-6e93625f6c3a4e45811c2177d79dca50";//ApiKey
ChatRequest chatRequest = new ChatRequest(q);
String json = JSONUtil.toJsonStr(chatRequest);
String result = HttpRequest.post(url)
.header("Authorization","Bearer " + ApiKey)
.header("Content-Type","application/json")
.body(json)
.execute().body();
System.out.println(result);
return result;
}
}


建立ChatRequest類,使用者構造請求參數

更多參數查閱官方文件

https://help.aliyun.com/zh/dashscope

package cn.unclecode.dashscope.request;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.logging.log4j.message.Message;
import java.util.ArrayList;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public classChatRequest{
String model;
List<ChatRequest.Chat> messages;
Parameters parameters;
publicChatRequest(String q){
model = "qwen-turbo";
List<ChatRequest.Chat> chats = new ArrayList<>();
chats.add(new Chat("system","你是生活助手機器人。"));
chats.add(new Chat("user",q));
messages = chats;
parameters = new Parameters();
}
classChat{
public String role;
public String content;
Chat(String role,String content){
this.role = role;
this.content = content;
}
}
classParameters{
public String result_format = "text";
}
}



啟動計畫,使用介面測試工具向介面發起請求

響應數據為

{
"choices": [
{
"message": {
"role""assistant",
"content""是的,2000年是閏年。閏年的規則是每4年一閏,但是能被100整除的年份不是閏年,除非它同時也能被400整除。所以,2000年能夠被400整除,因此它是閏年。"
},
"finish_reason""stop",
"index"0,
"logprobs"null
}
 ],
"object""chat.completion",
"usage": {
"prompt_tokens"32,
"completion_tokens"68,
"total_tokens"100
 },
"created"1715704993,
"system_fingerprint"null,
"model""qwen-turbo",
"id""chatcmpl-39f7dbe568e09c85b06d3a7d3fa4ec74"
}

總結

以上就是所有內容,本教程只是簡單的問答處理,有更多需求,可以參考官方文件,在此基礎上做修改。

官方文件:https://help.aliyun.com/zh/dashscope