文档

使用通义千问

更新时间:

通义千问模型具有强大的自然语言处理能力,您可以通过API接口调用通义千问模型,将通义千问模型集成到您的业务中。

前提条件

  • 请您参考API-KEY的获取与配置,开通DashScope并获得API-KEY。

  • 请在模型概览中选择您需要使用的模型。

  • 您可以使用OpenAI SDK、DashScope SDK或HTTP接口调用通义千问模型,请您根据您的需求,参考以下方式准备您的计算环境。

    说明

    如果您之前使用OpenAI SDK以及HTTP方式调用OpenAI的服务,只需在原有框架下调整API-KEY、base_url、model等参数,就可以直接调用通义千问模型。

    调用方式

    准备条件

    通过OpenAI Python SDK调用

    您可以通过以下命令安装或更新OpenAI SDK:

    # 如果下述命令报错,请将pip替换为pip3
    pip install -U openai

    您需要配置的base_url如下:

    https://dashscope.aliyuncs.com/compatible-mode/v1

    通过OpenAI兼容-HTTP调用

    如果您需要通过OpenAI兼容的HTTP方式进行调用,需要配置的完整访问endpoint如下:

    POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions

    通过DashScope SDK调用

    DashScope SDK提供了Python和Java两个版本,请参考安装SDK,安装最新版SDK。

    通过DashScope HTTP调用

    如果您需要通过DashScope的HTTP方式进行调用,需要配置的完整访问endpoint如下:

    POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation

说明

我们推荐您将API-KEY配置到环境变量中以降低API-KEY的泄漏风险,详情可参考通过环境变量设置API-KEY。您也可以在代码中配置API-KEY,但是会存在泄露风险。

场景示例

单轮对话

您可以将通义千问应用在内容创作、翻译服务、文本摘要等多种场景。您可以参考以下示例代码,通过OpenAI或者DashScope的方式体验通义千问模型的单轮对话能力。

OpenAI兼容

您可以通过OpenAI SDK或OpenAI兼容的HTTP方式调用通义千问模型,体验单轮对话的功能。

Python

示例代码

from openai import OpenAI
import os

def get_response():
    client = OpenAI(
        api_key=os.getenv("DASHSCOPE_API_KEY"), # 如果您没有配置环境变量,请在此处用您的API Key进行替换
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填写DashScope服务的base_url
    )
    completion = client.chat.completions.create(
        model="qwen-turbo",
        messages=[
            {'role': 'system', 'content': 'You are a helpful assistant.'},
            {'role': 'user', 'content': '你是谁?'}],
        temperature=0.8,
        top_p=0.8
        )
    print(completion.model_dump_json())

if __name__ == '__main__':
    get_response()

返回结果

{
  "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-turbo",
  "object": "chat.completion",
  "service_tier": null,
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 36,
    "prompt_tokens": 22,
    "total_tokens": 58
  }
}

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-turbo",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user", 
            "content": "你是谁?"
        }
    ]
}'

返回结果

{
  "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-turbo",
  "id": "chatcmpl-94149c5a-137f-9b87-b2c8-61235e85f540"
}

DashScope

您可以通过DashScope SDK或HTTP方式调用通义千问模型,体验单轮对话的功能。

Python

示例代码

import random
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.14.0
from dashscope import Generation


def call_with_messages():
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '你是谁?'}]
    response = Generation.call(model="qwen-turbo",
                               messages=messages,
                               # 设置随机数种子seed,如果没有设置,则随机数种子默认为1234
                               seed=random.randint(1, 10000),
                               temperature=0.8,
                               top_p=0.8,
                               top_k=50,
                               # 将输出设置为"message"格式
                               result_format='message')
    if response.status_code == HTTPStatus.OK:
        print(response)
    else:
        print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
            response.request_id, response.status_code,
            response.code, response.message
        ))


if __name__ == '__main__':
    call_with_messages()

返回结果

{
  "status_code": 200,
  "request_id": "82bb30e8-de5c-989e-9486-603221879b72",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "我是通义千问,由阿里云开发的AI助手。我被设计用来回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?"
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 22,
    "output_tokens": 36,
    "total_tokens": 58
  }
}

Java

示例代码

// Copyright (c) Alibaba, Inc. and its affiliates.
// 建议dashscope SDK的版本 >= 2.12.0
import java.util.Arrays;
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()
                .model("qwen-turbo")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topK(50)
                .temperature(0.8f)
                .topP(0.8)
                .seed(1234)
                .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) {
            // 使用日志框架记录异常信息
            // Logger.error("An error occurred while calling the generation service", e);
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }
}

返回结果

{
  "requestId": "4e9a8f25-0b75-9859-9de7-e122e6f15c5b",
  "usage": {
    "input_tokens": 22,
    "output_tokens": 16,
    "total_tokens": 38
  },
  "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-turbo",
    "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"
}

多轮对话

相比于单轮对话,多轮对话可以让大模型参考历史对话信息,更符合日常交流的场景。实现多轮对话的关键在于维护一个存放历史对话信息的列表,并将更新后的列表作为大模型的输入,从而使大模型可以参考历史对话信息进行回复。您可以参考以下示例代码,将每一轮的对话历史添加到messages列表中,实现多轮对话的功能。

说明

如果对话轮数较多,可能会超过大模型可以输入的token上限。您可以采用对话历史摘要固定窗口大小等方法,控制输入大模型的token数量。

OpenAI兼容

您可以通过OpenAI SDK或OpenAI兼容的HTTP方式调用通义千问模型,体验多轮对话的功能。

Python

示例代码

from openai import OpenAI
import os

def get_response(messages):
    client = OpenAI(
        # 如果您没有配置环境变量,请在此处用您的API Key进行替换
        api_key=os.getenv("DASHSCOPE_API_KEY"), 
        # 填写DashScope服务的base_url
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    completion = client.chat.completions.create(
        model="qwen-turbo",
        messages=messages,
        temperature=0.8,
        top_p=0.8
        )
    return completion

messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
# 您可以自定义设置对话轮数,当前为3
for i in range(3):
    user_input = input("请输入:")
    # 将用户问题信息添加到messages列表中
    messages.append({'role': 'user', 'content': user_input})
    assistant_output = get_response(messages).choices[0].message.content
    # 将大模型的回复信息添加到messages列表中
    messages.append({'role': 'assistant', 'content': assistant_output})
    print(f'用户输入:{user_input}')
    print(f'模型输出:{assistant_output}')
    print('\n')

返回结果

2024-04-08_18-58-36 (1).gif

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-turbo",
    "messages":[      
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "你好"
        },
        {
            "role": "assistant",
            "content": "你好啊,我是通义千问。"
        },
        {
            "role": "user",
            "content": "你有哪些技能?"
        }
    ],
    "seed":1234,
    "top_p":0.8,
    "temperature":0.8
}'

返回结果

{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "作为一个人工智能助手,我有多种技能,包括但不限于:\n\n1. **语言理解与生成**:能够理解和生成自然语言文本,进行对话交流。\n2. **信息检索**:帮助用户查找和提供相关的信息。\n3. **知识问答**:解答各类问题,涵盖各种主题领域。\n4. **翻译**:支持多种语言之间的翻译。\n5. **文本总结**:对长篇文章或段落进行概括。\n6. **写作辅助**:提供建议、修改句子结构等写作帮助。\n7. **情感分析**:识别和理解文本中的情感倾向。\n8. **代码解释和辅助**:对编程问题进行解答和指导。\n\n请告诉我你需要什么帮助,我会尽力提供支持。"
      },
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null
    }
  ],
  "object": "chat.completion",
  "usage": {
    "prompt_tokens": 43,
    "completion_tokens": 155,
    "total_tokens": 198
  },
  "created": 1721098376,
  "system_fingerprint": null,
  "model": "qwen-turbo",
  "id": "chatcmpl-eccf185f-ed9f-9476-a664-a97d9534b0d5"
}

DashScope

您可以通过DashScope SDK或HTTP方式调用通义千问模型,体验多轮对话的功能。

Python

示例代码

from dashscope import Generation

def get_response(messages):
    response = Generation.call(model="qwen-turbo",
                               messages=messages,
                               # 将输出设置为"message"格式
                               result_format='message')
    return response


messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]

# 您可以自定义设置对话轮数,当前为3
for i in range(3):
    user_input = input("请输入:")
    # 将用户问题信息添加到messages列表中
    messages.append({'role': 'user', 'content': user_input})
    assistant_output = get_response(messages).output.choices[0]['message']['content']
    # 将大模型的回复信息添加到messages列表中
    messages.append({'role': 'assistant', 'content': assistant_output})
    print(f'用户输入:{user_input}')
    print(f'模型输出:{assistant_output}')
    print('\n')

返回结果

2024-04-08_18-58-36 (1).gif

Java

示例代码

import java.util.ArrayList;
import java.util.List;
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 java.util.Scanner;

public class Main {

    public static GenerationParam createGenerationParam(List<Message> messages) {
        return GenerationParam.builder()
                .model("qwen-turbo")
                .messages(messages)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .build();
    }

    public static GenerationResult callGenerationWithMessages(GenerationParam param) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        return gen.call(param);
    }

    public static void main(String[] args) {
        try {
            List<Message> messages = new ArrayList<>();

            messages.add(createMessage(Role.SYSTEM, "You are a helpful assistant."));
            for (int i = 0; i < 3;i++) {
                Scanner scanner = new Scanner(System.in);
                System.out.print("请输入:");
                String userInput = scanner.nextLine();
                if ("exit".equalsIgnoreCase(userInput)) {
                    break;
                }
                messages.add(createMessage(Role.USER, userInput));
                GenerationParam param = createGenerationParam(messages);
                GenerationResult result = callGenerationWithMessages(param);
                System.out.println("模型输出:"+result.getOutput().getChoices().get(0).getMessage().getContent());
                messages.add(result.getOutput().getChoices().get(0).getMessage());
            }
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }

    private static Message createMessage(Role role, String content) {
        return Message.builder().role(role.getValue()).content(content).build();
    }
}

