Let a model call your function with tool calling
Learn LLMs · Beginner · 15 min · After Call a chat completion API with curl and Go
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.
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_MODEL=mistral-large-4
export LLM_API_KEY=your-key1Guess
2Read
Describe the tool
You list functions in a
toolsarray. Each has aname, adescriptionandparameters, 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 hastool_calls: anameandargumentsas a JSON string, and thefinish_reasonistool_calls.3Code
The model asks for a tool
1 / 2package 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) }Read the program. What will it print?
4Read
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_callsexactly as it came, and a message withroletool, thetool_call_idof the call and the result ascontent. The model reads the result and writes the final answer.5Code
The full loop
1 / 2package 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) }Read the program. What will it print?
6Fix
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) }7Say it back
8Mission · 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.
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
Published Dec 3, 2026 · Updated Dec 3, 2026