要在 Go 语言的应用中集成通义千问(Qwen)大模型,目前阿里云官方主要提供的是 HTTP API 接口 和 Python SDK ,暂未提供官方的 Go SDK。不过你可以通过调用其开放的 API(如 DashScope API)来实现与 Qwen 模型的交互。
以下是使用 Go 调用通义千问(Qwen)大模型的完整步骤:
✅ 第一步:获取 API 密钥
- 访问 DashScope 官网
- 注册/登录账号
- 进入「控制台」→「API Key 管理」
- 创建或复制你的 API Key(形如
sk-xxxxxxxxxxxxxxxxxxxxxxxx)
✅ 第二步:选择要使用的 Qwen 模型
常用模型包括:
qwen-maxqwen-plusqwen-turboqwen-vl-plus(支持图文)qwen-audio-plus(支持语音)
文档参考:DashScope 模型列表
✅ 第三步:使用 Go 发起 HTTP 请求调用 API
虽然没有官方 Go SDK,但你可以直接使用标准库 net/http 或第三方库(如 resty, gorequest)调用 API。
示例:调用 qwen-max 文本生成 API
go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
// 请求结构体
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type RequestBody struct {
Model string `json:"model"`
Input struct {
Messages []Message `json:"messages"`
} `json:"input"`
Parameters map[string]interface{} `json:"parameters,omitempty"`
}
// 响应结构体(简化版)
type ResponseBody struct {
Output struct {
Text string `json:"text"`
} `json:"output"`
RequestID string `json:"request_id"`
Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
} `json:"usage"`
}
func main() {
apiKey := "YOUR_API_KEY" // 替换为你的 DashScope API Key
url := "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
// 构造请求数据
var reqBody RequestBody
reqBody.Model = "qwen-max"
reqBody.Input.Messages = []Message{
{Role: "system", Content: "你是一个 helpful 助手"},
{Role: "user", Content: "请介绍一下你自己"},
}
// 可选参数(如 temperature, top_p 等)
reqBody.Parameters = map[string]interface{}{
"temperature": 0.7,
}
// 序列化 JSON
jsonData, err := json.Marshal(reqBody)
if err != nil {
log.Fatal("JSON marshal error:", err)
}
// 创建 HTTP 请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal("Request creation error:", err)
}
// 设置 Header
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal("HTTP request failed:", err)
}
defer resp.Body.Close()
// 读取响应
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
fmt.Printf("Error: %d\n", resp.StatusCode)
fmt.Printf("Response: %s\n", body)
return
}
// 解析响应
var result ResponseBody
if err := json.Unmarshal(body, &result); err != nil {
log.Fatal("JSON unmarshal error:", err)
}
// 输出结果
fmt.Println("Reply:", result.Output.Text)
fmt.Println("Tokens used:", result.Usage.InputTokens+result.Usage.OutputTokens)
}
✅ 第四步:安装依赖(可选)
如果你希望使用更高级的 HTTP 客户端,可以使用 resty:
bash
go get github.com/go-resty/resty/v2
然后用 resty 改写请求部分(更简洁):
go
import "github.com/go-resty/resty/v2"
client := resty.New()
var result ResponseBody
resp, err := client.R().
SetHeader("Authorization", "Bearer "+apiKey).
SetHeader("Content-Type", "application/json").
SetBody(reqBody).
SetResult(&result).
Post("https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation")
if err != nil {
log.Fatal(err)
}
fmt.Println("Reply:", result.Output.Text)
✅ 第五步:错误处理与重试机制(建议添加)
- 添加超时设置
- 对
5xx错误进行重试 - 日志记录和监控
✅ 第六步:环境变量管理(推荐)
不要硬编码 API Key,使用环境变量:
go
apiKey := os.Getenv("DASHSCOPE_API_KEY")
if apiKey == "" {
log.Fatal("DASHSCOPE_API_KEY not set")
}
运行前设置:
bash
export DASHSCOPE_API_KEY="sk-xxxxxxxxxxxx"
go run main.go
🔔 注意事项
| 项目 | 说明 |
|---|---|
| 官方 Go SDK | ❌ 尚未提供 |
| 是否收费 | ✅ 免费额度 + 按量计费(查看官网定价) |
| 请求频率限制 | ⚠️ 有 QPS 限制,注意控制并发 |
| 支持流式输出 | ✅ 支持 incremental output(需设置 incremental_output=true 并使用 SSE 解析) |
🚀 扩展:支持流式输出(SSE)
若需实时流式返回(如 Chatbot 场景),需启用 incremental_output 并解析 Server-Sent Events (SSE),这需要更复杂的事件解析逻辑。可以使用 golang.org/x/exp/event 或手动解析。
示例参数添加:
json
"parameters": {
"incremental_output": true
}
然后使用 http.Request 逐行读取 text/event-stream 响应。
📚 参考文档
- DashScope API 文档:
https://help.aliyun.com/zh/dashscope/developer-reference/ - API 快速入门:
https://help.aliyun.com/zh/dashscope/developer-reference/quick-start - 模型调用示例(Python):
https://github.com/modelscope/modelscope/tree/master/modelscope/pipelines
✅ 总结
尽管目前没有官方 Go SDK,但通过 HTTP API 调用 Qwen 是完全可行且稳定的。你可以封装一个 qwen-go-client 包来复用代码。
如果你希望我帮你封装一个通用的 Go 客户端库(支持同步/异步/流式),也可以告诉我,我可以为你生成完整的模块结构。
是否需要我提供一个可复用的 Go package 示例?