请求体 文本输入 Python import os
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用百炼 API Key 将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.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': '你是谁?'}],
)
print(completion.model_dump_json())
Node.js import OpenAI from "openai";
const openai = new OpenAI(
{
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
);
async function main() {
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))
}
main();
HTTP
curl 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": "你是谁?"
}
]
}'
PHP <?php
// 设置请求的 URL
$url = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:$apiKey = "sk-xxx";
$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_HTTPHEADER, $headers);
// 执行 cURL 会话
$response = curl_exec($ch);
// 检查是否有错误发生
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// 关闭 cURL 资源
curl_close($ch);
// 输出响应结果
echo $response;
?>
C# 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";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API Key 未设置。请确保环境变量 'DASHSCOPE_API_KEY' 已设置。");
return;
}
// 设置请求 URL 和内容
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
{
return $"请求失败: {response.StatusCode}";
}
}
}
}
Go package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type RequestBody struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
}
func main() {
// 创建 HTTP 客户端
client := &http.Client{}
// 构建请求体
requestBody := RequestBody{
// 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
Model: "qwen-plus",
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: "你是谁?",
},
},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal(err)
}
// 创建 POST 请求
req, err := http.NewRequest("POST", "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// 设置请求头
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:apiKey := "sk-xxx"
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, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// 打印响应内容
fmt.Printf("%s\n", bodyText)
}
流式输出 Python import os
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用百炼 API Key 将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-plus",
messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '你是谁?'}],
stream=True,
stream_options={"include_usage": True}
)
for chunk in completion:
print(chunk.model_dump_json())
响应示例
{"id":"chatcmpl-ecd76cbd-ec86-9546-880f-556fd2bb44b5","choices":[{"delta":{"content":"","function_call":null,"refusal":null,"role":"assistant","tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1724916712,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-ecd76cbd-ec86-9546-880f-556fd2bb44b5","choices":[{"delta":{"content":"我是","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1724916712,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-ecd76cbd-ec86-9546-880f-556fd2bb44b5","choices":[{"delta":{"content":"阿里","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1724916712,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-ecd76cbd-ec86-9546-880f-556fd2bb44b5","choices":[{"delta":{"content":"云","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1724916712,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-ecd76cbd-ec86-9546-880f-556fd2bb44b5","choices":[{"delta":{"content":"开发的一款超大规模语言","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1724916712,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-ecd76cbd-ec86-9546-880f-556fd2bb44b5","choices":[{"delta":{"content":"模型,我叫通义千问","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1724916712,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-ecd76cbd-ec86-9546-880f-556fd2bb44b5","choices":[{"delta":{"content":"。","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1724916712,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-ecd76cbd-ec86-9546-880f-556fd2bb44b5","choices":[{"delta":{"content":"","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1724916712,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-ecd76cbd-ec86-9546-880f-556fd2bb44b5","choices":[],"created":1724916712,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":{"completion_tokens":17,"prompt_tokens":22,"total_tokens":39}}
curl curl --location "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-plus",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你是谁?"
}
],
"stream":true
}'
响应示例
data: {"choices":[{"delta":{"content":"","role":"assistant"},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1724916884,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e45656c0-efae-940b-a3b8-18c9e6528ecb"}
data: {"choices":[{"finish_reason":null,"delta":{"content":"我是"},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1724916884,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e45656c0-efae-940b-a3b8-18c9e6528ecb"}
data: {"choices":[{"delta":{"content":"阿里"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1724916884,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e45656c0-efae-940b-a3b8-18c9e6528ecb"}
data: {"choices":[{"delta":{"content":"云"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1724916884,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e45656c0-efae-940b-a3b8-18c9e6528ecb"}
data: {"choices":[{"delta":{"content":"开发的一款超大规模语言"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1724916884,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e45656c0-efae-940b-a3b8-18c9e6528ecb"}
data: {"choices":[{"delta":{"content":"模型,我叫通义千问"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1724916884,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e45656c0-efae-940b-a3b8-18c9e6528ecb"}
data: {"choices":[{"delta":{"content":"。"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1724916884,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e45656c0-efae-940b-a3b8-18c9e6528ecb"}
data: {"choices":[{"delta":{"content":""},"finish_reason":"stop","index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1724916884,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e45656c0-efae-940b-a3b8-18c9e6528ecb"}
data: [DONE]
Node.js import OpenAI from "openai";
const openai = new OpenAI(
{
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
);
async function main() {
const completion = await openai.chat.completions.create({
model: "qwen-plus",
messages: [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "你是谁?"}
],
stream: true,
});
for await (const chunk of completion) {
console.log(JSON.stringify(chunk));
}
}
main();
响应示例
{"choices":[{"delta":{"content":"","role":"assistant"},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1728455257,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-bdcd77c7-6c52-9501-9ad0-fbda95386bbc"}
{"choices":[{"finish_reason":null,"delta":{"content":"我是来自"},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1728455257,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-bdcd77c7-6c52-9501-9ad0-fbda95386bbc"}
{"choices":[{"delta":{"content":"阿里"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1728455257,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-bdcd77c7-6c52-9501-9ad0-fbda95386bbc"}
{"choices":[{"delta":{"content":"云"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1728455257,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-bdcd77c7-6c52-9501-9ad0-fbda95386bbc"}
{"choices":[{"delta":{"content":"的大规模语言模型"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1728455257,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-bdcd77c7-6c52-9501-9ad0-fbda95386bbc"}
{"choices":[{"delta":{"content":",我叫通"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1728455257,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-bdcd77c7-6c52-9501-9ad0-fbda95386bbc"}
{"choices":[{"delta":{"content":"义千问。"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1728455257,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-bdcd77c7-6c52-9501-9ad0-fbda95386bbc"}
{"choices":[{"delta":{"content":""},"finish_reason":"stop","index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1728455257,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-bdcd77c7-6c52-9501-9ad0-fbda95386bbc"}
图像输入 关于大模型分析图像的更多用法,请参考:视觉理解 。 Python import os
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用百炼 API Key 将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-vl-plus",
messages=[{"role": "user","content": [
{"type": "text","text": "这是什么"},
{"type": "image_url",
"image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}}
]}]
)
print(completion.model_dump_json())
curl 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-vl-plus",
"messages": [{
"role": "user",
"content":
[{"type": "text","text": "这是什么"},
{"type": "image_url","image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}}]
}]
}'
Node.js import OpenAI from "openai";
const openai = new OpenAI(
{
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
);
async function main() {
const response = await openai.chat.completions.create({
model: "qwen-vl-max",
messages: [{role: "user",content: [
{ type: "text", text: "这是什么?" },
{ type: "image_url",image_url: {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}}
]}]
});
console.log(JSON.stringify(response));
}
main();
视频输入 关于大模型分析视频的更多用法,请参考:视觉理解 。 Python import os
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用百炼 API Key 将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-vl-max-latest",
messages=[{
"role": "user",
"content": [
{
"type": "video",
"video": [
"https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
"https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
"https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
"https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"]
},
{
"type": "text",
"text": "描述这个视频的具体过程"
}]}]
)
print(completion.model_dump_json())
curl 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-vl-max-latest",
"messages": [
{
"role": "user",
"content": [
{
"type": "video",
"video": [
"https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
"https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
"https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
"https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"
]
},
{
"type": "text",
"text": "描述这个视频的具体过程"
}
]
}
]
}'
Node.js // 确保之前在 package.json 中指定了 "type": "module"
import OpenAI from "openai";
const openai = new OpenAI({
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.chat.completions.create({
model: "qwen-vl-max-latest",
messages: [{
role: "user",
content: [
{
type: "video",
video: [
"https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
"https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
"https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
"https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"
]
},
{
type: "text",
text: "描述这个视频的具体过程"
}
]}]
});
console.log(JSON.stringify(response));
}
main();
工具调用 完整的 Function Call 流程代码请参考:Function Call(工具调用) 。 Python 请求示例
import os
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用百炼 API Key 将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # 填写 DashScope SDK 的 base_url
)
tools = [
# 工具 1 获取当前时刻的时间
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "当你想知道现在的时间时非常有用。",
"parameters": {} # 因为获取当前时间无需输入参数,因此 parameters 为空字典
}
},
# 工具 2 获取指定城市的天气
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "当你想查询指定城市的天气时非常有用。",
"parameters": {
"type": "object",
"properties": {
# 查询天气时需要提供位置,因此参数设置为 location
"location": {
"type": "string",
"description": "城市或县区,比如北京市、杭州市、余杭区等。"
}
},
"required": ["location"]
}
}
}
]
messages = [{"role": "user", "content": "杭州天气怎么样"}]
completion = client.chat.completions.create(
model="qwen-plus",
messages=messages,
tools=tools
)
print(completion.model_dump_json())
响应示例
{
"id": "chatcmpl-9894dd96-4cd9-9d10-9ad1-cd7d8ce7a579",
"choices": [
{
"finish_reason": "tool_calls",
"index": 0,
"logprobs": null,
"message": {
"content": "",
"role": "assistant",
"function_call": null,
"tool_calls": [
{
"id": "call_105fec8d4a954d89b280fe",
"function": {
"arguments": "{\"location\": \"杭州市\"}",
"name": "get_current_weather"
},
"type": "function",
"index": 0
}
]
}
}
],
"created": 1726048255,
"model": "qwen-plus",
"object": "chat.completion",
"service_tier": null,
"system_fingerprint": null,
"usage": {
"completion_tokens": 18,
"prompt_tokens": 224,
"total_tokens": 242
}
}
curl 请求示例
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": "杭州天气怎么样"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "当你想知道现在的时间时非常有用。",
"parameters": {}
}
},
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "当你想查询指定城市的天气时非常有用。",
"parameters": {
"type": "object",
"properties": {
"location":{
"type": "string",
"description": "城市或县区,比如北京市、杭州市、余杭区等。"
}
},
"required": ["location"]
}
}
}
]
}'
响应示例
{
"choices": [
{
"message": {
"content": "",
"role": "assistant",
"tool_calls": [
{
"function": {
"name": "get_current_weather",
"arguments": "{\"location\": \"杭州市\"}"
},
"index": 0,
"id": "call_b3b822e3aa6441369c42fc",
"type": "function"
}
]
},
"finish_reason": "tool_calls",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 224,
"completion_tokens": 18,
"total_tokens": 242
},
"created": 1726048351,
"system_fingerprint": null,
"model": "qwen-plus",
"id": "chatcmpl-c1417bcf-10db-9fd3-8af0-8f99a15a833f"
}
Node.js 请求示例
import OpenAI from "openai";
const openai = new OpenAI(
{
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
);
const messages = [{"role": "user", "content": "杭州天气怎么样"}];
const tools = [
// 工具 1 获取当前时刻的时间
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "当你想知道现在的时间时非常有用。",
// 因为获取当前时间无需输入参数,因此 parameters 为空
"parameters": {}
}
},
// 工具 2 获取指定城市的天气
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "当你想查询指定城市的天气时非常有用。",
"parameters": {
"type": "object",
"properties": {
// 查询天气时需要提供位置,因此参数设置为 location
"location": {
"type": "string",
"description": "城市或县区,比如北京市、杭州市、余杭区等。"
}
},
"required": ["location"]
}
}
}
];
async function main() {
const response = await openai.chat.completions.create({
model: "qwen-plus",
messages: messages,
tools: tools,
});
console.log(JSON.stringify(response));
}
main();
响应示例
{
"choices": [
{
"message": {
"content": "",
"role": "assistant",
"tool_calls": [
{
"function": {
"name": "get_current_weather",
"arguments": "{\"location\": \"杭州市\"}"
},
"index": 0,
"id": "call_75cb935df86f48929cb606",
"type": "function"
}
]
},
"finish_reason": "tool_calls",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 224,
"completion_tokens": 18,
"total_tokens": 242
},
"created": 1728455556,
"system_fingerprint": null,
"model": "qwen-plus",
"id": "chatcmpl-fee4749f-7c2a-9e16-a8cc-4111d89cf9f2"
}
联网搜索 Python import os
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用百炼 API Key 将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # 填写 DashScope 服务的 base_url
)
completion = client.chat.completions.create(
model="qwen-plus",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '中国队在巴黎奥运会获得了多少枚金牌'}],
extra_body={
"enable_search": True
}
)
print(completion.model_dump_json())
curl 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": "中国队在巴黎奥运会获得了多少枚金牌"
}
],
"enable_search": true
}'
Node.js import OpenAI from "openai";
const openai = new OpenAI(
{
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
);
async function main() {
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: "中国队在巴黎奥运会获得了多少枚金牌" }
],
enable_search:true
});
console.log(JSON.stringify(completion))
}
main();
异步调用 import os
import asyncio
from openai import AsyncOpenAI
import platform
client = AsyncOpenAI(
# 若没有配置环境变量,请用百炼 API Key 将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
async def main():
response = await client.chat.completions.create(
messages=[{"role": "user", "content": "你是谁"}],
model="qwen-plus",
)
print(response.model_dump_json())
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
文档理解 当前仅 qwen-long 模型支持对文档进行分析,详细用法请参考:长上下文 。 Python import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用百炼 API Key 将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
file_object = client.files.create(file=Path("百炼系列手机产品介绍.docx"), purpose="file-extract")
completion = client.chat.completions.create(
model="qwen-long",
messages=[
{'role': 'system', 'content': f'fileid://{file_object.id}'},
{'role': 'user', 'content': '这篇文章讲了什么?'}
]
)
print(completion.model_dump_json())
curl curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-long",
"input": {
"messages": [
{"role": "system","content": "fileid://file-fe-xxx"},
{"role": "user","content": "这篇文章讲了什么?"}
]
},
"parameters": {
"result_format": "message"
}
}'
Node.js import fs from "fs";
import OpenAI from "openai";
const openai = new OpenAI(
{
// 若没有配置环境变量,请用百炼 API Key 将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
);
async function getFileID() {
const fileObject = await openai.files.create({
file: fs.createReadStream("百炼系列手机产品介绍.docx"),
purpose: "file-extract"
});
return fileObject.id;
}
async function main() {
const fileID = await getFileID();
const completion = await openai.chat.completions.create({
model: "qwen-long", //模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
messages: [
{ role: "system", content: `fileid://${fileID}`},
{ role: "user", content: "这篇文章讲了什么?" }
],
});
console.log(JSON.stringify(completion))
}
main();