> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.reka.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.reka.ai/_mcp/server.

Function calling allows users to connect our latest models to external tools, streamlining agentic use cases, and allowing users to integrate our models much more deeply into their workflows. Some examples of tools that users could pass to our model are:

* **Calculator**: Connect our models to a calculator to eliminate all hallucinations, especially if working with complex computations.
* **Internal Databases** Connect our models to your internal tools/databases to allow customers to ask questions about inventory and product availability.
* **REST APIs**: Connect our models to any REST API, allowing our models to access to the particular real-time information that you need to drive your application-specific use case.

## Models That Support Function Calling

Currently, only Reka Flash supports function calling. We are working hard to quickly enable support for our other classes of models.

## Step By Step Example of How to Leverage Function Calling

![Function Calling Workflow](/_fern-img/00e682bbc743fbae1aed372d4db38d86d1647310ef4b487347a3898915c047d7.webp)

In this section, we will go through step by step how to use Reka's function calling capabilities with a concrete example. For this example, we will define two functions: `get_product_availability`, and `get_similar_products`. Both take in a product id, and `get_similar_products` additionally takes in the maximum number of results to return, allowing customers to ask questions about various products.

### Step 1: Define The Tools

First, we must create a specification for each function. We pass these specs to the model to connect them to the tools.

```json
[
    {
        "type": "function",
        "function": {
            "name": "get_product_availability",
            "description": "Determine whether or not a product is currently in stock given a product id.",
            "parameters": {
                "type": "object",
                "properties": {
                    "product_id": {
                        "type": "string",
                        "description": "The unique product id to retrieve availability information for"
                    }
                },
                "required": ["product_id"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_similar_products",
            "description": "Get a list of similar products to a given product id.",
            "parameters": {
                "type": "object",
                "properties": {
                    "product_id": {
                        "type": "string",
                        "description": "The unique product id to retrieve similar products for"
                    },
                    "max_results": {
                        "type": "int",
                        "description": "The maximum number of similar products to return",
                        "default": 3
                    }
                },
                "required": ["product_id"]
            }
        }
    }
]
```

## Step 2: Pass the Tools Along With a User Query to the Model

Now that we have defined the tools our model has access to, we can query the model by passing in these tools along with a user query:

**`OpenAI SDK`**

```python title="OpenAI SDK" maxLines=42
from openai import OpenAI

client = OpenAI(
    base_url="https://api.reka.ai/v1",
    api_key="YOUR_API_KEY",
)

messages = [
    {
        "content": "Is product a-12345 in stock right now?",
        "role": "user",
    },
]

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_product_availability",
            "description": "Determine whether or not a product is currently in stock given a product id.",
            "parameters": {
                "type": "object",
                "properties": {
                    "product_id": {
                        "type": "string",
                        "description": "The unique product id to retrieve availability information for"
                    }
                },
                "required": ["product_id"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_similar_products",
            "description": "Get a list of similar products to a given product id.",
            "parameters": {
                "type": "object",
                "properties": {
                    "product_id": {
                        "type": "string",
                        "description": "The unique product id to retrieve similar products for"
                    },
                    "max_results": {
                        "type": "int",
                        "description": "The maximum number of similar products to return",
                        "default": 3
                    }
                },
                "required": ["product_id"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="reka-flash",
    messages=messages,
    tool_choice="auto",
    tools=tools,
)
tool_call = response.choices[0].message.tool_calls[0]
print(tool_call)
```

**`Python`**

```python title="Python" maxLines=42
import requests

messages = [
    {
        "content": "Is product a-12345 in stock right now?",
        "role": "user",
    },
]

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_product_availability",
            "description": "Determine whether or not a product is currently in stock given a product id.",
            "parameters": {
                "type": "object",
                "properties": {
                    "product_id": {
                        "type": "string",
                        "description": "The unique product id to retrieve availability information for"
                    }
                },
                "required": ["product_id"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_similar_products",
            "description": "Get a list of similar products to a given product id.",
            "parameters": {
                "type": "object",
                "properties": {
                    "product_id": {
                        "type": "string",
                        "description": "The unique product id to retrieve similar products for"
                    },
                    "max_results": {
                        "type": "int",
                        "description": "The maximum number of similar products to return",
                        "default": 3
                    }
                },
                "required": ["product_id"]
            }
        }
    }
]

response = requests.post(
    "https://api.reka.ai/v1/chat/completions",
    headers={
        "X-Api-Key": "YOUR_API_KEY",
        "Content-Type": "application/json",
    },
    json={
        "model": "reka-flash",
        "messages": messages,
        "tool_choice": "auto",
        "tools": tools,
    },
)
data = response.json()
tool_call = data["choices"][0]["message"]["tool_calls"][0]
print(tool_call)
```

