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

# Function Calling: Connect AI to Your Tools with Swytcho

> Define tools as JSON schemas so the model chooses when to call them. Build agents that fetch live data, run calculations, and interact with external APIs.

Function calling bridges the gap between language models and real-world systems. Instead of only generating text, the model can signal that it wants to invoke a function you define — looking up a database, calling an external API, or running a calculation. Your code executes the function and returns the result, and the model incorporates that result into its final response. This is the foundational pattern for building AI agents.

## How It Works

You include a `tools` array in your request describing the functions available to the model. If the model determines that a function call is the best way to answer the user's request, it returns a response with `finish_reason: "tool_calls"` and a `tool_calls` array instead of a plain text reply. You then execute the requested function with the provided arguments, send the result back as a `tool` role message, and make one more API call to get the model's final answer.

## Step-by-Step

<Steps>
  ### Define your functions as JSON schemas in the `tools` array

  Each tool has a `type` of `"function"` and a `function` object with a `name`, a `description` that guides the model's decision to use it, and a `parameters` schema.

  ```python Python theme={null}
  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_current_weather",
              "description": "Get the current weather conditions for a specific city. Use this when the user asks about current weather.",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "city": {
                          "type": "string",
                          "description": "The city name, e.g. 'San Francisco'",
                      },
                      "unit": {
                          "type": "string",
                          "enum": ["celsius", "fahrenheit"],
                          "description": "The temperature unit to use",
                      },
                  },
                  "required": ["city"],
              },
          },
      }
  ]
  ```

  ### Send a request with the tools defined

  Include the `tools` array alongside your `messages`.

  ```python Python theme={null}
  import os
  import requests

  response = requests.post(
      "https://api.swytcho.com/v1/chat/completions",
      headers={
          "Authorization": f"Bearer {os.environ['SWYTCHO_API_KEY']}",
          "Content-Type": "application/json",
      },
      json={
          "model": "swytcho-1",
          "messages": [
              {"role": "user", "content": "What's the weather like in Tokyo right now?"}
          ],
          "tools": tools,
          "tool_choice": "auto",
      },
  )

  result = response.json()
  message = result["choices"][0]["message"]
  ```

  ### If the model returns `finish_reason: "tool_calls"`, execute the function

  Check whether the model wants to call a function. If it does, extract the function name and arguments, then run your actual function.

  ```python Python theme={null}
  import json

  if result["choices"][0]["finish_reason"] == "tool_calls":
      tool_call = message["tool_calls"][0]
      function_name = tool_call["function"]["name"]
      arguments = json.loads(tool_call["function"]["arguments"])

      # Route to the appropriate function
      if function_name == "get_current_weather":
          # Replace with your real weather API call
          function_result = get_current_weather(
              city=arguments["city"],
              unit=arguments.get("unit", "celsius"),
          )
  ```

  <Warning>
    Always validate and sanitize function arguments before passing them to your backend logic. The model constructs arguments based on user input and its own reasoning — treat them the same way you would treat any untrusted user input. Never pass raw arguments directly to a database query or shell command.
  </Warning>

  ### Send the function result back as a `tool` message

  Append the original assistant message (containing the `tool_calls`) and a new `tool` role message with the result to your messages array, then make another API call.

  ```python Python theme={null}
  messages = [
      {"role": "user", "content": "What's the weather like in Tokyo right now?"},
      message,  # The assistant's tool_calls message
      {
          "role": "tool",
          "tool_call_id": tool_call["id"],
          "content": json.dumps(function_result),
      },
  ]

  final_response = requests.post(
      "https://api.swytcho.com/v1/chat/completions",
      headers={
          "Authorization": f"Bearer {os.environ['SWYTCHO_API_KEY']}",
          "Content-Type": "application/json",
      },
      json={"model": "swytcho-1", "messages": messages, "tools": tools},
  )
  ```

  ### Get the final natural-language response

  The model now has the function result in context and returns a human-readable answer.

  ```python Python theme={null}
  final_result = final_response.json()
  print(final_result["choices"][0]["message"]["content"])
  # → "The current weather in Tokyo is 18°C with partly cloudy skies..."
  ```
</Steps>

## Controlling Tool Use with `tool_choice`

The `tool_choice` parameter lets you override the model's default behavior.

| Value                                                               | Behavior                                                                  |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| `"auto"`                                                            | The model decides whether to call a function or reply with text (default) |
| `"none"`                                                            | The model will never call a function, even if tools are defined           |
| `{"type": "function", "function": {"name": "get_current_weather"}}` | Forces the model to call that specific function                           |

Use `"none"` when you want to ask the model a follow-up question without triggering a tool call. Use a specific function name when the user action unambiguously maps to a single function and you want to skip the model's decision step.

## Parallel Function Calls

<Tip>
  The model can request multiple function calls in a single turn by returning more than one entry in the `tool_calls` array. Execute all requested functions in parallel, then send all results back in one follow-up request — one `tool` message per call, each referencing its corresponding `tool_call_id`. This significantly reduces round-trip latency for agents that need to gather several pieces of information at once.
</Tip>
