文档

通义千问API参考

更新时间:

本文介绍通义千问API的输入输出参数。

模型介绍、选型建议和使用方法请参考文本生成。也可以查看特定模型的用法:长上下文(Qwen-Long)、视觉理解(通义千问VL)、音频理解(通义千问Audio)、数学模型代码模型

您可以通过OpenAI 兼容或DashScope的方式调用通义千问API。

OpenAI 兼容

公有云

使用SDK调用时需配置的base_url:https://dashscope.aliyuncs.com/compatible-mode/v1

使用HTTP方式调用时需配置的endpoint:POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions

金融云

使用SDK调用时需配置的base_url:https://dashscope-finance.aliyuncs.com/compatible-mode/v1

使用HTTP方式调用时需配置的endpoint:POST https://dashscope-finance.aliyuncs.com/compatible-mode/v1/chat/completions

您需要已获取API Key配置API Key到环境变量。如果通过OpenAI SDK进行调用,还需要安装SDK

请求体

文本输入

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())

响应示例

{
  "id": "chatcmpl-0da38de9-5d2b-916d-9c6a-7af95993e275",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "我是通义千问,由阿里云开发的AI助手。我被设计用来回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?",
        "role": "assistant",
        "function_call": null,
        "tool_calls": null
      }
    }
  ],
  "created": 1721044114,
  "model": "qwen-plus",
  "object": "chat.completion",
  "service_tier": null,
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 36,
    "prompt_tokens": 22,
    "total_tokens": 58
  }
}

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 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))

响应示例

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "我是来自阿里云的超大规模语言模型,我叫通义千问。"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 22,
        "completion_tokens": 17,
        "total_tokens": 39
    },
    "created": 1728455191,
    "system_fingerprint": null,
    "model": "qwen-plus",
    "id": "chatcmpl-3a8c00cc-9c9f-9aba-b2d9-dc431e27d1b5"
}

HTTP

请求示例

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
// 设置请求的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;
?>
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}";
            }
        }
    }
}
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)
}

响应示例

{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "我是通义千问,由阿里云开发的AI助手。我被设计用来回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?"
      },
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null
    }
  ],
  "object": "chat.completion",
  "usage": {
    "prompt_tokens": 22,
    "completion_tokens": 36,
    "total_tokens": 58
  },
  "created": 1721044596,
  "system_fingerprint": null,
  "model": "qwen-plus",
  "id": "chatcmpl-94149c5a-137f-9b87-b2c8-61235e85f540"
}

流式输出

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"
    }
);

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));
}

响应示例

{"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())

响应示例

{
  "id": "chatcmpl-9b2665ca-4d9c-9799-9675-e2947ccc2c3e",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "图中是一名女子和她的狗在沙滩上互动。狗狗坐在地上,伸出爪子像是要握手或者击掌的样子。这名女士穿着格子衬衫,似乎正在与狗狗进行亲密的接触,并且面带微笑。背景是海洋和日出或日落时分的天空。这是一张充满温馨感的照片,展现了人与宠物之间的友谊时刻。",
        "refusal": null,
        "role": "assistant",
        "function_call": null,
        "tool_calls": null
      }
    }
  ],
  "created": 1724920555,
  "model": "qwen-vl-plus",
  "object": "chat.completion",
  "service_tier": null,
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 79,
    "prompt_tokens": 1276,
    "total_tokens": 1355
  }
}

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"}}]
    }]
}'

响应示例

{
    "choices": [
        {
            "message": {
                "content": "这张图片显示了一位女士和一只狗在海滩上互动。她们似乎正在享受彼此的陪伴,狗狗坐在沙滩上伸出爪子与这位女士握手或玩耍。\n\n背景中可以看到海浪拍打着海岸线,并且有日落时分柔和光线照射下的天空。这给人一种宁静而温馨的感觉,可能是在傍晚或者清晨的时候拍摄的照片。这种场景通常象征着友谊、爱以及人与宠物之间的深厚情感连接。",
                "role": "assistant"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 1275,
        "completion_tokens": 92,
        "total_tokens": 1367
    },
    "created": 1728458088,
    "system_fingerprint": null,
    "model": "qwen-vl-plus",
    "id": "chatcmpl-5b471a38-02a4-92b0-a076-45378c986aea"
}

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 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));

响应示例

{
    "choices": [
        {
            "message": {
                "content": "这是一张在海滩上拍摄的照片。照片中,一位穿着格子衬衫的女性坐在沙滩上,与一只戴着项圈的黄色拉布拉多犬互动。背景是大海和天空,阳光洒在她们身上,营造出温暖的氛围。",
                "role": "assistant"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 1271,
        "completion_tokens": 55,
        "total_tokens": 1326
    },
    "created": 1728455324,
    "system_fingerprint": null,
    "model": "qwen-vl-max",
    "id": "chatcmpl-2c878e62-613c-9acd-a0e3-bb77cce98960"
}

视频输入

关于大模型分析视频的更多用法,请参考:视觉理解

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())

响应示例

{
    "id": "chatcmpl-2be1f4f7-84c8-9dcc-9dab-d4608c5781ad",
    "choices": [{
        "finish_reason": "stop",
        "index": 0,
        "logprobs": null,
        "message": {
            "content": "这个视频展示了一场足球比赛的瞬间。具体过程如下:\n\n1. **背景**:视频是在一个大型体育场内拍摄的,观众席上坐满了观众,灯光明亮,气氛热烈。\n2. **球员**:场上有两队球员,一队穿着红色球衣,另一队穿着蓝色球衣。守门员穿着绿色球衣。\n3. **动作**:一名穿着红色球衣的球员在禁区内接到传球,准备射门。守门员迅速反应,向球的方向扑去,试图阻止进球。\n4. **射门**:红色球衣的球员成功将球踢向球门,球飞向球门的右上角。\n5. **进球**:守门员虽然尽力扑救,但未能阻止球进入球门。球击中了球门的右上角,守门员倒在地上,球网被球击中,显示出进球的瞬间。\n\n整个过程充满了紧张和激动,展示了足球比赛中的精彩瞬间。",
            "refusal": null,
            "role": "assistant",
            "function_call": null,
            "tool_calls": null
        }
    }],
    "created": 1728717102,
    "model": "qwen-vl-max-latest",
    "object": "chat.completion",
    "service_tier": null,
    "system_fingerprint": null,
    "usage": {
        "completion_tokens": 210,
        "prompt_tokens": 1466,
        "total_tokens": 1676
    }
}

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": "描述这个视频的具体过程"
                }
            ]
        }
    ]
}'

响应示例

{
    "choices": [
        {
            "message": {
                "content": "这个视频展示了一场足球比赛的瞬间。具体过程如下:\n\n1. **背景**:视频是在一个大型体育场内拍摄的,观众席上坐满了观众,灯光明亮,气氛热烈。\n2. **球员**:场上有两队球员,一队穿着红色球衣,另一队穿着蓝色球衣。守门员穿着绿色球衣。\n3. **动作**:一名穿着红色球衣的球员在禁区内准备射门。守门员试图扑救,但未能成功。\n4. **进球**:红色球衣的球员成功将球踢入球门,球网被球击中,显示出进球的瞬间。\n\n整个过程充满了紧张和激动,展示了足球比赛中的精彩瞬间。",
                "role": "assistant"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 1466,
        "completion_tokens": 152,
        "total_tokens": 1618
    },
    "created": 1728723529,
    "system_fingerprint": null,
    "model": "qwen-vl-max-latest",
    "id": "chatcmpl-74b07727-7c7a-9e73-b5d9-2868cd3d4d7a"
}

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();

响应示例

{
    "choices": [
        {
            "message": {
                "content": "这个视频展示了一场足球比赛的瞬间。具体过程如下:\n\n1. **背景**:视频是在一个大型体育场内拍摄的,观众席上坐满了观众,灯光明亮,气氛热烈。\n2. **球员**:场上有两队球员,一队穿着红色球衣,另一队穿着蓝色球衣。守门员穿着绿色球衣。\n3. **动作**:一名身穿红色球衣的球员在禁区内准备射门。他将球踢向球门。\n4. **守门员**:守门员看到球飞来,迅速做出反应,向球的方向扑去,试图将球扑出。\n5. **进球**:尽管守门员尽力扑救,但球还是飞进了球门,网子被球撞得晃动。\n\n这个视频捕捉到了足球比赛中进球的精彩瞬间,展示了球员的技巧和守门员的反应。",
                "role": "assistant"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 1466,
        "completion_tokens": 189,
        "total_tokens": 1655
    },
    "created": 1728723569,
    "system_fingerprint": null,
    "model": "qwen-vl-max-latest",
    "id": "chatcmpl-d96b4000-5b7d-98e4-8be8-01d4ea3c6109"
}

工具调用

完整的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"]
        }
    }
}
];

