Tool & Function Calling

Use tools in your prompts

Tool calls (also known as function calls) give an LLM access to external tools. The LLM does not call the tools directly. Instead, it suggests the tool to call. The user then calls the tool separately and provides the results back to the LLM. Finally, the LLM formats the response into an answer to the user’s original question.

OpenRouter standardizes the tool calling interface across models and providers, making it easy to integrate external tools with any supported model.

Supported Models: You can find models that support tool calling by filtering on openrouter.ai/models?supported_parameters=tools.

If you prefer to learn from a full end-to-end example, keep reading.

Request Body Examples

Tool calling with OpenRouter involves three key steps. Here are the essential request body formats for each step:

Step 1: Inference Request with Tools

1{
2 "model": "google/gemini-2.0-flash-001",
3 "messages": [
4 {
5 "role": "user",
6 "content": "What are the titles of some James Joyce books?"
7 }
8 ],
9 "tools": [
10 {
11 "type": "function",
12 "function": {
13 "name": "search_gutenberg_books",
14 "description": "Search for books in the Project Gutenberg library",
15 "parameters": {
16 "type": "object",
17 "properties": {
18 "search_terms": {
19 "type": "array",
20 "items": {"type": "string"},
21 "description": "List of search terms to find books"
22 }
23 },
24 "required": ["search_terms"]
25 }
26 }
27 }
28 ]
29}

Step 2: Tool Execution (Client-Side)

After receiving the model’s response with tool_calls, execute the requested tool locally and prepare the result:

1// Model responds with tool_calls, you execute the tool locally
2const toolResult = await searchGutenbergBooks(["James", "Joyce"]);

Step 3: Inference Request with Tool Results

1{
2 "model": "google/gemini-2.0-flash-001",
3 "messages": [
4 {
5 "role": "user",
6 "content": "What are the titles of some James Joyce books?"
7 },
8 {
9 "role": "assistant",
10 "content": null,
11 "tool_calls": [
12 {
13 "id": "call_abc123",
14 "type": "function",
15 "function": {
16 "name": "search_gutenberg_books",
17 "arguments": "{\"search_terms\": [\"James\", \"Joyce\"]}"
18 }
19 }
20 ]
21 },
22 {
23 "role": "tool",
24 "tool_call_id": "call_abc123",
25 "name": "search_gutenberg_books",
26 "content": "[{\"id\": 4300, \"title\": \"Ulysses\", \"authors\": [{\"name\": \"Joyce, James\"}]}]"
27 }
28 ],
29 "tools": [
30 {
31 "type": "function",
32 "function": {
33 "name": "search_gutenberg_books",
34 "description": "Search for books in the Project Gutenberg library",
35 "parameters": {
36 "type": "object",
37 "properties": {
38 "search_terms": {
39 "type": "array",
40 "items": {"type": "string"},
41 "description": "List of search terms to find books"
42 }
43 },
44 "required": ["search_terms"]
45 }
46 }
47 }
48 ]
49}

Note: The tools parameter must be included in every request (Steps 1 and 3) so the router can validate the tool schema on each call.

Tool Calling Example

Here is Python code that gives LLMs the ability to call an external API — in this case Project Gutenberg, to search for books.

First, let’s do some basic setup:

1import json, requests
2from openai import OpenAI
3
4OPENROUTER_API_KEY = f"{{API_KEY_REF}}"
5
6# You can use any model that supports tool calling
7MODEL = "{{MODEL}}"
8
9openai_client = OpenAI(
10 base_url="https://openrouter.ai/api/v1",
11 api_key=OPENROUTER_API_KEY,
12)
13
14task = "What are the titles of some James Joyce books?"
15
16messages = [
17 {
18 "role": "system",
19 "content": "You are a helpful assistant."
20 },
21 {
22 "role": "user",
23 "content": task,
24 }
25]

Define the Tool

Next, we define the tool that we want to call. Remember, the tool is going to get requested by the LLM, but the code we are writing here is ultimately responsible for executing the call and returning the results to the LLM.

1def search_gutenberg_books(search_terms):
2 search_query = " ".join(search_terms)
3 url = "https://gutendex.com/books"
4 response = requests.get(url, params={"search": search_query})
5
6 simplified_results = []
7 for book in response.json().get("results", []):
8 simplified_results.append({
9 "id": book.get("id"),
10 "title": book.get("title"),
11 "authors": book.get("authors")
12 })
13
14 return simplified_results
15
16tools = [
17 {
18 "type": "function",
19 "function": {
20 "name": "search_gutenberg_books",
21 "description": "Search for books in the Project Gutenberg library based on specified search terms",
22 "parameters": {
23 "type": "object",
24 "properties": {
25 "search_terms": {
26 "type": "array",
27 "items": {
28 "type": "string"
29 },
30 "description": "List of search terms to find books in the Gutenberg library (e.g. ['dickens', 'great'] to search for books by Dickens with 'great' in the title)"
31 }
32 },
33 "required": ["search_terms"]
34 }
35 }
36 }
37]
38
39TOOL_MAPPING = {
40 "search_gutenberg_books": search_gutenberg_books
41}

