Large Language Models (LLMs) cannot access real-time data or external systems. Function Calling enables models to call external tools, such as APIs, databases, and user-defined functions. This allows a model to retrieve information or perform actions beyond its built-in capabilities.
How it works
Function Calling works through a multi-step interaction between your application and the LLM:
- Make the first model call The application sends the user's question and a list of available tools to the LLM.
-
Receive tool calling instructions from the model
If the model decides to call an external tool, it returns a JSON instruction that specifies the function name and input parameters.
If the model decides not to call a tool, it returns a natural language response.
- Run the tool in the application The application runs the specified tool and obtains the output.
- Make the second model call Add the tool's output to the messages array and call the model again.
- Receive the final response from the model The model combines the tool's output with the user's question to generate a natural language response.
Supported models
- Qwen
- DeepSeek
- GLM
- Kimi
- MiniMax
-
Text generation models
- Qwen-Max: Qwen3.8-Max series, Qwen3.7-Max series, Qwen3.6-Max series, Qwen3-Max series, and Qwen-Max series
- Qwen-Plus: Qwen3.7-Plus series, Qwen3.6-Plus series, Qwen3.5-Plus series, and Qwen-Plus series.
- Qwen-Flash: Qwen3.7-Flash series, Qwen3.6-Flash series, Qwen3.5-Flash series, and Qwen-Flash series
- Qwen-Coder: Qwen3-Coder series, Qwen2.5-Coder series, and 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 and Qwen3-VL-Flash series
- Qwen-Omni: Qwen3.5-Omni-Plus series, Qwen3.5-Omni-Flash series, and Qwen3-Omni-Flash series
- Qwen-Omni-Realtime: Qwen3.5-Omni-Plus-Realtime series and Qwen3.5-Omni-Flash-Realtime series
- Qwen3-VL open source series
-
Voice chat models
- Qwen-Audio-Realtime: Qwen-Audio-3.0-Realtime-Plus series and Qwen-Audio-3.0-Realtime-Flash series
Getting started
Before you begin, obtain an API key and configure it as an environment variable. If you use the OpenAI SDK or DashScope SDK, you must also install the SDK.
The following example shows the complete Function Calling flow for a weather query scenario.
- OpenAI compatible
- DashScope
How to use
Function Calling supports two ways to pass tool information:
- Method 1: Pass information through the tools parameter (recommended) For more information, see How to use. Follow the steps to define tools, create a messages array, make a Function Calling, run the tool function, and have the LLM summarize the tool function output.
-
Method 2: Pass information through a System Message
Passing information through the
toolsparameter provides the best results because the server automatically adapts to the optimal prompt template. If you are using a Qwen model and do not want to use thetoolsparameter, see Pass tool information through a System Message.
tools parameter.
Assume a business scenario that receives two types of questions: weather queries and time queries.
1. Define tools
Tools connect LLMs to external services. You must first define the tools.
1.1. Create tool functions
Create two tool functions: a weather query tool and a time query tool.
-
Weather query tool
This tool receives the
argumentsparameter. The format ofargumentsis{"location": "queried location"}. The tool's output 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 a real business scenario, you can replace this with a tool such as Amap Weather.
-
Time query tool
The time query tool does not require any input parameters. The tool's output is a string in the format:
"Current time: {queried time}.".If you use Node.js, run
npm install date-fnsto install the date-fns package for obtaining the time.
1.2. Create the tools array
Before humans can choose a tool, they need to understand its function, usage scenarios, and input parameters. The same applies to LLMs. The model selects the appropriate tool based on this information. Provide the tool information in the following JSON format.
| For the weather query tool, the format of the tool description information is as follows: |
tools) in your code. This array includes the function name, description, and parameter definition for each tool. The array is passed as a parameter in subsequent requests.
2. Create the messages array
Function Calling passes instructions and context to the LLM through the messages array. Before making a call, the messages array must contain a System Message and a User Message.
System Message
Although the function and usage scenarios of the tools have been described when you created the tools array, further emphasizing when to call the tools in the System Message usually improves the accuracy of tool calling. For the current scenario, you can set the System Prompt to:
User Message
The User Message is used to pass the user's question. Assuming the user asks "Weather in Shanghai", the messages array at this point is:
Because the available tools include weather and time queries, you can also ask about the current time.
3. Make a Function Calling
Pass the created tools and messages to the LLM to make a Function Calling. The LLM determines whether to call a tool. If it does, it returns the tool's function name and parameters.
For supported models, see Supported models.
"get_current_weather" and the function's input parameter as "{\"location\": \"Shanghai\"}".
content parameter. When you input "Hello", the tool_calls parameter is empty, and the returned object format is:
If thetool_callsparameter is empty, your program can directly return thecontentwithout running the following steps.
If you want the LLM to select a specific tool every time you make a Function Calling, see Forced tool calling.
4. Run the tool function
Running the tool function translates the model's decision into an actual operation.
The process of running the tool function is completed by your computing environment, not the LLM.The LLM only outputs a string. Before running the tool function, you need to parse the tool function name and its input parameters separately.
-
Tool function
Create a mapping
function_mapperfrom the tool function name to the tool function entity to map the returned tool function string to the 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 to extract the input parameter information.
In real business scenarios, many tools perform specific actions (such as sending emails or uploading files) rather than querying data, and do not output a string. We recommend adding status description information (such as "Email sent successfully" or "Operation failed") for such tools to help the LLM understand the execution status.
5. Let the LLM summarize the tool function output
The output format of the tool function is relatively fixed. Directly returning it to the user might sound robotic. Submit the tool output to the model context and call the model again to generate a natural language style response.
-
Add an Assistant Message
After you make a Function Calling, you obtain an Assistant Message through
completion.choices[0].message. First, add it to themessagesarray. -
Add a Tool Message
Add the tool's output to the
messagesarray in the format{"role": "tool", "content": "tool output", "tool_call_id": completion.choices[0].message.tool_calls[0].id}.- Make sure the tool's output is in string format.
tool_call_idis a unique identifier generated by the system for each tool call request. The model may request to call multiple tools at once. When returning multiple tool results to the model,tool_call_idensures that the tool's output result can be matched with its calling intent.
messages array is:
messages array, run the following code.
content: "The weather in Shanghai today is cloudy. If you have any other questions, feel free to ask."
Advanced usage
Specify the tool calling method
Parallel tool calling
A single city weather query requires only one tool call. If a question requires multiple tool calls, such as "What's the weather like in Beijing and Shanghai?" or "What's the weather in Hangzhou and what time is it now?", after you make a Function Calling, only one piece of tool call information will be returned. For example, if you ask "What's the weather like in Beijing and Shanghai?":
parallel_tool_calls request parameter to true when you make a Function Calling.
Parallel tool calling is suitable for tasks that have no dependencies. If there are dependencies between tasks (the input of tool A is related to the output of tool B), see Getting started to implement serial tool calling (calling one tool at a time) through a
while loop.tool_calls array in the returned object contains the input parameter information for both Beijing and Shanghai:
Forced tool calling
LLMs generate content with a degree of uncertainty and may choose the wrong tool. To force the use or disabling of a specific tool for a certain type of question, you can modify the tool_choice parameter. The default value of the tool_choice parameter is "auto", which means the LLM autonomously decides how to make a tool call.
When the LLM summarizes the 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 forcibly call a specific tool for a certain type of question, you can set the
tool_choiceparameter to{"type": "function", "function": {"name": "the_function_to_call"}}. The LLM will not participate in the tool selection and will only output the input parameter information. Assuming the current scenario only involves weather query questions, you can modify thefunction_callingcode to:
get_current_weather.
Before using this strategy, make sure the question is related to the selected tool. Otherwise, it may return unexpected results.
tool_calls parameter in the returned object is not empty), you can set the tool_choice parameter to "required". Function Calling will then always return tool and input parameter information.
Assuming that all questions in the current scenario require a tool call, you can modify the function_calling code to:
tool_calls parameter in the returned object will never be empty.
Before using this strategy, make sure the question is related to the tools. Otherwise, it may return unexpected results.
-
Force no tool usage
If you need Function Calling to never make a tool call (the returned object contains response content in
contentand thetool_callsparameter is empty), you can set thetool_choiceparameter to"none", or do not pass thetoolsparameter. Thetool_callsparameter returned by Function Calling will always be empty. Assuming that no questions in the current scenario require a tool call, you can modify thefunction_callingcode to:
Multi-turn conversation
A user might ask "Weather in Beijing" in the first turn, and then "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 a multi-turn conversation scenario, keep the messages array complete after each turn. Add the new User Message to this array and then make a Function Calling and subsequent steps. The messages structure is as follows:
Streaming output
Using streaming output lets you obtain the tool function name and input parameter information in real time, which improves the user experience. In this case:
- The parameter information for the tool call is returned in chunks as a data stream.
- The tool function name is returned in the first data chunk of the stream response.
arguments):
tool_calls below with the content above.
Tool calling with the Responses API
The preceding 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 format has the following differences:
| Dimension | Chat Completions | Responses API |
|---|---|---|
| Tool definition format | ||
| Tool call output | response.choices[0].message.tool_calls | Items in response.output where type is function_call |
| Tool result passback | ||
| Final response | response.choices[0].message.content | response.output_text |
Tool calling for omni-modal models
Omni-modal models support tool calling. The calling methods for the Qwen-Omni series and Qwen-Omni-Realtime series are different.
Qwen-Omni series
The Qwen3.5-Omni-Plus, Qwen3.5-Omni-Flash, and Qwen3-Omni-Flash series support tool calling through the OpenAI compatible API. The stage of obtaining tool information differs from other models in the following ways:
- Streaming output is mandatory: Qwen-Omni only supports streaming output. When obtaining tool information, you must also set
stream=True. - Text-only output is recommended: The model only needs text information when obtaining tool information (function name and parameters). To avoid generating unnecessary audio, we recommend setting
modalities=["text"]. When the output includes both text and audio modalities, you need to skip the audio data chunks when obtaining tool information.
For more information about Qwen-Omni, see Non-real-time (Qwen-Omni).
arguments), see Streaming output.
Qwen-Omni-Realtime series
The Qwen3.5-Omni-Plus-Realtime and Qwen3.5-Omni-Flash-Realtime series support tool calling and are suitable for voice conversation scenarios. You can call them through the DashScope SDK or the native WebSocket protocol.
Workflow:
After establishing a WebSocket connection, pass the tool definition through session.update to enter the following interaction flow:
Phase 1: Speech input and tool calling
- The user asks a question by voice. The client collects the audio and sends it to the server (corresponding to the
append_audio()method). After the server's VAD detects the end of speech, it performs model inference and determines that a tool needs to be called. - The server returns the tool call information to the client (corresponding to the
response.function_call_arguments.doneevent), including the function name (name), function input parameters (arguments), and call identifier (call_id). An example is as follows:
- The client runs the corresponding tool function locally based on the function name and input parameters to obtain the execution result.
- The client sends the tool execution result back to the server (corresponding to the
conversation.item.createevent), including the call identifier (call_id) and execution result (output). An example is as follows:
- The client continues to send a
response.createevent to trigger the server to generate the final voice answer based on the tool execution result. - The client receives the voice and text returned by the server (corresponding to the
response.audio.deltaandresponse.audio_transcript.deltaevents) and plays the voice response to the user.
The Qwen-Omni-Realtime series does not support thetool_choiceandparallel_tool_callsparameters.
For more information about Qwen-Omni-Realtime, see Real-time (Qwen-Omni-Realtime), Client events, and Server-side events.
DashScope Python SDK
Tool calling for deep thinking models
Deep thinking models perform inference before outputting tool call information, which improves the interpretability and reliability of decisions.
- Thinking process The model analyzes the user's intent, identifies the required tools, verifies the legality of parameters, and plans the calling strategy step by step.
-
Tool calling
The model outputs one or more function call requests in a structured format.
Parallel tool calling is supported.
For more information about text generation thinking models, see Deep thinking. For more information about multimodal thinking models, see Image and video understanding and Non-real-time (Qwen-Omni).
TheIn thinking mode (tool_choiceparameter only supports being set to"auto"(default value, which means the model autonomously selects the tool) or"none"(forces the model not to select a tool).
enable_thinking=True), the tool_choice parameter does not support being set to "required" or an object (for example, {"type": "function", "function": {...}}). Setting tool_choice to either value while thinking mode is enabled causes the request to fail with the error The tool_choice parameter does not support being set to required or object in thinking mode. Do not rely on tool_choice="required" as a way to guarantee that tool_calls is non-empty in thinking mode. If you need reliable MCP tool calling while thinking mode is enabled, use the Responses API to connect to MCP instead.
- OpenAI compatible
- DashScope
- Python
- Node.js
- HTTP
Example code
Return result
Enter "Weather in the four municipalities" to obtain the following result:Going live
Test tool calling accuracy
- Establish an evaluation system: Build a test dataset that reflects real-world business scenarios and define clear evaluation metrics, such as tool selection accuracy, parameter extraction accuracy, and the end-to-end success rate.
- Optimize prompts Based on problems identified during testing, such as incorrect tool selections or parameters, you can optimize the system prompts, tool descriptions, and parameter descriptions.
-
Upgrade the model
If prompt tuning fails to improve performance, upgrading to a more powerful model version, such as
qwen3.6-plus, is the most direct and effective method.
Dynamically control the number of tools
When an application integrates dozens or even hundreds of tools, providing all of them to the model can cause the following problems:
- Performance degradation: The model's difficulty in selecting the correct tool from a large set of tools increases dramatically.
- Cost and latency: Many tool descriptions will consume a large amount of input tokens, leading to increased costs and slower responses.
-
Semantic retrieval
Convert tool descriptions (
description) into vectors using an embedding model and store them in a vector database. When a user submits a query, you can perform a vector similarity search on the query vector to recall the top K most relevant tools. -
Hybrid retrieval
This method combines the fuzzy match of semantic retrieval with the exact match of traditional keywords or metadata tags. To do this, add
tagsorkeywordsfields to the tools. During retrieval, performing both vector search and keyword filtering can significantly improve recall accuracy, especially for high-frequency or specific scenarios. - Lightweight LLM router For more complex routing logic, you can use a smaller, faster, and less expensive model, such as Qwen-Flash, as a router model. This model's task is to output a list of relevant tool names based on the user's query.
- Keep the candidate set concise: Regardless of the method used, we recommend providing no more than 20 tools to the main model. This provides an optimal balance between the model's cognitive load, cost, latency, and accuracy.
- Layered filtering strategy: You can build a funnel-style routing strategy. For example, you can first use low-cost keyword or rule matching to filter out clearly irrelevant tools. Then, you can perform semantic retrieval on the remaining tools to improve efficiency and quality.
Tool security principles
When granting tool execution capabilities to an LLM, security is the primary consideration. The core principles are least privilege and human confirmation.
- Principle of least privilege: The toolset provided to the model must strictly adhere to the principle of least privilege. By default, tools should be read-only, such as tools for querying weather or searching documents. Avoid providing any "write" permissions that involve state changes or resource operations.
- Isolate dangerous tools: Do not provide dangerous tools directly to the LLM, such as tools for executing arbitrary code (
code interpreter), operating the file system (fs.delete), performing database delete or update operations (db.drop_table), or handling financial transactions (payment.transfer). - Human involvement: A manual review and confirmation process is required for all high-privilege or irreversible operations. The model can generate an operation request, but the final "execute" button must be clicked by a human user. For example, the model can prepare an email, but the user must confirm the send operation.
User experience optimization
The function calling process involves multiple steps, and a problem at any step can negatively affect the user experience.
Handle tool run failures
Tool execution failures are common. You can adopt the following strategies:
- Maximum retries: Set a reasonable retry limit, such as 3, to avoid long user waits or system resource waste due to continuous failures.
- Provide fallback responses: If retries are exhausted or an unresolvable error is encountered, return a clear and friendly prompt to the user, such as: "Sorry, I can't find the relevant information at the moment. The service might be busy. Please try again later."
Cope with processing latency
High latency can reduce user satisfaction. You can implement optimizations on both the frontend and backend.
- Set a timeout: Set an independent and reasonable timeout for each step of the function calling process. If a timeout occurs, the operation should be immediately interrupted and feedback should be provided to the user.
- Provide instant feedback: When a function call starts, we recommend displaying a prompt on the interface, such as "Querying the weather for you..." or "Searching for relevant information...". This gives the user real-time feedback on the progress.
Billing
In addition to the tokens in the messages array, tool descriptions are also billed as input tokens.
Pass tool information through a System Message
Pass tool information through a System Message
We recommend passing tool information to the large language model (LLM) using the
tools parameter, as described in the How to use section. To pass tool information through a System Message, use the prompt template in the following code for optimal model performance:- OpenAI compatible
- DashScope
- Python
- Node.js
Example code
After running the preceding code, you can use an XML parser to extract the tool call information, including the function name and input parameters, from between the<tool_call>and</tool_call>tags.