**`JavaScript`**

```javascript title="JavaScript" maxLines=42
const tools = [
    {
        name: 'get_product_availability',
        description: 'Determine whether or not a product is currently in stock given a product id.',
        parameters: {
            type: 'object',
            properties: {
                product_id: {
                    type: 'string',
                    description: 'The unique product id to retrieve availability information for'
                }
            },
            required: ['product_id']
        }
    },
    {
        name: 'get_similar_products',
        description: 'Get a list of similar products to a given product id.',
        parameters: {
            type: 'object',
            properties: {
                product_id: {
                    type: 'string',
                    description: 'The unique product id to retrieve similar products for'
                },
                max_results: {
                    type: 'int',
                    description: 'The maximum number of similar products to return',
                    default: 3
                }
            },
            required: ['product_id']
        }
    }
];

const response = await fetch('https://api.reka.ai/v1/chat/completions', {
    method: 'POST',
    headers: {
        'X-Api-Key': 'YOUR_API_KEY',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        model: 'reka-flash',
        tool_choice: 'auto',
        tools: tools,
        messages: [
            { role: 'user', content: 'Is product a-12345 in stock right now?' }
        ],
    }),
});

const data = await response.json();
console.log(data.choices[0].message.tool_calls[0]);
```

**`Go`**

```go title="Go" maxLines=42
package main

import (
	"fmt"
	"io"
	"net/http"
	"strings"
)

func main() {
	jsonStr := `{
		"model": "reka-flash",
		"tool_choice": "auto",
		"tools": [
			{
				"name": "get_product_availability",
				"description": "Determine whether or not a product is currently in stock given a product id.",
				"parameters": {
					"type": "object",
					"properties": {
						"product_id": {
							"type": "string",
							"description": "The unique product id to retrieve availability information for"
						}
					},
					"required": ["product_id"]
				}
			},
			{
				"name": "get_similar_products",
				"description": "Get a list of similar products to a given product id.",
				"parameters": {
					"type": "object",
					"properties": {
						"product_id": {
							"type": "string",
							"description": "The unique product id to retrieve similar products for"
						},
						"max_results": {
							"type": "int",
							"description": "The maximum number of similar products to return",
							"default": 3
						}
					},
					"required": ["product_id"]
				}
			}
		],
		"messages": [
			{
				"role": "user",
				"content": "Is product a-12345 in stock right now?"
			}
		]
	}`

	req, _ := http.NewRequest("POST", "https://api.reka.ai/v1/chat/completions", strings.NewReader(jsonStr))
	req.Header.Set("X-Api-Key", "YOUR_API_KEY")
	req.Header.Set("Content-Type", "application/json")

	resp, _ := http.DefaultClient.Do(req)
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}
```

**`Java`**

```java title="Java" maxLines=42
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

HttpClient client = HttpClient.newHttpClient();
String jsonBody = """
        {
            "model": "reka-flash",
            "tool_choice": "auto",
            "tools": [
                {
                    "name": "get_product_availability",
                    "description": "Determine whether or not a product is currently in stock given a product id.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "product_id": {
                                "type": "string",
                                "description": "The unique product id to retrieve availability information for"
                            }
                        },
                        "required": ["product_id"]
                    }
                },
                {
                    "name": "get_similar_products",
                    "description": "Get a list of similar products to a given product id.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "product_id": {
                                "type": "string",
                                "description": "The unique product id to retrieve similar products for"
                            },
                            "max_results": {
                                "type": "int",
                                "description": "The maximum number of similar products to return",
                                "default": 3
                            }
                        },
                        "required": ["product_id"]
                    }
                }
            ],
            "messages": [
                {
                    "role": "user",
                    "content": "Is product a-12345 in stock right now?"
                }
            ]
        }
        """;

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.reka.ai/v1/chat/completions"))
        .header("X-Api-Key", "YOUR_API_KEY")
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
        .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
```

