# Tool calling

Let a model call your functions: define tools, run what it asks for, send the results back.

With tool calling (also called function calling) a model can ask your code to do something it cannot do itself, such as look up an order or read the weather. You describe your functions in the request. The model answers with the function to call and its arguments. You run it and send the result back, and the model writes the final answer. eWest never runs your functions: the model only asks, and your code does the work.

## Which models

A chat model supports tools when `supports_tools` is `true` in `GET /v1/models/{id}` (the Tool use row in model comparisons). Every chat model in the catalog sets it today. Tools work on [chat completions](https://ewest.ai/docs/chat), on `POST /v1/messages` and on `POST /v1/responses`, and with streaming.

## The loop

1. Send your `messages` and a `tools` list. Each tool is `{"type": "function", "function": {"name", "description", "parameters"}}`, where `parameters` is a JSON Schema for the arguments. Good descriptions matter: the model chooses tools by them.
2. If the model wants a tool, the answer has `finish_reason: "tool_calls"` and `message.tool_calls`. Each call has an `id`, `function.name` and `function.arguments`.
3. Run the function. `arguments` is a JSON **string**: parse it, and expect that it can be invalid or miss a field, because the model writes it.
4. Add the assistant message to `messages` exactly as it came back, then one message per call with `role: "tool"`, the call's `tool_call_id` and your result as a string.
5. Send the request again, with the same `tools`. The model either answers in text (`finish_reason: "stop"`) or asks for more tools. Repeat, and put a limit on the number of rounds.

cURL:

```bash
# 1. Describe the tools. The answer has finish_reason "tool_calls" and a tool_calls list.
curl https://api.ewest.ai/v1/chat/completions \
  -H "Authorization: Bearer $EWEST_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "ewest/gemini-flash",
       "max_tokens": 1024,
       "messages": [{"role": "user", "content": "What is the weather in Paris?"}],
       "tools": [{"type": "function", "function": {
         "name": "get_weather",
         "description": "Current weather for a city.",
         "parameters": {"type": "object",
                        "properties": {"city": {"type": "string"}},
                        "required": ["city"]}}}]}'

# 2. Run the function yourself, then send the conversation back: your first message, the
# assistant message as it came back (with its tool_calls), and one "tool" message per call.
# Put the id from step 1 where this example says CALL_ID.
curl https://api.ewest.ai/v1/chat/completions \
  -H "Authorization: Bearer $EWEST_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "ewest/gemini-flash",
       "max_tokens": 1024,
       "messages": [
         {"role": "user", "content": "What is the weather in Paris?"},
         {"role": "assistant", "content": null, "tool_calls": [
           {"id": "CALL_ID", "type": "function",
            "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}]},
         {"role": "tool", "tool_call_id": "CALL_ID", "content": "{\"temp_c\": 18, \"sky\": \"sunny\"}"}
       ],
       "tools": [{"type": "function", "function": {
         "name": "get_weather",
         "description": "Current weather for a city.",
         "parameters": {"type": "object",
                        "properties": {"city": {"type": "string"}},
                        "required": ["city"]}}}]}'
```

Python:

```python
import json, os, requests

TOOLS = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Current weather for a city.",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string", "description": "For example Paris"}},
            "required": ["city"],
        },
    },
}]

def get_weather(city):  # your own code: call a real weather service here
    return {"city": city, "temp_c": 18, "sky": "sunny"}

FUNCTIONS = {"get_weather": get_weather}

def chat(messages):
    res = requests.post(
        "https://api.ewest.ai/v1/chat/completions",
        headers={"Authorization": f"Bearer {os.environ['EWEST_KEY']}"},
        json={"model": "ewest/gemini-flash", "max_tokens": 1024, "messages": messages, "tools": TOOLS},
        timeout=100,
    )
    res.raise_for_status()
    return res.json()["choices"][0]

messages = [{"role": "user", "content": "What is the weather in Paris and in Rome?"}]
for _ in range(5):  # a limit, so a model that keeps asking cannot loop forever
    choice = chat(messages)
    message = choice["message"]
    messages.append(message)  # keep the assistant message as it came back
    calls = message.get("tool_calls") or []
    if not calls:  # a text answer: done
        break
    for call in calls:  # there can be several in one answer
        try:
            args = json.loads(call["function"]["arguments"])
            result = FUNCTIONS[call["function"]["name"]](**args)
        except Exception as err:  # tell the model, so it can correct itself
            result = {"error": str(err)}
        messages.append({"role": "tool", "tool_call_id": call["id"], "content": json.dumps(result)})
else:  # the loop ended without a text answer
    raise RuntimeError("gave up after 5 tool rounds")

print(message["content"])
```

JavaScript:

```javascript
const tools = [{
  type: "function",
  function: {
    name: "get_weather",
    description: "Current weather for a city.",
    parameters: {
      type: "object",
      properties: { city: { type: "string", description: "For example Paris" } },
      required: ["city"],
    },
  },
}];

// Your own code: call a real weather service here.
const functions = {
  get_weather: ({ city }) => ({ city, temp_c: 18, sky: "sunny" }),
};

async function chat(messages) {
  const res = await fetch("https://api.ewest.ai/v1/chat/completions", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ model: "ewest/gemini-flash", max_tokens: 1024, messages, tools }),
  });
  if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`);
  return (await res.json()).choices[0];
}

