Skip to main content

Function Calling

Large models cannot access real-time data or external systems. Function Calling allows models to call external tools (APIs, databases, custom functions, etc.) to obtain information or perform actions, breaking through the limitations of the model's own capabilities.

How it works

Function Calling works through multi-step interactions between your application and the model:
  1. Initiate the first model call The application sends the user's question and the list of available tools to the model.
  2. Receive the model's tool call instruction (tool name and parameters) If the model determines that an external tool needs to be called, it returns a JSON-formatted instruction specifying the function name and parameters.
    If the model determines that no tool call is needed, it returns a natural language response.
  3. Run the tool on the application side The application executes the specified tool and obtains the output result.
  4. Initiate the second model call Add the tool output to the messages array (messages) and call the model again.
  5. Receive the final response from the model The model synthesizes the tool output and the user's question to generate a natural language response.
Workflow diagram:
image

Supported models

  • Qwen
  • DeepSeek
  • GLM
  • Kimi
  • MiniMax
  • Text generation models
    • Qwen Max: Qwen4-Max series, Qwen3.8-Max series, Qwen3.7-Max series, Qwen3.6-Max series, Qwen3-Max series, Qwen-Max series
    • Qwen Plus: Qwen3.7-Plus series, Qwen3.6-Plus series, Qwen3.5-Plus series, Qwen-Plus series
    • Qwen Flash: Qwen3.8-Flash series, Qwen3.7-Flash series, Qwen3.6-Flash series, Qwen3.5-Flash series, Qwen-Flash series
    • Qwen Coder: Qwen3-Coder series, Qwen2.5-Coder series, Qwen-Coder series
    • Qwen Turbo: Qwen-Turbo series
    • Qwen3.6 open-source series
    • Qwen3.5 open-source series
    • Qwen3 open-source series
    • Qwen2.5 open-source series
    • Qwen3.8 open-source series
  • Multimodal models
    • Qwen VL: Qwen3-VL-Plus series, Qwen3-VL-Flash series
    • Qwen Omni: Qwen3.8-Omni-Flash, Qwen3.5-Omni-Plus series, Qwen3.5-Omni-Flash series, Qwen3-Omni-Flash series
    • Qwen Omni-Realtime: Qwen3.8-Omni-Flash-Realtime, Qwen3.5-Omni-Plus-Realtime series, Qwen3.5-Omni-Flash-Realtime series
    • Qwen3-VL open-source series
  • Voice conversation models
    • Qwen-Audio-Realtime: Qwen-Audio-3.1-Realtime-Plus, Qwen-Audio-3.1-Realtime-Flash, Qwen-Audio-3.0-Realtime-Plus series, Qwen-Audio-3.0-Realtime-Flash series
    • Qwen-Audio-Live: Declare functions in the Realtime API session and return their results.

QuickStart

You must have already obtained and configured an API Key and configured the API Key in environment variables. If you call via the OpenAI SDK or DashScope SDK, you also need to install the SDK. The following example demonstrates the complete Function Calling workflow for a weather query scenario.
  • OpenAI compatible
  • DashScope
python
from openai import OpenAI
from datetime import datetime
import json
import os
import random

client = OpenAI(
    # API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    # If the environment variable is unset, replace the next line with your Model Studio API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region. Replace {WorkspaceId} with your actual Workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# Simulate a user question
USER_QUESTION = "新加坡天气咋样"
# Define the tool list
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如新加坡、纽约等。",
                    }
                },
                "required": ["location"],
            },
        },
    },
]

# Simulate a weather query tool
def get_current_weather(arguments):
    weather_conditions = ["晴天", "多云", "雨天"]
    random_weather = random.choice(weather_conditions)
    location = arguments["location"]
    return f"{location}今天是{random_weather}。"

# Encapsulate the model response function
def get_response(messages):
    completion = client.chat.completions.create(
        model="qwen4-max",
        extra_body={"enable_thinking": False},
        messages=messages,
        tools=tools,
    )
    return completion

messages = [{"role": "user", "content": USER_QUESTION}]
response = get_response(messages)
assistant_output = response.choices[0].message
if assistant_output.content is None:
    assistant_output.content = ""
messages.append(assistant_output)
# If no tool call is needed, print the content directly
if assistant_output.tool_calls is None:
    print(f"无需调用天气查询工具,直接回复:{assistant_output.content}")
else:
    # Enter the tool calling loop
    while assistant_output.tool_calls is not None:
        # Process all tool calls in this turn to avoid omitting results from calls after the first
        for tool_call in assistant_output.tool_calls:
            tool_call_id = tool_call.id
            func_name = tool_call.function.name
            arguments = json.loads(tool_call.function.arguments)
            print(f"正在调用工具 [{func_name}],参数:{arguments}")
            # Run the tool
            tool_result = get_current_weather(arguments)
            # Construct the tool return message
            tool_message = {
                "role": "tool",
                "tool_call_id": tool_call_id,
                "content": tool_result,  # Keep the original tool output
            }
            print(f"工具返回:{tool_message['content']}")
            messages.append(tool_message)
        # Call the model again to get a summarized natural language response
        response = get_response(messages)
        assistant_output = response.choices[0].message
        if assistant_output.content is None:
            assistant_output.content = ""
        messages.append(assistant_output)
    print(f"助手最终回复:{assistant_output.content}")
After running, you get the following output:
正在调用工具 [get_current_weather],参数:{'location': '新加坡'}
工具返回:新加坡今天是多云。
助手最终回复:新加坡今天是多云的天气。

How to use

Function Calling supports two ways to pass in tool information:
  • Method 1: Pass in via the tools parameter (recommended) See How to use and follow the steps: define tools, create the messages array, initiate Function Calling, run tool functions, and have the model summarize the tool function output.
  • Method 2: Pass in via a System Message Passing tools in through the tools parameter works best; the server automatically adapts the optimal prompt template. If you use a Qwen model and do not expect to use the tools parameter, see Passing tool information via a System Message.
The following uses the OpenAI-compatible API as an example to introduce the detailed usage of Function Calling step by step through the tools parameter. Assume that the business scenario receives two types of questions: weather queries and time queries.

1. Define tools

Tools connect large models with external services, so you need to define the tools first.

1.1. Create tool functions

Create two tool functions: a weather query tool and a time query tool.
  • Weather query tool It accepts an arguments parameter, where arguments is in the format {"location": "Location to query"}. The output of the tool is a string in the format: "{Location} today is {weather}".
    For demonstration purposes, the weather query tool defined here does not actually query the weather; it randomly selects from sunny, cloudy, or rainy. In actual business, you can replace it with tools such as the Amap Weather Query API.
  • Time query tool The time query tool does not require input parameters. The output of the tool is a string in the format: "Current time: {queried time}.".
    If you use Node.js, run npm install date-fns to install date-fns, a package for obtaining the time:
python
## Step 1.1: Define tool functions

# Add the import for the random module
import random
from datetime import datetime

# Simulate a weather query tool. Example output: "The weather in Beijing today is rainy."
def get_current_weather(arguments):
    # Define a list of alternative weather conditions
    weather_conditions = ["晴天", "多云", "雨天"]
    # Randomly select a weather condition
    random_weather = random.choice(weather_conditions)
    # Extract location information from JSON
    location = arguments["location"]
    # Return the formatted weather information
    return f"{location}今天是{random_weather}。"

# A tool to query the current time. Example output: "Current time: 2024-04-15 17:15:18."
def get_current_time():
    # Get the current date and time
    current_datetime = datetime.now()
    # Format the current date and time
    formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
    # Return the formatted current time
    return f"当前时间:{formatted_time}。"

# Test the tool functions and print the results. You can remove the following four lines of test code when running the subsequent steps.
print("测试工具输出:")
print(get_current_weather({"location": "上海"}))
print(get_current_time())
print("\n")
After running the tool, you get the output:
测试工具输出:
上海今天是多云。
当前时间:2025-01-08 20:21:45。