**`REST`**

```shell title="REST" maxLines=42
curl -X POST https://api.reka.ai/v1/chat/completions \
    -H "X-Api-Key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
        "model": "reka-flash",
        "tool_choice": "auto",
        "tools": [
            {
                "name": "get_product_availability",
                "description": "Determine whether or not a product is currently in stock given a product id.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "product_id": {
                            "type": "string",
                            "description": "The unique product id to retrieve availability information for"
                        }
                    },
                    "required": ["product_id"]
                }
            },
            {
                "name": "get_similar_products",
                "description": "Get a list of similar products to a given product id.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "product_id": {
                            "type": "string",
                            "description": "The unique product id to retrieve similar products for"
                        },
                        "max_results": {
                            "type": "int",
                            "description": "The maximum number of similar products to return",
                            "default": 3
                        }
                    },
                    "required": ["product_id"]
                }
            }
        ],
        "messages": [
            {
                "role": "user",
                "content": "Is product a-12345 in stock right now?"
            }
        ]
    }'
```

The response will contain a tool call like:

```json
{
    "id": "c25b10ed-22b6-4dee-8c22-48844d60d5e8",
    "type": "function",
    "function": {
        "name": "get_product_availability",
        "arguments": "{\"product_id\": \"a-12345\"}"
    }
}
```

#### Tool Choice

The `tool_choice` parameter controls how the model uses the tools you pass. There are three available options:

* **auto** lets the model decide whether or not to invoke a tool. This is the recommended way to do function calling with our models
* **none** disables tool calling. In this case, even if you pass tools to the model, the model will not invoke any tools
* **tool** forces the model to invoke one or more of the tools it has been passed

### Model Response Type

![Tool Choice Flowchart](/_fern-img/c26ef765cd1c3d995613c4fd476f15e445421cf25f0e53d50852d4df6bdcf7c6.webp)

Note that if `tool_choice` is set to `auto`, the model will decide whether or not to invoke a function. If the model chooses to invoke a function, the response message will contain `tool_calls` and `content` will be `null`/`None`. If the model refrains from making a function call, the converse will be true: `tool_calls` will be `null`/`None` and `content` will contain the model's natural language response.

### Step 3: Execute the Function

In the case the model decides to invoke a tool, the next step is to execute the function to obtain the output from the function invocation.

```python
import json

def get_product_availability(product_id: str):
    """This function will actually check the availability of the product
    (by querying a database, for instance)"""

    return "AVAILABLE" # Mock response for the purposes of this example

args = json.loads(tool_call.function.arguments)
product_id = args.get("product_id")
tool_output = get_product_availability(product_id)
```

### Step 4: Pass the Result Back to the Model

Finally, we can pass the result back to the model in order to receive a natural language response based on the result of the function execution. The message history must include the original user message, the assistant's tool call, and the tool output:

**`OpenAI SDK`**

```python title="OpenAI SDK"
import json

messages.extend([
    {
        "role": "assistant",
        "tool_calls": [{
            "id": tool_call.id,
            "type": "function",
            "function": {
                "name": tool_call.function.name,
                "arguments": tool_call.function.arguments,
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": json.dumps({"status": tool_output})
    },
])

response = client.chat.completions.create(
    model="reka-flash",
    messages=messages,
)

print(response.choices[0].message.content)
```

**`Python`**

```python title="Python"
import json
import requests

response = requests.post(
    "https://api.reka.ai/v1/chat/completions",
    headers={
        "X-Api-Key": "YOUR_API_KEY",
        "Content-Type": "application/json",
    },
    json={
        "model": "reka-flash",
        "messages": [
            {
                "role": "user",
                "content": "Is product a-12345 in stock right now?"
            },
            {
                "role": "assistant",
                "tool_calls": [{
                    "id": "c25b10ed-22b6-4dee-8c22-48844d60d5e8",
                    "type": "function",
                    "function": {
                        "name": "get_product_availability",
                        "arguments": "{\"product_id\": \"a-12345\"}"
                    }
                }]
            },
            {
                "role": "tool",
                "tool_call_id": "c25b10ed-22b6-4dee-8c22-48844d60d5e8",
                "content": "{\"status\": \"AVAILABLE\"}"
            }
        ],
    },
)
data = response.json()
print(data["choices"][0]["message"]["content"])
```