Note that the “tool” is just a normal function. We then write a JSON “spec” compatible with the OpenAI function calling parameter. We’ll pass that spec to the LLM so that it knows this tool is available and how to use it. It will request the tool when needed, along with any arguments. We’ll then marshal the tool call locally, make the function call, and return the results to the LLM.

Tool use and tool results

Let’s make the first OpenRouter API call to the model:

1request_1 = {
2 "model": {{MODEL}},
3 "tools": tools,
4 "messages": messages
5}
6
7response_1 = openai_client.chat.completions.create(**request_1).message

The LLM responds with a finish reason of tool_calls, and a tool_calls array. In a generic LLM response-handler, you would want to check the finish_reason before processing tool calls, but here we will assume it’s the case. Let’s keep going, by processing the tool call:

1# Append the response to the messages array so the LLM has the full context
2# It's easy to forget this step!
3messages.append(response_1)
4
5# Now we process the requested tool calls, and use our book lookup tool
6for tool_call in response_1.tool_calls:
7 '''
8 In this case we only provided one tool, so we know what function to call.
9 When providing multiple tools, you can inspect `tool_call.function.name`
10 to figure out what function you need to call locally.
11 '''
12 tool_name = tool_call.function.name
13 tool_args = json.loads(tool_call.function.arguments)
14 tool_response = TOOL_MAPPING[tool_name](**tool_args)
15 messages.append({
16 "role": "tool",
17 "tool_call_id": tool_call.id,
18 "name": tool_name,
19 "content": json.dumps(tool_response),
20 })

The messages array now has:

  1. Our original request
  2. The LLM’s response (containing a tool call request)
  3. The result of the tool call (a json object returned from the Project Gutenberg API)

Now, we can make a second OpenRouter API call, and hopefully get our result!

1request_2 = {
2 "model": MODEL,
3 "messages": messages,
4 "tools": tools
5}
6
7response_2 = openai_client.chat.completions.create(**request_2)
8
9print(response_2.choices[0].message.content)

The output will be something like:

Here are some books by James Joyce:
* *Ulysses*
* *Dubliners*
* *A Portrait of the Artist as a Young Man*
* *Chamber Music*
* *Exiles: A Play in Three Acts*

We did it! We’ve successfully used a tool in a prompt.

Interleaved Thinking

Interleaved thinking allows models to reason between tool calls, enabling more sophisticated decision-making after receiving tool results. This feature helps models chain multiple tool calls with reasoning steps in between and make nuanced decisions based on intermediate results.

Important: Interleaved thinking increases token usage and response latency. Consider your budget and performance requirements when enabling this feature.

How Interleaved Thinking Works

With interleaved thinking, the model can:

  • Reason about the results of a tool call before deciding what to do next
  • Chain multiple tool calls with reasoning steps in between
  • Make more nuanced decisions based on intermediate results
  • Provide transparent reasoning for its tool selection process

Example: Multi-Step Research with Reasoning

Here’s an example showing how a model might use interleaved thinking to research a topic across multiple sources:

Initial Request:

1{
2 "model": "anthropic/claude-3.5-sonnet",
3 "messages": [
4 {
5 "role": "user",
6 "content": "Research the environmental impact of electric vehicles and provide a comprehensive analysis."
7 }
8 ],
9 "tools": [
10 {
11 "type": "function",
12 "function": {
13 "name": "search_academic_papers",
14 "description": "Search for academic papers on a given topic",
15 "parameters": {
16 "type": "object",
17 "properties": {
18 "query": {"type": "string"},
19 "field": {"type": "string"}
20 },
21 "required": ["query"]
22 }
23 }
24 },
25 {
26 "type": "function",
27 "function": {
28 "name": "get_latest_statistics",
29 "description": "Get latest statistics on a topic",
30 "parameters": {
31 "type": "object",
32 "properties": {
33 "topic": {"type": "string"},
34 "year": {"type": "integer"}
35 },
36 "required": ["topic"]
37 }
38 }
39 }
40 ]
41}

Model’s Reasoning and Tool Calls:

  1. Initial Thinking: “I need to research electric vehicle environmental impact. Let me start with academic papers to get peer-reviewed research.”

  2. First Tool Call: search_academic_papers({"query": "electric vehicle lifecycle environmental impact", "field": "environmental science"})

  3. After First Tool Result: “The papers show mixed results on manufacturing impact. I need current statistics to complement this academic research.”

  4. Second Tool Call: get_latest_statistics({"topic": "electric vehicle carbon footprint", "year": 2024})

  5. After Second Tool Result: “Now I have both academic research and current data. Let me search for manufacturing-specific studies to address the gaps I found.”

  6. Third Tool Call: search_academic_papers({"query": "electric vehicle battery manufacturing environmental cost", "field": "materials science"})

  7. Final Analysis: Synthesizes all gathered information into a comprehensive response.

Best Practices for Interleaved Thinking

  • Clear Tool Descriptions: Provide detailed descriptions so the model can reason about when to use each tool
  • Structured Parameters: Use well-defined parameter schemas to help the model make precise tool calls
  • Context Preservation: Maintain conversation context across multiple tool interactions
  • Error Handling: Design tools to provide meaningful error messages that help the model adjust its approach

Implementation Considerations

When implementing interleaved thinking:

  • Models may take longer to respond due to additional reasoning steps
  • Token usage will be higher due to the reasoning process
  • The quality of reasoning depends on the model’s capabilities
  • Some models may be better suited for this approach than others

A Simple Agentic Loop

In the example above, the calls are made explicitly and sequentially. To handle a wide variety of user inputs and tool calls, you can use an agentic loop.

Here’s an example of a simple agentic loop (using the same tools and initial messages as above):

1def call_llm(msgs):
2 resp = openai_client.chat.completions.create(
3 model={{MODEL}},
4 tools=tools,
5 messages=msgs
6 )
7 msgs.append(resp.choices[0].message.dict())
8 return resp
9
10def get_tool_response(response):
11 tool_call = response.choices[0].message.tool_calls[0]
12 tool_name = tool_call.function.name
13 tool_args = json.loads(tool_call.function.arguments)
14
15 # Look up the correct tool locally, and call it with the provided arguments
16 # Other tools can be added without changing the agentic loop
17 tool_result = TOOL_MAPPING[tool_name](**tool_args)
18
19 return {
20 "role": "tool",
21 "tool_call_id": tool_call.id,
22 "name": tool_name,
23 "content": tool_result,
24 }
25
26max_iterations = 10
27iteration_count = 0
28
29while iteration_count < max_iterations:
30 iteration_count += 1
31 resp = call_llm(_messages)
32
33 if resp.choices[0].message.tool_calls is not None:
34 messages.append(get_tool_response(resp))
35 else:
36 break
37
38if iteration_count >= max_iterations:
39 print("Warning: Maximum iterations reached")
40
41print(messages[-1]['content'])

Best Practices and Advanced Patterns

Function Definition Guidelines

When defining tools for LLMs, follow these best practices:

Clear and Descriptive Names: Use descriptive function names that clearly indicate the tool’s purpose.

1// Good: Clear and specific
2{ "name": "get_weather_forecast" }
1// Avoid: Too vague
2{ "name": "weather" }

Comprehensive Descriptions: Provide detailed descriptions that help the model understand when and how to use the tool.

1{
2 "description": "Get current weather conditions and 5-day forecast for a specific location. Supports cities, zip codes, and coordinates.",
3 "parameters": {
4 "type": "object",
5 "properties": {
6 "location": {
7 "type": "string",
8 "description": "City name, zip code, or coordinates (lat,lng). Examples: 'New York', '10001', '40.7128,-74.0060'"
9 },
10 "units": {
11 "type": "string",
12 "enum": ["celsius", "fahrenheit"],
13 "description": "Temperature unit preference",
14 "default": "celsius"
15 }
16 },
17 "required": ["location"]
18 }
19}

Streaming with Tool Calls

When using streaming responses with tool calls, handle the different content types appropriately:

1const stream = await fetch('/api/chat/completions', {
2 method: 'POST',
3 headers: { 'Content-Type': 'application/json' },
4 body: JSON.stringify({
5 model: 'anthropic/claude-3.5-sonnet',
6 messages: messages,
7 tools: tools,
8 stream: true
9 })
10});
11
12const reader = stream.body.getReader();
13let toolCalls = [];
14
15while (true) {
16 const { done, value } = await reader.read();
17 if (done) {
18 break;
19 }
20
21 const chunk = new TextDecoder().decode(value);
22 const lines = chunk.split('\n').filter(line => line.trim());
23
24 for (const line of lines) {
25 if (line.startsWith('data: ')) {
26 const data = JSON.parse(line.slice(6));
27
28 if (data.choices[0].delta.tool_calls) {
29 toolCalls.push(...data.choices[0].delta.tool_calls);
30 }
31
32 if (data.choices[0].delta.finish_reason === 'tool_calls') {
33 await handleToolCalls(toolCalls);
34 } else if (data.choices[0].delta.finish_reason === 'stop') {
35 // Regular completion without tool calls
36 break;
37 }
38 }
39 }
40}

Tool Choice Configuration

Control tool usage with the tool_choice parameter:

1// Let model decide (default)
2{ "tool_choice": "auto" }
1// Disable tool usage
2{ "tool_choice": "none" }
1// Force specific tool
2{
3 "tool_choice": {
4 "type": "function",
5 "function": {"name": "search_database"}
6 }
7}

Multi-Tool Workflows

Design tools that work well together:

1{
2 "tools": [
3 {
4 "type": "function",
5 "function": {
6 "name": "search_products",
7 "description": "Search for products in the catalog"
8 }
9 },
10 {
11 "type": "function",
12 "function": {
13 "name": "get_product_details",
14 "description": "Get detailed information about a specific product"
15 }
16 },
17 {
18 "type": "function",
19 "function": {
20 "name": "check_inventory",
21 "description": "Check current inventory levels for a product"
22 }
23 }
24 ]
25}

This allows the model to naturally chain operations: search → get details → check inventory.

For more details on OpenRouter’s message format and tool parameters, see the API Reference.