---
title: "Let a model call your function with tool calling"
slug: "tool-calling"
description: "Describe a function to the model, run it when the model asks, send back the result and read the final answer, step by step in Go."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-llm/tool-calling"
---

# Let a model call your function with tool calling

How does a model ask your code to run a function and use the result in its answer?

## Run it against a real free API

The outputs in this lesson are simulated by a local mock server. To get real answers, create a free key at Mistral AI Free Plan and set these variables. Never put the key in your code.

```sh
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_MODEL=mistral-large-4
export LLM_API_KEY=your-key
```

[Mistral AI Free Plan: what is free and how to get a key](https://aifree.dev/offer/mistral-ai-free-plan)

## Predict

You give the model a get_weather tool and ask about the weather in Hanoi. Who runs get_weather?

- The model, inside the provider's servers
- Your program, when the model asks for it
- The API, by looking it up on the internet

Answer: Your program, when the model asks for it — The model replies with the name and arguments; your code runs the function and sends the result back.

The model asks. Your program decides whether to run the function.

## Describe the tool

You list functions in a `tools` array. Each has a `name`, a `description` and `parameters`, written as a JSON Schema object. The model reads this description like text. When a question needs the function, the reply has no text. It has `tool_calls`: a `name` and `arguments` as a JSON string, and the `finish_reason` is `tool_calls`.

## The model asks for a tool

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	tools := []map[string]any{{
		"type": "function",
		"function": map[string]any{
			"name":        "get_weather",
			"description": "Get the current weather in a city",
			"parameters": map[string]any{
				"type":       "object",
				"properties": map[string]any{"city": map[string]any{"type": "string"}},
				"required":   []string{"city"},
			},
		},
	}}
	payload, _ := json.Marshal(map[string]any{
		"model":    os.Getenv("LLM_MODEL"),
		"messages": []map[string]string{{"role": "user", "content": "What is the weather in Hanoi?"}},
		"tools":    tools,
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer res.Body.Close()

	var out struct {
		Choices []struct {
			FinishReason string `json:"finish_reason"`
			Message      struct {
				ToolCalls []struct {
					Function struct {
						Name      string `json:"name"`
						Arguments string `json:"arguments"`
					} `json:"function"`
				} `json:"tool_calls"`
			} `json:"message"`
		} `json:"choices"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	choice := out.Choices[0]
	call := choice.Message.ToolCalls[0].Function
	fmt.Println("finish reason:", choice.FinishReason)
	fmt.Println("tool:", call.Name)
	fmt.Println("arguments:", call.Arguments)
}
```

Output:

```
finish reason: tool_calls
tool: get_weather
arguments: {"city":"Hanoi"}
```

_Simulated response (local mock server), 2026-12-03._

This is the simulated output. The mock picks the city after the word "in"; a real model decides it by itself.

## Close the loop

Now your code runs the function with those arguments. Then send a second request with the whole conversation so far: your question, the assistant message with its `tool_calls` exactly as it came, and a message with `role` `tool`, the `tool_call_id` of the call and the result as `content`. The model reads the result and writes the final answer.

## The full loop

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

var tools = []map[string]any{{
	"type": "function",
	"function": map[string]any{
		"name":        "get_weather",
		"description": "Get the current weather in a city",
		"parameters": map[string]any{
			"type":       "object",
			"properties": map[string]any{"city": map[string]any{"type": "string"}},
			"required":   []string{"city"},
		},
	},
}}

// getWeather is your code: the model never runs it.
func getWeather(city string) string {
	return fmt.Sprintf(`{"city":%q,"temp_c":31,"condition":"sunny"}`, city)
}

func chat(messages []any) json.RawMessage {
	payload, _ := json.Marshal(map[string]any{
		"model":    os.Getenv("LLM_MODEL"),
		"messages": messages,
		"tools":    tools,
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer res.Body.Close()
	var out struct {
		Choices []struct {
			Message json.RawMessage `json:"message"`
		} `json:"choices"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	return out.Choices[0].Message
}

func main() {
	messages := []any{
		map[string]string{"role": "user", "content": "What is the weather in Hanoi?"},
	}
	first := chat(messages)

	var assistant struct {
		ToolCalls []struct {
			ID       string `json:"id"`
			Function struct {
				Name      string `json:"name"`
				Arguments string `json:"arguments"`
			} `json:"function"`
		} `json:"tool_calls"`
	}
	json.Unmarshal(first, &assistant)
	call := assistant.ToolCalls[0]
	var args struct {
		City string `json:"city"`
	}
	json.Unmarshal([]byte(call.Function.Arguments), &args)
	fmt.Printf("model asked for %s(%s)\n", call.Function.Name, args.City)

	messages = append(messages, first, map[string]string{
		"role":         "tool",
		"tool_call_id": call.ID,
		"content":      getWeather(args.City),
	})
	var final struct {
		Content string `json:"content"`
	}
	json.Unmarshal(chat(messages), &final)
	fmt.Println(final.Content)
}
```

Output:

```
model asked for get_weather(Hanoi)
It is 31°C and sunny in Hanoi.
```

_Simulated response (local mock server), 2026-12-03._

`getWeather` is a local function that returns fixed data. This is the simulated output.

## Fix it

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	messages := []any{
		map[string]string{"role": "user", "content": "What is the weather in Hanoi?"},
		map[string]any{
			"role":    "assistant",
			"content": nil,
			"tool_calls": []map[string]any{{
				"id":       "call_mock_1",
				"type":     "function",
				"function": map[string]string{"name": "get_weather", "arguments": `{"city":"Hanoi"}`},
			}},
		},
		map[string]string{
			"role":    "tool",
			"content": `{"city":"Hanoi","temp_c":31,"condition":"sunny"}`,
		},
	}
	payload, _ := json.Marshal(map[string]any{
		"model":    os.Getenv("LLM_MODEL"),
		"messages": messages,
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer res.Body.Close()

	var out struct {
		Error   struct{ Message string } `json:"error"`
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
	}
	body, _ := io.ReadAll(res.Body)
	json.Unmarshal(body, &out)
	if res.StatusCode != http.StatusOK {
		fmt.Fprintln(os.Stderr, "request failed:", res.Status+":", out.Error.Message)
		os.Exit(1)
	}
	fmt.Println(out.Choices[0].Message.Content)
}
```

The second request is rejected. What is missing?

- The tool message has no tool_call_id
- The tools array is empty
- The temperature is not set

Answer: The tool message has no tool_call_id — The API cannot tell which tool call the result answers, so it refuses the request.

Error message:

```
request failed: 400 Bad Request: tool message needs tool_call_id
```

Fixed:

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	messages := []any{
		map[string]string{"role": "user", "content": "What is the weather in Hanoi?"},
		map[string]any{
			"role":    "assistant",
			"content": nil,
			"tool_calls": []map[string]any{{
				"id":       "call_mock_1",
				"type":     "function",
				"function": map[string]string{"name": "get_weather", "arguments": `{"city":"Hanoi"}`},
			}},
		},
		map[string]string{
			"role":         "tool",
			"tool_call_id": "call_mock_1",
			"content": `{"city":"Hanoi","temp_c":31,"condition":"sunny"}`,
		},
	}
	payload, _ := json.Marshal(map[string]any{
		"model":    os.Getenv("LLM_MODEL"),
		"messages": messages,
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer res.Body.Close()

	var out struct {
		Error   struct{ Message string } `json:"error"`
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
	}
	body, _ := io.ReadAll(res.Body)
	json.Unmarshal(body, &out)
	if res.StatusCode != http.StatusOK {
		fmt.Fprintln(os.Stderr, "request failed:", res.Status+":", out.Error.Message)
		os.Exit(1)
	}
	fmt.Println(out.Choices[0].Message.Content)
}
```

Output:

```
It is 31°C and sunny in Hanoi.
```

_Simulated response (local mock server), 2026-12-03._

## Say it back

Describe the two requests of a tool-calling exchange and what your own code does between them.

Our sentence: The first request carries the question and the tool description, and the model answers with a tool call: a name and JSON arguments. My code runs the function itself. The second request sends back the conversation, the assistant's tool call and a tool message with the result and the call id, and the model writes the final answer.

## Mission (15 min)

Use your free key from the offer at the top. Run the full loop against a real model. Then add a second tool, for example one that returns the time in a city, and check that the model picks the right one.

```sh
export LLM_BASE_URL=<base URL from the offer page>
export LLM_MODEL=<model id from the offer page>
export LLM_API_KEY=<your key>
go run main.go
```

## Common questions

### Does the model really run my function?

No. The model only writes text, here the name of a function and its arguments in JSON. Your program runs the function, so you decide what is allowed, check the arguments and handle errors. That is also why a tool should never do something dangerous just because the model asked for it. Treat the arguments like input from a user.

### What does the tool_call_id do?

The model can ask for several calls in one reply. The id ties each result you send back to the call it answers, so the model knows which result belongs to which call. A tool message without it is rejected by many APIs, which is the error you fixed in this lesson.

### What if the model asks for a tool that does not exist?

Models can invent names or send arguments that do not match your schema. Validate both before you run anything. If a call is wrong, send a tool message with the error text, and the model will often correct itself on the next try. Also put a limit on how many rounds your loop allows, so it cannot run forever.

## Sources

- https://platform.openai.com/docs/guides/function-calling (read 2026-12-03)
- https://docs.mistral.ai/capabilities/function_calling/ (read 2026-12-03)
- https://pkg.go.dev/encoding/json (read 2026-12-03)
- https://pkg.go.dev/net/http (read 2026-12-03)

Simulated responses from a local mock server, not from a real model. Run with local mock server (scripts/course-llm-mock.ts), go1.27.4 darwin/arm64, curl on 2026-12-03.