**`JavaScript`**

```javascript title="JavaScript"
const response = await fetch('https://api.reka.ai/v1/chat/completions', {
    method: 'POST',
    headers: {
        'X-Api-Key': 'YOUR_API_KEY',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        model: 'reka-flash',
        messages: [
            {
                role: 'user',
                content: 'Is product a-12345 in stock right now?'
            },
            {
                role: 'assistant',
                tool_calls: [{
                    id: 'c25b10ed-22b6-4dee-8c22-48844d60d5e8',
                    type: 'function',
                    function: {
                        name: 'get_product_availability',
                        arguments: '{"product_id": "a-12345"}'
                    }
                }]
            },
            {
                role: 'tool',
                tool_call_id: 'c25b10ed-22b6-4dee-8c22-48844d60d5e8',
                content: '{"status": "AVAILABLE"}'
            }
        ],
    }),
});

const data = await response.json();
console.log(data.choices[0].message.content);
```

**`Go`**

```go title="Go"
package main

import (
	"fmt"
	"io"
	"net/http"
	"strings"
)

func main() {
	jsonStr := `{
		"model": "reka-flash",
		"messages": [
			{
				"role": "user",
				"content": "Is product a-12345 in stock right now?"
			},
			{
				"role": "assistant",
				"tool_calls": [{
					"id": "c25b10ed-22b6-4dee-8c22-48844d60d5e8",
					"type": "function",
					"function": {
						"name": "get_product_availability",
						"arguments": "{\"product_id\": \"a-12345\"}"
					}
				}]
			},
			{
				"role": "tool",
				"tool_call_id": "c25b10ed-22b6-4dee-8c22-48844d60d5e8",
				"content": "{\"status\": \"AVAILABLE\"}"
			}
		]
	}`

	req, _ := http.NewRequest("POST", "https://api.reka.ai/v1/chat/completions", strings.NewReader(jsonStr))
	req.Header.Set("X-Api-Key", "YOUR_API_KEY")
	req.Header.Set("Content-Type", "application/json")

	resp, _ := http.DefaultClient.Do(req)
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}
```

**`Java`**

```java title="Java"
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

HttpClient client = HttpClient.newHttpClient();
String jsonBody = """
        {
            "model": "reka-flash",
            "messages": [
                {
                    "role": "user",
                    "content": "Is product a-12345 in stock right now?"
                },
                {
                    "role": "assistant",
                    "tool_calls": [{
                        "id": "c25b10ed-22b6-4dee-8c22-48844d60d5e8",
                        "type": "function",
                        "function": {
                            "name": "get_product_availability",
                            "arguments": "{\\"product_id\\": \\"a-12345\\"}"
                        }
                    }]
                },
                {
                    "role": "tool",
                    "tool_call_id": "c25b10ed-22b6-4dee-8c22-48844d60d5e8",
                    "content": "{\\"status\\": \\"AVAILABLE\\"}"
                }
            ]
        }
        """;

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.reka.ai/v1/chat/completions"))
        .header("X-Api-Key", "YOUR_API_KEY")
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
        .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
```

**`REST`**

```shell title="REST"
curl -X POST https://api.reka.ai/v1/chat/completions \
    -H "X-Api-Key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
        "model": "reka-flash",
        "messages": [
            {
                "role": "user",
                "content": "Is product a-12345 in stock right now?"
            },
            {
                "role": "assistant",
                "tool_calls": [{
                    "id": "c25b10ed-22b6-4dee-8c22-48844d60d5e8",
                    "type": "function",
                    "function": {
                        "name": "get_product_availability",
                        "arguments": "{\"product_id\": \"a-12345\"}"
                    }
                }]
            },
            {
                "role": "tool",
                "tool_call_id": "c25b10ed-22b6-4dee-8c22-48844d60d5e8",
                "content": "{\"status\": \"AVAILABLE\"}"
            }
        ]
    }'
```

This will return a response like:

```
Yes, product a-12345 is currently available.
```