> ## Documentation Index
> Fetch the complete documentation index at: https://docs.inceptionlabs.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Tool Use

> Use tool calling on the Mercury 3 chat completions endpoint to let the model invoke functions, fetch data, and orchestrate multi-step agent workflows.

Mercury 3 supports OpenAI-compatible tool calling on the chat completions endpoint, including parallel tool calls. You define functions the model may call; when the model decides tools are needed, it returns one or more `tool_calls` with JSON arguments. You then execute the functions and send the results back so the model can produce a final answer.

Set your [API key](https://platform.inceptionlabs.ai/dashboard/api-keys) as an environment variable and install the SDK.

```bash macOS / Linux theme={null}
export INCEPTION_API_KEY="your_api_key_here"
```

```cmd Windows (Command Prompt) theme={null}
set INCEPTION_API_KEY=your_api_key_here
```

```powershell Windows (PowerShell) theme={null}
$env:INCEPTION_API_KEY="your_api_key_here"
```

```bash Python theme={null}
pip install inceptionai
```

```bash TypeScript theme={null}
npm install inceptionai
```

## Request a tool call

Pass your function definitions in `tools`. The model returns a `tool_call` when it needs one.

```bash cURL theme={null}
curl https://api.inceptionlabs.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $INCEPTION_API_KEY" \
  -d '{
    "model": "mercury-3",
    "messages": [{"role": "user", "content": "What'"'"'s the weather like in San Francisco?"}],
    "tools": [{"type": "function", "function": {"name": "get_weather", "description": "Get the current weather in a given location", "parameters": {"type": "object", "properties": {"location": {"type": "string", "description": "City and state, e.g., '"'"'San Francisco, CA'"'"'"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}}, "required": ["location", "unit"]}}}]
  }'
```

```python Python theme={null}
from inceptionai import Inception

client = Inception()  # reads INCEPTION_API_KEY from the environment

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and state, e.g., 'San Francisco, CA'"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["location", "unit"]
        }
    }
}]

completion = client.chat.completions.create(
    model="mercury-3",
    messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
    tools=tools,
)
tool_call = completion.choices[0].message.tool_calls[0].function

print(f"Function called: {tool_call.name}")
print(f"Arguments: {tool_call.arguments}")
```

```typescript TypeScript theme={null}
import Inception from 'inceptionai';

const client = new Inception(); // reads INCEPTION_API_KEY from the environment

const tools = [
  {
    type: 'function' as const,
    function: {
      name: 'get_weather',
      description: 'Get the current weather in a given location',
      parameters: {
        type: 'object',
        properties: {
          location: { type: 'string', description: "City and state, e.g., 'San Francisco, CA'" },
          unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
        },
        required: ['location', 'unit'],
      },
    },
  },
];

const completion = await client.chat.completions.create({
  model: 'mercury-3',
  messages: [{ role: 'user', content: "What's the weather like in San Francisco?" }],
  tools,
});
const toolCall = completion.choices[0]?.message.tool_calls?.[0]?.function;

console.log(`Function called: ${toolCall?.name}`);
console.log(`Arguments: ${toolCall?.arguments}`);
```

## Return the tool result

Execute the requested function, then append the assistant message and a `tool` message (matched by `tool_call_id`) and call the API again. The model uses the result to produce its final response. Repeat this loop for multi-step agent workflows. The examples below reuse the `tools` definition from above.

```python Python theme={null}
import json
from inceptionai import Inception

client = Inception()

def get_weather(location: str, unit: str) -> str:
    # Call your real weather API here.
    return json.dumps({"location": location, "unit": unit, "temperature": 18})

messages = [{"role": "user", "content": "What's the weather like in San Francisco?"}]

# First request — the model asks for a tool call.
completion = client.chat.completions.create(
    model="mercury-3",
    messages=messages,
    tools=tools,
)
message = completion.choices[0].message
tool_call = message.tool_calls[0]
args = json.loads(tool_call.function.arguments)

# Execute the function and send the result back.
result = get_weather(**args)
messages.append(message.model_dump(exclude_none=True))
messages.append({
    "role": "tool",
    "tool_call_id": tool_call.id,
    "content": result,
})

final = client.chat.completions.create(
    model="mercury-3",
    messages=messages,
    tools=tools,
)
print(final.choices[0].message.content)
```

```typescript TypeScript theme={null}
import Inception from 'inceptionai';

const client = new Inception();

function getWeather(location: string, unit: string): string {
  // Call your real weather API here.
  return JSON.stringify({ location, unit, temperature: 18 });
}

const messages = [
  { role: 'user' as const, content: "What's the weather like in San Francisco?" },
];

// First request — the model asks for a tool call.
const completion = await client.chat.completions.create({
  model: 'mercury-3',
  messages,
  tools,
});
const message = completion.choices[0].message;
const toolCall = message.tool_calls![0];
const args = JSON.parse(toolCall.function.arguments);

// Execute the function and send the result back.
const result = getWeather(args.location, args.unit);
const finalMessages = [
  ...messages,
  message,
  {
    role: 'tool' as const,
    tool_call_id: toolCall.id,
    content: result,
  },
];

const final = await client.chat.completions.create({
  model: 'mercury-3',
  messages: finalMessages,
  tools,
});
console.log(final.choices[0]?.message.content);
```

## Parallel tool calls

Mercury 3 can return multiple tool calls in one response when the operations are independent. Execute them concurrently to reduce latency, then append one `tool` message for each call before requesting the final response.

```python Python theme={null}
import json
from concurrent.futures import ThreadPoolExecutor

messages = [{
    "role": "user",
    "content": "What's the weather in San Francisco and New York?",
}]

completion = client.chat.completions.create(
    model="mercury-3",
    messages=messages,
    tools=tools,
)
message = completion.choices[0].message

def execute_tool(tool_call):
    args = json.loads(tool_call.function.arguments)
    return get_weather(**args)

with ThreadPoolExecutor() as executor:
    results = list(executor.map(execute_tool, message.tool_calls))

messages.append(message.model_dump(exclude_none=True))
for tool_call, result in zip(message.tool_calls, results):
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": result,
    })

final = client.chat.completions.create(
    model="mercury-3",
    messages=messages,
    tools=tools,
)
print(final.choices[0].message.content)
```

Use sequential calls when a later operation depends on the result of an earlier one.

## Tool calling parameters

* `tool_choice` Use `tool_choice` to enforce the tool calling behavior that you desire. By default, `tool_choice` is set to `"auto"`. This means that the model will choose to either emit tool calls or output text. If set to `"none"`, tool calls are prevented. If set to `"required"`, the model is forced to emit a tool call in that turn. Use this to enforce the behavior you desire. Just add `tool_choice` to the payload to use it. See below for an example:

```python theme={null}
payload = {
    "model": MODEL,
    "messages": messages,
    "tools": TOOLS,
    "tool_choice": "auto", # <- add this line: "auto" or "required" or "none"
}
body = requests.post(API_URL, headers=HEADERS, json=payload).json()
```

* `strict` Use `strict` to force the model to output the correct tool calling schema that you have specified. We recommend setting this field to `True` for best results. To do this, add `"strict": True` to your tool definition. See below for an example.

```python theme={null}
{
    "type": "function",
    "function": {
        "name": "list_directory",
        "description": "List the entries (files and subdirectories) inside a directory.",
        "strict": True, # <- add this line here
        "parameters": {
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Absolute directory path, e.g. '/repo'.",
                },
            },
            "required": ["path"],
            "additionalProperties": False,
        },
    },
}
```

## Coding agent tool calling demo

See how you can use tool calling with Mercury 3 with the following simple coding agent example. We assume a small codebase of the following structure:

```python theme={null}
### structure ###
/repo
  ├── main.py
  └── stats.py
#################

### stats.py ###
def compute_average(values):
    """Return the arithmetic mean of a list of numbers."""
    if not values:
        return 0.0
    return sum(values) / len(values)
#################

### main.py ###
from stats import compute_average

print(compute_average([1, 2, 3]))
#################
```

### Define tools

First, define your tools. Here, we define two tools for a read-only coding agent: `list_directory` and `read_file`.

```python theme={null}
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "list_directory",
            "description": "List the entries (files and subdirectories) inside a directory.",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Absolute directory path, e.g. '/repo'.",
                    },
                },
                "required": ["path"],
                "additionalProperties": False,
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "read_file",
            "description": "Return the full text contents of a file.",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Absolute file path, e.g. '/repo/stats.py'.",
                    },
                },
                "required": ["path"],
                "additionalProperties": False,
            },
        },
    },
]
```

### Prompt your model

We prompt the model to search the codebase for a specific function and return its definition to the user.

```python theme={null}
SYSTEM_PROMPT = (
    "You are a coding assistant with access to a small filesystem via two tools: "
    "`list_directory` and `read_file`. Use tools to explore the repo before answering. "
    "When you have enough information, reply in plain text with the answer."
)

USER_PROMPT = (
    "The repo lives at `/repo`. Find the definition of the function "
    "`compute_average` and quote its body back to me."
)

messages = [
    {"role": "system", "content": SYSTEM_PROMPT},
    {"role": "user", "content": USER_PROMPT},
]
```

### Run your agent

```python theme={null}
# setup
API_URL = "https://api.inceptionlabs.ai/v1/chat/completions"
MODEL = "mercury-3"
HEADERS = {
    "Authorization": f"Bearer {os.environ['INCEPTION_API_KEY']}",
    "Content-Type": "application/json",
}

# agent loop
for turn in range(3):
    payload = {
        "model": MODEL,
        "messages": messages,
        "tools": TOOLS,
    }
    body = requests.post(API_URL, headers=HEADERS, json=payload).json()
    # 1. parse body for content and tool_calls.
    # 2. execute tools in tool_calls.
    # 3. append model output and tool call results to messages.
```

### Results

When we run the above code, we get the following results:

**Step 1:**

Model's tool call:

```python theme={null}
{'name': 'list_directory', 'arguments': '{"path": "/repo"}'}
```

Tool call output:

```python theme={null}
{"path": "/repo", "entries": ["main.py", "stats.py", "README.md"]}
```

**Step 2:**

Model's tool call:

```python theme={null}
{'name': 'read_file', 'arguments': '{"path": "/repo/stats.py"}'}
```

Tool call output:

```python theme={null}
{"path": "/repo/stats.py", "contents": "def compute_average(values):\n    \"\"\"Return the arithmetic mean of a list of numbers.\"\"\"\n    if not values:\n        return 0.0\n    return sum(values) / len(values)\n"}
```

**Step 3:**

Model's output:

````text theme={null}
Here is the definition of `compute_average` from **/repo/stats.py**:

```python
def compute_average(values):
    """Return the arithmetic mean of a list of numbers."""
    if not values:
        return 0.0
    return sum(values) / len(values)
```
````

See the full demo's code in [this cookbook](https://docs.inceptionlabs.ai/cookbooks/coding-agent-mercury-tool-calling.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.