const response = await openai.chat.completions.create({
    model: "qwen-plus",
    messages: messages,
    tools: tools,
});

console.log(JSON.stringify(response));

响应示例

{
    "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())

响应示例

{
    "id": "chatcmpl-96ab11c8-4a9d-9bcf-a96c-8c604174f708",
    "choices": [
        {
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null,
            "message": {
                "content": "中国队在2024年巴黎奥运会中获得了40枚金牌,这个成绩让中国队与美国队并列金牌榜的第一位。此外,中国体育代表团还获得了27枚银牌和24枚铜牌。这一成就不仅追平了美国队的金牌数,还创造了中国参加境外奥运会所获得金牌数最多的纪录。",
                "refusal": null,
                "role": "assistant",
                "function_call": null,
                "tool_calls": null
            }
        }
    ],
    "created": 1728456238,
    "model": "qwen-plus",
    "object": "chat.completion",
    "service_tier": null,
    "system_fingerprint": null,
    "usage": {
        "completion_tokens": 74,
        "prompt_tokens": 542,
        "total_tokens": 616
    }
}

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
}'

响应示例

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "中国队在2024巴黎奥运会获得了40枚金牌。这个成绩帮助中国代表队创造了自1984年全面参加夏季奥运会以来,在境外参赛的历史最佳战绩。同时,这一金牌数目也与美国队持平,并且超过了2012年伦敦奥运会时中国队所获得的39枚金牌的成绩,创下了中国队参加境外奥运会金牌数目的最高纪录。"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 1109,
        "completion_tokens": 82,
        "total_tokens": 1191
    },
    "created": 1728456382,
    "system_fingerprint": null,
    "model": "qwen-plus",
    "id": "chatcmpl-3f8f873d-b8b0-9f5c-9464-ef1b550d7285"
}

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 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))

响应示例

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "中国队在2024年巴黎奥运会中获得了40枚金牌。这个成绩帮助中国体育代表团创造了在境外参加奥运会所获得金牌数最多的纪录。除此之外,中国运动员们还赢得了27枚银牌和24枚铜牌。"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 707,
        "completion_tokens": 53,
        "total_tokens": 760
    },
    "created": 1728458480,
    "system_fingerprint": null,
    "model": "qwen-plus",
    "id": "chatcmpl-f1c5534e-2ff9-9bf7-9ad2-5b0ca7ae1fcc"
}

异步调用

请求示例

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())

响应示例

{
    "id": "chatcmpl-e517181d-5b98-9c23-b57e-e6de5178bd4a",
    "choices": [
        {
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null,
            "message": {
                "content": "我是来自阿里云的超大规模语言模型,我叫通义千问。",
                "refusal": null,
                "role": "assistant",
                "function_call": null,
                "tool_calls": null
            }
        }
    ],
    "created": 1726124351,
    "model": "qwen-plus",
    "object": "chat.completion",
    "service_tier": null,
    "system_fingerprint": null,
    "usage": {
        "completion_tokens": 17,
        "prompt_tokens": 10,
        "total_tokens": 27
    }
}

文档理解

当前仅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())

响应示例

{
    "id": "chatcmpl-e4f7345c-e4b6-9a1e-babe-783a9adf7ea8",
    "choices": [
        {
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null,
            "message": {
                "content": "这篇文章介绍了多个型号的百炼系列手机产品,包括百炼X1、通义Vivid 7、星尘S9 Pro、百炼Ace Ultra、百炼Zephyr Z9以及百炼Flex Fold+,详细描述了各款手机的特点、配置和售价等信息。",
                "refusal": null,
                "role": "assistant",
                "function_call": null,
                "tool_calls": null
            }
        }
    ],
    "created": 1728388101,
    "model": "qwen-long",
    "object": "chat.completion",
    "service_tier": null,
    "system_fingerprint": null,
    "usage": {
        "completion_tokens": 63,
        "prompt_tokens": 5395,
        "total_tokens": 5458
    }
}

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"
    }
}'

响应示例

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "这篇文章是关于百炼系列手机的产品介绍,涵盖了六款不同的手机型号:百炼X1、通义Vivid 7、星尘S9 Pro、百炼Ace Ultra、百炼Zephyr Z9以及百炼Flex Fold+。文中详细描述了每款手机的主要特点和规格,例如屏幕尺寸与分辨率、内存与存储容量、电池大小、相机功能以及其他特色功能,并提供了各款手机的参考售价范围。"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 5490,
        "output_tokens": 95,
        "input_tokens": 5395
    },
    "request_id": "45326bfa-e2cd-9f4f-8b3b-730faf7fd3e7"
}

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"
    }
);
const file_object = await openai.files.create({
    file: fs.createReadStream("百炼系列手机产品介绍.docx"),
    purpose: "file-extract"
});

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://${file_object.id}`},
        { role: "user", content: "这篇文章讲了什么?" }
    ],
});
console.log(JSON.stringify(completion))

响应示例