1.2 Create the tools array

Before selecting a tool, humans need to understand the tool's function, use cases, and input parameters. The same applies to large models—the model selects the appropriate tool based on this information. Provide tool information in the following JSON format.
  • The type field is fixed to "function";
  • The function field is of Object type;
    • The name field is the custom name of the tool function; it is recommended to use the same name as the function, such as get_current_weather or get_current_time;
    • The description field describes the function of the tool function; the large model refers to this field to decide whether to use the tool function.
    • The parameters field describes the input parameters of the tool function and is of Object type; the large model refers to this field to extract input parameters. If the tool function does not require input parameters, you do not need to specify the parameters parameter.
      • The type field is fixed to "object";
      • The properties field describes the name, data type, and description of the input parameters; it is of Object type, where the Key is the name of an input parameter and the Value is the data type and description of the input parameter;
      • The required field specifies which parameters are required and is of Array type.
For the weather query tool, the tool description information is in the following format:
{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "当你想查询指定城市的天气时非常有用。",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "城市或县区,比如北京市、杭州市、余杭区等。"
                }
            },
            "required": ["location"]
        }
    }
}
Before initiating Function Calling, define a tool information array (tools) in the code, which contains the function name, description, and parameter definitions of each tool. This array is passed in as a parameter in subsequent requests.
python
# Paste the following code after the code in Step 1.1

## Step 1.2: Create the tools array

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "当你想知道现在的时间时非常有用。",
            "parameters": {}
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。",
                    }
                },
                "required": ["location"]
            }
        }
    }
]
tool_name = [tool["function"]["name"] for tool in tools]
print(f"创建了{len(tools)}个工具,为:{tool_name}\n")

2. Create the messages array

Function Calling passes instructions and context to the large model through the messages array. Before initiating the call, the messages array must contain a System Message and a User Message.

System Message

Although the tool functions and use cases have already been described when creating the tools array, further emphasizing in the System Message when to call tools usually improves the accuracy of tool calling. In this scenario, you can set the System Prompt to:
你是一个很有帮助的助手。如果用户提问关于天气的问题,请调用 ‘get_current_weather’ 函数;
如果用户提问关于时间的问题,请调用‘get_current_time’函数。
请以友好的语气回答问题。

User Message

The User Message is used to pass in the user's question. Assume the user asks "What's the weather in Shanghai"; the messages array at this point is:
python
# Step 2: Create the messages array
# Paste the following code after the code in Step 1.2
# Example User Message for a text generation model
messages = [
    {
        "role": "system",
        "content": """你是一个很有帮助的助手。如果用户提问关于天气的问题,请调用 ‘get_current_weather’ 函数;
     如果用户提问关于时间的问题,请调用‘get_current_time’函数。
     请以友好的语气回答问题。""",
    },
    {
        "role": "user",
        "content": "上海天气"
    }
]

# Example User Message for a multimodal model
# messages=[
#  {
#         "role": "system",
#         "content": """You are a helpful assistant. If the user asks about the weather, call the 'get_current_weather' function;
#      if the user asks about the time, call the 'get_current_time' function.
#      Please answer the questions in a friendly tone.""",
#     },
#     {"role": "user",
#      "content": [{"type": "image_url","image_url": {"url": "https://img.alicdn.com/imgextra/i2/O1CN01FbTJon1ErXVGMRdsN_!!6000000000405-0-tps-1024-683.jpg"}},
#                  {"type": "text", "text": "Query the current weather for the location in the image"}]},
# ]

print("messages 数组创建完成\n")
Since the available tools include weather query and time query, you can also ask questions about the current time.

3. Initiate Function Calling

Pass the created tools and messages to the large model to initiate a Function Calling. The large model determines whether to call a tool. If a tool is called, it returns the function name and parameters of that tool.
For supported models, see Supported models.
python
# Step 3: Make the function calling request
# Paste the following code after the code in Step 2
from openai import OpenAI
import os

client = OpenAI(
    # API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    # If the environment variable is unset, replace the next line with your Model Studio API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region. Replace {WorkspaceId} with your actual Workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

def function_calling():
    completion = client.chat.completions.create(
        # This example uses qwen4-max. You can change the model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
        model="qwen4-max",
        extra_body={"enable_thinking": False},
        messages=messages,
        tools=tools
    )
    print("返回对象:")
    print(completion.choices[0].message.model_dump_json())
    print("\n")
    return completion

print("正在发起function calling...")
completion = function_calling()
Since the user's question is about the weather in Shanghai, the large model specifies the name of the tool function to use as: "get_current_weather", and the input parameter of the function as: "{\"location\": \"Shanghai\"}".
{
    "content": "",
    "refusal": null,
    "role": "assistant",
    "audio": null,
    "function_call": null,
    "tool_calls": [
        {
            "id": "call_6596dafa2a6a46f7a217da",
            "function": {
                "arguments": "{\"location\": \"上海\"}",
                "name": "get_current_weather"
            },
            "type": "function",
            "index": 0
        }
    ]
}
Note that if the large model determines that the question does not require a tool, it replies directly through the content parameter. When the input is "Hello", the tool_calls parameter is empty, and the returned object is in the format:
{
    "content": "你好!有什么可以帮助你的吗?如果你有关于天气或者时间的问题,我特别擅长回答。",
    "refusal": null,
    "role": "assistant",
    "audio": null,
    "function_call": null,
    "tool_calls": null
}
If the tool_calls parameter is empty, you can have the program directly return content without running the following steps.
If you want the model to be able to select a specified tool each time after initiating Function Calling, see Force tool calling .

4. Run the tool function

Running the tool function turns the model's decision into an actual operation.
The process of running the tool function is performed by your computing environment, not the model.
The model only outputs a string format. Before running the tool function, you need to parse the tool function name and input parameters separately.
  • Tool function Create a mapping from tool function name to tool function entity via function_mapper, which maps the returned tool function string to the actual tool function entity;
  • Input parameters The input parameters returned by Function Calling are a JSON string. Use a tool to parse it into a JSON object and extract the input parameter information.
After parsing, pass the parameters to the tool function and execute it to obtain the output result.
python
# Step 4: Run the tool function
# Paste the following code after the code in Step 3
import json

print("正在执行工具函数...")
# Get the function name and input parameters from the returned result
function_name = completion.choices[0].message.tool_calls[0].function.name
arguments_string = completion.choices[0].message.tool_calls[0].function.arguments

# Use the json module to parse the parameter string
arguments = json.loads(arguments_string)
# Create a function mapping table
function_mapper = {
    "get_current_weather": get_current_weather,
    "get_current_time": get_current_time
}
# Get the function entity
function = function_mapper[function_name]
# If the input parameter is empty, call the function directly
if arguments == {}:
    function_output = function()
# Otherwise, pass the parameters and then call the function
else:
    function_output = function(arguments)
# Print the tool's output
print(f"工具函数输出:{function_output}\n")
After running, you get the following output:
上海今天是多云。
In actual business, many tools perform specific operations (such as email sending or file upload) rather than data queries and do not output strings. It is recommended to add status description information for such tools (such as "Email sent" or "Operation failed") to help the model understand the execution status.

5. The model summarizes the tool function output

The output format of a tool function is relatively fixed, and directly returning it to the user may sound stiff. By submitting the tool output to the model context and calling the model again, you can generate a reply in natural language style.
  1. Add the Assistant Message After initiating Function Calling, use completion.choices[0].message to get the Assistant Message, and first add it to the messages array;
  2. Add the Tool Message Add the tool output to the messages array in the form of {"role": "tool", "content": "工具的输出","tool_call_id": completion.choices[0].message.tool_calls[0].id}.
    • The output of a tool is usually a string. When the model needs to understand images produced by the tool, content can accept a content array, for example [{"type": "text", "text": "Image generated successfully."}, {"type": "image_url", "image_url": {"url": "https://example.com/image.png"}}], where url supports public-network URLs or Base64 Data URIs. When an image URL is passed as a string, it is treated as plain text and not parsed as an image.
    • tool_call_id is a unique identifier generated by the system for each tool call request. The model may request calling multiple tools at once; when returning multiple tool results to the model, tool_call_id ensures that each tool's output can be matched to its calling intent.
python
# Step 5.1: Submit the tool output to the LLM
# Paste the following code after the code in Step 4

messages.append(completion.choices[0].message)
print("已添加assistant message")
messages.append({"role": "tool", "content": function_output, "tool_call_id": completion.choices[0].message.tool_calls[0].id})
print("已添加tool message\n")
At this point, the messages array is:
[
  System Message -- 指引模型调用工具的策略
  User Message -- 用户的问题
  Assistant Message -- 模型返回的工具调用信息
  Tool Message -- 工具的输出信息(如果采用下文介绍的并行工具调用,可能有多个 Tool Message)
]
After updating the messages array, run the following code.
python
# Step 5.2: Have the LLM summarize the tool output
# Paste the following code after the code in Step 5.1
print("正在总结工具输出...")
completion = function_calling()
You can get the reply content from content: "The weather in Shanghai is cloudy today. If you have other questions, feel free to keep asking."
{
    "content": "上海今天的天气是多云。如果您有其他问题,欢迎继续提问。",
    "refusal": null,
    "role": "assistant",
    "audio": null,
    "function_call": null,
    "tool_calls": null
}
At this point, you have completed a complete Function Calling process.

Advanced usage

Specify the tool calling mode

Parallel tool calling

kimi-k3 does not support controlling the parallelism of tool calling through parallel_tool_calls: even when set to false, it may still return multiple tool_calls in one round. The caller needs to traverse and handle all the tool calls actually returned.
A single-city weather query requires only one tool call. If a question requires multiple tool calls, such as "What is the weather in Beijing and Shanghai" or "Weather in Hangzhou, and what time is it now", since parallel_tool_calls defaults to true, after initiating Function Calling, the model can include multiple tool call messages in a single response. Taking the question "What is the weather in Beijing and Shanghai" as an example, the tool_calls array in the returned object contains the input parameter information for Beijing and Shanghai:
{
    "content": "",
    "role": "assistant",
    "tool_calls": [
        {
            "function": {
                "name": "get_current_weather",
                "arguments": "{\"location\": \"北京市\"}"
            },
            "index": 0,
            "id": "call_c2d8a3a24c4d4929b26ae2",
            "type": "function"
        },
        {
            "function": {
                "name": "get_current_weather",
                "arguments": "{\"location\": \"上海市\"}"
            },
            "index": 1,
            "id": "call_dc7f2f678f1944da9194cd",
            "type": "function"
        }
    ]
}
If you want the model to return only one tool call at a time, set the request parameter parallel_tool_calls to false when initiating Function Calling:
python
def function_calling():
    completion = client.chat.completions.create(
        model="qwen4-max",  # This example uses qwen4-max. You can change the model name as needed.
        extra_body={"enable_thinking": False},
        messages=messages,
        tools=tools,
        # When set to False, only one tool call is returned at a time
        parallel_tool_calls=False
    )
    print("返回对象:")
    print(completion.choices[0].message.model_dump_json())
    print("\n")
    return completion

print("正在发起function calling...")
completion = function_calling()
The returned result only contains the input parameter information of Beijing:
{
    "content": "",
    "refusal": null,
    "role": "assistant",
    "audio": null,
    "function_call": null,
    "tool_calls": [
        {
            "id": "call_61a2bbd82a8042289f1ff2",
            "function": {
                "arguments": "{\"location\": \"北京市\"}",
                "name": "get_current_weather"
            },
            "type": "function",
            "index": 0
        }
    ]
}
Parallel tool calling is suitable for cases where tasks have no dependencies on each other. If tasks are dependent (the input of tool A is related to the output of tool B), see QuickStart to implement serial tool calling (calling one tool at a time) with a while loop.

Force tool calling

The content generated by LLMs is non-deterministic and may select the wrong tool. To force the use of or disable a specific tool for a certain type of question, modify the tool_choice parameter. The default value of the tool_choice parameter is "auto", which means the LLM autonomously decides how to perform tool calling.
When the LLM summarizes tool function output, remove the tool_choice parameter; otherwise, the API will still return tool call information.
  • Force the use of a specific tool If you want Function Calling to force the invocation of a specific tool for a certain type of question, set the tool_choice parameter to {"type": "function", "function": {"name": "the_function_to_call"}}. The LLM will not participate in tool selection and will only output parameter information. Assume the current scenario only involves weather query questions. You can modify the function_calling code as follows:
def function_calling():
    completion = client.chat.completions.create(
        model="qwen4-max",
        extra_body={"enable_thinking": False},
        messages=messages,
        tools=tools,
        tool_choice={"type": "function", "function": {"name": "get_current_weather"}}
    )
    print(completion.model_dump_json())

function_calling()
async function functionCalling() {
    const response = await openai.chat.completions.create({
        model: "qwen4-max",
        enable_thinking: false,
        messages: messages,
        tools: tools,
        tool_choice: {"type": "function", "function": {"name": "get_current_weather"}}
    });
    console.log("返回对象:");
    console.log(JSON.stringify(response.choices[0].message));
    console.log("\n");
    return response;
}

const response = await functionCalling();
Regardless of the input question, the tool function in the returned object will always be get_current_weather.
Before using this strategy, make sure the questions are relevant to the selected tool; otherwise, unexpected results may be returned.
Force the use of at least one tool For some questions that require tools, the LLM may judge that no tool call is needed. To force Function Calling to always perform tool calling (the tool_calls parameter in the returned object is not empty), set the tool_choice parameter to "required", and Function Calling will always return tool and parameter information.
Qwen series models do not currently support setting tool_choice to "required": in non-thinking mode, required cannot guarantee that a tool will be called, and in thinking mode, "required" is currently not supported.
Assume the questions in the current scenario all require tool calls. You can modify the function_calling code as follows:
python
def function_calling():
    completion = client.chat.completions.create(
        model="kimi/kimi-k3",
        messages=messages,
        tools=tools,
        tool_choice="required"
    )
    print(completion.model_dump_json())

function_calling()
Regardless of the input question, the tool_calls parameter in the returned object will never be empty.
Before using this strategy, make sure the questions are relevant to the tool; otherwise, unexpected results may be returned.
  • Force no tool usage If you want Function Calling to never perform tool calls (the returned object contains the response content content while the tool_calls parameter is empty), set the tool_choice parameter to "none", or do not pass in the tools parameter. The tool_calls parameter returned by Function Calling will always be empty. Assume the questions in the current scenario do not require any tool calls. You can modify the function_calling code as follows:
def function_calling():
    completion = client.chat.completions.create(
        model="qwen4-max",
        extra_body={"enable_thinking": False},
        messages=messages,
        tools=tools,
        tool_choice="none"
    )
    print(completion.model_dump_json())

function_calling()
async function functionCalling() {
    const completion = await openai.chat.completions.create({
        model: "qwen4-max",
        enable_thinking: false,
        messages: messages,
        tools: tools,
        tool_choice: "none"
    });
    console.log("返回对象:");
    console.log(JSON.stringify(completion.choices[0].message));
    console.log("\n");
    return completion;
}

const completion = await functionCalling();

Multi-turn conversations

A user may ask about the "weather in Beijing" in the first turn and "what about Shanghai?" in the second. If the model context lacks the information from the first turn, the model cannot determine which tool to call. In multi-turn scenarios, keep the messages array intact after each turn, add the User Message on that basis, and then initiate Function Calling and the subsequent steps. The messages structure is as follows:
[
  System Message -- 指引模型调用工具的策略
  User Message -- 用户的问题
  Assistant Message -- 模型返回的工具调用信息
  Tool Message -- 工具的输出信息
  Assistant Message -- 模型总结的工具调用信息
  User Message -- 用户第二轮的问题
]

Streaming output

Streaming output lets you obtain tool function names and parameter information in real time, improving user experience. Specifically:
  • Parameter information of tool calls: returned in chunks as a data stream.
  • Tool function names: returned in the first data chunk of the streaming response.
python
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region. Replace {WorkspaceId} with your actual Workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如新加坡市、杭州市、余杭区等。",
                    }
                },
                "required": ["location"],
            },
        },
    },
]

stream = client.chat.completions.create(
    model="qwen4-max",
    extra_body={"enable_thinking": False},
    messages=[{"role": "user", "content": "杭州天气?"}],
    tools=tools,
    stream=True
)

for chunk in stream:
    delta = chunk.choices[0].delta
    print(delta.tool_calls)
After running, you get the following output:
[ChoiceDeltaToolCall(index=0, id='call_8f08d2b0fc0c4d8fab7123', function=ChoiceDeltaToolCallFunction(arguments='{"location":', name='get_current_weather'), type='function')]
[ChoiceDeltaToolCall(index=0, id='', function=ChoiceDeltaToolCallFunction(arguments=' "杭州"}', name=None), type='function')]
None
Run the following code to assemble the parameter information (arguments):
python
tool_calls = {}
for response_chunk in stream:
    delta_tool_calls = response_chunk.choices[0].delta.tool_calls
    if delta_tool_calls:
        for tool_call_chunk in delta_tool_calls:
            call_index = tool_call_chunk.index
            tool_call_chunk.function.arguments = tool_call_chunk.function.arguments or ""
            if call_index not in tool_calls:
                tool_calls[call_index] = tool_call_chunk
            else:
                tool_calls[call_index].function.arguments += tool_call_chunk.function.arguments
print(tool_calls[0].model_dump_json())
The following output is obtained:
{"index":0,"id":"call_16c72bef988a4c6c8cc662","function":{"arguments":"{\"location\": \"杭州\"}","name":"get_current_weather"},"type":"function"}
In the step where the LLM summarizes tool function output, the added Assistant Message must follow the format below. Simply replace the elements in tool_calls below with the above content.
{
    "content": "",
    "refusal": None,
    "role": "assistant",
    "audio": None,
    "function_call": None,
    "tool_calls": [
        {
            "id": "call_xxx",
            "function": {
                "arguments": '{"location": "xx"}',
                "name": "get_current_weather",
            },
            "type": "function",
            "index": 0,
        }
    ],
}

Tool calling with the Responses API

The above examples are based on the OpenAI Chat Completions and DashScope APIs. If you use the OpenAI Responses API, the overall process is the same, but the API formats differ as follows:
DimensionChat CompletionsResponses API
Tool definition format
{
    "type": "function",
    "function": {
        "name":...,
        "parameters":...
    }
}
{
    "type": "function",
    "name":...,
    "parameters":...
}
Tool call outputresponse.choices[0].message.tool_callsThe item in response.output whose type is function_call
Returning tool results
{
    "role": "tool",
    "tool_call_id":...,
    "content":...
}
{
    "type": "function_call_output",
    "call_id":...,
    "output":...
}
Final responseresponse.choices[0].message.contentresponse.output_text
Both APIs support two forms for tool results: string and content array. In the Responses API, the element types of the output array are input_text and input_image; image_url takes a URL or Base64 Data URI directly, without nested objects. For field descriptions, see Create a response.
python
from openai import OpenAI
import json
import os
import random

# Initialize the client
client = OpenAI(
    # If the environment variable is unset, replace the next line with your Model Studio API key: api_key="sk-xxx",
    # API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# Simulate a user question
USER_QUESTION = "新加坡天气咋样"
# Define the tool list
tools = [
    {
        "type": "function",
        "name": "get_current_weather",
        "description": "当你想查询指定城市的天气时非常有用。",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "城市或县区,比如新加坡、伦敦等。",
                }
            },
            "required": ["location"],
        },
    }
]

# Simulate a weather query tool
def get_current_weather(arguments):
    weather_conditions = ["晴天", "多云", "雨天"]
    random_weather = random.choice(weather_conditions)
    location = arguments["location"]
    return f"{location}今天是{random_weather}。"

# Encapsulate the model response function
def get_response(input_data):
    response = client.responses.create(
        model="qwen4-max",
        extra_body={"enable_thinking": False},
        input=input_data,
        tools=tools,
    )
    return response

# Maintain the conversation context
conversation = [{"role": "user", "content": USER_QUESTION}]

response = get_response(conversation)
function_calls = [item for item in response.output if item.type == "function_call"]
# If no tool call is needed, print the content directly
if not function_calls:
    print(f"助手最终回复:{response.output_text}")
else:
    # Enter the tool calling loop
    while function_calls:
        for fc in function_calls:
            func_name = fc.name
            arguments = json.loads(fc.arguments)
            print(f"正在调用工具 [{func_name}],参数:{arguments}")
            # Run the tool
            tool_result = get_current_weather(arguments)
            print(f"工具返回:{tool_result}")
            # Append the tool call and result as a pair to the context
            conversation.append(
                {
                    "type": "function_call",
                    "name": fc.name,
                    "arguments": fc.arguments,
                    "call_id": fc.call_id,
                }
            )
            conversation.append(
                {
                    "type": "function_call_output",
                    "call_id": fc.call_id,
                    "output": tool_result,
                }
            )
        # Call the model again with the full context
        response = get_response(conversation)
        function_calls = [
            item for item in response.output if item.type == "function_call"
        ]
    print(f"助手最终回复:{response.output_text}")

Tool calling for omni models

Omni models support tool calling. The Qwen-Omni series and the Qwen-Omni-Realtime series are called in different ways.

Qwen-Omni series

For text tool calling, use qwen3.8-omni-flash, which can be accessed through Chat Completions or Responses. The following Python and JavaScript examples use Chat Completions, with thinking disabled and text and tool call increments read in streaming mode. For audio and video input, see Qwen3.8-Omni-Flash. The example sets reasoning_effort="none" to disable thinking. To perform tool calling with thinking, you can omit this parameter, use the default xhigh, and read reasoning_content, content, and tool_calls separately. In this case, multi-turn requests must add the thinking content, response, and tool calls of the assistant message from the previous turn to the history before passing in tool results; preserve_thinking is enabled by default. For more information, see Passing the thinking process. First, install the OpenAI SDK, configure DASHSCOPE_API_KEY, and set DASHSCOPE_BASE_URL to the Chat Completions endpoint of your workspace. The API Key and the endpoint must use the same region.
python
from openai import OpenAI
import os

client = OpenAI(
    # API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),

    base_url=os.environ["DASHSCOPE_BASE_URL"],
)
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。",
                    }
                },
                "required": ["location"],
            },
        },
    },
]

completion = client.chat.completions.create(
    model="qwen3.8-omni-flash",
    reasoning_effort="none",
    messages=[{"role": "user", "content": "杭州天气?"}],
    stream=True,
    tools=tools
)

for chunk in completion:
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    if delta.content:
        print("Text:", delta.content)
    if delta.tool_calls:
        print(delta.tool_calls)
The format of Python tool call increments is illustrated below; the actual content is returned by the model, and the function name and arguments may arrive in multiple data chunks:
[ChoiceDeltaToolCall(index=0, id='call_391c8e5787bc4972a388aa', function=ChoiceDeltaToolCallFunction(arguments=None, name='get_current_weather'), type='function')]
[ChoiceDeltaToolCall(index=0, id='call_391c8e5787bc4972a388aa', function=ChoiceDeltaToolCallFunction(arguments=' {"location": "杭州市"}', name=None), type='function')]
For the code that assembles the input parameter information (arguments), see Streaming output.
Existing calls to Qwen3.5-Omni-Plus, Qwen3.5-Omni-Flash, and Qwen3-Omni-Flash must set stream=True. You can use modalities=["text"] to obtain tool information; when Qwen3.5-Omni also outputs audio, you need to skip the audio data chunks.

Qwen-Omni-Realtime series

Qwen3.8-Omni-Flash-Realtime, Qwen3.5-Omni-Plus-Realtime, and Qwen3.5-Omni-Flash-Realtime support custom Function Calling, suitable for voice conversation scenarios. The following flows are invoked through the DashScope SDK or the native WebSocket protocol. For access methods and SDK configuration, see the Realtime calling guide. For the server-side MCP tool calling and approval flows of Qwen3.8-Omni-Flash-Realtime, see MCP interaction flow. Workflow: After a WebSocket connection is established, pass in tool definitions via session.update to enter the following interaction flow: Phase 1: Voice input and tool calling
  1. The user initiates a voice question, and the client captures the audio and sends it to the server (corresponding to the append_audio() method). After the server-side VAD detects the end of the speech, the model performs inference and determines that a tool needs to be called.
  2. The server returns the tool call information to the client (corresponding to the response.function_call_arguments.done event), including the function name (name), function input parameters (arguments), and the call identifier (call_id). An example is as follows:
{
    "type": "response.function_call_arguments.done",
    "response_id": "resp_JnTOsWXlFhKcFohZbtfz6",
    "item_id": "item_Rhcms7CauTNsQprV5S4Hr",
    "output_index": 0,
    "name": "get_current_weather",
    "call_id": "call_2be200f4cafe419b9530dd",
    "arguments": "{\"location\": \"杭州\"}"
}
  1. Based on the function name and input parameters, the client executes the corresponding tool function locally and obtains the execution result.
Phase 2: The client returns tool results and triggers the final response
  1. The client sends the tool execution result back to the server (corresponding to the conversation.item.create event), including the call identifier (call_id) and the execution result (output). An example is as follows:
{
    "type": "conversation.item.create",
    "item": {
        "type": "function_call_output",
        "call_id": "call_2be200f4cafe419b9530dd",
        "output": "杭州今天天气为晴,气温25℃,微风"
    }
}
  1. The client then sends the response.create event, triggering the server to generate the final voice response based on the tool execution result.
  2. The client receives the voice and text returned by the server (corresponding to the response.audio.delta and response.audio_transcript.delta events) and plays the voice response to the user.
The Qwen-Omni-Realtime series does not support the tool_choice and parallel_tool_calls parameters.
For more information about Qwen-Omni-Realtime, see Realtime (Qwen-Omni-Realtime), Client events, and Server events.
DashScope Python SDK
# DashScope Python SDK v1.25.17
import os
import uuid
import threading
import traceback
import json
import base64
import signal
import sys
import time
from typing import Dict, Any, Optional, List
import pyaudio
import queue
import contextlib
import dashscope
from dashscope.audio.qwen_omni import *

# ==================== Constant Definitions ====================
VOICE = 'Tina'
MODEL = "qwen3.5-omni-plus-realtime"
# To access the Beijing region, replace WS_URL with: wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/realtime
WS_URL = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime"
# Configure the API key. If the environment variable is unset, replace the next line with dashscope.api_key = "sk-xxx"
dashscope.api_key = os.getenv('DASHSCOPE_API_KEY')
AUDIO_SAMPLE_RATE = 16000
AUDIO_CHUNK_SIZE = 3200
OUTPUT_AUDIO_SAMPLE_RATE = 24000

# ==================== Tool Definitions ====================
def get_train_price(src: str, dst: str) -> str:
    """查询火车票价格"""
    return f"{src}到{dst}的火车票价格为100~200元。"

def get_flight_price(src: str, dst: str) -> str:
    """查询飞机票价格"""
    return f"{src}到{dst}的机票价格为200~300美元。"

def get_current_weather(location: str) -> str:
    """查询指定城市天气"""
    return f"{location}今天天气为霾转晴,气温4/-4℃,微风"

# Unified OpenAI format tool definitions
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。",
                    }
                },
                "required": ["location"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_flight_price",
            "description": "当你想查询飞机票价格时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "src": {
                        "type": "string",
                        "description": "飞机起飞的城市,比如北京市、杭州市等。",
                    },
                    "dst": {
                        "type": "string",
                        "description": "飞机降落的城市,比如北京市、杭州市区等。",
                    },
                },
                "required": ["src", "dst"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_train_price",
            "description": "当你想查询火车票价格时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "src": {
                        "type": "string",
                        "description": "火车出发的城市,比如北京市、杭州市等。",
                    },
                    "dst": {
                        "type": "string",
                        "description": "火车到达的城市,比如北京市、杭州市区等。",
                    },
                },
                "required": ["src", "dst"],
            },
        },
    },
]

# Mapping of tool names to functions
TOOL_FUNCTIONS = {
    "get_current_weather": get_current_weather,
    "get_flight_price": get_flight_price,
    "get_train_price": get_train_price,
}

# ==================== Tool Call Handling ====================
def handle_tool_call(tool_call_response: Dict[str, Any]) -> Dict[str, Any]:
    """
    处理工具调用请求

    Args:
        tool_call_response: 包含 name, arguments, call_id 的工具调用信息

    Returns:
        更新后的工具调用响应,包含 output 字段
    """
    try:
        function_name = tool_call_response['name']
        tool_call_arguments = json.loads(tool_call_response['arguments'])

        print(f'[Tool Call] 开始处理: name={function_name}, args={tool_call_arguments}')

        # Find the corresponding function
        if function_name not in TOOL_FUNCTIONS:
            tool_call_response['output'] = f"客户端未找到工具: {function_name}"
            print(f'[Tool Call] 错误: 未找到工具 {function_name}')
            return tool_call_response

        # Call the function
        func = TOOL_FUNCTIONS[function_name]
        result = func(**tool_call_arguments)
        tool_call_response['output'] = result

        print(f'[Tool Call] 完成: {result}')
        return tool_call_response

    except Exception as e:
        error_msg = f"工具调用失败: {str(e)}"
        tool_call_response['output'] = error_msg
        print(f'[Tool Call] 异常: {error_msg}')
        traceback.print_exc()
        return tool_call_response

def send_tool_call_response(conversation: OmniRealtimeConversation, response: Dict[str, Any]) -> None:
    """发送工具调用结果到服务端"""
    conversation.create_item({
        "id": 'item_' + uuid.uuid4().hex,
        "type": "function_call_output",
        "call_id": response['call_id'],
        "output": response["output"],
    })

# ==================== PCM Audio Player ====================
class PCMPlayer:
    """
    PCM 音频播放器

    使用双线程架构实现实时音频播放:
    - 解码线程:将 base64 编码的音频数据解码为原始 PCM 数据
    - 播放线程:将 PCM 数据写入音频输出设备

    支持动态添加音频数据、取消播放、保存音频文件等功能。
    """

    def __init__(self, pya: pyaudio.PyAudio, sample_rate=24000, chunk_size_ms=100, save_file=False):
        """
        初始化 PCM 播放器

        Args:
            pya: pyaudio.PyAudio 实例
            sample_rate: 音频采样率(Hz),默认 24000
            chunk_size_ms: 音频块大小(毫秒),影响取消播放的延迟,默认 100ms
            save_file: 是否保存播放的音频到文件(result.pcm),默认 False
        """

        self.pya = pya
        self.sample_rate = sample_rate
        self.chunk_size_bytes = chunk_size_ms * sample_rate * 2 // 1000
        self.player_stream = pya.open(format=pyaudio.paInt16,
                                       channels=1,
                                       rate=sample_rate,
                                       output=True)

        self.raw_audio_buffer: queue.Queue = queue.Queue()
        self.b64_audio_buffer: queue.Queue = queue.Queue()
        self.status_lock = threading.Lock()
        self.status = 'playing'
        self.decoder_thread = threading.Thread(target=self.decoder_loop)
        self.player_thread = threading.Thread(target=self.player_loop)
        self.decoder_thread.start()
        self.player_thread.start()
        self.complete_event: threading.Event = None
        self.save_file = save_file
        if self.save_file:
            self.out_file = open('result.pcm', 'wb')

    def decoder_loop(self):
        """解码线程:将 base64 音频数据解码为 PCM 原始数据"""
        while self.status != 'stop':
            recv_audio_b64 = None
            with contextlib.suppress(queue.Empty):
                recv_audio_b64 = self.b64_audio_buffer.get(timeout=0.1)
            if recv_audio_b64 is None:
                continue
            recv_audio_raw = base64.b64decode(recv_audio_b64)
            # push raw audio data into queue by chunk
            for i in range(0, len(recv_audio_raw), self.chunk_size_bytes):
                chunk = recv_audio_raw[i:i + self.chunk_size_bytes]
                self.raw_audio_buffer.put(chunk)
                if self.save_file:
                    self.out_file.write(chunk)

    def player_loop(self):
        """播放线程:将 PCM 数据写入音频输出设备"""
        while self.status != 'stop':
            recv_audio_raw = None
            with contextlib.suppress(queue.Empty):
                recv_audio_raw = self.raw_audio_buffer.get(timeout=0.1)
            if recv_audio_raw is None:
                if self.complete_event:
                    self.complete_event.set()
                continue
            # write chunk to pyaudio audio player, wait until finish playing this chunk.
            self.player_stream.write(recv_audio_raw)

    def cancel_playing(self):
        """取消播放:清空所有缓冲队列"""
        self.b64_audio_buffer.queue.clear()
        self.raw_audio_buffer.queue.clear()

    def add_data(self, data):
        """添加 base64 编码的音频数据到播放队列"""
        self.b64_audio_buffer.put(data)

    def wait_for_complete(self):
        """等待播放完成"""
        self.complete_event = threading.Event()
        self.complete_event.wait()
        self.complete_event = None

    def shutdown(self):
        """关闭播放器并释放资源"""
        self.status = 'stop'
        self.decoder_thread.join()
        self.player_thread.join()
        self.player_stream.close()
        if self.save_file:
            self.out_file.close()

# ==================== Audio Manager ====================
class AudioManager:
    """管理音频输入输出资源"""

    def __init__(self):
        self.pya: Optional[pyaudio.PyAudio] = None
        self.mic_stream: Optional[pyaudio.Stream] = None
        self.player: Optional[PCMPlayer] = None

    def initialize(self) -> None:
        """初始化音频设备"""
        print('初始化音频设备...')
        self.pya = pyaudio.PyAudio()
        self.mic_stream = self.pya.open(
            format=pyaudio.paInt16,
            channels=1,
            rate=AUDIO_SAMPLE_RATE,
            input=True
        )
        self.player = PCMPlayer(self.pya, sample_rate=OUTPUT_AUDIO_SAMPLE_RATE)
        print('音频设备初始化完成')

    def read_audio_chunk(self) -> Optional[bytes]:
        """读取音频数据块"""
        if not self.mic_stream:
            return None
        try:
            return self.mic_stream.read(AUDIO_CHUNK_SIZE, exception_on_overflow=False)
        except Exception as e:
            print(f'[Error] 读取音频数据失败: {e}')
            return None

    def cleanup(self) -> None:
        """清理音频资源"""
        print('清理音频资源...')
        if self.player:
            self.player.shutdown()
        if self.mic_stream:
            self.mic_stream.close()
        if self.pya:
            self.pya.terminate()
        print('音频资源清理完成')

# ==================== Callback Handler ====================
class OmniCallback(OmniRealtimeCallback):
    """Omni 实时对话回调处理器"""

    def __init__(self, audio_manager: AudioManager):
        self.audio_manager = audio_manager
        self.tool_calls: Dict[str, Dict[str, Any]] = {}
        self.all_response_text: str = ''
        self.last_package_time: float = 0
        self.is_first_text: bool = True
        self.is_first_audio: bool = True
        self.conversation: Optional[OmniRealtimeConversation] = None

    def set_conversation(self, conversation: OmniRealtimeConversation) -> None:
        """设置对话实例引用"""
        self.conversation = conversation

    def on_open(self) -> None:
        """连接建立时的回调"""
        print('连接已建立')
        self.audio_manager.initialize()
        self.last_package_time = time.time() * 1000
        self.is_first_text = True
        self.is_first_audio = True
        self.tool_calls = {}
        self.all_response_text = ''

    def on_close(self, close_status_code: int, close_msg: str) -> None:
        """连接关闭时的回调"""
        print(f'连接已关闭: code={close_status_code}, msg={close_msg}')
        self.audio_manager.cleanup()
        sys.exit(0)

    def on_event(self, response: Dict[str, Any]) -> None:
        """处理事件回调"""
        try:
            event_type = response.get('type', '')

            # Session created
            if event_type == 'session.created':
                print(f'会话已启动: {response["session"]["id"]}')

            # Speech-to-text completed
            elif event_type == 'conversation.item.input_audio_transcription.completed':
                print(f'用户问题: {response.get("transcript", "")}')

            # Incremental text response
            elif event_type in ('response.audio_transcript.delta', 'response.text.delta'):
                if self.is_first_text:
                    self.is_first_text = False
                    latency = time.time() * 1000 - self.last_package_time
                    print(f'首字延迟 (VAD结束): {latency:.0f} ms')

                text = response.get('delta', '')
                self.all_response_text += text

            # Incremental audio response
            elif event_type == 'response.audio.delta':
                if self.is_first_audio:
                    self.is_first_audio = False
                    latency = time.time() * 1000 - self.last_package_time
                    print(f'首音延迟 (VAD结束): {latency:.0f} ms')

                audio_interval = time.time() * 1000 - self.last_package_time
                print(f'音频间隔: {audio_interval:.0f} ms')
                self.last_package_time = time.time() * 1000

                recv_audio_b64 = response.get('delta', '')
                if self.audio_manager.player:
                    self.audio_manager.player.add_data(recv_audio_b64)

            # VAD detected speech start
            elif event_type == 'input_audio_buffer.speech_started':
                print('====== VAD 检测到语音开始 ======')
                if self.audio_manager.player:
                    self.audio_manager.player.cancel_playing()

            # VAD detected speech end
            elif event_type == 'input_audio_buffer.speech_stopped':
                print('====== VAD 检测到语音结束 ======')
                self.last_package_time = time.time() * 1000
                self.is_first_text = True
                self.is_first_audio = True
                self.tool_calls = {}

            # Function call arguments completed
            elif event_type == 'response.function_call_arguments.done':
                print('====== 收到工具调用请求 ======')
                call_id = response.get('call_id', '')
                self.tool_calls[call_id] = response.copy()
                self.tool_calls[call_id]['processed'] = False

            # Response completed
            elif event_type == 'response.done':
                print('====== 响应完成 ======')
                print(f'完整回复: {self.all_response_text}')

                if self.conversation:
                    response_id = self.conversation.get_last_response_id()
                    text_delay = self.conversation.get_last_first_text_delay()
                    audio_delay = self.conversation.get_last_first_audio_delay()

                    # Print detailed metrics only when all are available
                    if response_id is not None and text_delay is not None and audio_delay is not None:
                        print(f'[Metric] 响应ID: {response_id}, '
                              f'首字延迟: {text_delay:.0f}ms, '
                              f'首音延迟: {audio_delay:.0f}ms')
                    else:
                        print('[Metric] 指标信息暂不可用(可能是工具调用后的响应)')

                self.all_response_text = ''

        except Exception as e:
            print(f'[Error] 处理事件异常: {e}')
            traceback.print_exc()

    def process_pending_tool_calls(self) -> bool:
        """
        处理待处理的工具调用

        Returns:
            是否有新的工具调用需要响应
        """
        has_pending = False

        for call_id, tool_call in self.tool_calls.items():
            if not tool_call.get('processed', False):
                has_pending = True
                tool_call['processed'] = True

                # Handle the tool call
                result = handle_tool_call(tool_call)

                # Send the result to the server
                if self.conversation:
                    send_tool_call_response(self.conversation, result)

        return has_pending

# ==================== Main Program ====================
def main():
    """主函数"""
    print('正在初始化 Omni 实时对话...')

    # Create an audio manager
    audio_manager = AudioManager()

    # Create a callback handler
    callback = OmniCallback(audio_manager)

    # Create a conversation instance
    conversation = OmniRealtimeConversation(
        api_key=dashscope.api_key,
        url=WS_URL,
        model=MODEL,
        callback=callback,
    )

    # Set the conversation reference in the callback
    callback.set_conversation(conversation)

    # Establish connection
    conversation.connect()

    # Configure session parameters
    omni_output_modalities = [MultiModality.AUDIO, MultiModality.TEXT]

    conversation.update_session(
        output_modalities=omni_output_modalities,
        voice=VOICE,
        input_audio_format=AudioFormat.PCM_16000HZ_MONO_16BIT,
        output_audio_format=AudioFormat.PCM_24000HZ_MONO_16BIT,
        enable_input_audio_transcription=True,
        enable_turn_detection=True,
        turn_detection_type='server_vad',
        tools=TOOLS,
    )

    # Set up signal handling
    def signal_handler(sig, frame):
        print('\n接收到 Ctrl+C,正在停止...')
        conversation.close()
        audio_manager.cleanup()
        print('Omni 实时对话已停止')
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    print("按 Ctrl+C 停止对话...\n")

    # Main loop: continuously send audio and check for tool calls
    try:
        while True:
            # Process pending tool calls
            has_tool_calls = callback.process_pending_tool_calls()

            if has_tool_calls:
                print("*** 工具调用完成,创建新响应 ***")
                conversation.create_response(
                    instructions=None,
                    output_modalities=omni_output_modalities
                )
                print('====== 工具调用处理完成 ======\n')

            # Read and send audio data
            audio_data = audio_manager.read_audio_chunk()
            if audio_data:
                audio_b64 = base64.b64encode(audio_data).decode('ascii')
                conversation.append_audio(audio_b64)
            else:
                break

    except KeyboardInterrupt:
        signal_handler(signal.SIGINT, None)
    except Exception as e:
        print(f'[Error] 主循环异常: {e}')
        traceback.print_exc()
    finally:
        conversation.close()
        audio_manager.cleanup()

if __name__ == '__main__':
    main()

Tool calling for deep thinking models

Deep thinking models perform reasoning before outputting tool call information, improving the interpretability and reliability of decisions.
  1. Thinking Process The model analyzes the user intent step by step, identifies the required tools, verifies parameter validity, and plans the calling strategy;
  2. Tool calling The model outputs one or more function call requests in a structured format.
    Parallel tool calling is supported.
The following shows an example of streaming tool calls with a deep thinking model.
For text generation thinking models, see Deep thinking ; for multimodal thinking models, see Image and video understanding and Non-real-time (Qwen-Omni) .
When thinking mode is enabled (enable_thinking=True), tool_choice does not support being set to "required" or the object form; setting both at the same time causes an error (The tool_choice parameter does not support being set to required or object in thinking mode), and the two are incompatible. To perform tool calls (such as MCP calls) reliably in thinking mode, it is recommended to use the Responses API to access MCP instead; see MCP.
  • OpenAI compatible
  • DashScope
  • Python
  • Node.js
  • HTTP

Sample Code

import os
from openai import OpenAI

# Initialize the OpenAI client and configure the Alibaba Cloud DashScope service
client = OpenAI(
    # API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    # If the environment variable is unset, replace the next line with your Model Studio API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # Read the API key from the environment variable
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# Define the list of available tools
tools = [
    # Tool 1: Get the current time
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "当你想知道现在的时间时非常有用。",
            "parameters": {}  # No parameters required
        }
    },
    # Tool 2: Get the weather in a specific city
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如新加坡市、杭州市、余杭区等。"
                    }
                },
                "required": ["location"]  # Required parameter
            }
        }
    }
]

messages = [{"role": "user", "content": input("请输入问题:")}]

# Example message for a multimodal model
# messages = [{
#     "role": "user",
#     "content": [
#              {"type": "image_url","image_url": {"url": "https://img.alicdn.com/imgextra/i4/O1CN014CJhzi20NOzo7atOC_!!6000000006837-2-tps-2048-1365.png"}},
#              {"type": "text", "text": "Based on the location in the image, what is the current weather there?"}]
#     }]

completion = client.chat.completions.create(
    # This example uses qwen4-max. You can replace it with other deep thinking models.
    model="qwen4-max",
    messages=messages,
    extra_body={
        # Enable deep thinking.
        "enable_thinking": True
    },
    tools=tools,
    parallel_tool_calls=True,
    stream=True,
    # Uncomment to get token consumption information
    # stream_options={
    #     "include_usage": True
    # }
)

reasoning_content = ""  # Define the complete thinking process
answer_content = ""     # Define the complete response
tool_info = []          # Store tool call information
is_answering = False   # Determine if the thinking process has ended and the response has begun
print("="*20+"思考过程"+"="*20)
for chunk in completion:
    if not chunk.choices:
        # Process usage statistics information
        print("\n"+"="*20+"Usage"+"="*20)
        print(chunk.usage)
    else:
        delta = chunk.choices[0].delta
        # Process the AI's thinking process (chain of thought)
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content is not None:
            reasoning_content += delta.reasoning_content
            print(delta.reasoning_content,end="",flush=True)  # Output the thinking process in real time

        # Process the final response content
        else:
            if not is_answering:  # Print the title when entering the response phase for the first time
                is_answering = True
                print("\n"+"="*20+"回复内容"+"="*20)
            if delta.content is not None:
                answer_content += delta.content
                print(delta.content,end="",flush=True)  # Stream the response content

            # Process tool call information (supports parallel tool calling)
            if delta.tool_calls is not None:
                for tool_call in delta.tool_calls:
                    index = tool_call.index  # Tool call index, for parallel calling

                    # Dynamically expand the tool information storage list
                    while len(tool_info) <= index:
                        tool_info.append({})

                    # Collect the tool call ID (for subsequent function calls)
                    if tool_call.id:
                        tool_info[index]['id'] = tool_info[index].get('id', '') + tool_call.id

                    # Collect the function name (for subsequent routing to specific functions)
                    if tool_call.function and tool_call.function.name:
                        tool_info[index]['name'] = tool_info[index].get('name', '') + tool_call.function.name

                    # Collect function parameters (JSON string format, requires subsequent parsing)
                    if tool_call.function and tool_call.function.arguments:
                        tool_info[index]['arguments'] = tool_info[index].get('arguments', '') + tool_call.function.arguments

print(f"\n"+"="*19+"工具调用信息"+"="*19)
if not tool_info:
    print("没有工具调用")
else:
    print(tool_info)

Response

Enter "What is the weather in the four municipalities" and you will get the following response:
====================思考过程====================
好的,用户问的是“四个直辖市的天气”。首先,我需要明确四个直辖市是哪几个。根据中国的行政区划,直辖市包括北京、上海、天津和重庆。所以用户想知道这四个城市的天气情况。

接下来,我需要检查可用的工具。提供的工具中有get_current_weather函数,参数是location,类型字符串。每个城市需要单独查询,因为函数一次只能查一个地点。因此,我需要为每个直辖市调用一次这个函数。

然后,我需要考虑如何生成正确的工具调用。每个调用应该包含城市名称作为参数。比如,第一个调用是北京,第二个是上海,依此类推。确保参数名称是location,值是正确的城市名。

另外,用户可能希望得到每个城市的天气信息,所以需要确保每个函数调用都正确无误。可能需要连续调用四次,每次对应一个城市。不过,根据工具的使用规则,可能需要分多次处理,或者一次生成多个调用。但根据示例,可能每次只调用一个函数,所以可能需要逐步进行。

最后,确认是否有其他需要考虑的因素,比如参数是否正确,城市名称是否准确,以及是否需要处理可能的错误情况,比如城市不存在或API不可用。但目前看来,四个直辖市都是明确的,应该没问题。
====================回复内容====================

===================工具调用信息===================
[{'id': 'call_767af2834c12488a8fe6e3', 'name': 'get_current_weather', 'arguments': '{"location": "北京市"}'}, {'id': 'call_2cb05a349c89437a947ada', 'name': 'get_current_weather', 'arguments': '{"location": "上海市"}'}, {'id': 'call_988dd180b2ca4b0a864ea7', 'name': 'get_current_weather', 'arguments': '{"location": "天津市"}'}, {'id': 'call_4e98c57ea96a40dba26d12', 'name': 'get_current_weather', 'arguments': '{"location": "重庆市"}'}]

Going live

Test tool calling accuracy

  • Build an evaluation system: Build test datasets that closely reflect real business scenarios, and define clear evaluation metrics such as tool selection accuracy, parameter extraction accuracy, and end-to-end success rate.
  • Optimize prompts Based on the specific problems exposed by testing (wrong tool selection, parameter errors), optimize the system prompt, tool descriptions, and parameter descriptions in a targeted way.
  • Upgrade the model When prompt tuning cannot improve performance, upgrading to a more capable model version (such as qwen3.6-plus) is the most direct and effective approach.

Dynamically control the number of tools

When the number of tools integrated in your application reaches dozens or even hundreds, providing all of them to the model causes the following problems:
  • Performance degradation: the difficulty of the model selecting the correct tool from a huge tool set increases dramatically;
  • Cost and latency: a large amount of tool descriptions consumes a huge number of input tokens, leading to higher costs and slower responses;
Solution: add a tool routing/retrieval layer before calling the model, which filters out a small and relevant subset of tools from the tool library based on the user query, and then provides it to the model. Several mainstream approaches to implementing tool routing:
  • Semantic retrieval Convert tool description information (description) into vectors via an Embedding model and store them in a vector database. When a user query arrives, use vector similarity search on the query vector to recall the most relevant Top-K tools.
  • Hybrid retrieval Combine the "fuzzy match" capability of semantic retrieval with the "exact match" capability of traditional keywords or metadata tags. Add tags or keywords fields to tools, and perform vector search and keyword filtering simultaneously during retrieval, which can significantly improve recall precision in high-frequency or specific scenarios.
  • Lightweight LLM router For more complex routing logic, you can use a smaller, faster, and cheaper model (such as Qwen-Flash) as a front-end "routing model". Its task is to output a list of relevant tool names based on the user's question.
Best practices
  • Keep the candidate set lean: Regardless of the method used, the number of tools ultimately provided to the main model should be no more than 20. This is the optimal balance point among model cognitive load, cost, latency, and accuracy.
  • Layered filtering strategy: You can build a funnel-style routing strategy. For example, first use extremely low-cost keyword/rule matching for the first round of screening to filter out obviously irrelevant tools, and then perform semantic retrieval on the remaining tools, improving both efficiency and quality.

Tool Security Principles

When exposing tool execution capabilities to a large model, security is the primary consideration. Core principles: "least privilege" and "human confirmation".
  • Principle of least privilege: The tool set provided to the model should strictly follow the principle of least privilege. By default, tools should be read-only (such as querying the weather or searching documents), and you should avoid directly providing any "write" permissions that involve state changes or resource operations.
  • Isolate dangerous tools: Do not directly provide dangerous tools to the large model, such as executing arbitrary code (code interpreter), manipulating the file system (fs.delete), performing database deletion or update operations (db.drop_table), or tools involving fund transfers (payment.transfer).
  • Human in the loop: For all high-privilege or irreversible operations, a manual review and confirmation step must be introduced. The model can generate operation requests, but the final execution "button" must be clicked by a human user. For example, the model can prepare an email, but the send operation requires user confirmation.

User Experience Optimization

The Function Calling pipeline is long, and a problem in any stage can affect the user experience.

Handling Tool Execution Failures

Tool execution failures are common. You can adopt the following strategies:
  • Maximum retries: Set a reasonable retry limit (for example, 3 times) to prevent consecutive failures from keeping users waiting for a long time or wasting system resources.
  • Provide fallback messages: When retries are exhausted or an unsolvable error occurs, return a clear, friendly message to the user, for example: "Sorry, I cannot find the relevant information right now. The service may be busy. Please try again later."

Handling Processing Latency

High latency reduces user satisfaction and should be optimized from both the frontend interaction and backend perspectives.
  • Set timeout periods: Set an independent and reasonable timeout for each step of Function Calling. Once a timeout occurs, immediately interrupt the operation and provide feedback.
  • Provide instant feedback: When Function Calling starts executing, it is recommended to show a prompt in the interface, such as "Querying the weather for you..." or "Searching for relevant information...", to give users real-time feedback on the processing progress.

Billing Details

In addition to the tokens in the messages array, tool descriptions are also billed as input tokens.
We recommend that you refer to the How to use section and pass tool information to the large model through the tools parameter. If you need to pass tool information through the System Message, for the best model performance, refer to the prompt template in the following code:
  • OpenAI compatible
  • DashScope
  • Python
  • Node.js

Sample Code

import os
from openai import OpenAI
import json

client = OpenAI(
    # API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    # If the environment variable is unset, replace the next line with your Model Studio API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region. Replace {WorkspaceId} with your actual Workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# Custom System prompt, which can be modified according to your needs
custom_prompt = "你是一个智能助手,专门负责调用各种工具来帮助用户解决问题。你可以根据用户的需求选择合适的工具并正确调用它们。"

tools = [
    # Tool 1: Get the current time
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "当你想知道现在的时间时非常有用。",
            "parameters": {}
        }
    },
    # Tool 2: Get the weather in a specific city
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如新加坡市、杭州市、余杭区等。"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Iterate through the tools list to build a description for each tool
tools_descriptions = []
for tool in tools:
    tool_json = json.dumps(tool, ensure_ascii=False)
    tools_descriptions.append(tool_json)

# Combine all tool descriptions into a single string
tools_content = "\n".join(tools_descriptions)

system_prompt = f"""{custom_prompt}

# Tools

You may call one or more functions to assist with the user query.

You are provided with function signatures within <tools></tools> XML tags:
<tools>
{tools_content}
</tools>

For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
<tool_call>
{{"name": <function-name>, "arguments": <args-json-object>}}
</tool_call>"""

messages = [
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": "几点了"}
]

completion = client.chat.completions.create(
    model="qwen4-max",
    extra_body={"enable_thinking": False},
    messages=messages,
)
print(completion.model_dump_json())
After running the above code, you can use an XML parser to extract the tool call information between <tool_call> and </tool_call>, including the function name and input parameters.

Error codes

If the model call fails and returns an error message, see Error codes to resolve the issue.