# Function calling (https://inference.net/docs/api/function-calling)

## Introduction

**Function calling** provides a powerful and flexible way for models to interface with your code or external services, and has two primary use cases:

|               |                                                                                                                                                                                          |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Fetching Data | Retrieve up-to-date information to incorporate into the model's response (RAG). Useful for searching knowledge bases and retrieving specific data from APIs (e.g. current weather data). |
| Taking Action | Perform actions like submitting a form, calling APIs, modifying application state (UI/frontend or backend), or taking agentic workflow actions (like handing off the conversation).      |

<Callout tone="info">

If you only want the model to produce JSON, see [structured outputs](/docs/api/structured-outputs/).

</Callout>

## Getting started

You'll need an Inference.net account and API key to use Function Calling. See the [API quickstart](/docs/api/quickstart/) for instructions on how to create an account and get an API key.

Install the [OpenAI SDK](https://platform.openai.com/docs/libraries) for your language of choice.
To connect to Inference.net using the OpenAI SDK, you will need to set the base URL to `https://api.inference.net/v1`.
In this example, we are reading the API key from the environment variable `INFERENCE_API_KEY`.

<CodeTabs>

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.inference.net/v1",
  apiKey: process.env.INFERENCE_API_KEY,
});
```

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
)
```

```bash
export INFERENCE_API_KEY=<your-api-key>
# All requests use:
#   -H "Authorization: Bearer $INFERENCE_API_KEY"
#   -H "Content-Type: application/json"
```

</CodeTabs>

## Overview

You can extend the capabilities of models by giving them access to functions that you define called `tools`. This is also called "function calling".

With function calling, you'll tell the model what tools are available to it, and it will decide which one to use.

You'll then execute the function code, send back the results, and the model will incorporate them into its final response.

![Function calling diagram steps](/docs/images/function-calling-diagram-steps.png)

### Sample function

Let's look at the steps to allow a model to use a real `get_weather` function defined below:

<CodeTabs>

```typescript
async function getWeather(latitude: number, longitude: number) {
  const response = await fetch(
    `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m`
  );
  const data = await response.json();
  return data.current.temperature_2m;
}
```

```python
import requests

def get_weather(latitude, longitude):
    response = requests.get(
        f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}"
        f"&current=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m"
    )
    data = response.json()
    return data["current"]["temperature_2m"]
```

</CodeTabs>

<Callout tone="info">

All functions must return strings. You can format the string as JSON or another format if you like, but the return type itself must be a string.

</Callout>

Unlike the diagram earlier, this function expects precise `latitude` and `longitude` instead of a general `location` parameter.

## Step-by-step example

### Step 1: Call the model with the get_weather tool defined

<CodeTabs>

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.inference.net/v1",
  apiKey: process.env.INFERENCE_API_KEY,
});

const tools: OpenAI.ChatCompletionTool[] = [{
  type: "function",
  function: {
    name: "get_weather",
    description: "Get current temperature for provided coordinates in celsius.",
    parameters: {
      type: "object",
      properties: {
        lat: { type: "number" },
        lon: { type: "number" },
      },
      required: ["lat", "lon"],
      additionalProperties: false,
    },
    strict: true,
  },
}];

const messages: OpenAI.ChatCompletionMessageParam[] = [
  {
    role: "system",
    content: "You are a helpful assistant that can answer questions and uses tools to get information.",
  },
  {
    role: "user",
    content: "What's the weather like in Paris today?",
  },
];

const completion = await client.chat.completions.create({
  model: "kimi-k3-fast",
  messages,
  tools,
});
```

```python
import os
import json
from openai import OpenAI

client = OpenAI(
    base_url="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
)

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current temperature for provided coordinates in celsius.",
        "parameters": {
            "type": "object",
            "properties": {
                "lat": {"type": "number"},
                "lon": {"type": "number"},
            },
            "required": ["lat", "lon"],
            "additionalProperties": False,
        },
        "strict": True,
    },
}]

messages = [
    {"role": "system", "content": "You are a helpful assistant that can answer questions and uses tools to get information."},
    {"role": "user", "content": "What's the weather like in Paris today?"},
]

completion = client.chat.completions.create(
    model="kimi-k3-fast",
    messages=messages,
    tools=tools,
)
```

```bash
curl https://api.inference.net/v1/chat/completions \
  -H "Authorization: Bearer $INFERENCE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "kimi-k3-fast",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant that can answer questions and uses tools to get information."},
      {"role": "user", "content": "What'\''s the weather like in Paris today?"}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get current temperature for provided coordinates in celsius.",
        "parameters": {
          "type": "object",
          "properties": {
            "lat": { "type": "number" },
            "lon": { "type": "number" }
          },
          "required": ["lat", "lon"],
          "additionalProperties": false
        },
        "strict": true
      }
    }]
  }'