{
    "choices": [
        {
            "message": {
                "content": "这篇文章介绍了百炼系列的六款手机产品,包括百炼X1、通义Vivid 7、星尘S9 Pro、百炼Ace Ultra、百炼Zephyr Z9以及百炼Flex Fold+。文中详细描述了各款手机的特点、配置及售价信息。这些手机分别针对不同的用户需求,如极致视觉体验、智能摄影、高性能游戏、轻薄便携以及创新折叠屏设计等,旨在为用户提供多样化的选择,以满足他们对科技生活的追求。",
                "role": "assistant"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 5395,
        "completion_tokens": 108,
        "total_tokens": 5503
    },
    "created": 1728457650,
    "system_fingerprint": null,
    "model": "qwen-long",
    "id": "chatcmpl-ae5f726b-ffe0-9d46-b5a7-9c01028975d9"
}

model string (必选)

模型名称。

支持的模型:通义千问大语言模型(商业版、开源版、Qwen-Long)、通义千问VL、数学模型、代码模型

通义千问Audio暂不支持OpenAI兼容模式,仅支持DashScope方式。

具体模型名称计费,请参见模型列表

messages array (必选)

由历史对话组成的消息列表。

消息类型

System Message object (可选)

用于指定模型的目标或角色。如果设置系统消息,请放在messages列表的第一位。

属性

content string (必选)

消息内容。

role string (必选)

固定为system

User Message object (必选)

用户发送给模型的消息。

属性

content string 或 array (必选)

消息内容。如果您的输入只有文本,则为string类型;如果您的输入包含图像等多模态数据,则为array类型。

如需传入音频给通义千问Audio模型,请前往DashScope查看,暂不支持使用OpenAI兼容的方式。

属性

type string (必选)

有三个可取值:textimage_urlvideotext表示用户的输入文本;image_url表示用户的输入图像信息;video表示用户的输入视频信息。

text string (必选)

表示用户的输入文本。

image_url string (必选)

表示用户的输入图像信息。可以为图片的URL或本地路径信息。传入本地文件请参考使用本地文件

video array (必选)

表示用户的输入视频信息。您可以通过图片列表传入,暂时只支持通过URL形式传入图片。

如果您需要直接输入视频文件,请提交工单进行申请以及获取使用方式。

role string (必选)

固定为user

Assistant Message object (可选)

模型对用户消息的回复。

属性

content string (可选)

消息内容。仅当助手消息中指定tool_calls参数时非必选。

role string (必选)

固定为assistant

partial boolean (可选)

用于控制是否开启Partial mode。关于Partial mode的使用方法,请参考Partial mode

当前仅支持qwen coder系列模型。

tool_calls array (可选)

模型回复的要调用的工具和调用工具时需要的参数。包含一个或多个对象。由上一轮模型响应的tool_calls字段获得。

属性

id string

本次工具响应的ID。

type string

工具的类型,当前只支持function

function object

需要被调用的函数。

属性

name string

需要被调用的函数名。

arguments string

需要输入到工具中的参数,为JSON字符串。

index integer

工具信息在tool_calls列表中的索引。

Tool Message object (可选)

工具的输出信息。详细说明:Function Call(调用外部工具)

属性

content string (必选)

消息内容,一般为工具函数的输出。

role string (必选)

固定为tool

stream boolean (可选)

是否流式输出回复。参数值:

  • false(默认值):模型生成完所有内容后一次性返回结果。

  • true:边生成边输出,即每生成一部分内容就立即输出一个片段(chunk)。您需要实时地逐个读取这些片段以获得完整的结果。

stream_options object (可选)

当启用流式输出时,可通过将本参数设置为{"include_usage": true},在输出的最后一行显示所使用的Token数。

如果设置为false,则最后一行不显示使用的Token数。

本参数仅在设置stream为true下生效。

temperature float (可选)

采样温度,用于控制模型生成文本的多样性。

temperature越高,生成的文本更多样,反之,生成的文本更确定。

取值范围: [0, 2)

由于temperature与top_p均可以控制生成文本的多样性,因此建议您只设置其中一个值。更多说明,请参见temperature和top_p

top_p float (可选)

核采样的概率阈值,用于控制模型生成文本的多样性。

top_p越高,生成的文本更多样。反之,生成的文本更确定。

取值范围:(0,1.0]

由于temperature与top_p均可以控制生成文本的多样性,因此建议您只设置其中一个值。更多说明,请参见temperature和top_p

presence_penalty float (可选)

控制模型生成文本时的内容重复度。

取值范围:[-2.0, 2.0]。正数会减少重复度,负数会增加重复度。

适用场景:

较高的presence_penalty适用于要求多样性、趣味性或创造性的场景,如创意写作或头脑风暴。

较低的presence_penalty适用于要求一致性或专业术语的场景,如技术文档或其他正式文档。

原理介绍

如果参数值是正数,模型将对目前文本中已存在的Token施加一个惩罚值(惩罚值与文本出现的次数无关),减少这些Token重复出现的几率,从而减少内容重复度,增加用词多样性。

示例

提示词:把这句话翻译成中文“This movie is good. The plot is good, the acting is good, the music is good, and overall, the whole movie is just good. It is really good, in fact. The plot is so good, and the acting is so good, and the music is so good.”

参数值为2.0:这部电影很好。剧情很棒,演技棒,音乐也非常好听,总的来说,整部电影都好得不得了。实际上它真的很优秀。剧情非常精彩,演技出色,音乐也是那么的动听。

参数值为0.0:这部电影很好。剧情好,演技好,音乐也好,总的来说,整部电影都很好。事实上,它真的很棒。剧情非常好,演技也非常出色,音乐也同样优秀。

参数值为-2.0:这部电影很好。情节很好,演技很好,音乐也很好,总的来说,整部电影都很好。实际上,它真的很棒。情节非常好,演技也非常好,音乐也非常好。

response_format object (可选) 默认值为{"type": "text"}

用于指定返回内容的格式。可选值:{"type": "text"}{"type": "json_object"}。设置为{"type": "json_object"}时会输出标准格式的JSON字符串。

支持qwen-max-0919、qwen-max-latest、qwen-plus、qwen-plus-0919、qwen-plus-latest、qwen-turbo-0919、qwen-turbo-latest以及qwen2.5系列模型(不包含math与coder模型)。

max_tokens integer (可选)

允许模型生成的最大Token数。

默认值和最大值都是模型的最大输出长度。关于各模型的最大输出长度,请参见模型列表

max_tokens参数适用于需要限制字数(如生成摘要、关键词)、控制成本或减少响应时间的场景。

seed integer (可选)

设置seed参数会使文本生成过程更具有确定性,通常用于使模型每次运行的结果一致。

在每次模型调用时传入相同的seed值(由您指定),并保持其他参数不变,模型将很可能返回相同的结果。

取值范围:无符号64位整数,即0到264−1。

stop string 或 array (可选)

使用stop参数后,当模型生成的文本即将包含指定的字符串或token_id时,将自动停止生成。

您可以在stop参数中传入敏感词来控制模型的输出。

stop为array类型时,不可以将token_id和字符串同时作为元素输入,比如不可以指定stop为["你好",104307]

tools array (可选)

用于指定可供模型调用的工具数组,可以包含一个或多个工具对象。一次function call流程模型会从中选择一个工具。

目前不支持通义千问VL/Audio,也不建议用于数学和代码模型。建议您使用qwen-max或qwen-plus模型。

属性

type string (必选)

表示tools的类型,当前仅支持function。

function object (必选)

属性

name string (必选)

类型为string,表示工具函数的名称,必须是字母、数字,可以包含下划线和短划线,最大长度为64。

description string (必选)

表示工具函数的描述,供模型选择何时以及如何调用工具函数。

parameters object (必选)

表示工具的参数描述,需要是一个合法的JSON Schema。JSON Schema的描述可以见链接。如果parameters参数为空,表示function没有入参。

enable_search boolean (可选)

用于控制模型在生成文本时是否使用互联网搜索结果进行参考。取值如下:

  • true:启用互联网搜索,模型会将搜索结果作为文本生成过程中的参考信息,但模型会基于其内部逻辑判断是否使用互联网搜索结果。

    如果模型没有搜索互联网,建议优化Prompt。
  • false(默认):关闭互联网搜索。

启用互联网搜索功能可能会增加Token消耗。
若您通过SDK调用,请通过extra_body配置。配置方式为:extra_body: {"enable_search": true}
qwen-vl系列、qwen开源系列与qwen-long模型暂时不支持配置该参数。

chat响应对象(非流式输出)

{
  "id": "chatcmpl-0da38de9-5d2b-916d-9c6a-7af95993e275",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "我是通义千问,由阿里云开发的AI助手。我被设计用来回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?",
        "role": "assistant",
        "function_call": null,
        "tool_calls": null
      }
    }
  ],
  "created": 1721044114,
  "model": "qwen-plus",
  "object": "chat.completion",
  "service_tier": null,
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 36,
    "prompt_tokens": 22,
    "total_tokens": 58
  }
}

id string

本次调用的唯一标识符。

choices array

模型生成内容的数组,可以包含一个或多个choices对象。

属性

finish_reason string

有三种情况:

  • 因触发输入参数中的stop条件,或自然停止输出时为stop

  • 因生成长度过长而结束为length

  • 因需要调用工具而结束为tool_calls

index integer

choices列表中的序列编号。

message object

本次调用模型输出的消息。

属性

content string

本次调用模型生成的文本。

role string

消息的角色,固定为assistant

tool_calls array

模型回复的要调用的工具以及调用工具所需的参数。可以包含一个或多个工具响应对象。

属性

id string

本次工具响应的ID。

type string

工具的类型,当前只支持function

function object

需要被调用的函数。

属性

name string

需要被调用的函数名。

arguments string

需要输入到工具中的参数,为JSON字符串。

由于大模型响应有一定随机性,输出的JSON字符串并不总满足于您的函数,建议您在将参数输入函数前进行参数的有效性校验。

index integer

