Function Calling SDK platforms tutorial

Function calling makes it easier for you to get structured data outputs from generative models. You can then use these outputs to call other APIs and return the relevant response data to the model. In other words, function calling helps you connect generative models to external systems so that the generated content includes the most up-to-date and accurate information.

You can provide Gemini models with descriptions of functions. These are functions that you write in the language of your app (that is, they're not Google Cloud Functions). The model may ask you to call a function and send back the result to help the model handle your query.

If you haven't already, check out the Introduction to function calling to learn more.

Example API for lighting control

Imagine you have a basic lighting control system with an application programming interface (API) and you want to allow users to control the lights through simple text requests. You can use the Function Calling feature to interpret lighting change requests from users and translate them into API calls to set the lighting values. This hypothetical lighting control system lets you control the brightness of the light and it's color temperature, defined as two separate parameters:

Parameter Type Required Description
brightness number yes Light level from 0 to 100. Zero is off and 100 is full brightness.
colorTemperature string yes Color temperature of the light fixture which can be daylight, cool or warm.

For simplicity, this imaginary lighting system only has one light, so the user does not have to specify a room or location. Here is an example JSON request you could send to the lighting control API to change the light level to 50% using the daylight color temperature:

  "brightness": "50",
  "colorTemperature": "daylight"

This tutorial shows you how to set up a Function Call for the Gemini API to interpret users lighting requests and map them to API settings to control a light's brightness and color temperature values.

Before you begin: Set up your project and API key

Before calling the Gemini API, you need to set up your project and configure your API key.

Define an API function

Create a function that makes an API request. This function should be defined within the code of your application, but could call services or APIs outside of your application. The Gemini API does not call this function directly, so you can control how and when this function is executed through your application code. For demonstration purposes, this tutorial defines a mock API function that just returns the requested lighting values:

func setLightValues(brightness int, colorTemp string) map[string]any {
    // This mock API returns the requested lighting values
    return map[string]any{
        "brightness":       brightness,
        "colorTemperature": colorTemp}

Create a function declaration

Create the function declaration that you'll pass to the generative model. When you declare a function for use by the model, you should include as much detail as possible in the function and parameter descriptions. The generative model uses this information to determine which function to select and how to provide values for the parameters in the function call. The following code shows how to declare the lighting control function:

lightControlTool := &genai.Tool{
    FunctionDeclarations: []*genai.FunctionDeclaration{{
        Name:        "controlLight",
        Description: "Set the brightness and color temperature of a room light.",
        Parameters: &genai.Schema{
            Type: genai.TypeObject,
            Properties: map[string]*genai.Schema{
                "brightness": {
                    Type:        genai.TypeString,
                    Description: "Light level from 0 to 100. Zero is off and"+
                        " 100 is full brightness.",
                "colorTemperature": {
                    Type:        genai.TypeString,
                    Description: "Color temperature of the light fixture which" +
                        " can be `daylight`, `cool` or `warm`.",
            Required: []string{"currencyDate", "currencyFrom"},

Declare functions during model initialization

When you want to use function calling with a model, you must provide your function declarations when you initialize the model object. You declare functions by setting the model's Tools parameter:

// ...

lightControlTool := &genai.Tool{
    // ...

// Use a model that supports function calling, like a Gemini 1.5 model
model := client.GenerativeModel("gemini-1.5-flash")

// Specify the function declaration.
model.Tools = []*genai.Tool{lightControlTool}

Generate a function call

Once you have initialized model with your function declarations, you can prompt the model with the defined function. You should use use function calling using chat prompting (SendMessage()), since function calling generally benefits from having the context of previous prompts and responses.

// Start new chat session.
session := model.StartChat()

prompt := "Dim the lights so the room feels cozy and warm."

// Send the message to the generative model.
resp, err := session.SendMessage(ctx, genai.Text(prompt))
if err != nil {
    log.Fatalf("Error sending message: %v\n", err)

// Check that you got the expected function call back.
part := resp.Candidates[0].Content.Parts[0]
funcall, ok := part.(genai.FunctionCall)
if !ok {
    log.Fatalf("Expected type FunctionCall, got %T", part)
if g, e := funcall.Name, lightControlTool.FunctionDeclarations[0].Name; g != e {
    log.Fatalf("Expected FunctionCall.Name %q, got %q", e, g)
fmt.Printf("Received function call response:\n%q\n\n", part)

apiResult := map[string]any{
    "brightness":  "30",
    "colorTemperature":  "warm" }

// Send the hypothetical API result back to the generative model.
fmt.Printf("Sending API result:\n%q\n\n", apiResult)
resp, err = session.SendMessage(ctx, genai.FunctionResponse{
    Name:     lightControlTool.FunctionDeclarations[0].Name,
    Response: apiResult,
if err != nil {
    log.Fatalf("Error sending message: %v\n", err)

// Show the model's response, which is expected to be text.
for _, part := range resp.Candidates[0].Content.Parts {
    fmt.Printf("%v\n", part)