```

</CodeTabs>

<Callout tone="info">

Less powerful models may not reliably respond with tool calls, and may not provide all requested parameters.
Experiment with system prompts and other models to find the best results.

</Callout>

### Step 2: Pull the selected function call from the model's response

```json
[
  {
    "id": "call_12345xyz",
    "type": "function",
    "function": {
      "name": "get_weather",
      "arguments": "{\"lat\":48.8566,\"lon\":2.3522}"
    }
  }
]
```

### Step 3: Execute the `get_weather` function

<CodeTabs>

```typescript
const toolCall = completion.choices[0].message.tool_calls[0];
const args = JSON.parse(toolCall.function.arguments);

const result = await getWeather(args.lat, args.lon);
```

```python
tool_call = completion.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)

result = get_weather(args["lat"], args["lon"])
```

</CodeTabs>

### Step 4: Supply the result and call the model again

<CodeTabs>

```typescript
messages.push(completion.choices[0].message); // append model's function call message
messages.push({                               // append result message
  role: "tool",
  tool_call_id: toolCall.id,
  content: result.toString(),
});

const completion2 = await client.chat.completions.create({
  model: "kimi-k3-fast",
  messages,
  tools,
});

console.log(completion2.choices[0].message.content);
```

```python
messages.append(completion.choices[0].message)  # append model's function call message
messages.append({                               # append result message
    "role": "tool",
    "tool_call_id": tool_call.id,
    "content": str(result),
})

completion_2 = client.chat.completions.create(
    model="kimi-k3-fast",
    messages=messages,
    tools=tools,
)

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

</CodeTabs>

### Output

```json
"The current temperature in Paris is 14°C (57.2°F)."
```

## Defining functions

Functions can be set in the `tools` parameter of each API request.

A function is defined by its schema, which informs the model what it does and what input arguments it expects. It comprises the following fields:

| Field       | Description                                         |
| ----------- | --------------------------------------------------- |
| name        | The function's name (e.g. get_weather)              |
| description | Details on when and how to use the function         |
| parameters  | JSON schema defining the function's input arguments |

Take a look at this example:

```json
{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Retrieves current weather for the given location.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and country e.g. Bogotá, Colombia"
                },
                "units": {
                    "type": "string",
                    "enum": [
                        "celsius",
                        "fahrenheit"
                    ],
                    "description": "Units the temperature will be returned in."
                }
            },
            "required": [
                "location",
                "units"
            ],
            "additionalProperties": false
        },
        "strict": true
    }
}
```

Because the `parameters` are defined by a [JSON schema](https://json-schema.org/), you can leverage many of its rich features like property types, enums, and descriptions.

### SDK helpers

While you can define function schemas directly, [OpenAI's SDKs](https://platform.openai.com/docs/libraries) have helpers to convert `pydantic` and `zod` objects into schemas.

<Callout tone="info">

Not all `pydantic` and `zod` features are supported by function calling, but simple, flat schemas are supported.

</Callout>

Here is an example of how to use the SDK to define a schema.

<CodeTabs>

```typescript
import OpenAI from "openai";
import { z } from "zod";
import { zodFunction } from "openai/helpers/zod";

const client = new OpenAI({
  baseURL: "https://api.inference.net/v1",
  apiKey: process.env.INFERENCE_API_KEY,
});

const GetWeatherParameters = z.object({
  location: z.string().describe("City and country e.g. Bogotá, Colombia"),
});

const tools = [
  zodFunction({ name: "getWeather", parameters: GetWeatherParameters }),
];

const messages: OpenAI.ChatCompletionMessageParam[] = [
  { role: "user", content: "What's the weather like in Paris today?" },
];

const response = await client.chat.completions.create({
  model: "kimi-k3-fast",
  messages,
  tools,
});

console.log(response.choices[0].message.tool_calls);
```

```python
import os
from openai import OpenAI, pydantic_function_tool
from pydantic import BaseModel, Field

client = OpenAI(
    base_url="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
)

class GetWeather(BaseModel):
    location: str = Field(
        ...,
        description="City and country e.g. Bogotá, Colombia",
    )

tools = [pydantic_function_tool(GetWeather)]

completion = client.chat.completions.create(
    model="kimi-k3-fast",
    messages=[
        {"role": "system", "content": "You are a helpful assistant that can answer questions and help with tasks."},
        {"role": "user", "content": "What's the weather like in Paris today?"},
    ],
    tools=tools,
)

print(completion.choices[0].message.tool_calls)
```

</CodeTabs>

### Best practices for defining functions

1.  **Write clear and detailed function names, parameter descriptions, and instructions.**

    - **Explicitly describe the purpose of the function and each parameter** (and its format), and what the output represents.
    - **Use the system prompt to describe when (and when not) to use each function.** Generally, tell the model _exactly_ what to do.
    - **Include examples and edge cases**, especially to rectify any recurring failures.

2.  **Apply software engineering best practices.**

    - **Make the functions obvious and intuitive**. ([principle of least surprise](https://en.wikipedia.org/wiki/Principle_of_least_astonishment))
    - **Use enums** and object structure to make invalid states unrepresentable. (e.g. `toggle_light(on: bool, off: bool)` allows for invalid calls)
    - **Pass the intern test.** Can an intern/human correctly use the function given nothing but what you gave the model? (If not, what questions do they ask you? Add the answers to the prompt.)

3.  **Offload the burden from the model and use code where possible.**

    - **Don't make the model fill arguments you already know.** For example, if you already have an `order_id` based on a previous menu, don't have an `order_id` param – instead, have no params `submit_refund()` and pass the `order_id` with code.
    - **Combine functions that are always called in sequence.** For example, if you always call `mark_location()` after `query_location()`, just move the marking logic into the query function call.

4.  **Keep the number of functions small for higher accuracy.**

    - **Evaluate your performance** with different numbers of functions.
    - **Aim for fewer than 20 functions** at any one time, though this is just a soft suggestion.

## Streaming

Use streaming to show function calls as the model produces them. A tool call can arrive as one `delta` with its name and complete `arguments`, or as several deltas that each carry a fragment of `arguments`. Aggregate the deltas by `index` in both cases, as the snippet below does. While the model writes a call's arguments, chunks with an empty `delta` can arrive to keep the connection open. Ignore them.

Streaming function calls is very similar to streaming regular responses: you set `stream` to `true` and get chunks with `delta` objects.

<CodeTabs>

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.inference.net/v1",
  apiKey: process.env.INFERENCE_API_KEY,
});

const tools: OpenAI.ChatCompletionTool[] = [{
  type: "function",
  function: {
    name: "get_weather",
    description: "Get current temperature for a given location.",
    parameters: {
      type: "object",
      properties: {
        location: {
          type: "string",
          description: "City and country e.g. Bogotá, Colombia",
        },
      },
      required: ["location"],
      additionalProperties: false,
    },
    strict: true,
  },
}];

const stream = await client.chat.completions.create({
  model: "kimi-k3-fast",
  messages: [{ role: "user", content: "What's the weather like in Paris today?" }],
  tools,
  stream: true,
});

for await (const chunk of stream) {
  const delta = chunk.choices[0].delta;
  console.log(delta.tool_calls);
}
```

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
)

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current temperature for a given location.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and country e.g. Bogotá, Colombia",
                },
            },
            "required": ["location"],
            "additionalProperties": False,
        },
        "strict": True,
    },
}]

stream = client.chat.completions.create(
    model="kimi-k3-fast",
    messages=[{"role": "user", "content": "What's the weather like in Paris today?"}],
    tools=tools,
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta
    print(delta.tool_calls)
```

```bash
curl -N https://api.inference.net/v1/chat/completions \
  -H "Authorization: Bearer $INFERENCE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "kimi-k3-fast",
    "stream": true,
    "messages": [
      {"role": "user", "content": "What'\''s the weather like in Paris today?"}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get current temperature for a given location.",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "City and country e.g. Bogotá, Colombia"
            }
          },
          "required": ["location"],
          "additionalProperties": false
        },
        "strict": true
      }
    }]
  }'
```

</CodeTabs>

Output of `delta.tool_calls` when the call arrives as one delta:

```text
[{"index": 0, "id": "call_DdmO9pD3xa9XTPNJ32zg2hcA", "function": {"arguments": "{\"location\":\"Paris, France\"}", "name": "get_weather"}, "type": "function"}]
null
```

When a call arrives in fragments, append each delta's `arguments` to the call with the same `index`.

When the model calls one or more functions the `tool_calls` field of each `delta` will be populated. Each `tool_call` contains the following fields:

| Field    | Description                                            |
| -------- | ------------------------------------------------------ |
| index    | Identifies which function call the delta is for        |
| id       | Tool call id.                                          |
| function | Function call delta (name and arguments)               |
| type     | Type of tool_call (always function for function calls) |

The first delta of each tool call has `id`, `type`, and `function.name` set. Later deltas for the same call carry only `arguments` fragments.

Below is a code snippet demonstrating how to aggregate the `delta` objects into a final `tool_calls` object.

<CodeTabs>

```typescript
const finalToolCalls: Record<number, any> = {};

for await (const chunk of stream) {
  const toolCalls = chunk.choices[0].delta.tool_calls || [];
  for (const toolCall of toolCalls) {
    const { index } = toolCall;

    if (!finalToolCalls[index]) {
      finalToolCalls[index] = toolCall;
    } else {
      finalToolCalls[index].function.arguments += toolCall.function.arguments;
    }
  }
}
```

```python
final_tool_calls = {}

for chunk in stream:
    for tool_call in chunk.choices[0].delta.tool_calls or []:
        index = tool_call.index

        if index not in final_tool_calls:
            final_tool_calls[index] = tool_call
        else:
            final_tool_calls[index].function.arguments += tool_call.function.arguments
```

</CodeTabs>

Accumulated `final_tool_calls[0]`:

```json
{
    "index": 0,
    "id": "call_RzfkBpJgzeR0S242qfvjadNe",
    "function": {
        "name": "get_weather",
        "arguments": "{\"location\":\"Paris, France\"}"
    }
}
```