# Function Calling

Commonstack Chat API supports tool calling capabilities, enabling models to invoke functions, execute tools in parallel, and handle complex multi-step workflows.Oh.

### Example

{% code expandable="true" %}

```bash
curl -X POST "https://api.commonstack.ai/v1/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <api-key>" \
  -d '{
    "model": "anthropic/claude-sonnet-4.5",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant that can check weather."
      },
      {
        "role": "user",
        "content": "What is the weather 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": "The city and state, e.g. San Francisco, CA"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "Temperature unit"
              }
            },
            "required": ["location"]
          }
        }
      }
    ],
    "tool_choice": "auto",
    "max_tokens": 1000,
    "stream": false
  }'
```

{% endcode %}

### tool\_choice

A string or an object to control when and how tools are called.

<table><thead><tr><th width="363.2578125" valign="bottom">Tool Choice</th><th valign="bottom">Description</th></tr></thead><tbody><tr><td valign="bottom">​<code>auto​</code></td><td valign="bottom">Model decides whether to call tools</td></tr><tr><td valign="bottom">​<code>none</code>​</td><td valign="bottom">Model will not call any tools</td></tr><tr><td valign="bottom"><code>​{type: 'function', name: 'tool_name'}​</code></td><td valign="bottom">Force specific tool call</td></tr></tbody></table>

### Multiple Tools

Supports multi-tool calling to implement complex workflows.

{% tabs %}
{% tab title="Weather tool" %}

```go
// Weather tool definition
var weatherTool = Tool{
    Type: "function",
    Function: Function{
        Name:        "get_weather",
        Description: "Get the current weather in a given location",
        Parameters: Parameters{
            Type: "object",
            Properties: map[string]Property{
                "location": {
                    Type:        "string",
                    Description: "The city and state, e.g. San Francisco, CA or Miami, FL",
                },
                "unit": {
                    Type:        "string",
                    Description: "Temperature unit",
                    Enum:        []string{"celsius", "fahrenheit"},
                },
            },
            Required: []string{"location"},
        },
    },
}
```

{% endtab %}

{% tab title="Web search tool (based on DuckDuckGo V2 version)" %}

```go
// Web search tool definition (based on DuckDuckGo V2 version)
var webSearchTool = Tool{
    Type: "function",
    Function: Function{
        Name:        "web_search",
        Description: "Search the web for current information using DuckDuckGo search engine",
        Parameters: Parameters{
            Type: "object",
            Properties: map[string]Property{
                "query": {
                    Type:        "string",
                    Description: "The search query string",
                },
                "time_range": {
                    Type:        "string",
                    Description: "Time range for search results",
                    Enum:        []string{"day", "week", "month", "year", "all"},
                },
                "max_results": {
                    Type:        "integer",
                    Description: "Maximum number of results to return (default: 5)",
                },
            },
            Required: []string{"query"},
        },
    },
}
```

{% endtab %}

{% tab title="Web search function implementation" %}

```go
// Web search function implementation
func performWebSearch(query string, timeRange string, maxResults int) (*WebSearchResponse, error) {
    // Implement actual DuckDuckGo search logic here
    // Based on V2 version implementation in search results
  

    // Simulate search results
    results := []WebSearchResult{
        {
            Title:   "Web Search Result for: " + query,
            URL:     "https://example.com/result1",
            Summary: "This is a summary of the search result for your query: " + query,
        },
        {
            Title:   "Another Result for: " + query,
            URL:     "https://example.com/result2",
            Summary: "Another summary showing relevant information about your search.",
        },
    }
  

    return &WebSearchResponse{
        Message: fmt.Sprintf("Found %d results for your search", len(results)),
        Results: results,
    }, nil
}
```

{% endtab %}
{% endtabs %}

### Tool Call Response

When tools are called, the response includes function call information:

{% code expandable="true" %}

```json
{
  "id": "817433aba3f1d7ab268d28bf9c8958ea",
  "object": "chat.completion",
  "created": 1768276116,
  "model": "anthropic/claude-sonnet-4-5",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "",
        "tool_calls": [
          {
            "id": "toolu_bdrk_01Gv3nmWK48W98s1dgc8Un6e",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"location\":\"San Francisco, CA\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 623,
    "completion_tokens": 56,
    "total_tokens": 679,
    "tps": 25.43,
    "ttft": 2.2,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cache_creation_input_tokens": 0,
      "cache_read_input_tokens": 0,
      "cached_tokens": 0,
      "image_tokens": 0,
      "text_tokens": 0,
      "video_tokens": 0
    }
  }
}
```

{% endcode %}

{% hint style="info" %}

#### Best Practices

* **Optimize Tool Execution:** Improve efficiency by executing independent tool calls in parallel.
* **Error Handling:** Implement independent error handling and retry mechanisms for each tool call.
* **Result Caching:** Apply appropriate caching strategies for tool call results.
* **Rate Limiting:** Comply with the API provider's rate limiting requirements.
* **Timeout Control:** Set a reasonable timeout for each tool call.
  {% endhint %}
