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
- Ling
- Xing
-
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 obtained and configured an API Key and set it as an environment variable. If you call through 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 through the tools parameter (recommended) See How to use and follow the steps of defining tools, creating the messages array, initiating Function Calling, running the tool functions, and having the model summarize the tool function output to make the call.
- Method 2: Pass in through a System Message Passing in through the tools parameter delivers the best results, as the server automatically applies the optimal prompt template. If you use Qwen models and do not want to use the tools parameter, see Passing tool information through a System Message.
1. Define tools
Tools connect the model to 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
Accepts the
argumentsparameter, whereargumentsis in the format{"location": "the location to query"}. 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 picks from sunny, cloudy, or rainy. In real business scenarios, you can replace it with tools such as the Amap weather query API.
-
Time query tool
The time query tool requires no 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 retrieving 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 format of the tool description information is as follows: |
python
2. Create the messages array
Function Calling passes instructions and context to the model via the messages array. Before initiating the 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 in the user's question. Suppose the user asks "What's the weather in Shanghai"; the messages array at this point is:
python
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.
python
"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.
python
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 initiating Function Calling, you get the Assistant Message via
completion.choices[0].message; first, add it to the messages array; -
Add the Tool Message
Add the tool's output to the messages array in the form
{"role": "tool", "content": "tool output","tool_call_id": completion.choices[0].message.tool_calls[0].id}.- The tool's output is usually a string. When the model needs to understand an image produced by the tool,
contentaccepts a content array, for example[{"type": "text", "text": "Image generated successfully."}, {"type": "image_url", "image_url": {"url": "https://example.com/image.png"}}], whereurlsupports a public URL or a Base64 Data URI. An image URL passed as a plain string is treated as plain text and is not parsed as an image. 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.
- The tool's output is usually a string. When the model needs to understand an image produced by the tool,
python
python
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
This section applies only to models that supportA 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?", the model can return multiple tool calls in one response after you make a Function Calling, becauseparallel_tool_calls. MiniMax/MiniMax-M3.1-Flash and kimi-k3 do not support using this parameter to control whether tool calls are parallel: setting it tofalsemay still result in multipletool_callsin one turn. Iterate over and process all tool calls actually returned by the model. kimi/kimi-k3.1-pro and kimi/kimi-k3.1-pro-highspeed do not support theparallel_tool_callsparameter.
parallel_tool_calls defaults to true. For example, if you ask "What's the weather like in Beijing and Shanghai?", the tool_calls array in the returned object contains the input parameter information for both Beijing and Shanghai:
parallel_tool_calls request parameter to false when you make a Function Calling:
python
Parallel tool calling is suitable when tasks are independent of each other. If tasks have dependencies (the input of tool A depends on the output of tool B), see QuickStart to implement serial tool calling (one tool at a time) with a while loop.
Forced tool calling
The named-function,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 therequired, andnonestrategies in this section apply only to models that support the correspondingtool_choicevalues. MiniMax/MiniMax-M3.1-Flash supports onlyauto; other values may return an error or have no effect, and specifying a named function does not guarantee that the model calls it.
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. Assume the current scenario contains only weather query questions; you can modify the function_calling code as follows:
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.
The Qwen series models do not support settingAssume all questions in the current scenario require tool calling; you can modify the function_calling code as follows:tool_choiceto"required": in non-thinking moderequiredcannot guarantee that a tool is always called, and in thinking mode"required"is not supported.
python
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. Assume none of the questions in the current scenario require tool calling; you can modify the function_calling code as follows:
Multi-turn conversation
The user may ask "What's the weather in Beijing" in the first turn and "What about Shanghai?" in the second. If the model's 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 a new User Message on top of it, and then initiate Function Calling and the 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.
python
arguments):
python
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 | The items in response.output whose type is function_call |
| Tool result passback | ||
| Final response | response.choices[0].message.content | response.output_text |
output array item types are input_text and input_image, and image_url takes a URL or a Base64 Data URI directly rather than a nested object. For field descriptions, see Create a response.
python
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
Use qwen3.8-omni-flash for text-based tool calling through Chat Completions or Responses. The Python and JavaScript examples below use Chat Completions streaming and read text and tool-call deltas with thinking disabled. For audio/video input, see Qwen3.8-Omni-Flash.
The examples set reasoning_effort="none" to disable thinking. For tool calls that require thinking, omit the parameter to use the default xhigh, and read reasoning_content, content, and tool_calls separately. In subsequent turns, include the previous assistant message with its reasoning, answer, and tool calls in the history, followed by the tool results. preserve_thinking is enabled by default. See Pass reasoning content.
First install the OpenAI SDK, configure DASHSCOPE_API_KEY, and set DASHSCOPE_BASE_URL to your workspace Chat Completions endpoint. Use the same region for the API key and endpoint.
python
arguments), see Streaming output.
Existing calls to Qwen3.5-Omni-Plus, Qwen3.5-Omni-Flash, and Qwen3-Omni-Flash requirestream=True. Usemodalities=["text"]when obtaining tool information; skip audio chunks when Qwen3.5-Omni also generates audio.
Qwen-Omni-Realtime series
Qwen3.8-Omni-Flash-Realtime, Qwen3.5-Omni-Plus-Realtime, and Qwen3.5-Omni-Flash-Realtime support custom Function Calling for voice conversations. The following workflow uses the DashScope SDK or the native WebSocket protocol. For connection and SDK configuration, see the real-time guide.
For server-executed MCP tools and the approval flow in Qwen3.8-Omni-Flash-Realtime, see MCP interaction.
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 details about Qwen-Omni-Realtime, see: Real-time (Qwen-Omni-Realtime), Client events, and Server 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 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 them together raises an error (The tool_choice parameter does not support being set to required or object in thinking mode) — the two are incompatible. To perform tool calling stably in thinking mode (such as MCP calls), it is recommended to use the Responses API to access MCP instead; see MCP.
- 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 description information is also billed as input tokens.
Pass tool information through a System Message
Pass tool information through a System Message
It is recommended that you refer to the How to use section and pass tool information to the model via the tools parameter. If you need to pass tool information via the System Message, for the best model performance, refer to the prompt template in the following code:
- 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.