返回结果

2024-04-08_18-58-36 (1).gif

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-turbo",
    "input":{
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "你好"
            },
            {
                "role": "assistant",
                "content": "你好啊,我是通义千问。"
            },
            {
                "role": "user",
                "content": "你有哪些技能?"
            }
        ]
    },
    "parameters": {
        "result_format": "message",
        "top_p":0.8,
        "top_k": 50,
        "temperature":0.8
    }
}'

返回结果

{
  "output": {
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "作为一个人工智能助手,我有多种技能,包括但不限于:\n\n1. **语言理解与生成**:能够理解和生成自然语言文本,进行对话交流。\n2. **信息检索**:帮助用户查找和提供相关的信息。\n3. **知识问答**:解答各类问题,涵盖各种主题领域。\n4. **翻译**:支持多种语言之间的翻译。\n5. **文本总结**:对长篇文章或段落进行概括。\n6. **写作辅助**:提供建议、修改句子结构等写作帮助。\n7. **情感分析**:识别和解读文本中的情感色彩。\n8. **代码解释**:简单编程问题的解答。\n\n虽然我可以提供很多帮助,但请注意我不是万能的,对于一些专业领域的复杂问题可能无法给出准确答案。"
        }
      }
    ]
  },
  "usage": {
    "total_tokens": 208,
    "output_tokens": 165,
    "input_tokens": 43
  },
  "request_id": "e9d88c17-bb36-9273-b678-88915961ab6e"
}

流式输出

大模型并不是一次性生成最终结果,而是逐步地生成中间结果,最终结果由中间结果拼接而成。使用非流式输出方式需要等待模型生成结束后再将生成的中间结果拼接后返回,而流式输出可以实时地将中间结果返回,您可以在模型进行输出的同时进行阅读,减少等待模型回复的时间。

OpenAI兼容

您可以通过OpenAI SDK或OpenAI兼容的HTTP方式调用通义千问模型,体验流式输出的功能。

Python

示例代码

from openai import OpenAI
import os

def get_response():
    client = OpenAI(
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    completion = client.chat.completions.create(
        model="qwen-turbo",
        messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
                  {'role': 'user', 'content': '你是谁?'}],
        stream=True,
        # 可选,配置以后会在流式输出的最后一行展示token使用信息
        stream_options={"include_usage": True}
        )
    for chunk in completion:
        print(chunk.model_dump_json())

if __name__ == '__main__':
    get_response()

返回结果

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

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-turbo",
    "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":1721101135,"system_fingerprint":null,"model":"qwen-turbo","id":"chatcmpl-xxx"}

data: {"choices":[{"finish_reason":null,"delta":{"content":"我是"},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1721101135,"system_fingerprint":null,"model":"qwen-turbo","id":"chatcmpl-xxx"}

data: {"choices":[{"delta":{"content":"通"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1721101135,"system_fingerprint":null,"model":"qwen-turbo","id":"chatcmpl-xxx"}

data: {"choices":[{"delta":{"content":"义"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1721101135,"system_fingerprint":null,"model":"qwen-turbo","id":"chatcmpl-xxx"}

data: {"choices":[{"delta":{"content":"千问,由阿里"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1721101135,"system_fingerprint":null,"model":"qwen-turbo","id":"chatcmpl-xxx"}

data: {"choices":[{"delta":{"content":"云开发的AI助手。我被"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1721101135,"system_fingerprint":null,"model":"qwen-turbo","id":"chatcmpl-xxx"}

data: {"choices":[{"delta":{"content":"设计用来回答各种问题、提供信息"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1721101135,"system_fingerprint":null,"model":"qwen-turbo","id":"chatcmpl-xxx"}

data: {"choices":[{"delta":{"content":"和与用户进行对话。有什么我可以"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1721101135,"system_fingerprint":null,"model":"qwen-turbo","id":"chatcmpl-xxx"}

data: {"choices":[{"delta":{"content":"帮助你的吗?"},"finish_reason":"stop","index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1721101135,"system_fingerprint":null,"model":"qwen-turbo","id":"chatcmpl-xxx"}

data: [DONE]

DashScope

您可以通过DashScope SDK或HTTP方式调用通义千问模型,体验流式输出的功能。

Python

示例代码

from http import HTTPStatus
from dashscope import Generation


def call_with_stream():
    messages = [
        {'role':'system','content':'you are a helpful assistant'},
        {'role': 'user','content': '你是谁?'}
        ]
    responses = Generation.call(
        model="qwen-turbo",
        messages=messages,
        # 设置输出为'message'格式
        result_format='message',
        # 设置输出方式为流式输出
        stream=True,
        # 增量式流式输出
        incremental_output=True
        )
    full_content = ""
    for response in responses:
        if response.status_code == HTTPStatus.OK:
            print(response)
            full_content += response.output.choices[0].message.content
        else:
            print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
                response.request_id, response.status_code,
                response.code, response.message
            ))
    print(f"Full content:{full_content}")

if __name__ == '__main__':
    call_with_stream()

返回结果

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

示例代码

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

import java.util.Arrays;
import java.util.concurrent.Semaphore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Semaphore;
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.ResultCallback;
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;

public class Main {

    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    private static void handleGenerationResult(GenerationResult message, StringBuilder fullContent) {
        fullContent.append(message.getOutput().getChoices().get(0).getMessage().getContent());
        logger.info("Received message: {}", 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);
        StringBuilder fullContent = new StringBuilder();

        result.blockingForEach(message -> handleGenerationResult(message, fullContent));

        logger.info("Full content: \n{}", fullContent.toString());
    }

    public static void streamCallWithCallback(Generation gen, Message userMsg)
            throws NoApiKeyException, ApiException, InputRequiredException, InterruptedException {
        GenerationParam param = buildGenerationParam(userMsg);
        Semaphore semaphore = new Semaphore(0);
        StringBuilder fullContent = new StringBuilder();

        gen.streamCall(param, new ResultCallback<GenerationResult>() {
            @Override
            public void onEvent(GenerationResult message) {
                handleGenerationResult(message, fullContent);
            }

            @Override
            public void onError(Exception err) {
                logger.error("Exception occurred: {}", err.getMessage());
                semaphore.release();
            }

            @Override
            public void onComplete() {
                logger.info("Completed");
                semaphore.release();
            }
        });

        semaphore.acquire();
        logger.info("Full content: \n{}", fullContent.toString());
    }

    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.builder()
                .model("qwen-turbo")
                .messages(Arrays.asList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .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);
            streamCallWithCallback(gen, userMsg);
        } catch (ApiException | NoApiKeyException | InputRequiredException | InterruptedException e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
    }
}

返回结果

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

Function Call(调用外部工具)

大模型在面对实时性问题、私域知识型问题或数学计算等问题时可能效果不佳。您可以使用function call功能,通过调用外部工具来提升模型的输出效果。您可以在调用大模型时,通过tools参数传入工具的名称、描述、入参等信息。Function Call的工作流程示意图如下所示:

image

Function Call的使用涉及到参数解析功能,因此对大模型的响应质量要求较高,推荐您优先使用qwen-max模型。

说明

Function Call信息暂时不支持增量输出。

OpenAI兼容

您可以通过OpenAI SDK或OpenAI兼容的HTTP方式调用通义千问模型,体验Function Call的功能。

Python

示例代码

from openai import OpenAI
from datetime import datetime
import json
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"), # 如果您没有配置环境变量,请在此处用您的API Key进行替换
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填写DashScope SDK的base_url
)

# 定义工具列表,模型在选择使用哪个工具时会参考工具的name和description
tools = [
    # 工具1 获取当前时刻的时间
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "当你想知道现在的时间时非常有用。",
            "parameters": {}  # 因为获取当前时间无需输入参数,因此parameters为空字典
        }
    },  
    # 工具2 获取指定城市的天气
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {  # 查询天气时需要提供位置,因此参数设置为location
                        "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。"
                    }
                }
            },
            "required": [
                "location"
            ]
        }
    }
]

# 模拟天气查询工具。返回结果示例:“北京今天是晴天。”
def get_current_weather(location):
    return f"{location}今天是雨天。 "

# 查询当前时间的工具。返回结果示例:“当前时间:2024-04-15 17:15:18。“
def get_current_time():
    # 获取当前日期和时间
    current_datetime = datetime.now()
    # 格式化当前日期和时间
    formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
    # 返回格式化后的当前时间
    return f"当前时间:{formatted_time}。"

# 封装模型响应函数
def get_response(messages):
    completion = client.chat.completions.create(
        model="qwen-max",
        messages=messages,
        tools=tools
        )
    return completion.model_dump()

def call_with_messages():
    print('\n')
    messages = [
            {
                "content": input('请输入:'),  # 提问示例:"现在几点了?" "一个小时后几点" "北京天气如何?"
                "role": "user"
            }
    ]
    print("-"*60)
    # 模型的第一轮调用
    i = 1
    first_response = get_response(messages)
    assistant_output = first_response['choices'][0]['message']
    print(f"\n第{i}轮大模型输出信息:{first_response}\n")
    if  assistant_output['content'] is None:
        assistant_output['content'] = ""
    messages.append(assistant_output)
    # 如果不需要调用工具,则直接返回最终答案
    if assistant_output['tool_calls'] == None:  # 如果模型判断无需调用工具,则将assistant的回复直接打印出来,无需进行模型的第二轮调用
        print(f"无需调用工具,我可以直接回复:{assistant_output['content']}")
        return
    # 如果需要调用工具,则进行模型的多轮调用,直到模型判断无需调用工具
    while assistant_output['tool_calls'] != None:
        # 如果判断需要调用查询天气工具,则运行查询天气工具
        if assistant_output['tool_calls'][0]['function']['name'] == 'get_current_weather':
            tool_info = {"name": "get_current_weather", "role":"tool"}
            # 提取位置参数信息
            location = json.loads(assistant_output['tool_calls'][0]['function']['arguments'])['properties']['location']
            tool_info['content'] = get_current_weather(location)
        # 如果判断需要调用查询时间工具,则运行查询时间工具
        elif assistant_output['tool_calls'][0]['function']['name'] == 'get_current_time':
            tool_info = {"name": "get_current_time", "role":"tool"}
            tool_info['content'] = get_current_time()
        print(f"工具输出信息:{tool_info['content']}\n")
        print("-"*60)
        messages.append(tool_info)
        assistant_output = get_response(messages)['choices'][0]['message']
        if  assistant_output['content'] is None:
            assistant_output['content'] = ""
        messages.append(assistant_output)
        i += 1
        print(f"第{i}轮大模型输出信息:{assistant_output}\n")
    print(f"最终答案:{assistant_output['content']}")

if __name__ == '__main__':
    call_with_messages()

返回结果

当输入:几点了?时,程序会进行如下输出:

2024-07-25_15-37-20 (1)

以下是发起Function Call流程(模型的第一轮调用)时模型的返回信息。当输入“杭州天气”时,模型会返回tool_calls参数;当输入“你好”时,模型判断无需调用工具,模型不会返回tool_calls参数。

输入:杭州天气

{
  "id": "chatcmpl-77e89311-6192-980b-a3b2-041cc2825efa",
  "choices": [
    {
      "finish_reason": "tool_calls",
      "index": 0,
      "logprobs": None,
      "message": {
        "content": "",
        "role": "assistant",
        "function_call": None,
        "tool_calls": [
          {
            "id": "call_191a35e5b9a04cf9918163",
            "function": {
              "arguments": "{\"properties\": {\"location\": \"杭州市\"}}",
              "name": "get_current_weather"
            },
            "type": "function",
            "index": 0
          }
        ]
      }
    }
  ],
  "created": 1721893100,
  "model": "qwen-max",
  "object": "chat.completion",
  "service_tier": None,
  "system_fingerprint": None,
  "usage": {
    "completion_tokens": 21,
    "prompt_tokens": 222,
    "total_tokens": 243
  }
}

输入:你好

{
  "id": "chatcmpl-54d7a8df-75b9-9c42-8968-8da938b7d72c",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": None,
      "message": {
        "content": "你好!有什么可以帮助你的吗?",
        "role": "assistant",
        "function_call": None,
        "tool_calls": None
      }
    }
  ],
  "created": 1721893161,
  "model": "qwen-max",
  "object": "chat.completion",
  "service_tier": None,
  "system_fingerprint": None,
  "usage": {
    "completion_tokens": 7,
    "prompt_tokens": 221,
    "total_tokens": 228
  }
}

HTTP

示例代码

import requests
import os
from datetime import datetime
import json

# 定义工具列表,模型在选择使用哪个工具时会参考工具的name和description
tools = [
    # 工具1 获取当前时刻的时间
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "当你想知道现在的时间时非常有用。",
            "parameters": {}  # 因为获取当前时间无需输入参数,因此parameters为空字典
        }
    },  
    # 工具2 获取指定城市的天气
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {  # 查询天气时需要提供位置,因此参数设置为location
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。"
                    }
                }
            },
            "required": [
                "location"
            ]
        }
    }
]

# 模拟天气查询工具。返回结果示例:“北京今天是晴天。”
def get_current_weather(location):
    return f"{location}今天是晴天。 "

# 查询当前时间的工具。返回结果示例:“当前时间:2024-04-15 17:15:18。“
def get_current_time():
    # 获取当前日期和时间
    current_datetime = datetime.now()
    # 格式化当前日期和时间
    formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
    # 返回格式化后的当前时间
    return f"当前时间:{formatted_time}。"

def get_response(messages):
    api_key = os.getenv("DASHSCOPE_API_KEY")
    url = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'
    headers = {'Content-Type': 'application/json',
            'Authorization':f'Bearer {api_key}'}
    body = {
        'model': 'qwen-max',
        "messages": messages,
        "tools":tools
    }

    response = requests.post(url, headers=headers, json=body)
    return response.json()


def call_with_messages():
    messages = [
            {
                "content": input('请输入:'),  # 提问示例:"现在几点了?" "一个小时后几点" "北京天气如何?"
                "role": "user"
            }
    ]
    
    # 模型的第一轮调用
    first_response = get_response(messages)
    print(f"\n第一轮调用结果:{first_response}")
    assistant_output = first_response['choices'][0]['message']
    if  assistant_output['content'] is None:
        assistant_output['content'] = ""
    messages.append(assistant_output)
    if 'tool_calls' not in assistant_output:  # 如果模型判断无需调用工具,则将assistant的回复直接打印出来,无需进行模型的第二轮调用
        print(f"最终答案:{assistant_output['content']}")
        return
    # 如果模型选择的工具是get_current_weather
    elif assistant_output['tool_calls'][0]['function']['name'] == 'get_current_weather':
        tool_info = {"name": "get_current_weather", "role":"tool"}
        location = json.loads(assistant_output['tool_calls'][0]['function']['arguments'])['properties']['location']
        tool_info['content'] = get_current_weather(location)
    # 如果模型选择的工具是get_current_time
    elif assistant_output['tool_calls'][0]['function']['name'] == 'get_current_time':
        tool_info = {"name": "get_current_time", "role":"tool"}
        tool_info['content'] = get_current_time()
    print(f"工具输出信息:{tool_info['content']}")
    messages.append(tool_info)

    # 模型的第二轮调用,对工具的输出进行总结
    second_response = get_response(messages)
    print(f"第二轮调用结果:{second_response}")
    print(f"最终答案:{second_response['choices'][0]['message']['content']}")

if __name__ == '__main__':
    call_with_messages()

返回结果

当输入:杭州天气时,程序会进行如下输出:

2024-07-16_14-43-10 (1)

以下是发起Function Call流程(模型的第一轮调用)时模型的返回信息。当输入“杭州天气”时,模型会返回tool_calls参数;当输入“你好”时,模型判断无需调用工具,模型不会返回tool_calls参数。

DashScope

您可以通过DashScope SDK或HTTP方式调用通义千问模型,体验Function Call的功能。

Python

示例代码

from dashscope import Generation
from datetime import datetime
import random
import json


# 定义工具列表,模型在选择使用哪个工具时会参考工具的name和description
tools = [
    # 工具1 获取当前时刻的时间
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "当你想知道现在的时间时非常有用。",
            "parameters": {}  # 因为获取当前时间无需输入参数,因此parameters为空字典
        }
    },  
    # 工具2 获取指定城市的天气
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {  # 查询天气时需要提供位置,因此参数设置为location
                        "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。"
                    }
                }
            },
            "required": [
                "location"
            ]
        }
    }
]

# 模拟天气查询工具。返回结果示例:“北京今天是晴天。”
def get_current_weather(location):
    return f"{location}今天是晴天。 "

# 查询当前时间的工具。返回结果示例:“当前时间:2024-04-15 17:15:18。“
def get_current_time():
    # 获取当前日期和时间
    current_datetime = datetime.now()
    # 格式化当前日期和时间
    formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
    # 返回格式化后的当前时间
    return f"当前时间:{formatted_time}。"

# 封装模型响应函数
def get_response(messages):
    response = Generation.call(
        model='qwen-max',
        messages=messages,
        tools=tools,
        seed=random.randint(1, 10000),  # 设置随机数种子seed,如果没有设置,则随机数种子默认为1234
        result_format='message'  # 将输出设置为message形式
    )
    return response

def call_with_messages():
    print('\n')
    messages = [
            {
                "content": input('请输入:'),  # 提问示例:"现在几点了?" "一个小时后几点" "北京天气如何?"
                "role": "user"
            }
    ]
    
    # 模型的第一轮调用
    first_response = get_response(messages)
    assistant_output = first_response.output.choices[0].message
    print(f"\n大模型第一轮输出信息:{first_response}\n")
    messages.append(assistant_output)
    if 'tool_calls' not in assistant_output:  # 如果模型判断无需调用工具,则将assistant的回复直接打印出来,无需进行模型的第二轮调用
        print(f"最终答案:{assistant_output.content}")
        return
    # 如果模型选择的工具是get_current_weather
    elif assistant_output.tool_calls[0]['function']['name'] == 'get_current_weather':
        tool_info = {"name": "get_current_weather", "role":"tool"}
        location = json.loads(assistant_output.tool_calls[0]['function']['arguments'])['properties']['location']
        tool_info['content'] = get_current_weather(location)
    # 如果模型选择的工具是get_current_time
    elif assistant_output.tool_calls[0]['function']['name'] == 'get_current_time':
        tool_info = {"name": "get_current_time", "role":"tool"}
        tool_info['content'] = get_current_time()
    print(f"工具输出信息:{tool_info['content']}\n")
    messages.append(tool_info)

    # 模型的第二轮调用,对工具的输出进行总结
    second_response = get_response(messages)
    print(f"大模型第二轮输出信息:{second_response}\n")
    print(f"最终答案:{second_response.output.choices[0].message['content']}")

if __name__ == '__main__':
    call_with_messages()
    

返回结果

通过运行以上代码,您可以输入问题,得到在工具辅助条件下模型的输出结果。使用过程示例如下图所示:2024-04-29_11-22-10 (1).gif

