文本生成模型能根据输入的提示词(Prompt)创作出连贯的文本,适用于内容创作、代码生成、智能客服、文本翻译及摘要生成等场景。
核心概念
与模型交互的核心是消息(Message)对象。每条消息由角色(Role)和内容(Content)组成,具体为:
系统消息(System Message):设定模型扮演的角色或遵循的指令。若不指定,默认为"You are a helpful assistant"。
用户消息(User Message):用户向模型提出的问题或输入的指令。
助手消息(Assistant Message):模型的回复内容。
输入为消息数组messages
,通常包含一个 system
消息(推荐)和一个 user
消息。
system
消息是可选的,但建议使用它来设定模型的角色和行为准则,以获得更稳定、一致的输出。
[
{"role": "system", "content": "你是一个有帮助的助手,需要提供精准、高效且富有洞察力的回应,随时准备协助用户处理各种任务与问题。"},
{"role": "user", "content": "你是谁?"}
]
输出的响应对象中会包含模型回复的内容,角色为assistant
,内容是根据输入生成的回复。
{
"role": "assistant",
"content": "你好!我是Qwen,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字、进行逻辑推理、编程等。我能够理解并生成多种语言,支持多轮对话和复杂任务处理。如果你有任何需要帮助的地方,尽管告诉我!"
}
快速开始
本节以调用通义千问模型为例,介绍文本生成模型的基础用法。若想获得更高质量的生成结果,可参考深度思考。
您需要已获取API Key并配置API Key到环境变量。如果通过OpenAI SDK或DashScope SDK进行调用,还需要安装SDK。
同步调用
OpenAI兼容
以下展示了模型完整响应的 JSON 示例,可以通过choices[0].message.content
字段提取模型的回复内容。
Python
import os
from openai import OpenAI
try:
client = OpenAI(
# 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
# 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
model="qwen-plus",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "你是谁?"},
],
)
# print(completion.choices[0].message.content)
print(completion.model_dump_json())
except Exception as e:
print(f"错误信息:{e}")
print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
Java
// 建议 OpenAI Java SDK版本 >= 3.5.0
// Maven依赖
// <dependency>
// <groupId>com.openai</groupId>
// <artifactId>openai-java</artifactId>
// <version>3.5.0</version>
// </dependency>
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
public class Main {
public static void main(String[] args) {
try {
// 创建 OpenAI 客户端,连接 DashScope 的兼容接口
OpenAIClient client = OpenAIOkHttpClient.builder()
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为.apiKey("sk-xxx")
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/compatible-mode/v1
.baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
.build();
// 创建 ChatCompletion 参数
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen-plus") // 指定模型
.addSystemMessage("You are a helpful assistant.")
.addUserMessage("你是谁?")
.build();
// 发送请求并获取响应
ChatCompletion chatCompletion = client.chat().completions().create(params);
// 若需要以Json格式输出,可使用fastjson2.JSON中的JSON.toJSONString(chatCompletion)
System.out.println(chatCompletion);
} catch (Exception e) {
System.err.println("错误信息:" + e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
}
}
Node.js
// 需要 Node.js v18+
// 使用 `import` 语法,需要 Node.js 环境支持 ES 模块 (ESM)。请确保您的package.json文件中包含"type": "module",或者将此文件保存为.mjs扩展名。
import OpenAI from "openai";
const openai = new OpenAI(
{
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:apiKey: "sk-xxx",
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen-plus", //模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "你是谁?" }
],
});
console.log(JSON.stringify(completion, null, 2))
Go
// OpenAI Go SDK版本不低于 v2.4.0
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/option"
)
func main() {
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:apiKey := "sk-xxx"
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
apiKey := os.Getenv("DASHSCOPE_API_KEY")
client := openai.NewClient(
option.WithAPIKey(apiKey),
// 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/compatible-mode/v1
option.WithBaseURL("https://dashscope.aliyuncs.com/compatible-mode/v1"),
)
chatCompletion, err := client.Chat.Completions.New(
context.TODO(), openai.ChatCompletionNewParams{
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage("You are a helpful assistant."),
openai.UserMessage("你是谁?"),
},
Model: "qwen-plus",
},
)
if err != nil {
fmt.Fprintf(os.Stderr, "请求失败: %v\n", err)
// 更多错误信息,请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code
os.Exit(1)
}
jsonData, _ := json.MarshalIndent(chatCompletion, "", " ")
fmt.Println(string(jsonData))
}
C#(HTTP)
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:string? apiKey = "sk-xxx";
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
// 设置请求 URL 和内容
// 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
string url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
// 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
string jsonContent = @"{
""model"": ""qwen-plus"",
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""你是谁?""
}
]
}";
// 发送请求并获取响应
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// 输出结果
Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// 设置请求头
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// 发送请求并获取响应
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
// 更多错误信息,请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code
return $"请求失败: {response.StatusCode}";
}
}
}
}
PHP(HTTP)
<?php
// 设置请求的URL
// 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
$url = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:$apiKey = "sk-xxx";
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
// 设置请求头
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// 设置请求体
$data = [
// 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
"model" => "qwen-plus",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "你是谁?"
]
]
];
// 初始化cURL会话
$ch = curl_init();
// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 执行cURL会话
$response = curl_exec($ch);
// 检查是否有错误发生
// 更多错误信息,请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// 关闭cURL资源
curl_close($ch);
// 输出响应结果
echo $response;
?>
curl
# ======= 重要提示 =======
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
# === 执行时请删除该注释 ===
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你是谁?"
}
]
}'
返回结果
{
"choices": [
{
"message": {
"role": "assistant",
"content": "我是通义千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!"
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 26,
"completion_tokens": 66,
"total_tokens": 92
},
"created": 1726127645,
"system_fingerprint": null,
"model": "qwen-plus",
"id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}
DashScope
以下展示了模型完整响应 JSON 示例,可以通过output.choices[0].message.content
字段提取模型的回复内容。
Python
import json
import os
from dashscope import Generation
import dashscope
# 若使用新加坡地域的模型,请释放下列注释
# dashscope.base_http_api_url = "https://dashscope-intl.aliyuncs.com/api/v1"
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "你是谁?"},
]
response = Generation.call(
# 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key = "sk-xxx",
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus",
messages=messages,
result_format="message",
)
if response.status_code == 200:
print(json.dumps(response, default=lambda o: o.__dict__, indent=4))
else:
print(f"HTTP返回码:{response.status_code}")
print(f"错误码:{response.code}")
print(f"错误信息:{response.message}")
print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
Java
// 建议 DashScope Java SDK版本 >= 2.20.6
// Maven依赖
// <dependency>
// <groupId>com.alibaba</groupId>
// <artifactId>dashscope-sdk-java</artifactId>
// <version>2.20.6</version>
// </dependency>
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Main {
// 若使用新加坡地域的模型,请释放下列注释
// static {Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";}
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
Generation gen = new Generation();
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("You are a helpful assistant.")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("你是谁?")
.build();
GenerationParam param = GenerationParam.builder()
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:.apiKey("sk-xxx")
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("错误信息:"+e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
}
}
Node.js(HTTP)
// 需要 Node.js v18+
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:const apiKey = "sk-xxx";
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
model: "qwen-plus",
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "你是谁?"
}
]
},
parameters: {
result_format: "message"
}
};
async function callApi() {
try {
// 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation
const response = await fetch('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
console.log(JSON.stringify(result));
} catch (error) {
// 操作失败: 错误信息
// 更多错误信息,请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code
console.error('操作失败:', error.message);
}
}
callApi();
Go(HTTP)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
// 构建简化的请求体
requestBody := map[string]interface{}{
"model": "qwen-plus",
"input": map[string]interface{}{
"messages": []map[string]string{
{
"role": "system",
"content": "You are a helpful assistant.",
},
{
"role": "user",
"content": "你是谁?",
},
},
},
"parameters": map[string]string{
"result_format": "message",
},
}
// 序列化为 JSON
jsonData, _ := json.Marshal(requestBody)
// 创建 HTTP 客户端和请求
client := &http.Client{}
// 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation
req, _ := http.NewRequest("POST", "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
// 设置请求头
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// 读取响应体
bodyText, _ := io.ReadAll(resp.Body)
// 打印响应内容
fmt.Printf("%s\n", bodyText)
}
C#(HTTP)
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:string? apiKey = "sk-xxx";
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
// 设置请求 URL 和内容
// 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation
string url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
string jsonContent = @"{
""model"": ""qwen-plus"",
""input"": {
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""你是谁?""
}
]
},
""parameters"": {
""result_format"": ""message""
}
}";
// 发送请求并获取响应
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// 输出结果
Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// 设置请求头
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// 发送请求并获取响应
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"请求失败: {response.StatusCode}";
}
}
}
}
PHP(HTTP)
<?php
// 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation
$url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
"model" => "qwen-plus",
"input" => [
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "你是谁?"
]
]
],
"parameters" => [
"result_format" => "message"
]
];
$jsonData = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $apiKey",
"Content-Type: application/json"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
echo "模型响应: " . $response;
} else {
echo "请求错误: " . $httpCode . " - " . $response;
}
curl_close($ch);
?>
curl
# ======= 重要提示 =======
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 以下为北京地域url,若使用新加坡地域的模型,需将url替换为:https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 执行时请删除该注释 ===
curl --location "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你是谁?"
}
]
},
"parameters": {
"result_format": "message"
}
}'
返回结果
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "我是通义千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!"
}
}
]
},
"usage": {
"total_tokens": 92,
"output_tokens": 66,
"input_tokens": 26
},
"request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}
异步调用
处理高并发请求时,调用异步接口能有效提升程序效率。
OpenAI兼容
Python
import os
import asyncio
from openai import AsyncOpenAI
import platform
# 创建异步客户端实例
client = AsyncOpenAI(
# 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
# 定义异步任务列表
async def task(question):
print(f"发送问题: {question}")
response = await client.chat.completions.create(
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": question}
],
model="qwen-plus", # 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
)
print(f"模型回复: {response.choices[0].message.content}")
# 主异步函数
async def main():
questions = ["你是谁?", "你会什么?", "天气怎么样?"]
tasks = [task(q) for q in questions]
await asyncio.gather(*tasks)
if __name__ == '__main__':
# 设置事件循环策略
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# 运行主协程
asyncio.run(main(), debug=False)
Java
import com.openai.client.OpenAIClientAsync;
import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
// 创建 OpenAI 客户端,连接 DashScope 的兼容接口
OpenAIClientAsync client = OpenAIOkHttpClientAsync.builder()
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为.apiKey("sk-xxx")
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 以下是北京地域base_url,如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/compatible-mode/v1
.baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
.build();
// 定义问题列表
List<String> questions = Arrays.asList("你是谁?", "你会什么?", "天气怎么样?");
// 创建异步任务列表
CompletableFuture<?>[] futures = questions.stream()
.map(question -> CompletableFuture.supplyAsync(() -> {
System.out.println("发送问题: " + question);
// 创建 ChatCompletion 参数
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen-plus") // 指定模型
.addSystemMessage("You are a helpful assistant.")
.addUserMessage(question)
.build();
// 发送异步请求并处理响应
return client.chat().completions().create(params)
.thenAccept(chatCompletion -> {
String content = chatCompletion.choices().get(0).message().content().orElse("无响应内容");
System.out.println("模型回复: " + content);
})
.exceptionally(e -> {
System.err.println("错误信息:" + e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
return null;
});
}).thenCompose(future -> future))
.toArray(CompletableFuture[]::new);
// 等待所有异步操作完成
CompletableFuture.allOf(futures).join();
}
}
DashScope
DashScope SDK的文本生成异步调用,目前仅支持Python。
# DashScope Python SDK版本需要不低于 1.19.0
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
# 若使用新加坡地域的模型,请释放下列注释
# dashscope.base_http_api_url = "https://dashscope-intl.aliyuncs.com/api/v1"
# 定义异步任务列表
async def task(question):
print(f"发送问题: {question}")
response = await AioGeneration.call(
# 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus", # 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
messages=[{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": question}],
result_format="message",
)
print(f"模型回复: {response.output.choices[0].message.content}")
# 主异步函数
async def main():
questions = ["你是谁?", "你会什么?", "天气怎么样?"]
tasks = [task(q) for q in questions]
await asyncio.gather(*tasks)
if __name__ == '__main__':
# 设置事件循环策略
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# 运行主协程
asyncio.run(main(), debug=False)
返回结果
注意:由于调用是异步的,实际运行时响应的返回顺序可能与示例不同。
发送问题: 你是谁?
发送问题: 你会什么?
发送问题: 天气怎么样?
模型回复: 你好!我是通义千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!
模型回复: 您好!我目前无法实时获取天气信息。您可以告诉我您所在的城市或地区,我会尽力为您提供一些通用的天气建议或信息。或者您也可以使用天气应用查看实时天气情况。
模型回复: 我会很多技能,比如:
1. **回答问题**:无论是学术问题、生活常识还是专业知识,我都可以尝试帮你解答。
2. **创作文字**:我可以写故事、公文、邮件、剧本等各类文本。
3. **逻辑推理**:我可以帮助你解决一些逻辑推理问题,比如数学题、谜语等。
4. **编程**:我可以提供编程帮助,包括代码编写、调试和优化。
5. **多语言支持**:我支持多种语言,包括但不限于中文、英文、法语、西班牙语等。
6. **观点表达**:我可以为你提供一些观点和建议,帮助你做出决策。
7. **玩游戏**:我们可以一起玩文字游戏,比如猜谜语、成语接龙等。
如果你有任何具体的需求或问题,欢迎告诉我,我会尽力帮助你!
模型选型建议
通用模型
通义千问Max、通义千问Plus 和通义千问Flash 均已升级至Qwen3系列,并兼容OpenAI调用方式,适用于智能客服、文本创作、内容润色以及摘要总结等多种场景。
通义千问Plus:在效果、速度和成本上表现均衡,是多数场景的推荐选择。
通义千问Max :通义千问系列效果最好的模型,适合处理复杂、多步骤任务。
通义千问Flash :通义千问系列速度最快、成本极低的模型,适用于执行简单任务。
特定场景模型
针对明确的业务需求,阿里云百炼提供多种专用优化模型,覆盖代码能力、超长文档、翻译、数据挖掘、法律、意图理解、角色扮演、深入研究等领域。
多模态模型
通义千问VL(文+图->文):具备图像理解能力,支持光学字符识别(OCR)、视觉推理和图文理解等任务。
通义千问Omni(全模态-> 文+音):支持视频、音频、图片、文本等多种数据输入,生成文本和语音输出,以应对跨模态复杂任务。
通义千问Audio(文+音->文):具有音频理解能力,支持语音转录、语义理解、情感分析、音频事件检测和语音聊天等功能。
语音识别模型(音->文):识别并转写音频中的语音内容,支持中文(含粤语等各种方言)、英文、日语、韩语等。
第三方模型
阿里云百炼支持 DeepSeek、Kimi、GLM-4.5、Llama、百川、MiniMax等众多知名的第三方大语言模型,完整模型列表请参考文本生成-第三方模型。
API 参考
模型调用的完整参数列表,请参考 OpenAI 兼容 API 参考和DashScope API 参考。
常见问题
Q:通义千问 API 为何无法分析网页链接?
A:通义千问 API 本身不具备直接访问和解析网页链接的能力,可以通过Function Calling、MCP等功能,或结合 Python 的 Beautiful Soup 等网页抓取工具读取网页信息。
Q:网页端通义千问和通义千问 API 的回复为什么不一致?
A:网页端通义千问在通义千问 API 的基础上做了额外的工程优化,因此可以达到解析网页、联网搜索、画图、制作 PPT等功能,这些本身并不属于大模型 API 的能力,可以通过联网搜索、Function Calling、MCP等功能优化模型的效果。