工具信息在tool_calls列表中对应的索引。

function_call(即将废弃)object

该值默认为null,请参考tool_calls参数。

created string

本次chat请求被创建时的时间戳。

model string

本次chat请求使用的模型名称。

object string

始终为chat.completion

usage object

本次chat请求使用的Token信息。

属性

prompt_tokens integer

用户的输入转换成Token后的长度。

completion_tokens integer

模型生成回复转换为Token后的长度。

total_tokens integer

prompt_tokenscompletion_tokens的总和。

chat响应chunk对象(流式输出)

{"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-turbo","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-turbo","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-turbo","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-turbo","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-turbo","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-turbo","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-turbo","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-turbo","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}}

id string

本次调用的唯一标识符。每个chunk对象有相同的id。

choices array

模型生成内容的数组,可包含一个或多个choices对象。如果设置include_usage参数为true,则最后一个chunk为空。

属性

delta object

chat请求的增量对象。

属性

content string

chunk的消息内容。

tools_calls array

属性

index integer

工具信息在tool_calls列表中对应的索引。

id string

本次工具响应的ID。

function object

需要被调用的函数。

属性

arguments string

需要输入到工具中的参数,所有chunk的arguments拼接后为完整的JSON字符串。

由于大模型响应有一定随机性,输出的JSON字符串并不总满足于您的函数,建议您在将参数输入函数前进行参数的有效性校验。

name string

函数名称,只在第一个chunk中有值。

type string

工具的类型,当前只支持function

function_call object

该值默认为null,请参考tool_calls参数。

role string

增量消息对象的角色,只在第一个chunk中有值。

finish_reason string

有四种情况:

  • 因触发输入参数中的stop条件,或自然停止输出时为stop

  • 当生成未结束时为null

  • 因生成长度过长而结束为length

  • 因需要调用工具而结束为tool_calls

index integer

choices列表中的序列编号。

created string

本次chat请求被创建时的时间戳。每个chunk对象有相同的时间戳。

model string

本次chat请求使用的模型名称。

object string

始终为chat.completion.chunk

usage object

本次chat请求使用的Token信息。只在include_usagetrue时,在最后一个chunk显示。

属性

prompt_tokens integer

用户的输入转换成Token后的长度。

completion_tokens integer

模型生成回复转换为Token后的长度。

total_tokens integer

prompt_tokenscompletion_tokens的总和。

DashScope

公有云

通过HTTP调用时需配置的endpoint:

使用通义千问大语言模型:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation

使用通义千问VL或通义千问Audio模型:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

金融云

通过HTTP调用时需配置的endpoint:

使用通义千问大语言模型:POST https://dashscope-finance.aliyuncs.com/api/v1/services/aigc/text-generation/generation

使用通义千问VL或通义千问Audio模型:POST https://dashscope-finance.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

您需要已获取API Key配置API Key到环境变量。如果通过DashScope SDK进行调用,还需要DashScope SDK

请求体

文本输入

Python

请求示例

import os
import dashscope

messages = [
    {'role': 'system', 'content': 'You are a helpful assistant.'},
    {'role': 'user', 'content': '你是谁?'}
    ]
response = dashscope.Generation.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=messages,
    result_format='message'
    )
print(response)

响应示例

{
  "status_code": 200,
  "request_id": "902fee3b-f7f0-9a8c-96a1-6b4ea25af114",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "我是阿里云开发的一款超大规模语言模型,我叫通义千问。"
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 22,
    "output_tokens": 17,
    "total_tokens": 39
  }
}

Java

请求示例

// 建议dashscope SDK的版本 >= 2.12.0
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;

public class Main {
    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")
                .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("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }
}

响应示例

{
  "requestId": "86dd52a9-23ec-9804-8f82-85f4c7fd5114",
  "usage": {
    "input_tokens": 22,
    "output_tokens": 17,
    "total_tokens": 39
  },
  "output": {
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "我是阿里云开发的一款超大规模语言模型,我叫通义千问。"
        }
      }
    ]
  }
}

curl

请求示例

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": "我是通义千问,由阿里云开发的AI助手。我被设计用来回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?"
        }
      }
    ]
  },
  "usage": {
    "total_tokens": 58,
    "output_tokens": 36,
    "input_tokens": 22
  },
  "request_id": "39377fd7-26dd-99f5-b539-5fd004b6ecb5"
}

流式输出

Python

请求示例

import os
import dashscope

messages = [
    {'role':'system','content':'you are a helpful assistant'},
    {'role': 'user','content': '你是谁?'}
    ]
responses = dashscope.Generation.call(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-plus",
    messages=messages,
    result_format='message',
    stream=True,
    incremental_output=True
    )
for response in responses:
    print(response)
    

响应示例

{"status_code": 200, "request_id": "xxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "我是"}}]}, "usage": {"input_tokens": 21, "output_tokens": 1, "total_tokens": 22}}
{"status_code": 200, "request_id": "xxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "通"}}]}, "usage": {"input_tokens": 21, "output_tokens": 2, "total_tokens": 23}}
{"status_code": 200, "request_id": "xxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "义"}}]}, "usage": {"input_tokens": 21, "output_tokens": 3, "total_tokens": 24}}
{"status_code": 200, "request_id": "xxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "千问,由阿里"}}]}, "usage": {"input_tokens": 21, "output_tokens": 8, "total_tokens": 29}}
{"status_code": 200, "request_id": "xxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "云开发的AI助手。我被"}}]}, "usage": {"input_tokens": 21, "output_tokens": 16, "total_tokens": 37}}
{"status_code": 200, "request_id": "xxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "设计用来回答各种问题、提供信息"}}]}, "usage": {"input_tokens": 21, "output_tokens": 24, "total_tokens": 45}}
{"status_code": 200, "request_id": "xxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "和与用户进行对话。有什么我可以"}}]}, "usage": {"input_tokens": 21, "output_tokens": 32, "total_tokens": 53}}
{"status_code": 200, "request_id": "xxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "stop", "message": {"role": "assistant", "content": "帮助你的吗?"}}]}, "usage": {"input_tokens": 21, "output_tokens": 36, "total_tokens": 57}}

Java

请求示例

import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 io.reactivex.Flowable;
import java.lang.System;

public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    private static void handleGenerationResult(GenerationResult message) {
        System.out.println(JsonUtils.toJson(message));
    }
    public static void streamCallWithMessage(Generation gen, Message userMsg)
            throws NoApiKeyException, ApiException, InputRequiredException {
        GenerationParam param = buildGenerationParam(userMsg);
        Flowable<GenerationResult> result = gen.streamCall(param);
        result.blockingForEach(message -> handleGenerationResult(message));
    }
    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.builder()
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-plus")
                .messages(Arrays.asList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)
                .build();
    }
    public static void main(String[] args) {
        try {
            Generation gen = new Generation();
            Message userMsg = Message.builder().role(Role.USER.getValue()).content("你是谁?").build();
            streamCallWithMessage(gen, userMsg);
        } catch (ApiException | NoApiKeyException | InputRequiredException  e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}

响应示例

{"requestId":"xxx","usage":{"input_tokens":11,"output_tokens":1,"total_tokens":12},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":"我是"}}]}}
{"requestId":"xxx","usage":{"input_tokens":11,"output_tokens":2,"total_tokens":13},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":"通"}}]}}
{"requestId":"xxx","usage":{"input_tokens":11,"output_tokens":3,"total_tokens":14},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":"义"}}]}}
{"requestId":"xxx","usage":{"input_tokens":11,"output_tokens":8,"total_tokens":19},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":"千问,由阿里"}}]}}
{"requestId":"xxx","usage":{"input_tokens":11,"output_tokens":16,"total_tokens":27},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":"云开发的AI助手。我被"}}]}}
{"requestId":"xxx","usage":{"input_tokens":11,"output_tokens":24,"total_tokens":35},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":"设计用来回答各种问题、提供信息"}}]}}
{"requestId":"xxx","usage":{"input_tokens":11,"output_tokens":32,"total_tokens":43},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":"和与用户进行对话。有什么我可以"}}]}}
{"requestId":"xxx","usage":{"input_tokens":11,"output_tokens":36,"total_tokens":47},"output":{"choices":[{"finish_reason":"stop","message":{"role":"assistant","content":"帮助你的吗?"}}]}}

curl

请求示例

curl --location "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--header "X-DashScope-SSE: enable" \
--data '{
    "model": "qwen-plus",
    "input":{
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "你是谁?"
            }
        ]
    },
    "parameters": {
        "result_format": "message",
        "incremental_output":true
    }
}'

响应示例

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"我是","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":23,"input_tokens":22,"output_tokens":1},"request_id":"xxx"}

id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"通","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":24,"input_tokens":22,"output_tokens":2},"request_id":"xxx"}

id:3
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"义","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":25,"input_tokens":22,"output_tokens":3},"request_id":"xxx"}

id:4
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"千问,由阿里","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":30,"input_tokens":22,"output_tokens":8},"request_id":"xxx"}

id:5
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"云开发的AI助手。我被","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":38,"input_tokens":22,"output_tokens":16},"request_id":"xxx"}

id:6
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"设计用来回答各种问题、提供信息","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":46,"input_tokens":22,"output_tokens":24},"request_id":"xxx"}