以下是发起Function Call流程(模型的第一轮调用)时模型的返回信息。当输入“杭州天气”时,模型会返回tool_calls参数;当输入“你好”时,模型判断无需调用工具,模型不会返回tool_calls参数。

输入:杭州天气

{
    "status_code": 200,
    "request_id": "bd803417-56a7-9597-9d3f-a998a35b0477",
    "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": "{\"properties\": {\"location\": \"杭州市\"}, \"type\": \"object\"}"
                            },
                            "id": "",
                            "type": "function"
                        }
                    ]
                }
            }
        ]
    },
    "usage": {
        "input_tokens": 222,
        "output_tokens": 27,
        "total_tokens": 249
    }
}

输入:你好

{
    "status_code": 200,
    "request_id": "28e9d70c-c4d7-9bfb-bd07-8cf4228dda91",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": null,
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "你好!有什么能帮到你的吗?如果有关于天气、时间或者其他问题,随时告诉我。"
                }
            }
        ]
    },
    "usage": {
        "input_tokens": 221,
        "output_tokens": 21,
        "total_tokens": 242
    }
}

Java

示例代码

// Copyright (c) Alibaba, Inc. and its affiliates.
// version >= 2.12.0
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.GenerationOutput.Choice;
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.ToolCallBase;
import com.alibaba.dashscope.tools.ToolCallFunction;
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;
import java.util.Scanner;

public class Main {

    public class GetWhetherTool {
        private String location;

        public GetWhetherTool(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_whether = generator.generateSchema(GetWhetherTool.class);
        ObjectNode jsonSchema_time = generator.generateSchema(GetTimeTool.class);


        FunctionDefinition fd_whether = FunctionDefinition.builder().name("get_current_whether").description("获取指定地区的天气")
                .parameters(JsonUtils.parseString(jsonSchema_whether.toString()).getAsJsonObject()).build();

        FunctionDefinition fd_time = 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();

        Scanner scanner = new Scanner(System.in);
        System.out.print("\n请输入:");
        String userInput = scanner.nextLine();
        Message userMsg =
                Message.builder().role(Role.USER.getValue()).content(userInput).build();

        List<Message> messages = new ArrayList<>();
        messages.addAll(Arrays.asList(systemMsg, userMsg));

        GenerationParam param = GenerationParam.builder().model("qwen-max")
                .messages(messages).resultFormat(ResultFormat.MESSAGE)
                .tools(Arrays.asList(ToolFunction.builder().function(fd_whether).build(),ToolFunction.builder().function(fd_time).build())).build();
        // 大模型的第一轮调用
        Generation gen = new Generation();
        GenerationResult result = gen.call(param);

        System.out.println("\n大模型第一轮输出信息:"+JsonUtils.toJson(result));

        for (Choice choice : result.getOutput().getChoices()) {
            messages.add(choice.getMessage());
            // 如果需要调用工具
            if (result.getOutput().getChoices().get(0).getMessage().getToolCalls() != null) {
                for (ToolCallBase toolCall : result.getOutput().getChoices().get(0).getMessage()
                        .getToolCalls()) {
                    if (toolCall.getType().equals("function")) {
                        // 获取工具函数名称和入参
                        String functionName = ((ToolCallFunction) toolCall).getFunction().getName();
                        String functionArgument = ((ToolCallFunction) toolCall).getFunction().getArguments();
                        // 大模型判断调用天气查询工具的情况
                        if (functionName.equals("get_current_whether")) {
                            GetWhetherTool GetWhetherFunction =
                                    JsonUtils.fromJson(functionArgument, GetWhetherTool.class);
                            String whether = GetWhetherFunction.call();
                            Message toolResultMessage = Message.builder().role("tool")
                                    .content(String.valueOf(whether)).toolCallId(toolCall.getId()).build();
                            messages.add(toolResultMessage);
                            System.out.println("\n工具输出信息:"+whether);
                        }
                        // 大模型判断调用时间查询工具的情况
                        else if (functionName.equals("get_current_time")) {
                            GetTimeTool GetTimeFunction =
                                    JsonUtils.fromJson(functionArgument, GetTimeTool.class);
                            String time = GetTimeFunction.call();
                            Message toolResultMessage = Message.builder().role("tool")
                                    .content(String.valueOf(time)).toolCallId(toolCall.getId()).build();
                            messages.add(toolResultMessage);
                            System.out.println("\n工具输出信息:"+time);
                        }
                    }
                }
            }
            // 如果无需调用工具,直接输出大模型的回复
            else {
                System.out.println("\n最终答案:"+result.getOutput().getChoices().get(0).getMessage().getContent());
                return;
            }
        }
        // 大模型的第二轮调用 包含工具输出信息
        param.setMessages(messages);
        result = gen.call(param);
        System.out.println("\n大模型第二轮输出信息:"+JsonUtils.toJson(result));
        System.out.println(("\n最终答案:"+result.getOutput().getChoices().get(0).getMessage().getContent()));
    }


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

返回结果

通过运行以上代码,您可以输入问题,得到在工具辅助条件下模型的输出结果。使用过程示例如下图所示:2024-07-17_10-20-07 (1)

以下是发起Function Call流程(模型的第一轮调用)时模型的返回信息。当输入“杭州天气”时,模型会返回tool_calls参数;当输入“你好”时,模型判断无需调用工具,模型不会返回tool_calls参数。

输入:杭州天气

{
    "requestId": "e2faa5cf-1707-973b-b216-36aa4ef52afc",
    "usage": {
        "input_tokens": 254,
        "output_tokens": 19,
        "total_tokens": 273
    },
    "output": {
        "choices": [
            {
                "finish_reason": "tool_calls",
                "message": {
                    "role": "assistant",
                    "content": "",
                    "tool_calls": [
                        {
                            "type": "function",
                            "id": "",
                            "function": {
                                "name": "get_current_whether",
                                "arguments": "{\"location\": \"杭州\"}"
                            }
                        }
                    ]
                }
            }
        ]
    }
}

输入:你好

{
    "requestId": "f6ca3828-3b5f-99bf-8bae-90b4aa88923f",
    "usage": {
        "input_tokens": 253,
        "output_tokens": 7,
        "total_tokens": 260
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "你好!有什么可以帮助你的吗?"
                }
            }
        ]
    }
}

HTTP

示例代码

import requests
import os
from datetime import datetime
import json

# 定义工具列表,模型在选择使用哪个工具时会参考工具的name和description
tools = [
    # 工具1 获取当前时刻的时间
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "当你想知道现在的时间时非常有用。",
            "parameters": {}  # 因为获取当前时间无需输入参数,因此parameters为空字典
        }
    },  
    # 工具2 获取指定城市的天气
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {  # 查询天气时需要提供位置,因此参数设置为location
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。"
                    }
                }
            },
            "required": [
                "location"
            ]
        }
    }
]

# 模拟天气查询工具。返回结果示例:“北京今天是晴天。”
def get_current_weather(location):
    return f"{location}今天是晴天。 "

# 查询当前时间的工具。返回结果示例:“当前时间:2024-04-15 17:15:18。“
def get_current_time():
    # 获取当前日期和时间
    current_datetime = datetime.now()
    # 格式化当前日期和时间
    formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
    # 返回格式化后的当前时间
    return f"当前时间:{formatted_time}。"

def get_response(messages):
    api_key = os.getenv("DASHSCOPE_API_KEY")
    url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation'
    headers = {'Content-Type': 'application/json',
            'Authorization':f'Bearer {api_key}'}
    body = {
        'model': 'qwen-max',
        "input": {
            "messages": messages
        },
        "parameters": {
            "result_format": "message",
            "tools": tools
        }
    }

    response = requests.post(url, headers=headers, json=body)
    return response.json()

def call_with_messages():
    messages = [
            {
                "content": input('请输入:'),  # 提问示例:"现在几点了?" "一个小时后几点" "北京天气如何?"
                "role": "user"
            }
    ]
    
    # 模型的第一轮调用
    first_response = get_response(messages)
    print(f"\n第一轮调用结果:{first_response}")
    assistant_output = first_response['output']['choices'][0]['message']
    messages.append(assistant_output)
    if 'tool_calls' not in assistant_output:  # 如果模型判断无需调用工具,则将assistant的回复直接打印出来,无需进行模型的第二轮调用
        print(f"最终答案:{assistant_output['content']}")
        return
    # 如果模型选择的工具是get_current_weather
    elif assistant_output['tool_calls'][0]['function']['name'] == 'get_current_weather':
        tool_info = {"name": "get_current_weather", "role":"tool"}
        location = json.loads(assistant_output['tool_calls'][0]['function']['arguments'])['properties']['location']
        tool_info['content'] = get_current_weather(location)
    # 如果模型选择的工具是get_current_time
    elif assistant_output['tool_calls'][0]['function']['name'] == 'get_current_time':
        tool_info = {"name": "get_current_time", "role":"tool"}
        tool_info['content'] = get_current_time()
    print(f"工具输出信息:{tool_info['content']}")
    messages.append(tool_info)

    # 模型的第二轮调用,对工具的输出进行总结
    second_response = get_response(messages)
    print(f"第二轮调用结果:{second_response}")
    print(f"最终答案:{second_response['output']['choices'][0]['message']['content']}")

if __name__ == '__main__':
    call_with_messages()
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONObject;

public class Main {
    private static final String USER_AGENT = "Java-HttpURLConnection/1.0";
    public static void main(String[] args) throws Exception {
        // 用户输入问题
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入:");
        String UserInput = scanner.nextLine();
        // 初始化messages
        JSONArray messages = new JSONArray();
        // 定义系统信息system_message
        JSONObject system_message = new JSONObject();
        system_message.put("role","system");
        system_message.put("content","You are a helpful assistant.");
        // 根据用户的输入构造user_message
        JSONObject user_message = new JSONObject();
        user_message.put("role","user");
        user_message.put("content",UserInput);
        // 将system_message和user_message依次添加到messages中
        messages.put(system_message);
        messages.put(user_message);
        // 进行模型的第一轮调用,并打印出结果
        JSONObject response_json = get_response(messages);
        System.out.println("第一轮调用结果:"+response_json);
        // 获取助手信息assistant_message
        JSONObject assistant_message = response_json.getJSONObject("output").getJSONArray("choices").getJSONObject(0).getJSONObject("message");
        // 初始化工具信息tool_message
        JSONObject tool_message = new JSONObject();

        // 如果assistant_message没有tool_calls参数,则直接打印出assistant_message中的响应信息并返回
        if (! assistant_message.has("tool_calls")){
            System.out.println("最终答案:"+assistant_message.get("content"));
            return;
        }
        // 如果assistant_message有tool_calls参数,说明模型判断需要调用工具
        else {
            // 将assistant_message添加到messages中
            messages.put(assistant_message);
            // 如果模型判断需要调用get_current_weather函数
            if (assistant_message.getJSONArray("tool_calls").getJSONObject(0).getJSONObject("function").getString("name").equals("get_current_weather")) {
                // 获取参数arguments信息,并提取出location参数
                JSONObject arguments_json = new JSONObject(assistant_message.getJSONArray("tool_calls").getJSONObject(0).getJSONObject("function").getString("arguments"));
                String location = arguments_json.getJSONObject("properties").getString("location");
                // 运行工具函数,得到工具的输出,并打印
                String tool_output = get_current_weather(location);
                System.out.println("工具输出信息:"+tool_output);
                // 构造tool_message信息
                tool_message.put("name","get_current_weather");
                tool_message.put("role","tool");
                tool_message.put("content",tool_output);
            }
            // 如果模型判断需要调用get_current_time函数
            if (assistant_message.getJSONArray("tool_calls").getJSONObject(0).getJSONObject("function").getString("name").equals("get_current_time")) {
                // 运行工具函数,得到工具的输出,并打印
                String tool_output = get_current_time();
                System.out.println("工具输出信息:"+tool_output);
                // 构造tool_message信息
                tool_message.put("name","get_current_time");
                tool_message.put("role","tool");
                tool_message.put("content",tool_output);
            }
            }
        // 将tool_message添加到messages中
        messages.put(tool_message);
        // 进行模型的第二轮调用,并打印出结果
        JSONObject second_response = get_response(messages);
        System.out.println("第二轮调用结果:"+second_response);
        System.out.println("最终答案:"+second_response.getJSONObject("output").getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content"));
    }
    // 定义获取天气的函数
    public static String get_current_weather(String location) {
        return location+"今天是晴天";
    }
    // 定义获取当前时间的函数
    public static String get_current_time() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String currentTime = "当前时间:" + now.format(formatter) + "。";
        return currentTime;
    }
    // 封装模型响应函数,输入:messages,输出:json格式化后的http响应
    public static JSONObject get_response(JSONArray messages) throws Exception{
        // 初始化工具库
        JSONArray tools = new JSONArray();
        // 定义工具1:获取当前时间
        String jsonString_time = "{\"type\": \"function\", \"function\": {\"name\": \"get_current_time\", \"description\": \"当你想知道现在的时间时非常有用。\", \"parameters\": {}}}";
        JSONObject get_current_time_json = new JSONObject(jsonString_time);
        // 定义工具2:获取指定地区天气
        String jsonString_weather = "{\"type\": \"function\", \"function\": {\"name\": \"get_current_weather\", \"description\": \"当你想查询指定城市的天气时非常有用。\", \"parameters\": {\"type\": \"object\", \"properties\": {\"location\": {\"type\": \"string\", \"description\": \"城市或县区,比如北京市、杭州市、余杭区等。\"}}}, \"required\": [\"location\"]}}";
        JSONObject get_current_whether_json = new JSONObject(jsonString_weather);
        // 将两个工具添加到工具库中
        tools.put(get_current_time_json);
        tools.put(get_current_whether_json);
        String toolsString = tools.toString();
        // 接口调用URL
        String urlStr = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        // 通过环境变量获取DASHSCOPE_API_KEY
        String apiKey = System.getenv("DASHSCOPE_API_KEY");

        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 定义请求头信息
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setDoOutput(true);
        // 定义请求体信息
        String jsonInputString = String.format("{\"model\": \"qwen-max\", \"input\": {\"messages\":%s}, \"parameters\": {\"result_format\": \"message\",\"tools\":%s}}",messages.toString(),toolsString);

        // 获取http响应response
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
            wr.flush();
        }
        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        }
        connection.disconnect();
        // 返回json格式化后的response
        return new JSONObject(response.toString());
    }
}

返回结果

当输入:杭州天气时,程序会进行如下输出:

2024-07-16_14-07-04 (1)

以下是发起Function Call流程(模型的第一轮调用)时模型的返回信息。当输入“杭州天气”时,模型会返回tool_calls参数;当输入“你好”时,模型判断无需调用工具,模型不会返回tool_calls参数。

输入:杭州天气

{
  "output": {
    "choices": [
      {
        "finish_reason": "tool_calls",
        "message": {
          "role": "assistant",
          "tool_calls": [
            {
              "function": {
                "name": "get_current_weather",
                "arguments": "{\"properties\": {\"location\": \"杭州市\"}}"
              },
              "id": "",
              "type": "function"
            }
          ],
          "content": ""
        }
      }
    ]
  },
  "usage": {
    "total_tokens": 243,
    "output_tokens": 21,
    "input_tokens": 222
  },
  "request_id": "1287a9d8-3e42-9dfe-a401-e2329e78c622"
}

输入:你好

{
  "output": {
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "你好!有什么可以帮助你的吗?"
        }
      }
    ]
  },
  "usage": {
    "total_tokens": 228,
    "output_tokens": 7,
    "input_tokens": 221
  },
  "request_id": "c547571f-c326-9b06-8d3d-d4b4c9418f7c"
}

Asyncio接口(实现异步调用)

您可以使用Asyncio接口调用实现并发,提高程序的效率。示例代码如下:

OpenAI SDK

示例代码

import os
import asyncio
from openai import AsyncOpenAI
import platform

# 创建异步客户端实例
client = AsyncOpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)

# 定义异步任务列表
async def task(question):
    print(f"Sending question: {question}")
    response = await client.chat.completions.create(
        messages=[
            {"role": "user", "content": question}
        ],
        model="qwen-max",
    )
    print(f"Received answer: {response.choices[0].message.content}")

# 主异步函数
async def main():
    questions = ["你是谁?", "你会什么?", "天气怎么样?"]
    tasks = [task(q) for q in questions]
    await asyncio.gather(*tasks)

if __name__ == '__main__':
    # 设置事件循环策略
    if platform.system() == 'Windows':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    # 运行主协程
    asyncio.run(main(), debug=False)

DashScope SDK

示例代码

说明

您的Dashscope Python SDK版本需要不低于 1.19.0。

import asyncio
import platform
from dashscope.aigc.generation import AioGeneration

# 定义异步任务列表
async def task(question):
    print(f"Sending question: {question}")
    response = await AioGeneration.call("qwen-turbo",
                                        prompt=question)
    print(f"Received answer: {response.output.text}")

# 主异步函数
async def main():
    questions = ["你是谁?", "你会什么?", "天气怎么样?"]
    tasks = [task(q) for q in questions]
    await asyncio.gather(*tasks)

if __name__ == '__main__':
    # 设置事件循环策略
    if platform.system() == 'Windows':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    # 运行主协程
    asyncio.run(main(), debug=False)

输入与输出参数

您可以通过下表查看不同调用方式的输入参数与输出参数。

数据类型列中各字段的含义如下所示:

  • string表示字符串类型;

  • array在Python中表示列表,在Java中表示ArrayList;

  • integer表示整数型;

  • float表示浮点型;

  • boolean表示布尔型;

  • object表示哈希表。

OpenAI SDK

输入参数

参数

类型

默认值

说明

model

string

-

用户使用model参数指明对应的模型,请参考模型概览

messages

array

-

用户与模型的对话历史。array中的每个元素形式为{"role":角色, "content": 内容}。角色当前可选值:system、user、assistant,其中,仅messages[0]中支持role为system,一般情况下,user和assistant需要交替出现,且messages中最后一个元素的role必须为user。

top_p(可选)

float

-

生成过程中的核采样方法概率阈值,例如,取值为0.8时,仅保留概率加起来大于等于0.8的最可能token的最小集合作为候选集。取值范围为(0,1.0),取值越大,生成的随机性越高;取值越低,生成的确定性越高。

temperature(可选)

float

-

用于控制模型回复的随机性和多样性。具体来说,temperature值控制了生成文本时对每个候选词的概率分布进行平滑的程度。较高的temperature值会降低概率分布的峰值,使得更多的低概率词被选择,生成结果更加多样化;而较低的temperature值则会增强概率分布的峰值,使得高概率词更容易被选择,生成结果更加确定。

取值范围: [0, 2),不建议取值为0,无意义。

presence_penalty

(可选)

float

-

用户控制模型生成时整个序列中的重复度。提高presence_penalty时可以降低模型生成的重复度,取值范围[-2.0, 2.0]。

重要

目前仅在千问商业模型和qwen1.5及以后的开源模型上支持该参数。

max_tokens(可选)

integer

-

指定模型可生成的最大token个数。根据模型不同有不同的上限限制,一般不超过2000。

seed(可选)

integer

-

生成时使用的随机数种子,用于控制模型生成内容的随机性。seed支持无符号64位整数。

stream(可选)

boolean

False

用于控制是否使用流式输出。当以stream模式输出结果时,接口返回结果为generator,需要通过迭代获取结果,每次输出为当前生成的增量序列。

stop(可选)

string or array

None

stop参数用于实现内容生成过程的精确控制,在模型生成的内容即将包含指定的字符串或token_id时自动停止。stop可以为string类型或array类型。

  • string类型

    当模型将要生成指定的stop词语时停止。

    例如将stop指定为"你好",则模型将要生成“你好”时停止。

  • array类型

    array中的元素可以为token_id或者字符串,或者元素为token_id的array。当模型将要生成的token或其对应的token_id在stop中时,模型生成将会停止。以下为stop为array时的示例(tokenizer对应模型为qwen-turbo):

    1.元素为token_id:

    token_id为108386和104307分别对应token为“你好”和“天气”,设定stop为[108386,104307],则模型将要生成“你好”或者“天气”时停止。

    2.元素为字符串:

    设定stop为["你好","天气"],则模型将要生成“你好”或者“天气”时停止。

    3.元素为array:

    token_id为108386和103924分别对应token为“你好”和“啊”,token_id为35946和101243分别对应token为“我”和“很好”。设定stop为[[108386, 103924],[35946, 101243]],则模型将要生成“你好啊”或者“我很好”时停止。

    说明

    stop为array类型时,不可以将token_id和字符串同时作为元素输入,比如不可以指定stop为["你好",104307]。qwen-vl相关模型目前不支持该参数。

tools(可选)

array

None

用于指定可供模型调用的工具库,一次function call流程模型会从中选择其中一个工具。tools中每一个tool的结构如下:

  • type,类型为string,表示tools的类型,当前仅支持function。

  • function,类型为object,键值包括name,description和parameters:

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

    • description:类型为string,表示工具函数的描述,供模型选择何时以及如何调用工具函数。

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

在function call流程中,无论是发起function call的轮次,还是向模型提交工具函数的执行结果,均需设置tools参数。当前支持的模型包括qwen-turbo、qwen-plus、qwen-max和qwen-max-longcontext。

说明

tools暂时无法与stream=True同时使用。qwen-vl相关模型目前不支持该参数。

stream_options(可选)

object

None

该参数用于配置在流式输出时是否展示使用的token数目。只有当stream为True的时候该参数才会激活生效。若您需要统计流式输出模式下的token数目,可将该参数配置为stream_options={"include_usage":True}

enable_search

(可选,通过extra_body配置)

boolean

False

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

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

  • False(默认):关闭互联网搜索。

配置方式为:extra_body={"enable_search":True}

出参描述

返回参数

数据类型

说明

备注

id

string

系统生成的标识本次调用的id。

model

string

本次调用的模型名。

system_fingerprint

string

模型运行时使用的配置版本,当前暂时不支持,返回为空字符串“”。

choices

array

模型生成内容的详情。

choices[i].finish_reason

string

有三种情况:

  • 正在生成时为null;

  • 因触发输入参数中的stop条件而结束为stop;

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

choices[i].message

object

模型输出的消息。

choices[i].message.role

string

模型的角色,固定为assistant。

choices[i].message.content

string

模型生成的文本。

choices[i].index

integer

生成的结果序列编号,默认为0。

created

integer

当前生成结果的时间戳(s)。

usage

object

计量信息,表示本次请求所消耗的token数据。

usage.prompt_tokens

integer

用户输入文本转换成token后的长度。

您可以参考本地tokenizer统计token数据进行token的估计。

usage.completion_tokens

integer

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

usage.total_tokens

integer

usage.prompt_tokens与usage.completion_tokens的总和。

OpenAI兼容-HTTP

输入参数

传参方式

参数

类型

默认值

说明

Header

Authorization

string

-

API-KEY,例如:Bearer d1**2a

Content-Type

string

-

请求类型,例如:application/json

Body

model

string

-

用户使用model参数指明对应的模型,请参考模型概览

messages

array

-

用户与模型的对话历史。array中的每个元素形式为{"role":角色, "content": 内容}。角色当前可选值:system、user、assistant,其中,仅messages[0]中支持role为system,一般情况下,user和assistant需要交替出现,且messages中最后一个元素的role必须为user。

top_p(可选)

float

-

生成过程中的核采样方法概率阈值,例如,取值为0.8时,仅保留概率加起来大于等于0.8的最可能token的最小集合作为候选集。取值范围为(0,1.0),取值越大,生成的随机性越高;取值越低,生成的确定性越高。

temperature(可选)

float

-

用于控制模型回复的随机性和多样性。具体来说,temperature值控制了生成文本时对每个候选词的概率分布进行平滑的程度。较高的temperature值会降低概率分布的峰值,使得更多的低概率词被选择,生成结果更加多样化;而较低的temperature值则会增强概率分布的峰值,使得高概率词更容易被选择,生成结果更加确定。

取值范围: [0, 2),不建议取值为0,无意义。

presence_penalty

(可选)

float

-

用户控制模型生成时整个序列中的重复度。提高presence_penalty时可以降低模型生成的重复度,取值范围[-2.0, 2.0]。

重要

目前仅在千问商业模型和qwen1.5及以后的开源模型上支持该参数。

max_tokens(可选)

integer

-

指定模型可生成的最大token个数。根据模型不同有不同的上限限制,一般不超过2000。

seed(可选)

integer

-

生成时使用的随机数种子,用于控制模型生成内容的随机性。seed支持无符号64位整数。

stream(可选)

boolean

False

用于控制是否使用流式输出。当以stream模式输出结果时,接口返回结果为generator,需要通过迭代获取结果,每次输出为当前生成的增量序列。

stop(可选)

string or array

None

stop参数用于实现内容生成过程的精确控制,在模型生成的内容即将包含指定的字符串或token_id时自动停止。stop可以为string类型或array类型。

  • string类型

    当模型将要生成指定的stop词语时停止。

    例如将stop指定为"你好",则模型将要生成“你好”时停止。

  • array类型

    array中的元素可以为token_id或者字符串,或者元素为token_id的array。当模型将要生成的token或其对应的token_id在stop中时,模型生成将会停止。以下为stop为array时的示例(tokenizer对应模型为qwen-turbo):

    1.元素为token_id:

    token_id为108386和104307分别对应token为“你好”和“天气”,设定stop为[108386,104307],则模型将要生成“你好”或者“天气”时停止。

    2.元素为字符串:

    设定stop为["你好","天气"],则模型将要生成“你好”或者“天气”时停止。

    3.元素为array:

    token_id为108386和103924分别对应token为“你好”和“啊”,token_id为35946和101243分别对应token为“我”和“很好”。设定stop为[[108386, 103924],[35946, 101243]],则模型将要生成“你好啊”或者“我很好”时停止。

    说明

    stop为array类型时,不可以将token_id和字符串同时作为元素输入,比如不可以指定stop为["你好",104307]。qwen-vl相关模型目前不支持该参数。

tools(可选)

array

None

用于指定可供模型调用的工具库,一次function call流程模型会从中选择其中一个工具。tools中每一个tool的结构如下:

  • type,类型为string,表示tools的类型,当前仅支持function。

  • function,类型为object,键值包括name,description和parameters:

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

    • description:类型为string,表示工具函数的描述,供模型选择何时以及如何调用工具函数。

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

在function call流程中,无论是发起function call的轮次,还是向模型提交工具函数的执行结果,均需设置tools参数。

说明

tools暂时无法与stream=True同时使用。qwen-vl相关模型目前不支持该参数。

stream_options(可选)

object

None

该参数用于配置在流式输出时是否展示使用的token数目。只有当stream为True的时候该参数才会激活生效。若您需要统计流式输出模式下的token数目,可将该参数配置为stream_options={"include_usage":True}

enable_search

(可选,通过extra_body配置)

boolean

False

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

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

  • False(默认):关闭互联网搜索。

配置方式为:extra_body={"enable_search":True}

出参描述

返回参数

数据类型

说明

备注

id

string

系统生成的标识本次调用的id。

model

string

本次调用的模型名。

system_fingerprint

string

模型运行时使用的配置版本,当前暂时不支持,返回为空字符串“”。

choices

array

模型生成内容的详情。

choices[i].finish_reason

string

有三种情况:

  • 正在生成时为null;

  • 因触发输入参数中的stop条件而结束为stop;

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

choices[i].message

object

模型输出的消息。

choices[i].message.role

string

模型的角色,固定为assistant。

choices[i].message.content

string

模型生成的文本。

choices[i].index

integer

生成的结果序列编号,默认为0。

created

integer

当前生成结果的时间戳(s)。

usage

object

计量信息,表示本次请求所消耗的token数据。

usage.prompt_tokens

integer

用户输入文本转换成token后的长度。

您可以参考本地tokenizer统计token数据进行token的估计。

usage.completion_tokens

integer

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

usage.total_tokens

integer

usage.prompt_tokens与usage.completion_tokens的总和。

DashScope SDK

输入参数

参数

数据类型

默认值

说明

model(必选)

string

指定用于对话的通义千问模型名。请参考模型概览

messages

array

  • messages:用户与模型的对话历史。array中的每个元素形式为{"role":角色, "content": 内容},角色当前可选值:systemuserassistanttool

    • system:表示系统级消息,用于指导模型按照预设的规范、角色或情境进行回应。是否使用system角色是可选的,如果使用则必须位于messages的最开始部分。

    • userassistant:表示用户和模型的消息。它们应交替出现在对话中,模拟实际对话流程。

    • tool:表示工具的消息。在使用function call功能时,如果要传入工具的结果,需将元素的形式设为{"content":"工具返回的结果", "name":"工具的函数名", "role":"tool"}。其中name是工具函数的名称,需要和上轮response中的tool_calls[i]['function']['name']参数保持一致;content是工具函数的输出。

  • prompt:用户输入的指令,用于指导模型生成回复。

说明

messages和prompt任选一个参数使用即可。由于和prompt组合使用的对话历史参数history即将废弃,仅依赖prompt指令会限制模型进行有记忆的对话能力。

messages参数允许模型参考历史对话,从而更准确地解析用户的意图,确保对话的流程性和连续性,因此在多轮对话场景下推荐您优先使用messages参数。

prompt

string

无(与messages不可同时为空)

seed(可选)

integer

生成时使用的随机数种子,用于控制模型生成内容的随机性。seed支持无符号64位整数。

max_tokens(可选)

说明

Java SDK中为maxTokens。

integer

1500或2000

指定模型可生成的最大token个数。

  • qwen-turbo最大值和默认值为1500 tokens。

  • qwen-maxqwen-max-1201qwen-max-longcontextqwen-plus模型,最大值和默认值均为2000 tokens。

top_p(可选)

说明

Java SDK中为topP。

float

生成过程中的核采样方法概率阈值,例如,取值为0.8时,仅保留概率加起来大于等于0.8的最可能token的最小集合作为候选集。取值范围为(0,1.0),取值越大,生成的随机性越高;取值越低,生成的确定性越高。

top_k(可选)

说明

Java SDK中为topK。

integer

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

repetition_penalty(可选)

说明

Java SDK中为repetitionPenalty。

float

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

presence_penalty(可选)

说明

Java SDK中暂不支持该参数。

float

用户控制模型生成时整个序列中的重复度。提高presence_penalty时可以降低模型生成的重复度,取值范围[-2.0, 2.0]。

temperature(可选)

float

用于控制模型回复的随机性和多样性。具体来说,temperature值控制了生成文本时对每个候选词的概率分布进行平滑的程度。较高的temperature值会降低概率分布的峰值,使得更多的低概率词被选择,生成结果更加多样化;而较低的temperature值则会增强概率分布的峰值,使得高概率词更容易被选择,生成结果更加确定。

取值范围:[0, 2),不建议取值为0,无意义。

stop (可选)

string or array

None

stop参数用于实现内容生成过程的精确控制,在模型生成的内容即将包含指定的字符串或token_id时自动停止。stop可以为string类型或array类型。

  • string类型

    当模型将要生成指定的stop词语时停止。

    例如将stop指定为"你好",则模型将要生成“你好”时停止。

  • array类型

    array中的元素可以为token_id或者字符串,或者元素为token_id的array。当模型将要生成的token或其对应的token_id在stop中时,模型生成将会停止。以下为stop为array时的示例(tokenizer对应模型为qwen-turbo):

    1.元素为token_id:

    token_id为108386和104307分别对应token为“你好”和“天气”,设定stop为[108386,104307],则模型将要生成“你好”或者“天气”时停止。

    2.元素为字符串:

    设定stop为["你好","天气"],则模型将要生成“你好”或者“天气”时停止。

    3.元素为array:

    token_id为108386和103924分别对应token为“你好”和“啊”,token_id为35946和101243分别对应token为“我”和“很好”。设定stop为[[108386, 103924],[35946, 101243]],则模型将要生成“你好啊”或者“我很好”时停止。

    说明

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

stream (可选)

boolean

False

用于控制是否使用流式输出。当以stream模式输出结果时,接口返回结果为generator,需要通过迭代获取结果,默认每次输出为当前生成的整个序列,最后一次输出为最终全部生成结果,可以通过设置参数incremental_output为False改变输出模式为非增量输出。

enable_search(可选)

说明

Java SDK中为enableSearch

boolean

False

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

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

  • False(默认):关闭互联网搜索。

result_format(可选)

说明

Java SDK中为resultFormat。

string

text

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

incremental_output (可选)

说明

Java SDK中为incrementalOutput。

boolean

False

控制在流式输出模式下是否开启增量输出,即后续输出内容是否包含已输出的内容。设置为True时,将开启增量输出模式,后面输出不会包含已经输出的内容,您需要自行拼接整体输出;设置为False则会包含已输出的内容。

默认False:

I

I like

I like apple

True:

I

like

apple

该参数只能在stream为True时使用。

说明

incremental_output暂时无法和tools参数同时使用。

tools

array

None

用于指定可供模型调用的工具库,一次function call流程模型会从中选择其中一个工具。tools中每一个tool的结构如下:

  • type,类型为string,表示tools的类型,当前仅支持function。

  • function,类型为object,键值包括name,description和parameters:

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

    • description:类型为string,表示工具函数的描述,供模型选择何时以及如何调用工具函数。

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

使用tools时需要同时指定result_format为message。在function call流程中,无论是发起function call的轮次,还是向模型提交工具函数的执行结果,均需设置tools参数。

说明

tools暂时无法和incremental_output参数同时使用。

tool_choice

说明

Java SDK中为toolChoice。

string or object

见说明

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

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

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

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

    • type只支持指定为"function"

    • function

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

说明

当前支持qwen-max/qwen-max-0428/qwen-max-0403/qwen-plus/qwen-turbo

返回结果

  • result_format设置为"message"时的结果示例:

    {
        "status_code": 200,
        "request_id": "05dc83af-7185-9e14-9b0b-4466de159d6a",
        "code": "",
        "message": "",
        "output": {
            "text": null,
            "finish_reason": null,
            "choices": [
                {
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": "首先,准备两个鸡蛋,一个西红柿,适量的盐、糖、料酒和生抽。将鸡蛋打入碗中,搅拌均匀,西红柿切块。锅中加油,油热后加入鸡蛋液,炒至金黄色,盛出备用。锅中加油,油热后加入西红柿块,翻炒均匀,加入适量的盐、糖、料酒和生抽,炒至西红柿软烂,加入炒好的鸡蛋,翻炒均匀即可。"
                    }
                }
            ]
        },
        "usage": {
            "input_tokens": 12,
            "output_tokens": 98,
            "total_tokens": 110
        }
    }
  • 发起function call时的结果示例:

    {
        "status_code": 200,
        "request_id": "a2b49cd7-ce21-98ff-87ac-b00cc590dc5e",
        "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': '{"properties": {"location": "北京市"}}'
                                    },
                                'id': '',
                                'type': 'function'}]
                    }
                }
            ]
        },
        "usage": {
            "input_tokens": 12,
            "output_tokens": 98,
            "total_tokens": 110
        }
    }

出参描述

返回参数

数据类型

说明

备注

status_code

integer

200(HTTPStatus.OK)表示请求成功,否则表示请求失败,可以通过code获取错误码,通过message字段获取错误详细信息。

说明

只有Python会输出该参数,使用Java调用失败会抛出异常,异常信息为code和message的内容。

request_id

string

系统生成的标志本次调用的id。

code

string

表示错误码,调用成功时为空值。仅适用于Python。

message

string

表示调用失败的详细信息,调用成功时为空值。仅适用于Python。

output

object

表示调用结果信息。

output.text

string

模型生成的回复。

在使用prompt传入指令时不为空

output.finish_reason

string

有四种情况:

  • 正在生成时为null;

  • 因触发输入参数中的stop条件而结束为stop;

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

  • 因发生工具调用为tool_calls。

output.choices

array

当result_format为message时输出choices。

当result_format为message时输出choices。

output.choices[i].finish_reason

string

有三种情况:

  • 正在生成时为null;

  • 因触发输入参数中的stop条件而结束为stop;

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

output.choices[i].message

object

模型输出的消息。

output.choices[i].message.role

string

模型的角色,固定为assistant。

output.choices[i].message.content

string

模型生成的文本。

output.choices[i].message.tool_calls

object

如果模型需要调用工具,则会生成tool_calls参数,应用于function call场景。

包含三个参数:type、function和id。type、function参数详情如下:

  • type,类型为string,当前只能设置为function。

  • function,类型为object,包含name和arguments两个参数:

    • name,类型为string,表示需要调用的工具的名称,如果是function call场景则表示要调用的工具函数名称。

    • arguments,类型为string,表示模型生成的要传入工具的参数。可以通过Python中的json.loads方法解析为字典。

usage

object

计量信息,表示本次请求所消耗的token数据。

usage.input_tokens

integer

用户输入文本转换成token后的长度。

您可以参考本地tokenizer统计token数据进行token的估计。

usage.output_tokens

integer

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

usage.total_tokens

integer

usage.input_tokens与usage.output_tokens的总和

DashScope HTTP

输入参数

传参方式

字段

数据类型

必选

描述

示例值

Header

Content-Type

string

请求类型:application/json

"Content-Type":"application/json"

Accept

string

选择text/event-stream则会开启SSE响应,默认无设置。

"Accept":"text/event-stream"

Authorization

string

API-KEY,例如:Bearer d1**2a

"Authorization":"Bearer d1**2a"

X-DashScope-SSE

string

设置为enable或者设置Accept: text/event-stream即可启用SSE响应。

"X-DashScope-SSE":"enable"

Body

model

string

指定用于对话的通义千问模型名。请参考模型概览

"model":"qwen-turbo"

input

object

输入模型的信息。

input.prompt

说明

字段中的点号(.)表示后者为前者的属性。在API测试工具中,并不能直接将Key设置为input.prompt。传入方式为"input":{"prompt":"xxx"}。

string

用户当前输入的期望模型执行指令,支持中英文。与input.messages指定其中一个即可。

"input":{"prompt":"你好"}

input.history

array

即将废弃,请使用messages字段用户与模型的对话历史,array中的每个元素形式为{"user":"用户输入","bot":"模型输出"}的一轮对话,多轮对话按时间正序排列。

"input":{"history":[{"user":"今天天气好吗?",

"bot":"今天天气不错,要出去玩玩嘛?"},

{"user":"那你有什么地方推荐?",

"bot":"我建议你去公园,春天来了,花朵开了,很美丽。"}]}

input.messages

array

表示用户与模型的对话历史。array中的每个元素形式为{"role":角色, "content": 内容},如果role为tool,元素形式为:

{"role":"tool","content":内容,"name":工具函数名}

角色可选值:systemuserassistanttool

"input":{

"messages":[

{

"role": "system",

"content": "You are a helpful assistant."

},

{

"role": "user",

"content": "你好,附近哪里有博物馆?"

}]

}

input.messages.role

string

messages存在的时候不能省略。

input.messages.content

string

input.messages.name

string

input.messages.role为tool时不能省略

role为tool表示当前message为function_call的调用结果,name是工具函数名,需要和上轮response中的tool_calls[i].function.name参数保持一致,content为工具函数的输出。

parameters

object

用于控制模型生成的参数

parameters.result_format

string

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

"parameters":{"result_format":"message"}

parameters.seed

integer

生成时使用的随机数种子,用户控制模型生成内容的随机性。seed支持无符号64位整数。在使用seed时,模型将尽可能生成相同或相似的结果,但目前不保证每次生成的结果完全相同。

"parameters":{"seed":666}

parameters.max_tokens

integer

用于限制模型生成token的数量,表示生成token个数的上限。其中qwen-turbo最大值和默认值为1500,qwen-max、qwen-max-1201 、qwen-max-longcontext 和 qwen-plus最大值和默认值均为2000。

"parameters":{"max_tokens":1500}

parameters.top_p

float

生成时,核采样方法的概率阈值。例如,取值为0.8时,仅保留累计概率之和大于等于0.8的概率分布中的token,作为随机采样的候选集。取值范围为(0,1.0),取值越大,生成的随机性越高;取值越低,生成的随机性越低。注意,取值不要大于等于1。

"parameters":{"top_p":0.7}

parameters.top_k

integer

生成时,采样候选集的大小。例如,取值为50时,仅将单次生成中得分最高的50个token组成随机采样的候选集。取值越大,生成的随机性越高;取值越小,生成的确定性越高。注意:如果top_k参数为空或者top_k的值大于100,表示不启用top_k策略,此时仅有top_p策略生效。

"parameters":{"top_k":50}

parameters.repetition_penalty

float

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

"parameters":{"repetition_penalty":1.0}

parameters.presence_penalty

float

用户控制模型生成时整个序列中的重复度。提高presence_penalty时可以降低模型生成的重复度,取值范围 [-2.0, 2.0]。

"parameters":{"presence_penalty":1.0}

parameters.temperature

float

用于控制随机性和多样性的程度。具体来说,temperature值控制了生成文本时对每个候选词的概率分布进行平滑的程度。较高的temperature值会降低概率分布的峰值,使得更多的低概率词被选择,生成结果更加多样化;而较低的temperature值则会增强概率分布的峰值,使得高概率词更容易被选择,生成结果更加确定。

取值范围:[0, 2),不建议取值为0,无意义。

"parameters":{"temperature":0.85}

parameters.stop

string/array

stop参数用于实现内容生成过程的精确控制,在模型生成的内容即将包含指定的字符串或token_id时自动停止,生成的内容不包含指定的内容。stop可以为string类型或array类型。

  • string类型

    当模型将要生成指定的stop词语时停止。

    例如将stop指定为"你好",则模型将要生成“你好”时停止。

  • array类型

    array中的元素可以为token_id或者字符串,或者元素为token_id的array。当模型将要生成的token或其对应的token_id在stop中时,模型生成将会停止。

    例如将stop指定为["你好","天气"]或者[108386,104307],则模型将要生成“你好”或者“天气”时停止。如果将stop指定为[[108386, 103924],[35946, 101243]],则模型将要生成“你好啊”或者“我很好”时停止。

    说明

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

"parameters":{"stop":["你好","天气"]}

parameters.enable_search

boolean

模型内置了互联网搜索服务,该参数控制模型在生成文本时是否参考使用互联网搜索结果。取值如下:

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

  • false(默认):关闭互联网搜索。

"parameters":{"enable_search":false}

parameters.incremental_output

boolean

控制在流式输出模式下是否开启增量输出,即后续输出内容是否包含已输出的内容。设置为True时,将开启增量输出模式,后面输出不会包含已经输出的内容,您需要自行拼接整体输出;设置为False则会包含已输出的内容。

默认False:

I

I like

I like apple

True:

I

like

apple

该参数只能在开启SSE响应时使用。

说明

incremental_output暂时无法和tools参数同时使用。

"parameters":{"incremental_output":false}

parameters.tools

array

用于指定可供模型调用的工具列表。当输入多个工具时,模型会选择其中一个生成结果。tools中每一个tool的结构如下:

  • type,类型为string,表示tools的类型,当前仅支持function。

  • function,类型为object,键值包括name,description和parameters:

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

    • description:类型为string,表示工具函数的描述,供模型选择何时以及如何调用工具函数。

    • parameters:类型为object,表示工具的参数描述,需要是一个合法的JSON Schema。JSON Schema的描述可以见链接

使用tools时需要同时指定result_format为message。在function call流程中,无论是发起function call的轮次,还是向模型提交工具函数的执行结果,均需设置tools参数。

说明

tools暂时无法和incremental_output参数同时使用。

"parameters":{"tools":[
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA"
                    },
                    "unit": {
                        "type": "string",
                        "enum": [
                            "celsius",
                            "fahrenheit"
                        ]
                    }
                },
                "required": [
                    "location"
                ]
            }
        }
    }
]}

parameters.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"

说明

当前支持qwen-max/qwen-max-0428/qwen-max-0403/qwen-plus/qwen-turbo。

{"type": "function", "function": {"name": "user_function"}}

出参描述

字段

数据类型

描述

示例值

output.text

string

模型输出的内容。当result_format设置为text时返回该字段。

我建议你去颐和园

output.finish_reason

string

有三种情况:正在生成时为null,生成结束时如果由于停止token导致则为stop,生成结束时如果因为生成长度过长导致则为length。当result_format设置为text时返回该字段。

stop

output.choices

array

当result_format设置为message时返回该字段。

  • 普通示例

    {
        "choices": [
            {
                "finish_reason": "null",
                "message": {
                    "role": "assistant",
                    "content": "周围的咖啡馆在..."
                }
            }
        ]
    }
  • function call示例

    {
        "choices": [
            {
                "finish_reason": "tool_calls",
                "message": {
                    "role": "assistant",
                    "content": "",
                    "tool_calls": [
                        {
                            "function": {
                                "name": "get_current_weather",
                                "arguments": "{\"location\": \"Boston\", \"unit\": \"fahrenheit\"}"
                            },
                            "type": "function"
                        }
                    ]
                }
            }
        ]
    }

output.choices[x].finish_reason

string

停止原因,null:生成过程中

stop:stop token导致结束

length:生成长度导致结束

output.choices[x].message

object

message每个元素形式为{"role":角色, "content": 内容}。角色可选值:systemuserassistant。content为模型输出的内容。

output.choices[x].message.role

string

output.choices[x].message.content

string

output.choices[x].message.tool_calls

object

如果模型需要调用工具,则会生成tool_calls参数,应用于function_call场景。其中包含type和function两个参数,参数详情如下:

  • type,类型为string,当前只可能为function

  • function,类型为dict,包含name和arguments两个参数:

    • name,类型为string,表示需要调用的工具的名称,如果是function_call场景则表示要调用的function名称

    • arguments,类型为string,表示模型生成的工具入参,在Python中可以使用json.loads方法转化为字典类型。

usage

object

本次调用使用的token信息。

usage.output_tokens

integer

模型输出内容的 token个数。

380

usage.input_tokens

integer

本次请求输入内容的token个数。在enable_search设置为true时,输入的 token 数目由于需要添加搜索相关内容,因此会比您在请求中的输入token个数多。

633

usage.total_tokens

integer

usage.output_tokens与usage.input_tokens的总和。

1013

request_id

string

本次请求的系统唯一码。

7574ee8f-38a3-4b1e-9280-11c33ab46e51

异常响应示例

此处以未传入正确API-KEY为例,向您展示异常响应的示例。

DashScope SDK

Request id: 54e9e525-bd50-9a05-9442-8801800c57fd, Status code: 401, error code: InvalidApiKey, error message: Invalid API-key provided.

OpenAI SDK

openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided. ', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}

DashScope-HTTP

{"code":"InvalidApiKey","message":"Invalid API-key provided.","request_id":"c2b1ab6e-e5a5-9d21-8579-88a10ce39c2f"}

OpenAI兼容-HTTP

{
    "error": {
        "message": "Incorrect API key provided. ",
        "type": "invalid_request_error",
        "param": null,
        "code": "invalid_api_key"
    }
}

状态码说明

DashScope通用状态码详情,请参见返回状态码说明

常见问题

  1. 通义千问、灵积、DashScope、百炼是什么关系?

    通义千问是阿里云研发的大语言模型;灵积是阿里云推出的模型服务平台,提供了包括通义千问在内的多种模型的服务接口,DashScope是灵积的英文名,两者指的是同一平台;百炼是阿里云推出的一站式大模型应用开发平台。

  2. 我如果想调用通义千问模型,是要通过DashScope还是百炼平台?

    对于需要模型调用的开发者而言,通过DashScope与百炼平台调用通义千问模型都是通过dashscope SDK或OpenAI兼容或HTTP方式实现。两个平台都可以获取到API-KEY,且是同步的。因此您只需准备好计算环境,并在两个平台任选其一创建API-KEY,即可发起通义千问模型的调用。

  3. 我想通过灵积调用通义千问开源模型,但是文档中没有相应介绍,我该看哪篇文档?

    qwen开源模型的使用方法请参考大语言模型文档。

  4. 我可以通过OpenAI兼容方式调用通义千问的多模态模型吗?

    可以,详情请您参考VL模型流式调用示例(输入图片url)