const messages = [{ role: "user", content: "What is the weather in Paris and in Rome?" }];
let message;
let answered = false;
for (let turn = 0; turn < 5 && !answered; turn++) { // a limit, so a model that keeps asking cannot loop forever
  message = (await chat(messages)).message;
  messages.push(message); // keep the assistant message as it came back
  const calls = message.tool_calls ?? [];
  answered = calls.length === 0; // a text answer: done
  for (const call of calls) { // there can be several in one answer
    let result;
    try {
      result = functions[call.function.name](JSON.parse(call.function.arguments));
    } catch (err) { // tell the model, so it can correct itself
      result = { error: String(err) };
    }
    messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
  }
}
if (!answered) throw new Error("gave up after 5 tool rounds");

console.log(message.content);
```

## Choosing when a tool is used

`tool_choice` controls it:

- `"auto"` (the default): the model decides.
- `"none"`: the model does not call a tool. The `tools` still count as part of the prompt.
- `"required"`: the model must call at least one tool.
- `{"type": "function", "function": {"name": "get_weather"}}`: the model must call that tool. A name that is not in `tools` is a `400` `invalid_request_error`.

## Several calls at once

A model can ask for more than one tool in the same answer, for example the weather in two cities. Answer every call, each with its own `tool_call_id`, before you send the request again. You can run them at the same time. `"parallel_tool_calls": false` asks the model for at most one call per answer. Treat the `id` as an opaque string: send it back unchanged, and do not parse it or rely on its length or format.

## Tool calls while streaming

With `"stream": true` the calls arrive as `delta.tool_calls` ([Streaming](https://ewest.ai/docs/streaming)). Each entry has an `index`. The first chunk for an index carries the call's `id` and `function.name`; the later ones carry pieces of `function.arguments`. Join the pieces for each index, and parse the result only when the stream has ended with `finish_reason: "tool_calls"`.

## Getting good results

- Give models that think before they answer room in `max_tokens`. With a small limit the model can use it all on thinking and return nothing or a cut-off call. 1024 is a good start; use more if you set `reasoning_effort`, and if the limit is too small for it the `400` names the minimum.
- When a function fails, send the error back as the tool's result instead of stopping. The model can usually correct the arguments.
- Other formats: on `POST /v1/messages` a tool has `name`, `description` and `input_schema`, the answer has `tool_use` blocks and `stop_reason: "tool_use"`, and you reply with a `tool_result` block in the next user message. On `POST /v1/responses` the answer has `function_call` items that you answer with `function_call_output` items, as in the OpenAI Responses API.
- Coding tools use all of this for you; see [Developer tools](https://ewest.ai/docs/guides). For schema-shaped answers without tools, see [Structured output](https://ewest.ai/docs/structured-output).

Source: https://ewest.ai/docs/tool-calling