id:7
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"和与用户进行对话。有什么我可以","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":54,"input_tokens":22,"output_tokens":32},"request_id":"xxx"}

id:8
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"帮助你的吗?","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":58,"input_tokens":22,"output_tokens":36},"request_id":"xxx"}

图像输入

关于大模型分析图像的更多用法,请参考:视觉理解

Python

请求示例

import os
import dashscope

messages = [
    {
        "role": "user",
        "content": [
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"},
            {"text": "这些是什么?"}
        ]
    }
]
response = dashscope.MultiModalConversation.call(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen-vl-max',
    messages=messages
    )
print(response)

响应示例

{
    "status_code": 200,
    "request_id": "3a031529-707f-9b7d-968c-172e7533debc",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "text": "图1中是一名女子和狗在沙滩上玩耍。\n图2是孟加拉虎的插画,它正向镜头走来。\n图3里是一只可爱的小白兔。"
                        }
                    ]
                }
            }
        ]
    },
    "usage": {
        "input_tokens": 3743,
        "output_tokens": 41,
        "image_tokens": 3697
    }
}

Java

请求示例

// Copyright (c) Alibaba, Inc. and its affiliates.

import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"),
                        Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"),
                        Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"),
                        Collections.singletonMap("text", "这些是什么?"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-plus")
                .message(userMessage)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

响应示例

{
  "requestId": "dcb38a0f-fd69-9071-bcde-c4530f9a7559",
  "usage": {
    "input_tokens": 3740,
    "output_tokens": 48
  },
  "output": {
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": [
            {
              "text": "图1中是一名女子和一只大金毛在沙滩上玩耍。\n图2是孟加拉虎的写实照片,老虎正向镜头走来。\n图3是一幅插画,主要展示了一只兔子。"
            }
          ]
        }
      }
    ]
  }
}

curl

请求示例

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen-vl-plus",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"},
                    {"text": "这些是什么?"}
                ]
            }
        ]
    }
}'

响应示例

{
  "output": {
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": [
            {
              "text": "图1中是一名女子和一只大金毛在沙滩上玩耍。\n图2是孟加拉虎的写实照片,老虎正向镜头走来。\n图3是一幅插画,主要展示了一只兔子。"
            }
          ]
        }
      }
    ]
  },
  "usage": {
    "output_tokens": 48,
    "input_tokens": 3740,
    "image_tokens": 3697
  },
  "request_id": "eb6204ea-4cba-91b1-95ab-e7836b7355d6"
}

视频输入

关于大模型分析视频的更多用法,请参考:视觉理解

Python

请求示例

from http import HTTPStatus
import os
# dashscope版本需要不低于1.20.10
import dashscope

messages = [{"role": "user",
             "content": [
                 {"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"]},
                 {"text": "描述这个视频的具体过程"}]}]
response = dashscope.MultiModalConversation.call(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model='qwen-vl-max-latest',
    messages=messages
)
if response.status_code == HTTPStatus.OK:
    print(response)
else:
    print(response.code)
    print(response.message)

响应示例

{
  "status_code": 200,
  "request_id": "957b3e07-6ed4-9a6c-9edb-b7672e941ef8",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": [
            {
              "text": "这个视频展示了一场足球比赛的瞬间。具体过程如下:\n\n1. **背景**:视频是在一个大型体育场拍摄的,观众席上坐满了观众,灯光明亮,气氛热烈。\n2. **球员**:场上有两队球员,一队穿着红色球衣,另一队穿着蓝色球衣。守门员穿着绿色球衣。\n3. **动作**:一名身穿红色球衣的球员在禁区内接到传球,准备射门。守门员迅速反应,向球的方向扑去,试图阻止进球。\n4. **射门**:红色球衣的球员成功将球踢向球门,球飞向守门员的右侧。\n5. **进球**:守门员虽然尽力扑救,但球还是从他的右侧飞入球门,进球成功。\n\n整个过程展示了足球比赛中的紧张和精彩瞬间,尤其是射门和守门员的扑救动作。"
            }
          ]
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 1466,
    "output_tokens": 194,
    "video_tokens": 1440
  }
}

Java

请求示例

// DashScope SDK版本需要不低于2.16.7
import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
    private static final String MODEL_NAME = "qwen-vl-max-latest";
    public static void videoImageListSample() throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage systemMessage = MultiModalMessage.builder()
                .role(Role.SYSTEM.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant.")))
                .build();
        MultiModalMessage userMessage = MultiModalMessage.builder()
                .role(Role.USER.getValue())
                .content(Arrays.asList(Collections.singletonMap("video", Arrays.asList("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")),
                        Collections.singletonMap("text", "描述这个视频的具体过程")))
                .build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .model(MODEL_NAME).message(systemMessage)
                .message(userMessage).build();
        MultiModalConversationResult result = conv.call(param);
        System.out.print(JsonUtils.toJson(result));
    }
    public static void main(String[] args) {
        try {
            videoImageListSample();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

响应示例

{
    "requestId": "73f712e8-500c-9875-be22-056e11376a27",
    "usage": {
        "input_tokens": 1466,
        "output_tokens": 198
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "text": "这个视频展示了一场足球比赛的瞬间。具体过程如下:\n\n1. **背景**:视频是在一个大型体育场拍摄的,观众席上坐满了观众,灯光明亮,气氛热烈。\n2. **球员**:场上有两队球员,一队穿着红色球衣,另一队穿着蓝色球衣。守门员穿着绿色球衣。\n3. **动作**:一名穿着红色球衣的球员在禁区内准备射门。他用右脚踢出一个低平球,球向球门飞去。\n4. **守门员**:守门员看到球飞来,迅速做出反应,向球的方向扑去,试图用双手将球扑出。\n5. **结果**:守门员没有成功扑到球,球飞入球门,进球得分。\n\n整个过程展示了足球比赛中的一个精彩瞬间,包括球员的射门、守门员的扑救以及进球的瞬间。"
                        }
                    ]
                }
            }
        ]
    }
}

curl

请求示例

curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-vl-max-latest",
  "input": {
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "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"
            ]
          },
          {
            "text": "描述这个视频的具体过程"
          }
        ]
      }
    ]
  }
}'

响应示例

{
    "output": {
        "choices": [{
            "finish_reason": "stop",
            "message": {
                "role": "assistant",
                "content": [{
                    "text": "这个视频展示了一场足球比赛的瞬间。具体过程如下:\n\n1. **背景**:比赛在一个大型体育场进行,观众席上坐满了观众,灯光明亮,气氛热烈。\n2. **球员**:场上有两支队伍,一支穿着红色球衣,另一支穿着蓝色球衣。守门员穿着绿色球衣。\n3. **动作**:一名身穿红色球衣的球员在禁区内接到传球,准备射门。守门员迅速反应,向球的方向扑去,试图阻止进球。\n4. **射门**:红色球衣的球员果断射门,球飞向球门。\n5. **扑救**:守门员尽力扑救,但球还是飞进了球门,球网被球撞得晃动。\n\n整个过程充满了紧张和刺激,展示了足球比赛中的精彩瞬间。"
                }]
            }
        }]
    },
    "usage": {
        "output_tokens": 178,
        "video_tokens": 1440,
        "input_tokens": 1466
    },
    "request_id": "65eeb762-c11a-9124-a5fb-8f9e382ebc15"
}

音频输入

关于大模型分析音频的更多用法,请参考:音频理解

Python

请求示例

import os
import dashscope

messages = [
    {
        "role": "user",
        "content": [
            {"audio": "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"},
            {"text": "这段音频在说什么?"}
        ]
    }
]
response = dashscope.MultiModalConversation.call(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen2-audio-instruct',
    messages=messages
    )
print(response)

响应示例

{
  "status_code": 200,
  "request_id": "cd6a86c7-ff55-9f3c-a379-d434e5af8079",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": [
            {
              "text": "这段音频说的是:'欢迎使用阿里云'"
            }
          ]
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 33,
    "output_tokens": 10,
    "audio_tokens": 85
  }
}

Java

请求示例

import java.util.Arrays;
import java.util.Collections;
import java.lang.System;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(Collections.singletonMap("audio", "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"),
                        Collections.singletonMap("text", "这段音频在说什么?"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen2-audio-instruct")
                .message(userMessage)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

响应示例

{
  "requestId": "e701e39b-4dfa-9dde-805a-f83782b3394a",
  "usage": {
    "input_tokens": 33,
    "output_tokens": 10
  },
  "output": {
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": [
            {
              "text": "这段音频说的是:'欢迎使用阿里云'"
            }
          ]
        }
      }
    ]
  }
}

curl

请求示例

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen2-audio-instruct",
    "input":{
        "messages":[
            {
                "role": "system",
                "content": [
                    {"text": "You are a helpful assistant."}
                ]
            },
            {
                "role": "user",
                "content": [
                    {"audio": "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"},
                    {"text": "这段音频在说什么?"}
                ]
            }
        ]
    }
}'

响应示例

{
  "output": {
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": [
            {
              "text": "这段音频说的是:'欢迎使用阿里云'"
            }
          ]
        }
      }
    ]
  },
  "usage": {
    "audio_tokens": 85,
    "output_tokens": 10,
    "input_tokens": 33
  },
  "request_id": "db617e5b-d706-9143-b011-8b0f05fe8fa3"
}

联网搜索

Python

请求示例

import os
import dashscope

messages = [
    {'role': 'system', 'content': 'You are a helpful assistant.'},
    {'role': 'user', 'content': '杭州明天天气是什么?'}
    ]
response = dashscope.Generation.call(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-plus",
    messages=messages,
    enable_search=True,
    result_format='message'
    )
print(response)

响应示例

{
    "status_code": 200,
    "request_id": "c264df1f-0ef3-9323-a55b-83adc5ee48e6",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "根据提供的信息,杭州明天的天气预报如下:\n\n- 明天白天天气晴朗,东风,风力4级。\n- 明天夜间天气多云,东北风,风力4级。\n\n请注意,这是一则历史预报信息,具体实际天气可能会有所变化。建议您在出行前再次查看最新的天气预报以获取最准确的信息。"
                }
            }
        ]
    },
    "usage": {
        "input_tokens": 885,
        "output_tokens": 76,
        "plugins": {
            "search": {
                "count": 1
            }
        },
        "total_tokens": 961
    }
}

Java

请求示例

// 建议dashscope SDK的版本 >= 2.12.0
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;

public class Main {
    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")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .enableSearch(true)
                .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("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }
}

响应示例

{
    "requestId": "4e0a961c-77bc-92a3-a65c-b1319fedc6bf",
    "usage": {
        "input_tokens": 901,
        "output_tokens": 73,
        "total_tokens": 974
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "明天,即2024年9月14日,杭州的天气预报显示为多云,有东北风,风力预计为4级。最低温度预计为26摄氏度,最高温度预计为32摄氏度。请注意,天气预报可能会有所变动,建议在出行前再次查看最新的天气预报信息。"
                }
            }
        ]
    }
}

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-plus",
    "input":{
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "明天杭州天气如何?"
            }
        ]
    },
    "parameters": {
        "enable_search": true,
        "result_format": "message"
    }
}'

响应示例

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "根据提供的信息,明天即2024年9月14日,杭州的天气预报显示如下:\n\n- 夜间天气:多云\n- 白天天气:多云\n- 风向:东北风\n- 风力:4级\n- 湿度:80%\n- 最低温度:26.0摄氏度\n- 最高温度:32.0摄氏度\n\n请注意,天气预报可能会有变化,建议在出行前再次查看最新的天气预报信息。"
                }
            }
        ]
    },
    "usage": {
        "plugins": {
            "search": {
                "count": 1
            }
        },
        "total_tokens": 1029,
        "output_tokens": 114,
        "input_tokens": 915
    },
    "request_id": "2e840007-683a-93c1-bd2d-84003ee6346e"
}

工具调用

完整的Function Call流程代码请参考:Function Call(调用外部工具)

Python

请求示例

import os
import dashscope

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"
            ]
        }
    }
]
messages = [{"role": "user", "content": "杭州天气怎么样"}]
response = dashscope.Generation.call(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen-plus',
    messages=messages,
    tools=tools,
    result_format='message'
)
print(response)

响应示例

{
  "status_code": 200,
  "request_id": "28d9b918-6287-95d1-9876-a67a9257c0c6",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "tool_calls",
        "message": {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "function": {
                "name": "get_current_weather",
                "arguments": "{\"location\": \"杭州市\"}"
              },
              "index": 0,
              "id": "call_e63b80aab9df4950b391d0",
              "type": "function"
            }
          ]
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 218,
    "output_tokens": 18,
    "total_tokens": 236
  }
}

Java

请求示例

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.aigc.conversation.ConversationParam.ResultFormat;
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.tools.FunctionDefinition;
import com.alibaba.dashscope.tools.ToolFunction;
import com.alibaba.dashscope.utils.JsonUtils;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public class GetWeatherTool {
        private String location;
        public GetWeatherTool(String location) {
            this.location = location;
        }
        public String call() {
            return location+"今天是晴天";
        }
    }
    public class GetTimeTool {
        public GetTimeTool() {
        }
        public String call() {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String currentTime = "当前时间:" + now.format(formatter) + "。";
            return currentTime;
        }
    }
    public static void SelectTool()
            throws NoApiKeyException, ApiException, InputRequiredException {
        SchemaGeneratorConfigBuilder configBuilder =
                new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON);
        SchemaGeneratorConfig config = configBuilder.with(Option.EXTRA_OPEN_API_FORMAT_VALUES)
                .without(Option.FLATTENED_ENUMS_FROM_TOSTRING).build();
        SchemaGenerator generator = new SchemaGenerator(config);
        ObjectNode jsonSchema_weather = generator.generateSchema(GetWeatherTool.class);
        ObjectNode jsonSchema_time = generator.generateSchema(GetTimeTool.class);
        FunctionDefinition fdWeather = FunctionDefinition.builder().name("get_current_weather").description("获取指定地区的天气")
                .parameters(JsonUtils.parseString(jsonSchema_weather.toString()).getAsJsonObject()).build();
        FunctionDefinition fdTime = FunctionDefinition.builder().name("get_current_time").description("获取当前时刻的时间")
                .parameters(JsonUtils.parseString(jsonSchema_time.toString()).getAsJsonObject()).build();
        Message systemMsg = Message.builder().role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant. When asked a question, use tools wherever possible.")
                .build();
        Message userMsg = Message.builder().role(Role.USER.getValue()).content("杭州天气").build();
        List<Message> messages = new ArrayList<>();
        messages.addAll(Arrays.asList(systemMsg, userMsg));
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-plus")
                .messages(messages)
                .resultFormat(ResultFormat.MESSAGE)
                .tools(Arrays.asList(
                        ToolFunction.builder().function(fdWeather).build(),
                        ToolFunction.builder().function(fdTime).build()))
                .build();
        Generation gen = new Generation();
        GenerationResult result = gen.call(param);
        System.out.println(JsonUtils.toJson(result));
    }
    public static void main(String[] args) {
        try {
            SelectTool();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(String.format("Exception %s", e.getMessage()));
        }
        System.exit(0);
    }
}

响应示例

{
  "requestId": "4d81dc3d-6570-9e33-9e7d-199b20bf568f",
  "usage": {
    "input_tokens": 245,
    "output_tokens": 18,
    "total_tokens": 263
  },
  "output": {
    "choices": [
      {
        "finish_reason": "tool_calls",
        "message": {
          "role": "assistant",
          "content": "",
          "tool_calls": [
            {
              "type": "function",
              "id": "call_26a878c36995449195e7f6",
              "function": {
                "name": "get_current_weather",
                "arguments": "{\"location\": \"杭州\"}"
              }
            }
          ]
        }
      }
    ]
  }
}

curl

请求示例

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": "user",
            "content": "杭州天气怎么样"
        }]
    },
    "parameters": {
        "result_format": "message",
        "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"]
            }
        }]
    }
}'

响应示例

{
  "output": {
    "choices": [
      {
        "finish_reason": "tool_calls",
        "message": {
          "role": "assistant",
          "tool_calls": [
            {
              "function": {
                "name": "get_current_weather",
                "arguments": "{\"location\": \"杭州市\"}"
              },
              "index": 0,
              "id": "call_aaab400803844cfc9fd6bd",
              "type": "function"
            }
          ],
          "content": ""
        }
      }
    ]
  },
  "usage": {
    "total_tokens": 236,
    "output_tokens": 18,
    "input_tokens": 218
  },
  "request_id": "10bdb494-05ee-9c45-9b38-bb544b5cb23e"
}

异步调用

请求示例

# 您的Dashscope Python SDK版本需要不低于 1.19.0。
import asyncio
import platform
import os
from dashscope.aigc.generation import AioGeneration

async def main():
    response = await AioGeneration.call(
        # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
        api_key=os.getenv('DASHSCOPE_API_KEY'),
        model="qwen-plus",
        messages=[{"role": "user", "content": "你是谁"}],
        result_format="message",
    )
    print(response)

if platform.system() == "Windows":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())

响应示例

{
    "status_code": 200,
    "request_id": "124ca191-68a5-90b8-84bd-5ef944883a94",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "我是阿里云开发的一款超大规模语言模型,我叫通义千问。作为一个语言模型,我的目标是生成与给定词语相关的高质量文本,帮助用户获得准确、有用的信息,解决他们的问题和困惑。无论是工作上的需求,如撰写邮件、制作报告、代码编写,还是生活中的问题,如情感交流、日常生活建议,亦或是学习上的辅助,如历史知识、地理信息、数学计算等,我都会尽我所能提供帮助。请随时向我提问或寻求帮助,我会尽力满足您的需求。"
                }
            }
        ]
    },
    "usage": {
        "input_tokens": 10,
        "output_tokens": 114,
        "total_tokens": 124
    }
}

model string (必选)

模型名称。

支持的模型:通义千问大语言模型(商业版、开源版、Qwen-Long)、通义千问VL、通义千问Audio、数学模型、代码模型

具体模型名称计费,请参见模型列表

messages array (必选)

由历史对话组成的消息列表。

通过HTTP调用时,请将messages 放入 input 对象中。

消息类型

System Message object

用于指定模型的目标或角色。如果设置系统消息,请放在messages列表的第一位。

属性

content string (必选)

消息内容。

role string (必选)

固定为system

User Message object

用户发送给模型的消息。

属性

content string 或 array (必选)

用户消息的内容。使用qwen 大语言模型时为string,使用qwen-vl或qwen-audio系列模型时为array。

属性

text string

传入的文本信息。

image string

使用图片理解功能时,传入的图片文件。

video array

使用视频理解功能时,传入的视频文件。您可以通过图片列表传入,暂时只支持通过URL形式传入图片。

如果您需要直接输入视频文件,请提交工单进行申请以及获取使用方式。

audio string

使用音频理解功能时,传入的音频文件。

role string (必选)

用户消息的角色,固定为user

Assistant Message object

模型对用户消息的回复。

属性

content string (必选)

助手消息的内容。

role string (必选)

助手消息的角色,固定为assistant

partial boolean (可选)

用于控制是否开启Partial mode。关于Partial mode的使用方法,请参考Partial mode

当前仅支持qwen coder系列模型。

Tool Message object

工具的输出信息。详细说明:Function Call(调用外部工具)

属性

content string (必选)

工具消息的内容,一般为工具函数的输出。

role string (必选)

工具消息的角色,固定为tool

temperature float (可选)

采样温度,用于控制模型生成文本的多样性。

temperature越高,生成的文本更多样,反之,生成的文本更确定。

取值范围: [0, 2)

通过HTTP调用时,请将 temperature 放入 parameters 对象中。

top_p float (可选)

核采样的概率阈值,用于控制模型生成文本的多样性。

top_p越高,生成的文本更多样。反之,生成的文本更确定。

取值范围:(0,1.0]。

Java SDK中为topP通过HTTP调用时,请将 top_p 放入 parameters 对象中。

top_k integer (可选)

生成过程中采样候选集的大小。例如,取值为50时,仅将单次生成中得分最高的50个Token组成随机采样的候选集。取值越大,生成的随机性越高;取值越小,生成的确定性越高。取值为None或当top_k大于100时,表示不启用top_k策略,此时仅有top_p策略生效。

Java SDK中为topK通过HTTP调用时,请将 top_k 放入 parameters 对象中。

repetition_penalty float (可选)

用于控制模型生成时连续序列中的重复度。提高repetition_penalty时可以降低模型生成的重复度,1.0表示不做惩罚。没有严格的取值范围,只要大于0即可。

Java SDK中为repetitionPenalty通过HTTP调用时,请将 repetition_penalty 放入 parameters 对象中。

vl_high_resolution_images boolean (可选)默认值为 false

用于控制是否提高输入图片的默认Token上限,只适用于qwen-vl-maxqwen-vl-max-0809qwen-vl-plus-0809模型。输入图片的默认Token上限为1280,配置为true时输入图片的Token上限为16384。

Java SDK不支持设置该参数通过HTTP调用时,请将 presence_penalty 放入 parameters 对象中。

presence_penalty float (可选)

控制模型生成文本时的内容重复度。

取值范围:[-2.0, 2.0]。正数会减少重复度,负数会增加重复度。

适用场景:

较高的presence_penalty适用于要求多样性、趣味性或创造性的场景,如创意写作或头脑风暴。

较低的presence_penalty适用于要求一致性或专业术语的场景,如技术文档或其他正式文档。

原理介绍

如果参数值是正数,模型将对目前文本中已存在的Token施加一个惩罚值(惩罚值与文本出现的次数无关),减少这些Token重复出现的几率,从而减少内容重复度,增加用词多样性。

示例

提示词:把这句话翻译成中文“This movie is good. The plot is good, the acting is good, the music is good, and overall, the whole movie is just good. It is really good, in fact. The plot is so good, and the acting is so good, and the music is so good.”

参数值为2.0:这部电影很好。剧情很棒,演技棒,音乐也非常好听,总的来说,整部电影都好得不得了。实际上它真的很优秀。剧情非常精彩,演技出色,音乐也是那么的动听。

参数值为0.0:这部电影很好。剧情好,演技好,音乐也好,总的来说,整部电影都很好。事实上,它真的很棒。剧情非常好,演技也非常出色,音乐也同样优秀。

参数值为-2.0:这部电影很好。情节很好,演技很好,音乐也很好,总的来说,整部电影都很好。实际上,它真的很棒。情节非常好,演技也非常好,音乐也非常好。

Java SDK不支持设置该参数通过HTTP调用时,请将 presence_penalty 放入 parameters 对象中。

max_tokens integer (可选)

允许模型生成的最大Token数。

默认值和最大值都是模型的最大输出长度。关于各模型的最大输出长度,请参见模型列表

max_tokens参数适用于需要限制字数(如生成摘要、关键词)、控制成本或减少响应时间的场景。

Java SDK中为maxTokens通过HTTP调用时,请将 max_tokens 放入 parameters 对象中。

seed integer (可选)

设置seed参数会使文本生成过程更具有确定性,通常用于使模型每次运行的结果一致。

在每次模型调用时传入相同的seed值(由您指定),并保持其他参数不变,模型将很可能返回相同的结果。

取值范围:无符号64位整数,即0到264−1。

通过HTTP调用时,请将 seed 放入 parameters 对象中。

stream boolean (可选)

是否流式输出回复。参数值:

  • false(默认值):模型生成完所有内容后一次性返回结果。

  • true:边生成边输出,即每生成一部分内容就立即输出一个片段(chunk)。

该参数仅支持Python SDK。通过Java SDK实现流式输出请通过streamCall接口调用;通过HTTP实现流式输出请在Header中指定X-DashScope-SSEenable

incremental_output boolean (可选)默认为false

在流式输出模式下是否开启增量输出。参数值:

  • false:每次输出为当前已经生成的整个序列,最后一次输出为生成的完整结果。

    I
    I like
    I like apple
    I like apple.
  • true:增量输出,即后续输出内容不包含已输出的内容。您需要实时地逐个读取这些片段以获得完整的结果。

    I
    like
    apple
    .
Java SDK中为incrementalOutput通过HTTP调用时,请将 incremental_output 放入 parameters 对象中。

result_format string (可选)

用于指定返回结果的格式,默认为text,也可选择message。推荐您优先使用message格式。

Java SDK中为resultFormat通过HTTP调用时,请将 result_format 放入 parameters 对象中。

stop string 或 array (可选)

使用stop参数后,当模型生成的文本即将包含指定的字符串或token_id时,将自动停止生成。

您可以在stop参数中传入敏感词来控制模型的输出。

stop为array类型时,不可以将token_id和字符串同时作为元素输入,比如不可以指定stop为["你好",104307]

tools array (可选)

用于指定可供模型调用的工具数组,可以包含一个或多个工具对象。一次function call流程模型会从中选择其中一个工具。使用tools时需要同时指定result_format参数为message。在function call流程中,无论是发起function call,还是向模型提交工具函数的执行结果,均需设置tools参数。

目前不支持通义千问VL/Audio,也不建议用于数学和代码模型。建议您使用qwen-max或qwen-plus模型。

属性

type string (必选)

表示tools的类型,当前仅支持function。

function object (必选)

属性

name string (必选)

类型为string,表示工具函数的名称,必须是字母、数字,可以包含下划线和短划线,最大长度为64。

description string (必选)

表示工具函数的描述,供模型选择何时以及如何调用工具函数。

parameters objcet (必选)

表示工具的参数描述,需要是一个合法的JSON Schema。JSON Schema的描述可以见链接。如果parameters参数为空,表示function没有入参。

通过HTTP调用时,请将 tools 放入 parameters JSON 对象中。暂时不支持qwen-vl与qwen-audio系列模型。

tool_choice string 或 object (可选)

在使用tools参数时,用于控制模型调用指定工具。有三种取值:

  • "none"表示不调用工具。tools参数为空时,默认值为"none"

  • "auto"表示由模型判断是否调用工具,可能调用也可能不调用。tools参数不为空时,默认值为"auto"

  • object结构可以指定模型调用的工具。例如tool_choice={"type": "function", "function": {"name": "user_function"}}

    • type只支持指定为"function"

    • function

      • name表示期望被调用的工具名称,例如"get_current_time"

Java SDK中为toolChoice通过HTTP调用时,请将 tool_choice 放入 parameters 对象中。

enable_search boolean (可选)

用于控制模型在生成文本时是否使用互联网搜索结果进行参考。取值如下:

  • true:启用互联网搜索,模型会将搜索结果作为文本生成过程中的参考信息,但模型会基于其内部逻辑判断是否使用互联网搜索结果。

    如果模型没有搜索互联网,建议优化Prompt。
  • false(默认):关闭互联网搜索。

若您的业务场景中需要使用互联网搜索能力,请配置该参数为true。

Java SDK中为enableSearch通过HTTP调用时,请将 enable_search 放入 parameters 对象中。
由于启用互联网搜索功能可能会增加token消耗,因此若您无需互联网搜索能力,不建议配置该参数。
qwen-vl系列、qwen-audio系列、qwen开源系列与qwen-long模型暂时不支持配置该参数。

chat响应对象(流式与非流式输出格式一致)

{
  "status_code": 200,
  "request_id": "902fee3b-f7f0-9a8c-96a1-6b4ea25af114",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "我是阿里云开发的一款超大规模语言模型,我叫通义千问。"
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 22,
    "output_tokens": 17,
    "total_tokens": 39
  }
}

status_code string

本次请求的状态码。200 表示请求成功,否则表示请求失败。

Java SDK不会返回该参数。调用失败会抛出异常,异常信息为status_codemessage的内容。

request_id string

本次调用的唯一标识符。

Java SDK返回参数为requestId。

code string

表示错误码,调用成功时为空值。

只有Python SDK返回该参数。

output object

表示调用结果信息。

属性

text string

模型生成的回复。当设置输入参数result_formattext时将回复内容返回到该字段。

finish_reason string

当设置输入参数result_formattext时该参数不为空。

有四种情况:

  • 正在生成时为null;

  • 因模型输出自然结束,或触发输入参数中的stop条件而结束时为stop;

  • 因生成长度过长而结束为length;

  • 因发生工具调用为tool_calls。

choices array

模型的输出信息。当result_format为message时返回choices参数。

属性

finish_reason string

有四种情况:

  • 正在生成时为null;

  • 因模型输出自然结束,或触发输入参数中的stop条件而结束时为stop;

  • 因生成长度过长而结束为length;

  • 因发生工具调用为tool_calls。

message object

模型输出的消息对象。

属性

role string

输出消息的角色,固定为assistant。

content string

输出消息的内容。

如果发起function call,则该值为空。

tool_calls array

如果模型需要调用工具,则会生成tool_calls参数。

属性

function objcet

调用工具的名称,以及输入参数。

属性

name string

调用工具的名称

arguments string

需要输入到工具中的参数,为JSON字符串。

由于大模型响应有一定随机性,输出的JSON字符串并不总满足于您的函数,建议您在将参数输入函数前进行参数的有效性校验。

index integer

当前tool_calls对象在tool_calls数组中的索引。

id string

本次工具响应的ID。

type string

工具类型,固定为function

usage object

本次chat请求使用的token信息。

属性

input_tokens integer

用户输入内容转换成token后的长度。

output_tokens integer

chat请求返回内容转换成token后的长度。

total_tokens integer

当输入为纯文本时返回该字段,为input_tokensoutput_tokens之和

image_tokens integer

输入内容包含image时返回该字段。为用户输入图片内容转换成token后的长度。

video_tokens integer

输入内容包含video时返回该字段。为用户输入视频内容转换成token后的长度。

audio_tokens integer

输入内容包含audio时返回该字段。为用户输入音频内容转换成token后的长度。

错误码

如果模型调用失败并返回报错信息,请参见错误码进行解决。