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:
- Initiate the first model call The application sends the user's question and the list of available tools to the model.
-
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.
- Run the tool on the application side The application executes the specified tool and obtains the output result.
- Initiate the second model call Add the tool output to the messages array (messages) and call the model again.
- Receive the final response from the model The model synthesizes the tool output and the user's question to generate a natural language response.
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
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.
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
argumentsparameter, whereargumentsis 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-fnsto install date-fns, a package for obtaining the time:
python
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.
| For the weather query tool, the tool description information is in the following format: |
python
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:
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
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
"get_current_weather", and the input parameter of the function as: "{\"location\": \"Shanghai\"}".
content parameter. When the input is "Hello", the tool_calls parameter is empty, and the returned object is in the format:
If thetool_callsparameter is empty, you can have the program directly returncontentwithout 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.
python
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.
-
Add the Assistant Message
After initiating Function Calling, use
completion.choices[0].messageto get the Assistant Message, and first add it to the messages array; -
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,
contentcan accept a content array, for example[{"type": "text", "text": "Image generated successfully."}, {"type": "image_url", "image_url": {"url": "https://example.com/image.png"}}], whereurlsupports 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_idis 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_idensures that each tool's output can be matched to its calling intent.
- The output of a tool is usually a string. When the model needs to understand images produced by the tool,
python
python
content: "The weather in Shanghai is cloudy today. If you have other questions, feel free to keep asking."
Advanced usage
Specify the tool calling mode
Parallel tool calling
kimi-k3 does not support controlling the parallelism of tool calling throughA 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", sinceparallel_tool_calls: even when set tofalse, it may still return multipletool_callsin one round. The caller needs to traverse and handle all the tool calls actually returned.
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:
parallel_tool_calls to false when initiating Function Calling:
python
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_choiceparameter 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:
get_current_weather.
Before using this strategy, make sure the questions are relevant to the selected tool; otherwise, unexpected results may be returned.
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 settingAssume the questions in the current scenario all require tool calls. You can modify the function_calling code as follows:tool_choiceto"required": in non-thinking mode,requiredcannot guarantee that a tool will be called, and in thinking mode,"required"is currently not supported.
python
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
contentwhile thetool_callsparameter is empty), set thetool_choiceparameter to"none", or do not pass in thetoolsparameter. Thetool_callsparameter 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:
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:
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
arguments):
python
tool_calls below with the above content.
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:
| Dimension | Chat Completions | Responses API |
|---|---|---|
| Tool definition format | ||
| Tool call output | response.choices[0].message.tool_calls | The item in response.output whose type is function_call |
| Returning tool results | ||
| Final response | response.choices[0].message.content | response.output_text |
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
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
arguments), see Streaming output.
Existing calls to Qwen3.5-Omni-Plus, Qwen3.5-Omni-Flash, and Qwen3-Omni-Flash must setstream=True. You can usemodalities=["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
- 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. - 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 the call identifier (call_id). An example is as follows:
- Based on the function name and input parameters, the client executes the corresponding tool function locally and obtains 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 the execution result (output). An example is as follows:
- The client then sends the
response.createevent, triggering the server to generate the final voice response 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 Realtime (Qwen-Omni-Realtime), Client events, and Server events.
DashScope Python SDK
Tool calling for deep thinking models
Deep thinking models perform reasoning before outputting tool call information, improving the interpretability and reliability of decisions.
- Thinking Process The model analyzes the user intent step by step, identifies the required tools, verifies parameter validity, and plans the calling strategy;
-
Tool calling
The model outputs one or more function call requests in a structured format.
Parallel tool calling is supported.
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_choicedoes 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
Response
Enter "What is the weather in the four municipalities" and you will get the following response: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;
-
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
tagsorkeywordsfields 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.
- 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.
Pass tool information through the System Message
Pass tool information through the System Message
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
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.