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-key

Mistral AI Free Plan: what is free and how to get a key

  1. 1Guess

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

    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.

  3. 3Code

    The model asks for a tool

    1 / 2
    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)
    }
    

    Read the program. What will it print?

  4. 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_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.

  5. 5Code

    The full loop

    1 / 2
    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)
    }
    

    Read the program. What will it print?

  6. 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)
    }
    
    The second request is rejected. What is missing?
  7. 7Say it back

  8. 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

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

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer