SPB Git

Repository Public

function-calling.md 117.6 KB 3,389 lines markdown

1Function calling lets you connect models to external tools and APIs.2Instead of generating text responses, the model determines when to call specific3functions and provides the necessary parameters to execute real-world actions.4This allows the model to act as a bridge between natural language and real-world5actions and data. Function calling has 3 primary use cases:67- [**Take Actions:**](https://ai.google.dev/gemini-api/docs/function-calling#meeting) Interact with external systems using APIs, such as scheduling appointments, creating invoices, sending emails, or controlling smart home devices.8- [**Augment Knowledge:**](https://ai.google.dev/gemini-api/docs/function-calling#weather) Access information from external sources like databases, APIs, and knowledge bases.9- [**Extend Capabilities:**](https://ai.google.dev/gemini-api/docs/function-calling#chart) Use external tools to perform computations and extend the limitations of the model, such as using a calculator or creating charts.1011You can browse examples of these use cases below:1213### Schedule Meeting1415This example shows how to define a function that schedules a meeting with attendees at a specific time, allowing the model to parse user requests and return structured arguments to trigger actions in external systems.1617### Python1819    from google import genai2021    schedule_meeting_function = {22        "type": "function",23        "name": "schedule_meeting",24        "description": "Schedules a meeting with specified attendees at a given time and date.",25        "parameters": {26            "type": "object",27            "properties": {28                "attendees": {"type": "array", "items": {"type": "string"}},29                "date": {"type": "string", "description": "Date (e.g., '2024-07-29')"},30                "time": {"type": "string", "description": "Time (e.g., '15:00')"},31                "topic": {"type": "string", "description": "The meeting topic."},32            },33            "required": ["attendees", "date", "time", "topic"],34        },35    }3637    client = genai.Client()3839    interaction = client.interactions.create(40        model="gemini-3.8-flash",41        input="Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about Q3 planning.",42        tools=[{"type": "function", **schedule_meeting_function}],43    )4445    for step in interaction.steps:46        if step.type == "function_call":47            print(f"Function to call: {step.name}")48            print(f"Arguments: {step.arguments}")4950### JavaScript5152    import { GoogleGenAI } from '@google/genai';5354    const client = new GoogleGenAI({});5556    const scheduleMeetingFunction = {57      type: 'function',58      name: 'schedule_meeting',59      description: 'Schedules a meeting with specified attendees at a given time and date.',60      parameters: {61        type: 'object',62        properties: {63          attendees: { type: 'array', items: { type: 'string' } },64          date: { type: 'string', description: 'Date (e.g., "2024-07-29")' },65          time: { type: 'string', description: 'Time (e.g., "15:00")' },66          topic: { type: 'string', description: 'The meeting topic.' },67        },68        required: ['attendees', 'date', 'time', 'topic'],69      },70    };7172    const interaction = await client.interactions.create({73      model: 'gemini-3.8-flash',74      input: 'Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.',75      tools: [scheduleMeetingFunction],76    });7778    for (const step of interaction.steps) {79      if (step.type === 'function_call') {80        console.log(`Function to call: ${step.name}`);81        console.log(`Arguments: ${JSON.stringify(step.arguments)}`);82      }83    }8485### Java8687    import com.google.genai.Client;88    import com.google.genai.gaos.models.interactions.CreateModelInteraction;89    import com.google.genai.gaos.models.interactions.Function;90    import com.google.genai.gaos.models.interactions.FunctionCallStep;91    import com.google.genai.gaos.models.interactions.Interaction;92    import com.google.genai.gaos.models.interactions.InteractionsInput;93    import com.google.genai.gaos.models.interactions.Model;94    import com.google.genai.gaos.models.interactions.Step;95    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;96    import java.util.Arrays;97    import java.util.Collections;98    import java.util.HashMap;99    import java.util.Map;100101    Client client = new Client();102103    Map<String, Object> attendeesProp = new HashMap<>();104    attendeesProp.put("type", "array");105    attendeesProp.put("items", Collections.singletonMap("type", "string"));106107    Map<String, Object> dateProp = new HashMap<>();108    dateProp.put("type", "string");109    dateProp.put("description", "Date (e.g., '2024-07-29')");110111    Map<String, Object> timeProp = new HashMap<>();112    timeProp.put("type", "string");113    timeProp.put("description", "Time (e.g., '15:00')");114115    Map<String, Object> topicProp = new HashMap<>();116    topicProp.put("type", "string");117    topicProp.put("description", "The meeting topic.");118119    Map<String, Object> properties = new HashMap<>();120    properties.put("attendees", attendeesProp);121    properties.put("date", dateProp);122    properties.put("time", timeProp);123    properties.put("topic", topicProp);124125    Map<String, Object> parameters = new HashMap<>();126    parameters.put("type", "object");127    parameters.put("properties", properties);128    parameters.put("required", Arrays.asList("attendees", "date", "time", "topic"));129130    Function scheduleMeetingFunction =131        Function.builder()132            .name("schedule_meeting")133            .description("Schedules a meeting with specified attendees at a given time and date.")134            .parameters(parameters)135            .build();136137    CreateModelInteraction params =138        CreateModelInteraction.builder()139            .model(Model.of("gemini-3.8-flash"))140            .input(141                InteractionsInput.of(142                    "Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about Q3 planning."))143            .tools(Arrays.asList(scheduleMeetingFunction))144            .build();145146    Interaction interaction =147        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();148149    if (interaction.steps().isPresent()) {150      for (Step step : interaction.steps().get()) {151        if (step instanceof FunctionCallStep) {152          FunctionCallStep functionCall = (FunctionCallStep) step;153          System.out.println("Function to call: " + functionCall.name().orElse(""));154          System.out.println("Arguments: " + functionCall.arguments().orElse(null));155        }156      }157    }158159### Go160161    package main162163    import (164        "context"165        "fmt"166        "log"167168        "google.golang.org/genai"169    )170171    func main() {172        ctx := context.Background()173        client, err := genai.NewClient(ctx, nil)174        if err != nil {175            log.Fatal(err)176        }177178        // Define the function declaration for the model179        scheduleMeetingFunc := &genai.FunctionDeclaration{180            Name:        "schedule_meeting",181            Description: "Schedules a meeting with specified attendees at a given time and date.",182            Parameters: &genai.Schema{183                Type: genai.TypeObject,184                Properties: map[string]*genai.Schema{185                    "attendees": {186                        Type:        genai.TypeArray,187                        Items:       &genai.Schema{Type: genai.TypeString},188                        Description: "List of people attending the meeting.",189                    },190                    "date": {191                        Type:        genai.TypeString,192                        Description: "Date (e.g., '2024-07-29')",193                    },194                    "time": {195                        Type:        genai.TypeString,196                        Description: "Time (e.g., '15:00')",197                    },198                    "topic": {199                        Type:        genai.TypeString,200                        Description: "The meeting topic.",201                    },202                },203                Required: []string{"attendees", "date", "time", "topic"},204            },205        }206207        config := &genai.GenerateContentConfig{208            Tools: []*genai.Tool{209                {FunctionDeclarations: []*genai.FunctionDeclaration{scheduleMeetingFunc}},210            },211        }212213        // Send request with function declarations214        response, err := client.Models.GenerateContent(215            ctx,216            "gemini-3.8-flash",217            genai.Text("Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about Q3 planning."),218            config,219        )220        if err != nil {221            log.Fatal(err)222        }223224        // Check for a function call225        if len(response.FunctionCalls()) > 0 {226            functionCall := response.FunctionCalls()[0]227            fmt.Printf("Function to call: %s\n", functionCall.Name)228            fmt.Printf("Arguments: %v\n", functionCall.Args)229        } else {230            fmt.Println("No function call found in the response.")231            fmt.Println(response.Text())232        }233    }234235### REST236237    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \238      -H "x-goog-api-key: $GEMINI_API_KEY" \239      -H 'Content-Type: application/json' \240      -d '{241        "model": "gemini-3.8-flash",242        "input": "Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.",243        "tools": [{244            "type": "function",245            "name": "schedule_meeting",246            "description": "Schedules a meeting with specified attendees at a given time and date.",247            "parameters": {248              "type": "object",249              "properties": {250                "attendees": {"type": "array", "items": {"type": "string"}},251                "date": {"type": "string"},252                "time": {"type": "string"},253                "topic": {"type": "string"}254              },255              "required": ["attendees", "date", "time", "topic"]256            }257        }]258      }'259260### Get Weather261262This example shows how to define a function that retrieves temperature data for a location, enabling the model to call external APIs to answer queries requiring real-time or external information.263264### Python265266    from google import genai267268    weather_function = {269        "type": "function",270        "name": "get_current_temperature",271        "description": "Gets the current temperature for a given location.",272        "parameters": {273            "type": "object",274            "properties": {275                "location": {276                    "type": "string",277                    "description": "The city name, e.g. San Francisco",278                },279            },280            "required": ["location"],281        },282    }283284    client = genai.Client()285286    interaction = client.interactions.create(287        model="gemini-3.8-flash",288        input="What's the temperature in London?",289        tools=[weather_function],290    )291292    for step in interaction.steps:293        if step.type == "function_call":294            print(f"Function to call: {step.name}")295            print(f"Arguments: {step.arguments}")296297### JavaScript298299    import { GoogleGenAI } from '@google/genai';300301    const client = new GoogleGenAI({});302303    const weatherFunctionDeclaration = {304      type: 'function',305      name: 'get_current_temperature',306      description: 'Gets the current temperature for a given location.',307      parameters: {308        type: 'object',309        properties: {310          location: {311            type: 'string',312            description: 'The city name, e.g. San Francisco',313          },314        },315        required: ['location'],316      },317    };318319    const interaction = await client.interactions.create({320      model: 'gemini-3.8-flash',321      input: "What's the temperature in London?",322      tools: [weatherFunctionDeclaration],323    });324325    for (const step of interaction.steps) {326      if (step.type === 'function_call') {327        console.log(`Function to call: ${step.name}`);328        console.log(`Arguments: ${JSON.stringify(step.arguments)}`);329      }330    }331332### Java333334    import com.google.genai.Client;335    import com.google.genai.gaos.models.interactions.CreateModelInteraction;336    import com.google.genai.gaos.models.interactions.Function;337    import com.google.genai.gaos.models.interactions.FunctionCallStep;338    import com.google.genai.gaos.models.interactions.Interaction;339    import com.google.genai.gaos.models.interactions.InteractionsInput;340    import com.google.genai.gaos.models.interactions.Model;341    import com.google.genai.gaos.models.interactions.Step;342    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;343    import java.util.Arrays;344    import java.util.HashMap;345    import java.util.Map;346347    Client client = new Client();348349    Map<String, Object> locationProp = new HashMap<>();350    locationProp.put("type", "string");351    locationProp.put("description", "The city name, e.g. San Francisco");352353    Map<String, Object> properties = new HashMap<>();354    properties.put("location", locationProp);355356    Map<String, Object> parameters = new HashMap<>();357    parameters.put("type", "object");358    parameters.put("properties", properties);359    parameters.put("required", Arrays.asList("location"));360361    Function weatherFunction =362        Function.builder()363            .name("get_current_temperature")364            .description("Gets the current temperature for a given location.")365            .parameters(parameters)366            .build();367368    CreateModelInteraction params =369        CreateModelInteraction.builder()370            .model(Model.of("gemini-3.8-flash"))371            .input(InteractionsInput.of("What's the temperature in London?"))372            .tools(Arrays.asList(weatherFunction))373            .build();374375    Interaction interaction =376        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();377378    if (interaction.steps().isPresent()) {379      for (Step step : interaction.steps().get()) {380        if (step instanceof FunctionCallStep) {381          FunctionCallStep functionCall = (FunctionCallStep) step;382          System.out.println("Function to call: " + functionCall.name().orElse(""));383          System.out.println("Arguments: " + functionCall.arguments().orElse(null));384        }385      }386    }387388### Go389390    package main391392    import (393        "context"394        "fmt"395        "log"396397        "google.golang.org/genai"398    )399400    func main() {401        ctx := context.Background()402        client, err := genai.NewClient(ctx, nil)403        if err != nil {404            log.Fatal(err)405        }406407        // Define the function declaration for the model408        weatherFunc := &genai.FunctionDeclaration{409            Name:        "get_current_temperature",410            Description: "Gets the current temperature for a given location.",411            Parameters: &genai.Schema{412                Type: genai.TypeObject,413                Properties: map[string]*genai.Schema{414                    "location": {415                        Type:        genai.TypeString,416                        Description: "The city name, e.g. San Francisco",417                    },418                },419                Required: []string{"location"},420            },421        }422423        config := &genai.GenerateContentConfig{424            Tools: []*genai.Tool{425                {FunctionDeclarations: []*genai.FunctionDeclaration{weatherFunc}},426            },427        }428429        // Send request with function declarations430        response, err := client.Models.GenerateContent(431            ctx,432            "gemini-3.8-flash",433            genai.Text("What's the temperature in London?"),434            config,435        )436        if err != nil {437            log.Fatal(err)438        }439440        // Check for a function call441        if len(response.FunctionCalls()) > 0 {442            functionCall := response.FunctionCalls()[0]443            fmt.Printf("Function to call: %s\n", functionCall.Name)444            fmt.Printf("Arguments: %v\n", functionCall.Args)445        } else {446            fmt.Println("No function call found in the response.")447            fmt.Println(response.Text())448        }449    }450451### REST452453    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \454      -H "x-goog-api-key: $GEMINI_API_KEY" \455      -H 'Content-Type: application/json' \456      -d '{457        "model": "gemini-3.8-flash",458        "input": "What'\''s the temperature in London?",459        "tools": [{460          "type": "function",461          "name": "get_current_temperature",462          "description": "Gets the current temperature for a given location.",463          "parameters": {464            "type": "object",465            "properties": {466              "location": {"type": "string", "description": "The city name"}467            },468            "required": ["location"]469          }470        }]471      }'472473### Create Chart474475This example shows how to define a function that generates a bar chart from structured data, demonstrating how the model can use external tools to perform computations or create visual assets:476477### Python478479    from google import genai480481    create_chart_function = {482        "type": "function",483        "name": "create_bar_chart",484        "description": "Creates a bar chart given a title, labels, and values.",485        "parameters": {486            "type": "object",487            "properties": {488                "title": {"type": "string", "description": "The title for the chart."},489                "labels": {"type": "array", "items": {"type": "string"}},490                "values": {"type": "array", "items": {"type": "number"}},491            },492            "required": ["title", "labels", "values"],493        },494    }495496    client = genai.Client()497498    interaction = client.interactions.create(499        model="gemini-3.8-flash",500        input="Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.",501        tools=[create_chart_function],502    )503504    for step in interaction.steps:505        if step.type == "function_call":506            print(f"Function to call: {step.name}")507            print(f"Arguments: {step.arguments}")508509### JavaScript510511    import { GoogleGenAI } from '@google/genai';512513    const client = new GoogleGenAI({});514515    const createChartFunctionDeclaration = {516      type: 'function',517      name: 'create_bar_chart',518      description: 'Creates a bar chart given a title, labels, and values.',519      parameters: {520        type: 'object',521        properties: {522          title: { type: 'string', description: 'The title for the chart.' },523          labels: { type: 'array', items: { type: 'string' } },524          values: { type: 'array', items: { type: 'number' } },525        },526        required: ['title', 'labels', 'values'],527      },528    };529530    const interaction = await client.interactions.create({531      model: 'gemini-3.8-flash',532      input: "Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.",533      tools: [createChartFunctionDeclaration],534    });535536    for (const step of interaction.steps) {537      if (step.type === 'function_call') {538        console.log(`${step.name}(${JSON.stringify(step.arguments)})`);539      }540    }541542### Java543544    import com.google.genai.Client;545    import com.google.genai.gaos.models.interactions.CreateModelInteraction;546    import com.google.genai.gaos.models.interactions.Function;547    import com.google.genai.gaos.models.interactions.FunctionCallStep;548    import com.google.genai.gaos.models.interactions.Interaction;549    import com.google.genai.gaos.models.interactions.InteractionsInput;550    import com.google.genai.gaos.models.interactions.Model;551    import com.google.genai.gaos.models.interactions.Step;552    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;553    import java.util.Arrays;554    import java.util.Collections;555    import java.util.HashMap;556    import java.util.Map;557558    Client client = new Client();559560    Map<String, Object> properties = new HashMap<>();561    Map<String, Object> titleMap = new HashMap<>();562    titleMap.put("type", "string");563    titleMap.put("description", "The title for the chart.");564    properties.put("title", titleMap);565566    Map<String, Object> labelsMap = new HashMap<>();567    labelsMap.put("type", "array");568    labelsMap.put("items", Collections.singletonMap("type", "string"));569    properties.put("labels", labelsMap);570571    Map<String, Object> valuesMap = new HashMap<>();572    valuesMap.put("type", "array");573    valuesMap.put("items", Collections.singletonMap("type", "number"));574    properties.put("values", valuesMap);575576    Map<String, Object> parameters = new HashMap<>();577    parameters.put("type", "object");578    parameters.put("properties", properties);579    parameters.put("required", Arrays.asList("title", "labels", "values"));580581    Function createChartFunction =582        Function.builder()583            .name("create_bar_chart")584            .description("Creates a bar chart given a title, labels, and values.")585            .parameters(parameters)586            .build();587588    CreateModelInteraction params =589        CreateModelInteraction.builder()590            .model(Model.of("gemini-3.8-flash"))591            .input(592                InteractionsInput.of(593                    "Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000."))594            .tools(Arrays.asList(createChartFunction))595            .build();596597    Interaction interaction =598        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();599600    if (interaction.steps().isPresent()) {601      for (Step step : interaction.steps().get()) {602        if (step instanceof FunctionCallStep) {603          FunctionCallStep functionCall = (FunctionCallStep) step;604          System.out.println("Function to call: " + functionCall.name().orElse(""));605          System.out.println("Arguments: " + functionCall.arguments().orElse(null));606        }607      }608    }609610### Go611612    package main613614    import (615        "context"616        "fmt"617        "log"618619        "google.golang.org/genai"620    )621622    func main() {623        ctx := context.Background()624        client, err := genai.NewClient(ctx, nil)625        if err != nil {626            log.Fatal(err)627        }628629        // Define the function declaration for the model630        createChartFunc := &genai.FunctionDeclaration{631            Name:        "create_bar_chart",632            Description: "Creates a bar chart given a title, labels, and values.",633            Parameters: &genai.Schema{634                Type: genai.TypeObject,635                Properties: map[string]*genai.Schema{636                    "title": {637                        Type:        genai.TypeString,638                        Description: "The title for the chart.",639                    },640                    "labels": {641                        Type:  genai.TypeArray,642                        Items: &genai.Schema{Type: genai.TypeString},643                    },644                    "values": {645                        Type:  genai.TypeArray,646                        Items: &genai.Schema{Type: genai.TypeNumber},647                    },648                },649                Required: []string{"title", "labels", "values"},650            },651        }652653        config := &genai.GenerateContentConfig{654            Tools: []*genai.Tool{655                {FunctionDeclarations: []*genai.FunctionDeclaration{createChartFunc}},656            },657        }658659        // Send request with function declarations660        response, err := client.Models.GenerateContent(661            ctx,662            "gemini-3.8-flash",663            genai.Text("Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000."),664            config,665        )666        if err != nil {667            log.Fatal(err)668        }669670        // Check for a function call671        if len(response.FunctionCalls()) > 0 {672            functionCall := response.FunctionCalls()[0]673            fmt.Printf("Function to call: %s\n", functionCall.Name)674            fmt.Printf("Arguments: %v\n", functionCall.Args)675        } else {676            fmt.Println("No function call found in the response.")677            fmt.Println(response.Text())678        }679    }680681### REST682683    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \684      -H "x-goog-api-key: $GEMINI_API_KEY" \685      -H 'Content-Type: application/json' \686      -d '{687        "model": "gemini-3.8-flash",688        "input": "Create a bar chart titled '\''Quarterly Sales'\'' with Q1: 50000, Q2: 75000, Q3: 60000.",689        "tools": [{690            "type": "function",691            "name": "create_bar_chart",692            "description": "Creates a bar chart given a title, labels, and values.",693            "parameters": {694              "type": "object",695              "properties": {696                "title": {"type": "string"},697                "labels": {"type": "array", "items": {"type": "string"}},698                "values": {"type": "array", "items": {"type": "number"}}699              },700              "required": ["title", "labels", "values"]701            }702        }]703      }'704705## How function calling works706707![function calling overview](https://ai.google.dev/static/gemini-api/docs/images/function-calling-overview.png)708709Function calling involves a structured interaction between your application, the710model, and external functions:7117121. **Define Function Declaration:** Define the function's name, parameters, and purpose to the model.7132. **Call LLM with function declarations:** Send user prompt along with the function declaration(s) to the model.7143. **Execute Function Code (Your Responsibility):** The model *doesn't* execute the function itself. Extract the name and args and execute in your application.7154. **Create User friendly response:** Send the result back to the model for a final, user-friendly response.716717This process can be repeated over multiple turns. The model supports calling718multiple functions in a single turn ([parallel function calling](https://ai.google.dev/gemini-api/docs/function-calling#parallel_function_calling)) and in sequence ([compositional function calling](https://ai.google.dev/gemini-api/docs/function-calling#compositional_function_calling)).719720### Step 1: Define a function declaration721722### Python723724    set_light_values_declaration = {725        "type": "function",726        "name": "set_light_values",727        "description": "Sets the brightness and color temperature of a light.",728        "parameters": {729            "type": "object",730            "properties": {731                "brightness": {732                    "type": "integer",733                    "description": "Light level from 0 to 100",734                },735                "color_temp": {736                    "type": "string",737                    "enum": ["daylight", "cool", "warm"],738                    "description": "Color temperature",739                },740            },741            "required": ["brightness", "color_temp"],742        },743    }744745    def set_light_values(brightness: int, color_temp: str) -> dict:746        """Set the brightness and color temperature of a room light."""747        return {"brightness": brightness, "colorTemperature": color_temp}748749### JavaScript750751    const setLightValuesTool = {752      type: 'function',753      name: 'set_light_values',754      description: 'Sets the brightness and color temperature of a light.',755      parameters: {756        type: 'object',757        properties: {758          brightness: { type: 'number', description: 'Light level from 0 to 100' },759          color_temp: { type: 'string', enum: ['daylight', 'cool', 'warm'] },760        },761        required: ['brightness', 'color_temp'],762      },763    };764765    function setLightValues(brightness, color_temp) {766      return { brightness: brightness, colorTemperature: color_temp };767    }768769### Java770771    import com.google.genai.gaos.models.interactions.Function;772    import java.util.Arrays;773    import java.util.HashMap;774    import java.util.Map;775    import java.util.function.BiFunction;776777    Map<String, Object> brightnessProp = new HashMap<>();778    brightnessProp.put("type", "integer");779    brightnessProp.put("description", "Light level from 0 to 100");780781    Map<String, Object> colorTempProp = new HashMap<>();782    colorTempProp.put("type", "string");783    colorTempProp.put("enum", Arrays.asList("daylight", "cool", "warm"));784    colorTempProp.put("description", "Color temperature");785786    Map<String, Object> properties = new HashMap<>();787    properties.put("brightness", brightnessProp);788    properties.put("color_temp", colorTempProp);789790    Map<String, Object> parameters = new HashMap<>();791    parameters.put("type", "object");792    parameters.put("properties", properties);793    parameters.put("required", Arrays.asList("brightness", "color_temp"));794795    Function setLightValuesDeclaration =796        Function.builder()797            .name("set_light_values")798            .description("Sets the brightness and color temperature of a light.")799            .parameters(parameters)800            .build();801802    BiFunction<Integer, String, Map<String, Object>> setLightValues =803        (brightness, colorTemp) -> {804          Map<String, Object> result = new HashMap<>();805          result.put("brightness", brightness);806          result.put("colorTemperature", colorTemp);807          return result;808        };809810### Go811812    package main813814    import "google.golang.org/genai"815816    var setLightValuesDeclaration = &genai.FunctionDeclaration{817        Name:        "set_light_values",818        Description: "Sets the brightness and color temperature of a light.",819        Parameters: &genai.Schema{820            Type: genai.TypeObject,821            Properties: map[string]*genai.Schema{822                "brightness": {823                    Type:        genai.TypeInteger,824                    Description: "Light level from 0 to 100",825                },826                "color_temp": {827                    Type:        genai.TypeString,828                    Enum:        []string{"daylight", "cool", "warm"},829                    Description: "Color temperature",830                },831            },832            Required: []string{"brightness", "color_temp"},833        },834    }835836    func setLightValues(brightness int, colorTemp string) map[string]any {837        return map[string]any{"brightness": brightness, "colorTemperature": colorTemp}838    }839840### Step 2: Call the model with function declarations841842### Python843844    from google import genai845846    client = genai.Client()847848    interaction = client.interactions.create(849        model="gemini-3.8-flash",850        input="Turn the lights down to a romantic level",851        tools=[set_light_values_declaration],852    )853854    fc_step = next(s for s in interaction.steps if s.type == "function_call")855    print(fc_step)856857### JavaScript858859    import { GoogleGenAI } from '@google/genai';860861    const client = new GoogleGenAI({});862863    const interaction = await client.interactions.create({864      model: 'gemini-3.8-flash',865      input: 'Turn the lights down to a romantic level',866      tools: [setLightValuesTool],867    });868869    const fcStep = interaction.steps.find(s => s.type === 'function_call');870    console.log(fcStep);871872### Java873874    import com.google.genai.Client;875    import com.google.genai.gaos.models.interactions.CreateModelInteraction;876    import com.google.genai.gaos.models.interactions.Function;877    import com.google.genai.gaos.models.interactions.FunctionCallStep;878    import com.google.genai.gaos.models.interactions.Interaction;879    import com.google.genai.gaos.models.interactions.InteractionsInput;880    import com.google.genai.gaos.models.interactions.Model;881    import com.google.genai.gaos.models.interactions.Step;882    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;883    import java.util.Arrays;884    import java.util.HashMap;885    import java.util.Map;886887    Client client = new Client();888889    Map<String, Object> brightnessProp = new HashMap<>();890    brightnessProp.put("type", "integer");891    brightnessProp.put("description", "Light level from 0 to 100");892893    Map<String, Object> colorTempProp = new HashMap<>();894    colorTempProp.put("type", "string");895    colorTempProp.put("enum", Arrays.asList("daylight", "cool", "warm"));896    colorTempProp.put("description", "Color temperature");897898    Map<String, Object> properties = new HashMap<>();899    properties.put("brightness", brightnessProp);900    properties.put("color_temp", colorTempProp);901902    Map<String, Object> parameters = new HashMap<>();903    parameters.put("type", "object");904    parameters.put("properties", properties);905    parameters.put("required", Arrays.asList("brightness", "color_temp"));906907    Function setLightValuesDeclaration =908        Function.builder()909            .name("set_light_values")910            .description("Sets the brightness and color temperature of a light.")911            .parameters(parameters)912            .build();913914    CreateModelInteraction params =915        CreateModelInteraction.builder()916            .model(Model.of("gemini-3.8-flash"))917            .input(InteractionsInput.of("Turn the lights down to a romantic level"))918            .tools(Arrays.asList(setLightValuesDeclaration))919            .build();920921    Interaction interaction =922        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();923924    FunctionCallStep fcStep = null;925    if (interaction.steps().isPresent()) {926      for (Step step : interaction.steps().get()) {927        if (step instanceof FunctionCallStep) {928          fcStep = (FunctionCallStep) step;929          break;930        }931      }932    }933    System.out.println(fcStep);934935### Go936937    ctx := context.Background()938    client, err := genai.NewClient(ctx, nil)939    if err != nil {940        log.Fatal(err)941    }942943    config := &genai.GenerateContentConfig{944        Tools: []*genai.Tool{945            {FunctionDeclarations: []*genai.FunctionDeclaration{setLightValuesDeclaration}},946        },947    }948949    contents := []*genai.Content{950        genai.NewContentFromText("Turn the lights down to a romantic level", genai.RoleUser),951    }952953    response, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, config)954    if err != nil {955        log.Fatal(err)956    }957958    fmt.Println(response.FunctionCalls()[0])959960The model returns a `function_call` step with `type`, `name`, and `arguments`:961962    type='function_call'963    name='set_light_values'964    arguments={'color_temp': 'warm', 'brightness': 25}965966### Step 3: Execute the function967968### Python969970    fc_step = next(s for s in interaction.steps if s.type == "function_call")971972    if fc_step.name == "set_light_values":973        result = set_light_values(**fc_step.arguments)974        print(f"Function execution result: {result}")975976### JavaScript977978    const fcStep = interaction.steps.find(s => s.type === 'function_call');979980    let result;981    if (fcStep.name === 'set_light_values') {982      result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp);983      console.log(`Function execution result: ${JSON.stringify(result)}`);984    }985986### Java987988    import com.google.genai.Client;989    import com.google.genai.gaos.models.interactions.CreateModelInteraction;990    import com.google.genai.gaos.models.interactions.Function;991    import com.google.genai.gaos.models.interactions.FunctionCallStep;992    import com.google.genai.gaos.models.interactions.Interaction;993    import com.google.genai.gaos.models.interactions.InteractionsInput;994    import com.google.genai.gaos.models.interactions.Model;995    import com.google.genai.gaos.models.interactions.Step;996    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;997    import java.util.Arrays;998    import java.util.Collections;999    import java.util.HashMap;1000    import java.util.Map;1001    import java.util.function.BiFunction;10021003    Client client = new Client();10041005    Map<String, Object> brightnessProp = new HashMap<>();1006    brightnessProp.put("type", "integer");1007    brightnessProp.put("description", "Light level from 0 to 100");10081009    Map<String, Object> colorTempProp = new HashMap<>();1010    colorTempProp.put("type", "string");1011    colorTempProp.put("enum", Arrays.asList("daylight", "cool", "warm"));1012    colorTempProp.put("description", "Color temperature");10131014    Map<String, Object> properties = new HashMap<>();1015    properties.put("brightness", brightnessProp);1016    properties.put("color_temp", colorTempProp);10171018    Map<String, Object> parameters = new HashMap<>();1019    parameters.put("type", "object");1020    parameters.put("properties", properties);1021    parameters.put("required", Arrays.asList("brightness", "color_temp"));10221023    Function setLightValuesDeclaration =1024        Function.builder()1025            .name("set_light_values")1026            .description("Sets the brightness and color temperature of a light.")1027            .parameters(parameters)1028            .build();10291030    BiFunction<Integer, String, Map<String, Object>> setLightValues =1031        (brightness, colorTemp) -> {1032          Map<String, Object> result = new HashMap<>();1033          result.put("brightness", brightness);1034          result.put("colorTemperature", colorTemp);1035          return result;1036        };10371038    CreateModelInteraction params =1039        CreateModelInteraction.builder()1040            .model(Model.of("gemini-3.8-flash"))1041            .input(InteractionsInput.of("Turn the lights down to a romantic level"))1042            .tools(Arrays.asList(setLightValuesDeclaration))1043            .build();10441045    Interaction interaction =1046        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();10471048    if (interaction.steps().isPresent()) {1049      for (Step step : interaction.steps().get()) {1050        if (step instanceof FunctionCallStep) {1051          FunctionCallStep fcStep = (FunctionCallStep) step;1052          if ("set_light_values".equals(fcStep.name().orElse(""))) {1053            Map<String, Object> args = fcStep.arguments().orElse(Collections.emptyMap());1054            int brightness = ((Number) args.getOrDefault("brightness", 25)).intValue();1055            String colorTemp = (String) args.getOrDefault("color_temp", "warm");1056            Map<String, Object> result = setLightValues.apply(brightness, colorTemp);1057            System.out.println("Function execution result: " + result);1058          }1059        }1060      }1061    }10621063### Go10641065    toolCall := response.FunctionCalls()[0]10661067    var result map[string]any1068    if toolCall.Name == "set_light_values" {1069        brightness := int(toolCall.Args["brightness"].(float64))1070        colorTemp := toolCall.Args["color_temp"].(string)1071        result = setLightValues(brightness, colorTemp)1072        fmt.Printf("Function execution result: %v\n", result)1073    }10741075### Step 4: Send result back to model10761077### Python10781079    final_interaction = client.interactions.create(1080        model="gemini-3.8-flash",1081        input=[1082            {1083                "type": "function_result",1084                "name": fc_step.name,1085                "call_id": fc_step.id,1086                "result": [{"type": "text", "text": json.dumps(result)}],1087            }1088        ],1089        tools=[set_light_values_declaration],1090        previous_interaction_id=interaction.id,1091    )10921093    print(final_interaction.output_text)10941095### JavaScript10961097    const finalInteraction = await client.interactions.create({1098      model: 'gemini-3.8-flash',1099      input: [{1100        type: 'function_result',1101        name: fcStep.name,1102        call_id: fcStep.id,1103        result: [{ type: 'text', text: JSON.stringify(result) }]1104      }],1105      tools: [setLightValuesTool],1106      previous_interaction_id: interaction.id,1107    });11081109    console.log(finalInteraction.output_text);11101111### Java11121113    import com.google.genai.Client;1114    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1115    import com.google.genai.gaos.models.interactions.Function;1116    import com.google.genai.gaos.models.interactions.FunctionCallStep;1117    import com.google.genai.gaos.models.interactions.FunctionResultStep;1118    import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion;1119    import com.google.genai.gaos.models.interactions.FunctionResultSubcontent;1120    import com.google.genai.gaos.models.interactions.Interaction;1121    import com.google.genai.gaos.models.interactions.InteractionsInput;1122    import com.google.genai.gaos.models.interactions.Model;1123    import com.google.genai.gaos.models.interactions.Step;1124    import com.google.genai.gaos.models.interactions.TextContent;1125    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1126    import java.util.Arrays;1127    import java.util.HashMap;1128    import java.util.Map;11291130    Client client = new Client();11311132    Map<String, Object> brightnessProp = new HashMap<>();1133    brightnessProp.put("type", "integer");1134    brightnessProp.put("description", "Light level from 0 to 100");11351136    Map<String, Object> colorTempProp = new HashMap<>();1137    colorTempProp.put("type", "string");1138    colorTempProp.put("enum", Arrays.asList("daylight", "cool", "warm"));1139    colorTempProp.put("description", "Color temperature");11401141    Map<String, Object> properties = new HashMap<>();1142    properties.put("brightness", brightnessProp);1143    properties.put("color_temp", colorTempProp);11441145    Map<String, Object> parameters = new HashMap<>();1146    parameters.put("type", "object");1147    parameters.put("properties", properties);1148    parameters.put("required", Arrays.asList("brightness", "color_temp"));11491150    Function setLightValuesDeclaration =1151        Function.builder()1152            .name("set_light_values")1153            .description("Sets the brightness and color temperature of a light.")1154            .parameters(parameters)1155            .build();11561157    CreateModelInteraction params =1158        CreateModelInteraction.builder()1159            .model(Model.of("gemini-3.8-flash"))1160            .input(InteractionsInput.of("Turn the lights down to a romantic level"))1161            .tools(Arrays.asList(setLightValuesDeclaration))1162            .build();11631164    Interaction interaction =1165        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();11661167    FunctionCallStep fcStep = null;1168    if (interaction.steps().isPresent()) {1169      for (Step step : interaction.steps().get()) {1170        if (step instanceof FunctionCallStep) {1171          fcStep = (FunctionCallStep) step;1172          break;1173        }1174      }1175    }11761177    if (fcStep != null) {1178      String resultJson = "{\"brightness\": 25, \"colorTemperature\": \"warm\"}";1179      FunctionResultStep resultStep =1180          FunctionResultStep.builder()1181              .name(fcStep.name().orElse(""))1182              .callId(fcStep.id().orElse(""))1183              .result(1184                  FunctionResultStepResultUnion.of(1185                      Arrays.<FunctionResultSubcontent>asList(1186                          TextContent.builder().text(resultJson).build())))1187              .build();11881189      CreateModelInteraction finalParams =1190          CreateModelInteraction.builder()1191              .model(Model.of("gemini-3.8-flash"))1192              .previousInteractionId(interaction.id().orElse(""))1193              .tools(Arrays.asList(setLightValuesDeclaration))1194              .input(InteractionsInput.ofStep(Arrays.<Step>asList(resultStep)))1195              .build();11961197      Interaction finalInteraction =1198          client1199              .interactions1200              .create(CreateInteractionRequestBody.of(finalParams))1201              .interaction()1202              .get();12031204      System.out.println(finalInteraction.outputText().orElse(""));1205    }12061207### Go12081209    functionResponsePart := &genai.Part{1210        FunctionResponse: &genai.FunctionResponse{1211            ID:       toolCall.ID,1212            Name:     toolCall.Name,1213            Response: result,1214        },1215    }12161217    contents = append(contents, response.Candidates[0].Content)1218    contents = append(contents, &genai.Content{1219        Role:  genai.RoleUser,1220        Parts: []*genai.Part{functionResponsePart},1221    })12221223    finalResponse, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", contents, config)1224    if err != nil {1225        log.Fatal(err)1226    }12271228    fmt.Println(finalResponse.Text())12291230### Stateless function calling12311232You can also use function calling in stateless mode by managing the conversation history on the client side and setting `store=false`.12331234In stateless mode, you must pass the full history of the conversation in the `input` field of each subsequent request. This history must include:12351. The initial `user_input` step.12362. All model-generated steps returned in Turn 1 (including `thought` and `function_call` steps) exactly as received.12373. The `function_result` step containing the output of your executed function.12381239### Python12401241    from google import genai1242    import json12431244    client = genai.Client()12451246    history = [1247        {1248            "type": "user_input",1249            "content": [{"type": "text", "text": "Turn the lights down to a romantic level"}]1250        }1251    ]12521253    interaction = client.interactions.create(1254        model="gemini-3.8-flash",1255        store=False,1256        input=history,1257        tools=[set_light_values_declaration],1258    )12591260    for step in interaction.steps:1261        history.append(step.model_dump())12621263    fc_step = next(s for s in interaction.steps if s.type == "function_call")1264    if fc_step.name == "set_light_values":1265        result = set_light_values(**fc_step.arguments)12661267    history.append({1268        "type": "function_result",1269        "name": fc_step.name,1270        "call_id": fc_step.id,1271        "result": [{"type": "text", "text": json.dumps(result)}],1272    })12731274    final_interaction = client.interactions.create(1275        model="gemini-3.8-flash",1276        store=False,1277        input=history,1278        tools=[set_light_values_declaration],1279    )12801281    print(final_interaction.output_text)12821283### JavaScript12841285    import { GoogleGenAI } from "@google/genai";12861287    const client = new GoogleGenAI({});12881289    async function main() {1290      const history = [1291        {1292          type: "user_input",1293          content: [{ type: "text", text: "Turn the lights down to a romantic level" }]1294        }1295      ];12961297      const interaction = await client.interactions.create({1298        model: "gemini-3.8-flash",1299        store: false,1300        input: history,1301        tools: [setLightValuesTool],1302      });13031304      history.push(...interaction.steps);13051306      const fcStep = interaction.steps.find(s => s.type === 'function_call');1307      let result;1308      if (fcStep.name === 'set_light_values') {1309        result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp);1310      }13111312      history.push({1313        type: 'function_result',1314        name: fcStep.name,1315        call_id: fcStep.id,1316        result: [{ type: 'text', text: JSON.stringify(result) }]1317      });13181319      const finalInteraction = await client.interactions.create({1320        model: 'gemini-3.8-flash',1321        store: false,1322        input: history,1323        tools: [setLightValuesTool],1324      });13251326      console.log(finalInteraction.output_text);1327    }13281329    await main();13301331### Java13321333    import com.google.genai.Client;1334    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1335    import com.google.genai.gaos.models.interactions.Function;1336    import com.google.genai.gaos.models.interactions.FunctionCallStep;1337    import com.google.genai.gaos.models.interactions.FunctionResultStep;1338    import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion;1339    import com.google.genai.gaos.models.interactions.FunctionResultSubcontent;1340    import com.google.genai.gaos.models.interactions.Interaction;1341    import com.google.genai.gaos.models.interactions.InteractionsInput;1342    import com.google.genai.gaos.models.interactions.Model;1343    import com.google.genai.gaos.models.interactions.Step;1344    import com.google.genai.gaos.models.interactions.TextContent;1345    import com.google.genai.gaos.models.interactions.UserInputStep;1346    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1347    import java.util.ArrayList;1348    import java.util.Arrays;1349    import java.util.HashMap;1350    import java.util.List;1351    import java.util.Map;13521353    Client client = new Client();13541355    Map<String, Object> brightnessProp = new HashMap<>();1356    brightnessProp.put("type", "integer");1357    brightnessProp.put("description", "Light level from 0 to 100");13581359    Map<String, Object> colorTempProp = new HashMap<>();1360    colorTempProp.put("type", "string");1361    colorTempProp.put("enum", Arrays.asList("daylight", "cool", "warm"));1362    colorTempProp.put("description", "Color temperature");13631364    Map<String, Object> properties = new HashMap<>();1365    properties.put("brightness", brightnessProp);1366    properties.put("color_temp", colorTempProp);13671368    Map<String, Object> parameters = new HashMap<>();1369    parameters.put("type", "object");1370    parameters.put("properties", properties);1371    parameters.put("required", Arrays.asList("brightness", "color_temp"));13721373    Function setLightValuesDeclaration =1374        Function.builder()1375            .name("set_light_values")1376            .description("Sets the brightness and color temperature of a light.")1377            .parameters(parameters)1378            .build();13791380    List<Step> history = new ArrayList<>();1381    history.add(1382        UserInputStep.builder()1383            .content(1384                Arrays.asList(1385                    TextContent.builder()1386                        .text("Turn the lights down to a romantic level")1387                        .build()))1388            .build());13891390    CreateModelInteraction params =1391        CreateModelInteraction.builder()1392            .model(Model.of("gemini-3.8-flash"))1393            .store(false)1394            .input(InteractionsInput.ofStep(history))1395            .tools(Arrays.asList(setLightValuesDeclaration))1396            .build();13971398    Interaction interaction =1399        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();14001401    FunctionCallStep fcStep = null;1402    if (interaction.steps().isPresent()) {1403      history.addAll(interaction.steps().get());1404      for (Step step : interaction.steps().get()) {1405        if (step instanceof FunctionCallStep) {1406          fcStep = (FunctionCallStep) step;1407          break;1408        }1409      }1410    }14111412    if (fcStep != null) {1413      String resultJson = "{\"brightness\": 25, \"colorTemperature\": \"warm\"}";1414      history.add(1415          FunctionResultStep.builder()1416              .name(fcStep.name().orElse(""))1417              .callId(fcStep.id().orElse(""))1418              .result(1419                  FunctionResultStepResultUnion.of(1420                      Arrays.<FunctionResultSubcontent>asList(1421                          TextContent.builder().text(resultJson).build())))1422              .build());14231424      CreateModelInteraction finalParams =1425          CreateModelInteraction.builder()1426              .model(Model.of("gemini-3.8-flash"))1427              .store(false)1428              .input(InteractionsInput.ofStep(history))1429              .tools(Arrays.asList(setLightValuesDeclaration))1430              .build();14311432      Interaction finalInteraction =1433          client1434              .interactions1435              .create(CreateInteractionRequestBody.of(finalParams))1436              .interaction()1437              .get();14381439      System.out.println(finalInteraction.outputText().orElse(""));1440    }14411442### Go14431444    ctx := context.Background()1445    client, err := genai.NewClient(ctx, nil)1446    if err != nil {1447        log.Fatal(err)1448    }14491450    config := &genai.GenerateContentConfig{1451        Tools: []*genai.Tool{1452            {FunctionDeclarations: []*genai.FunctionDeclaration{setLightValuesDeclaration}},1453        },1454    }14551456    history := []*genai.Content{1457        genai.NewContentFromText("Turn the lights down to a romantic level", genai.RoleUser),1458    }14591460    response, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", history, config)1461    if err != nil {1462        log.Fatal(err)1463    }14641465    toolCall := response.FunctionCalls()[0]1466    brightness := int(toolCall.Args["brightness"].(float64))1467    colorTemp := toolCall.Args["color_temp"].(string)1468    result := setLightValues(brightness, colorTemp)14691470    history = append(history, response.Candidates[0].Content)1471    history = append(history, &genai.Content{1472        Role: genai.RoleUser,1473        Parts: []*genai.Part{1474            {1475                FunctionResponse: &genai.FunctionResponse{1476                    ID:       toolCall.ID,1477                    Name:     toolCall.Name,1478                    Response: result,1479                },1480            },1481        },1482    })14831484    finalResponse, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", history, config)1485    if err != nil {1486        log.Fatal(err)1487    }14881489    fmt.Println(finalResponse.Text())14901491### REST14921493    # Turn 1: Send request with tools and store: false1494    RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \1495      -H "x-goog-api-key: $GEMINI_API_KEY" \1496      -H 'Content-Type: application/json' \1497      -d '{1498        "model": "gemini-3.8-flash",1499        "store": false,1500        "input": [1501          {1502            "type": "user_input",1503            "content": "Turn the lights down to a romantic level"1504          }1505        ],1506        "tools": [{1507          "type": "function",1508          "name": "set_light_values",1509          "description": "Sets the brightness and color temperature of a light.",1510          "parameters": {1511            "type": "object",1512            "properties": {1513              "brightness": {"type": "integer", "description": "Light level from 0 to 100"},1514              "color_temp": {"type": "string", "enum": ["daylight", "cool", "warm"]}1515            },1516            "required": ["brightness", "color_temp"]1517          }1518        }]1519      }')15201521    # Extract model steps (thought, function_call)1522    MODEL_STEPS=$(echo "$RESPONSE1" | jq '.steps')15231524    # Extract function call details to execute1525    FC_NAME=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .name')1526    FC_ID=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .id')15271528    # Assume local execution returns: {"brightness": 25, "colorTemperature": "warm"}1529    RESULT="{\"brightness\": 25, \"colorTemperature\": \"warm\"}"15301531    # Reconstruct history for Turn 21532    HISTORY=$(jq -n \1533      --argjson first_input '[{"type": "user_input", "content": "Turn the lights down to a romantic level"}]' \1534      --argjson model_steps "$MODEL_STEPS" \1535      --arg fc_name "$FC_NAME" \1536      --arg fc_id "$FC_ID" \1537      --arg result "$RESULT" \1538      '$first_input + $model_steps + [{"type": "function_result", "name": $fc_name, "call_id": $fc_id, "result": [{"type": "text", "text": $result}]}]')15391540    # Turn 2: Send the full history1541    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \1542      -H "x-goog-api-key: $GEMINI_API_KEY" \1543      -H 'Content-Type: application/json' \1544      -d "{1545        \"model\": \"gemini-3.8-flash\",1546        \"store\": false,1547        \"input\": $HISTORY,1548        \"tools\": [{1549          \"type\": \"function\",1550          \"name\": \"set_light_values\",1551          \"description\": \"Sets the brightness and color temperature of a light.\",1552          \"parameters\": {1553            \"type\": \"object\",1554            \"properties\": {1555              \"brightness\": {\"type\": \"integer\"},1556              \"color_temp\": {\"type\": \"string\"}1557            },1558            \"required\": [\"brightness\", \"color_temp\"]1559          }1560        }]1561      }"15621563## Function declarations15641565A function declaration is passed as a tool and includes:15661567- `type` (string): Must be `"function"` for custom functions.1568- `name` (string): Unique function name (use underscores or camelCase).1569- `description` (string): Clear explanation of the function's purpose.1570- `parameters` (object): Input parameters the function expects.1571  - `type` (string): Overall data type, such as `object`.1572  - `properties` (object): Individual parameters with type and description.1573  - `required` (array): Mandatory parameter names.15741575## Function calling with thinking models15761577Gemini 3 series models use an internal ["thinking"](https://ai.google.dev/gemini-api/docs/thinking) process that improves function calling. The SDKs automatically handle [thought signatures](https://ai.google.dev/gemini-api/docs/thought-signatures) for you.15781579## Parallel function calling15801581Call multiple functions at once when they are independent:15821583### Python15841585    power_disco_ball = {"type": "function", "name": "power_disco_ball", "description": "Powers the disco ball.",1586        "parameters": {"type": "object", "properties": {"power": {"type": "boolean"}}, "required": ["power"]}}1587    start_music = {"type": "function", "name": "start_music", "description": "Play music.",1588        "parameters": {"type": "object", "properties": {"energetic": {"type": "boolean"}, "loud": {"type": "boolean"}}, "required": ["energetic", "loud"]}}1589    dim_lights = {"type": "function", "name": "dim_lights", "description": "Dim the lights.",1590        "parameters": {"type": "object", "properties": {"brightness": {"type": "number"}}, "required": ["brightness"]}}15911592    client = genai.Client()15931594    interaction = client.interactions.create(1595        model="gemini-3.8-flash",1596        input="Turn this place into a party!",1597        tools=[power_disco_ball, start_music, dim_lights],1598        generation_config={"tool_choice": "any"},1599    )16001601    for step in interaction.steps:1602        if step.type == "function_call":1603            args = ", ".join(f"{key}={val}" for key, val in step.arguments.items())1604            print(f"{step.name}({args})")16051606### JavaScript16071608    const powerDiscoBall = { type: 'function', name: 'power_disco_ball', description: 'Powers the disco ball.',1609      parameters: { type: 'object', properties: { power: { type: 'boolean' } }, required: ['power'] } };1610    const startMusic = { type: 'function', name: 'start_music', description: 'Play music.',1611      parameters: { type: 'object', properties: { energetic: { type: 'boolean' }, loud: { type: 'boolean' } }, required: ['energetic', 'loud'] } };1612    const dimLights = { type: 'function', name: 'dim_lights', description: 'Dim the lights.',1613      parameters: { type: 'object', properties: { brightness: { type: 'number' } }, required: ['brightness'] } };16141615    const interaction = await client.interactions.create({1616      model: 'gemini-3.8-flash',1617      input: 'Turn this place into a party!',1618      tools: [powerDiscoBall, startMusic, dimLights],1619      generation_config: { tool_choice: 'any' },1620    });16211622    for (const step of interaction.steps) {1623      if (step.type === 'function_call') {1624        console.log(`${step.name}(${JSON.stringify(step.arguments)})`);1625      }1626    }16271628### Java16291630    import com.google.genai.Client;1631    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1632    import com.google.genai.gaos.models.interactions.Function;1633    import com.google.genai.gaos.models.interactions.FunctionCallStep;1634    import com.google.genai.gaos.models.interactions.GenerationConfig;1635    import com.google.genai.gaos.models.interactions.Interaction;1636    import com.google.genai.gaos.models.interactions.InteractionsInput;1637    import com.google.genai.gaos.models.interactions.Model;1638    import com.google.genai.gaos.models.interactions.Step;1639    import com.google.genai.gaos.models.interactions.ToolChoice;1640    import com.google.genai.gaos.models.interactions.ToolChoiceType;1641    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1642    import java.util.Arrays;1643    import java.util.Collections;1644    import java.util.HashMap;1645    import java.util.Map;16461647    Client client = new Client();16481649    Map<String, Object> discoParams = new HashMap<>();1650    discoParams.put("type", "object");1651    discoParams.put(1652        "properties", Collections.singletonMap("power", Collections.singletonMap("type", "boolean")));1653    discoParams.put("required", Arrays.asList("power"));16541655    Function powerDiscoBall =1656        Function.builder()1657            .name("power_disco_ball")1658            .description("Powers the disco ball.")1659            .parameters(discoParams)1660            .build();16611662    Map<String, Object> musicProps = new HashMap<>();1663    musicProps.put("energetic", Collections.singletonMap("type", "boolean"));1664    musicProps.put("loud", Collections.singletonMap("type", "boolean"));1665    Map<String, Object> musicParams = new HashMap<>();1666    musicParams.put("type", "object");1667    musicParams.put("properties", musicProps);1668    musicParams.put("required", Arrays.asList("energetic", "loud"));16691670    Function startMusic =1671        Function.builder()1672            .name("start_music")1673            .description("Play music.")1674            .parameters(musicParams)1675            .build();16761677    Map<String, Object> lightsParams = new HashMap<>();1678    lightsParams.put("type", "object");1679    lightsParams.put(1680        "properties",1681        Collections.singletonMap("brightness", Collections.singletonMap("type", "number")));1682    lightsParams.put("required", Arrays.asList("brightness"));16831684    Function dimLights =1685        Function.builder()1686            .name("dim_lights")1687            .description("Dim the lights.")1688            .parameters(lightsParams)1689            .build();16901691    CreateModelInteraction params =1692        CreateModelInteraction.builder()1693            .model(Model.of("gemini-3.8-flash"))1694            .input(InteractionsInput.of("Turn this place into a party!"))1695            .tools(Arrays.asList(powerDiscoBall, startMusic, dimLights))1696            .generationConfig(1697                GenerationConfig.builder().toolChoice(ToolChoice.of(ToolChoiceType.ANY)).build())1698            .build();16991700    Interaction interaction =1701        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();17021703    if (interaction.steps().isPresent()) {1704      for (Step step : interaction.steps().get()) {1705        if (step instanceof FunctionCallStep) {1706          FunctionCallStep fc = (FunctionCallStep) step;1707          System.out.println(fc.name().orElse("") + "(" + fc.arguments().orElse(null) + ")");1708        }1709      }1710    }17111712### Go17131714    package main17151716    import (1717        "context"1718        "fmt"1719        "log"17201721        "google.golang.org/genai"1722    )17231724    func main() {1725        ctx := context.Background()1726        client, err := genai.NewClient(ctx, nil)1727        if err != nil {1728            log.Fatal(err)1729        }17301731        powerDiscoBall := &genai.FunctionDeclaration{1732            Name:        "power_disco_ball",1733            Description: "Powers the disco ball.",1734            Parameters: &genai.Schema{1735                Type: genai.TypeObject,1736                Properties: map[string]*genai.Schema{1737                    "power": {Type: genai.TypeBoolean},1738                },1739                Required: []string{"power"},1740            },1741        }1742        startMusic := &genai.FunctionDeclaration{1743            Name:        "start_music",1744            Description: "Play music.",1745            Parameters: &genai.Schema{1746                Type: genai.TypeObject,1747                Properties: map[string]*genai.Schema{1748                    "energetic": {Type: genai.TypeBoolean},1749                    "loud":      {Type: genai.TypeBoolean},1750                },1751                Required: []string{"energetic", "loud"},1752            },1753        }1754        dimLights := &genai.FunctionDeclaration{1755            Name:        "dim_lights",1756            Description: "Dim the lights.",1757            Parameters: &genai.Schema{1758                Type: genai.TypeObject,1759                Properties: map[string]*genai.Schema{1760                    "brightness": {Type: genai.TypeNumber},1761                },1762                Required: []string{"brightness"},1763            },1764        }17651766        config := &genai.GenerateContentConfig{1767            Tools: []*genai.Tool{1768                {FunctionDeclarations: []*genai.FunctionDeclaration{powerDiscoBall, startMusic, dimLights}},1769            },1770            ToolConfig: &genai.ToolConfig{1771                FunctionCallingConfig: &genai.FunctionCallingConfig{1772                    Mode: genai.FunctionCallingConfigModeAny,1773                },1774            },1775        }17761777        response, err := client.Models.GenerateContent(1778            ctx,1779            "gemini-3.8-flash",1780            genai.Text("Turn this place into a party!"),1781            config,1782        )1783        if err != nil {1784            log.Fatal(err)1785        }17861787        for _, fn := range response.FunctionCalls() {1788            fmt.Printf("%s(%v)\n", fn.Name, fn.Args)1789        }1790    }17911792### REST17931794    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \1795      -H "x-goog-api-key: $GEMINI_API_KEY" \1796      -H 'Content-Type: application/json' \1797      -d '{1798        "model": "gemini-3.8-flash",1799        "input": "Turn this place into a party!",1800        "tools": [1801          {1802            "type": "function",1803            "name": "power_disco_ball",1804            "description": "Powers the disco ball.",1805            "parameters": {1806              "type": "object",1807              "properties": {1808                "power": {"type": "boolean"}1809              },1810              "required": ["power"]1811            }1812          },1813          {1814            "type": "function",1815            "name": "start_music",1816            "description": "Play music.",1817            "parameters": {1818              "type": "object",1819              "properties": {1820                "energetic": {"type": "boolean"},1821                "loud": {"type": "boolean"}1822              },1823              "required": ["energetic", "loud"]1824            }1825          },1826          {1827            "type": "function",1828            "name": "dim_lights",1829            "description": "Dim the lights.",1830            "parameters": {1831              "type": "object",1832              "properties": {1833                "brightness": {"type": "number"}1834              },1835              "required": ["brightness"]1836            }1837          }1838        ]1839      }'18401841## Compositional function calling18421843Chain multiple function calls together for complex requests (e.g., get location1844first, then get weather for that location).18451846### Python18471848    get_weather_forecast_declaration = {1849        "type": "function",1850        "name": "get_weather_forecast",1851        "description": "Gets the current weather temperature for a given location.",1852        "parameters": {1853            "type": "object",1854            "properties": {1855                "location": {"type": "string", "description": "The location"},1856            },1857            "required": ["location"],1858        },1859    }18601861    set_thermostat_temperature_declaration = {1862        "type": "function",1863        "name": "set_thermostat_temperature",1864        "description": "Sets the thermostat to a desired temperature.",1865        "parameters": {1866            "type": "object",1867            "properties": {1868                "temperature": {1869                    "type": "integer",1870                    "description": "The temperature in Celsius",1871                },1872            },1873            "required": ["temperature"],1874        },1875    }18761877    client = genai.Client()18781879    interaction = client.interactions.create(1880        model="gemini-3.8-flash",1881        input="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.",1882        tools=[1883            get_weather_forecast_declaration,1884            set_thermostat_temperature_declaration,1885        ],1886    )18871888    for step in interaction.steps:1889        if step.type == "function_call":1890            print(f"Function to call: {step.name}")1891            print(f"Arguments: {step.arguments}")1892        elif hasattr(step, "content") and step.content:1893             for part in step.content:1894                 if hasattr(part, "text"):1895                     print(part.text)18961897### JavaScript18981899    import { GoogleGenAI } from '@google/genai';19001901    const client = new GoogleGenAI({});19021903    const getWeatherForecastTool = {1904      type: 'function',1905      name: 'get_weather_forecast',1906      description: 'Gets the current weather temperature for a given location.',1907      parameters: {1908        type: 'object',1909        properties: {1910          location: { type: 'string', description: 'The location' },1911        },1912        required: ['location'],1913      },1914    };19151916    const setThermostatTemperatureTool = {1917      type: 'function',1918      name: 'set_thermostat_temperature',1919      description: 'Sets the thermostat to a desired temperature.',1920      parameters: {1921        type: 'object',1922        properties: {1923          temperature: {1924            type: 'integer',1925            description: 'The temperature in Celsius',1926          },1927        },1928        required: ['temperature'],1929      },1930    };19311932    const interaction = await client.interactions.create({1933      model: 'gemini-3.8-flash',1934      input: "If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.",1935      tools: [1936        getWeatherForecastTool,1937        setThermostatTemperatureTool,1938      ],1939    });19401941    for (const step of interaction.steps) {1942      if (step.type === 'function_call') {1943        console.log(`Function to call: ${step.name}`);1944        console.log(`Arguments: ${JSON.stringify(step.arguments)}`);1945      } else if (step.content) {1946        for (const part of step.content) {1947          if (part.text) {1948            console.log(part.text);1949          }1950        }1951      }1952    }19531954### Java19551956    import com.google.genai.Client;1957    import com.google.genai.gaos.models.interactions.Content;1958    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1959    import com.google.genai.gaos.models.interactions.Function;1960    import com.google.genai.gaos.models.interactions.FunctionCallStep;1961    import com.google.genai.gaos.models.interactions.Interaction;1962    import com.google.genai.gaos.models.interactions.InteractionsInput;1963    import com.google.genai.gaos.models.interactions.Model;1964    import com.google.genai.gaos.models.interactions.ModelOutputStep;1965    import com.google.genai.gaos.models.interactions.Step;1966    import com.google.genai.gaos.models.interactions.TextContent;1967    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1968    import java.util.Arrays;1969    import java.util.HashMap;1970    import java.util.Map;19711972    Client client = new Client();19731974    Map<String, Object> locationProp = new HashMap<>();1975    locationProp.put("type", "string");1976    locationProp.put("description", "The location");19771978    Map<String, Object> weatherProps = new HashMap<>();1979    weatherProps.put("location", locationProp);19801981    Map<String, Object> weatherParams = new HashMap<>();1982    weatherParams.put("type", "object");1983    weatherParams.put("properties", weatherProps);1984    weatherParams.put("required", Arrays.asList("location"));19851986    Function getWeatherForecastDeclaration =1987        Function.builder()1988            .name("get_weather_forecast")1989            .description("Gets the current weather temperature for a given location.")1990            .parameters(weatherParams)1991            .build();19921993    Map<String, Object> tempProp = new HashMap<>();1994    tempProp.put("type", "integer");1995    tempProp.put("description", "The temperature in Celsius");19961997    Map<String, Object> thermostatProps = new HashMap<>();1998    thermostatProps.put("temperature", tempProp);19992000    Map<String, Object> thermostatParams = new HashMap<>();2001    thermostatParams.put("type", "object");2002    thermostatParams.put("properties", thermostatProps);2003    thermostatParams.put("required", Arrays.asList("temperature"));20042005    Function setThermostatTemperatureDeclaration =2006        Function.builder()2007            .name("set_thermostat_temperature")2008            .description("Sets the thermostat to a desired temperature.")2009            .parameters(thermostatParams)2010            .build();20112012    CreateModelInteraction params =2013        CreateModelInteraction.builder()2014            .model(Model.of("gemini-3.8-flash"))2015            .input(2016                InteractionsInput.of(2017                    "If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C."))2018            .tools(Arrays.asList(getWeatherForecastDeclaration, setThermostatTemperatureDeclaration))2019            .build();20202021    Interaction interaction =2022        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();20232024    if (interaction.steps().isPresent()) {2025      for (Step step : interaction.steps().get()) {2026        if (step instanceof FunctionCallStep) {2027          FunctionCallStep fc = (FunctionCallStep) step;2028          System.out.println("Function to call: " + fc.name().orElse(""));2029          System.out.println("Arguments: " + fc.arguments().orElse(null));2030        } else if (step instanceof ModelOutputStep) {2031          ModelOutputStep outputStep = (ModelOutputStep) step;2032          if (outputStep.content().isPresent()) {2033            for (Content part : outputStep.content().get()) {2034              if (part instanceof TextContent) {2035                System.out.println(((TextContent) part).text().orElse(""));2036              }2037            }2038          }2039        }2040      }2041    }20422043### Go20442045    package main20462047    import (2048        "context"2049        "fmt"2050        "log"20512052        "google.golang.org/genai"2053    )20542055    func main() {2056        ctx := context.Background()2057        client, err := genai.NewClient(ctx, nil)2058        if err != nil {2059            log.Fatal(err)2060        }20612062        getWeatherForecastDecl := &genai.FunctionDeclaration{2063            Name:        "get_weather_forecast",2064            Description: "Gets the current weather temperature for a given location.",2065            Parameters: &genai.Schema{2066                Type: genai.TypeObject,2067                Properties: map[string]*genai.Schema{2068                    "location": {Type: genai.TypeString, Description: "The location"},2069                },2070                Required: []string{"location"},2071            },2072        }20732074        setThermostatTemperatureDecl := &genai.FunctionDeclaration{2075            Name:        "set_thermostat_temperature",2076            Description: "Sets the thermostat to a desired temperature.",2077            Parameters: &genai.Schema{2078                Type: genai.TypeObject,2079                Properties: map[string]*genai.Schema{2080                    "temperature": {Type: genai.TypeInteger, Description: "The temperature in Celsius"},2081                },2082                Required: []string{"temperature"},2083            },2084        }20852086        config := &genai.GenerateContentConfig{2087            Tools: []*genai.Tool{2088                {FunctionDeclarations: []*genai.FunctionDeclaration{getWeatherForecastDecl, setThermostatTemperatureDecl}},2089            },2090        }20912092        response, err := client.Models.GenerateContent(2093            ctx,2094            "gemini-3.8-flash",2095            genai.Text("If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C."),2096            config,2097        )2098        if err != nil {2099            log.Fatal(err)2100        }21012102        for _, fn := range response.FunctionCalls() {2103            fmt.Printf("Function to call: %s\n", fn.Name)2104            fmt.Printf("Arguments: %v\n", fn.Args)2105        }2106    }21072108### REST21092110    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \2111      -H "x-goog-api-key: $GEMINI_API_KEY" \2112      -H 'Content-Type: application/json' \2113      -d '{2114        "model": "gemini-3.8-flash",2115        "input": "If it'\''s warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.",2116        "tools": [2117          {2118            "type": "function",2119            "name": "get_weather_forecast",2120            "description": "Gets the current weather temperature for a given location.",2121            "parameters": {2122              "type": "object",2123              "properties": {2124                "location": {"type": "string"}2125              },2126              "required": ["location"]2127            }2128          },2129          {2130            "type": "function",2131            "name": "set_thermostat_temperature",2132            "description": "Sets the thermostat to a desired temperature.",2133            "parameters": {2134              "type": "object",2135              "properties": {2136                "temperature": {"type": "integer"}2137              },2138              "required": ["temperature"]2139            }2140          }2141        ]2142      }'21432144## Function calling modes21452146Control how the model uses tools using `tool_choice` in `generation_config`:21472148- `auto` (Default): Model decides whether to call a function or respond directly.2149- `any`: Model is constrained to always predict a function call.2150- `none`: Model is prohibited from making function calls.2151- `validated`: Model ensures function schema adherence.21522153### Python21542155    generation_config = {2156        "tool_choice": {2157            "allowed_tools": {2158                "mode": "any",2159                "tools": ["get_current_temperature"]2160            }2161        }2162    }21632164### JavaScript21652166    const generation_config = {2167      tool_choice: {2168        allowed_tools: {2169          mode: 'any',2170          tools: ['get_current_temperature']2171        }2172      }2173    };21742175### Java21762177    import com.google.genai.gaos.models.interactions.AllowedTools;2178    import com.google.genai.gaos.models.interactions.GenerationConfig;2179    import com.google.genai.gaos.models.interactions.ToolChoice;2180    import com.google.genai.gaos.models.interactions.ToolChoiceConfig;2181    import com.google.genai.gaos.models.interactions.ToolChoiceType;2182    import java.util.Arrays;21832184    GenerationConfig generationConfig =2185        GenerationConfig.builder()2186            .toolChoice(2187                ToolChoice.of(2188                    ToolChoiceConfig.builder()2189                        .allowedTools(2190                            AllowedTools.builder()2191                                .mode(ToolChoiceType.ANY)2192                                .tools(Arrays.asList("get_current_temperature"))2193                                .build())2194                        .build()))2195            .build();21962197### Go21982199    // Configure function calling mode2200    toolConfig := &genai.ToolConfig{2201        FunctionCallingConfig: &genai.FunctionCallingConfig{2202            Mode:                 genai.FunctionCallingConfigModeAny,2203            AllowedFunctionNames: []string{"get_current_temperature"},2204        },2205    }22062207    // Create the generation config2208    config := &genai.GenerateContentConfig{2209        Tools:      tools, // not defined here.2210        ToolConfig: toolConfig,2211    }22122213### REST22142215    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \2216      -H "x-goog-api-key: $GEMINI_API_KEY" \2217      -H 'Content-Type: application/json' \2218      -d '{2219        "model": "gemini-3.8-flash",2220        "input": "What is the temperature in Boston?",2221        "tools": [{2222          "type": "function",2223          "name": "get_current_temperature",2224          "description": "Gets the current temperature for a given location.",2225          "parameters": {2226            "type": "object",2227            "properties": {2228              "location": {"type": "string"}2229            },2230            "required": ["location"]2231          }2232        }],2233        "generation_config": {2234          "tool_choice": {2235            "allowed_tools": {2236              "mode": "any",2237              "tools": ["get_current_temperature"]2238            }2239          }2240        }2241      }'22422243## Multi-tool use22442245You can enable multiple tools, combining built-in tools with function calling in2246the same request. Gemini 3 models can combine built-in tools with function2247calling out-of-the-box in Interactions. Passing `previous_interaction_id`2248automatically circulates the built-in tool context.22492250### Python22512252    from google import genai2253    import json22542255    client = genai.Client()22562257    get_weather = {2258        "type": "function",2259        "name": "get_weather",2260        "description": "Gets the weather for a requested city.",2261        "parameters": {2262            "type": "object",2263            "properties": {2264                "city": {2265                    "type": "string",2266                    "description": "The city and state, e.g. Utqiaġvik, Alaska",2267                },2268            },2269            "required": ["city"],2270        },2271    }22722273    tools = [2274        {"type": "google_search"},2275        get_weather2276    ]22772278    interaction = client.interactions.create(2279        model="gemini-3.8-flash",2280        input="What is the northernmost city in the United States? What's the weather like there today?",2281        tools=tools2282    )22832284    for step in interaction.steps:2285        if step.type == "function_call":2286            print(f"Function call: {step.name} (ID: {step.id})")2287            result = {"response": "Very cold. 22 degrees Fahrenheit."}2288            interaction_2 = client.interactions.create(2289                model="gemini-3.8-flash",2290                previous_interaction_id=interaction.id,2291                tools=tools,2292                input=[{2293                    "type": "function_result",2294                    "name": step.name,2295                    "call_id": step.id,2296                    "result": [{"type": "text", "text": json.dumps(result)}]2297                }]2298            )22992300            print(interaction_2.output_text)23012302### JavaScript23032304    import { GoogleGenAI } from '@google/genai';23052306    const client = new GoogleGenAI({});23072308    const weatherTool = {2309      type: 'function',2310      name: 'get_weather',2311      description: 'Gets the weather for a given location.',2312      parameters: {2313        type: 'object',2314        properties: {2315          location: {2316            type: 'string',2317            description: 'The city and state, e.g. San Francisco, CA',2318          },2319        },2320        required: ['location'],2321      },2322    };23232324    const tools = [2325      { type: 'google_search' }, // Built-in tool2326      weatherTool,2327    ];23282329    const interaction = await client.interactions.create({2330      model: 'gemini-3.8-flash',2331      input: "What is the northernmost city in the United States? What's the weather like there today?",2332      tools: tools,2333    });23342335    for (const step of interaction.steps) {2336      if (step.type === 'function_call') {2337        console.log(`Function call: ${step.name} (ID: ${step.id})`);2338        const result = { response: 'Very cold. 22 degrees Fahrenheit.' };2339        const interaction_2 = await client.interactions.create({2340          model: 'gemini-3.8-flash',2341          previous_interaction_id: interaction.id,2342          tools: tools,2343          input: [2344            {2345              type: 'function_result',2346              name: step.name,2347              call_id: step.id,2348              result: [{ type: 'text', text: JSON.stringify(result) }],2349            },2350          ],2351        });23522353        console.log(interaction_2.output_text);2354      }2355    }23562357### Java23582359    import com.google.genai.Client;2360    import com.google.genai.gaos.models.interactions.CreateModelInteraction;2361    import com.google.genai.gaos.models.interactions.Function;2362    import com.google.genai.gaos.models.interactions.FunctionCallStep;2363    import com.google.genai.gaos.models.interactions.FunctionResultStep;2364    import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion;2365    import com.google.genai.gaos.models.interactions.FunctionResultSubcontent;2366    import com.google.genai.gaos.models.interactions.GoogleSearch;2367    import com.google.genai.gaos.models.interactions.Interaction;2368    import com.google.genai.gaos.models.interactions.InteractionsInput;2369    import com.google.genai.gaos.models.interactions.Model;2370    import com.google.genai.gaos.models.interactions.Step;2371    import com.google.genai.gaos.models.interactions.TextContent;2372    import com.google.genai.gaos.models.interactions.Tool;2373    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;2374    import java.util.Arrays;2375    import java.util.HashMap;2376    import java.util.List;2377    import java.util.Map;23782379    Client client = new Client();23802381    Map<String, Object> cityProp = new HashMap<>();2382    cityProp.put("type", "string");2383    cityProp.put("description", "The city and state, e.g. Utqiaġvik, Alaska");23842385    Map<String, Object> properties = new HashMap<>();2386    properties.put("city", cityProp);23872388    Map<String, Object> parameters = new HashMap<>();2389    parameters.put("type", "object");2390    parameters.put("properties", properties);2391    parameters.put("required", Arrays.asList("city"));23922393    Function getWeather =2394        Function.builder()2395            .name("get_weather")2396            .description("Gets the weather for a requested city.")2397            .parameters(parameters)2398            .build();23992400    List<Tool> tools = Arrays.asList(GoogleSearch.builder().build(), getWeather);24012402    CreateModelInteraction params =2403        CreateModelInteraction.builder()2404            .model(Model.of("gemini-3.8-flash"))2405            .input(2406                InteractionsInput.of(2407                    "What is the northernmost city in the United States? What's the weather like there today?"))2408            .tools(tools)2409            .build();24102411    Interaction interaction =2412        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();24132414    if (interaction.steps().isPresent()) {2415      for (Step step : interaction.steps().get()) {2416        if (step instanceof FunctionCallStep) {2417          FunctionCallStep fcStep = (FunctionCallStep) step;2418          System.out.printf(2419              "Function call: %s (ID: %s)%n", fcStep.name().orElse(""), fcStep.id().orElse(""));2420          String resultJson = "{\"response\": \"Very cold. 22 degrees Fahrenheit.\"}";24212422          FunctionResultStep resultStep =2423              FunctionResultStep.builder()2424                  .name(fcStep.name().orElse(""))2425                  .callId(fcStep.id().orElse(""))2426                  .result(2427                      FunctionResultStepResultUnion.of(2428                          Arrays.<FunctionResultSubcontent>asList(2429                              TextContent.builder().text(resultJson).build())))2430                  .build();24312432          CreateModelInteraction params2 =2433              CreateModelInteraction.builder()2434                  .model(Model.of("gemini-3.8-flash"))2435                  .previousInteractionId(interaction.id().orElse(""))2436                  .tools(tools)2437                  .input(InteractionsInput.ofStep(Arrays.<Step>asList(resultStep)))2438                  .build();24392440          Interaction interaction2 =2441              client2442                  .interactions2443                  .create(CreateInteractionRequestBody.of(params2))2444                  .interaction()2445                  .get();24462447          System.out.println(interaction2.outputText().orElse(""));2448        }2449      }2450    }24512452### Go24532454    package main24552456    import (2457        "context"2458        "fmt"2459        "log"24602461        "google.golang.org/genai"2462    )24632464    func main() {2465        ctx := context.Background()2466        client, err := genai.NewClient(ctx, nil)2467        if err != nil {2468            log.Fatal(err)2469        }24702471        getWeather := &genai.FunctionDeclaration{2472            Name:        "get_weather",2473            Description: "Gets the weather for a given location.",2474            Parameters: &genai.Schema{2475                Type: genai.TypeObject,2476                Properties: map[string]*genai.Schema{2477                    "location": {2478                        Type:        genai.TypeString,2479                        Description: "The city and state, e.g. San Francisco, CA",2480                    },2481                },2482                Required: []string{"location"},2483            },2484        }24852486        tools := []*genai.Tool{2487            {GoogleSearch: &genai.GoogleSearch{}},2488            {FunctionDeclarations: []*genai.FunctionDeclaration{getWeather}},2489        }24902491        config := &genai.GenerateContentConfig{2492            Tools: tools,2493        }24942495        prompt := "What is the northernmost city in the United States? What's the weather like there today?"2496        response1, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", genai.Text(prompt), config)2497        if err != nil {2498            log.Fatal(err)2499        }25002501        toolCall := response1.FunctionCalls()[0]2502        fmt.Printf("Function call: %s (ID: %s)\n", toolCall.Name, toolCall.ID)25032504        history := []*genai.Content{2505            genai.NewContentFromText(prompt, genai.RoleUser),2506            response1.Candidates[0].Content,2507            {2508                Role: genai.RoleUser,2509                Parts: []*genai.Part{2510                    {2511                        FunctionResponse: &genai.FunctionResponse{2512                            ID:       toolCall.ID,2513                            Name:     toolCall.Name,2514                            Response: map[string]any{"response": "Very cold. 22 degrees Fahrenheit."},2515                        },2516                    },2517                },2518            },2519        }25202521        response2, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", history, config)2522        if err != nil {2523            log.Fatal(err)2524        }25252526        fmt.Println(response2.Text())2527    }25282529### REST25302531    # Turn 1: Send request with built-in google_search tool and custom weather tool2532    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \2533      -H "x-goog-api-key: $GEMINI_API_KEY" \2534      -H 'Content-Type: application/json' \2535      -d '{2536        "model": "gemini-3.8-flash",2537        "input": "What is the northernmost city in the United States? What'\''s the weather like there today?",2538        "tools": [2539          {"type": "google_search"},2540          {2541            "type": "function",2542            "name": "get_weather",2543            "description": "Gets the weather for a given location.",2544            "parameters": {2545              "type": "object",2546              "properties": {2547                "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}2548              },2549              "required": ["location"]2550            }2551          }2552        ]2553      }'25542555    # Turn 2: Provide function result and pass previous_interaction_id2556    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \2557      -H "x-goog-api-key: $GEMINI_API_KEY" \2558      -H 'Content-Type: application/json' \2559      -d '{2560        "model": "gemini-3.8-flash",2561        "previous_interaction_id": "INTERACTION_ID",2562        "tools": [2563          {"type": "google_search"},2564          {2565            "type": "function",2566            "name": "get_weather",2567            "description": "Gets the weather for a given location.",2568            "parameters": {2569              "type": "object",2570              "properties": {2571                "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}2572              },2573              "required": ["location"]2574            }2575          }2576        ],2577        "input": [2578          {2579            "type": "function_result",2580            "name": "get_weather",2581            "call_id": "call_123",2582            "result": [{"type": "text", "text": "{\"response\": \"Very cold. 22 degrees Fahrenheit.\"}"}]2583          }2584        ]2585      }'25862587## Multimodal function responses25882589For Gemini 3 series models, you can include multimodal content in2590the function response parts that you send to the model. The model can process2591this multimodal content in its next turn to produce a more informed response.25922593To include multimodal data in a function response, include it as one or more content blocks in the `result` field of the `function_result` step. Each content block must specify its `type` (e.g., `"text"`, `"image"`).25942595The following example shows how to send a function response containing image data back to the model in an interaction:25962597### Python25982599    import base642600    from google import genai2601    import requests26022603    client = genai.Client()26042605    tool_call = next(s for s in interaction.steps if s.type == "function_call")26062607    image_path = "https://goo.gle/instrument-img"2608    image_bytes = requests.get(image_path).content26092610    base64_image_data = base64.b64encode(image_bytes).decode("utf-8")26112612    final_interaction = client.interactions.create(2613        model="gemini-3.8-flash",2614        previous_interaction_id=interaction.id,2615        input=[2616            {2617                "type": "function_result",2618                "name": tool_call.name,2619                "call_id": tool_call.id,2620                "result": [2621                    {"type": "text", "text": "instrument.jpg"},2622                    {2623                        "type": "image",2624                        "mime_type": "image/jpeg",2625                        "data": base64_image_data,2626                    },2627                ],2628            }2629        ],2630    )26312632    print(final_interaction.output_text)26332634### JavaScript26352636    import { GoogleGenAI } from "@google/genai";26372638    const client = new GoogleGenAI({});26392640    const toolCall = interaction.steps.find(s => s.type === 'function_call');26412642    const base64ImageData = "BASE64_IMAGE_DATA";26432644    const finalInteraction = await client.interactions.create({2645        model: 'gemini-3.8-flash',2646        previous_interaction_id: interaction.id,2647        input: [{2648            type: 'function_result',2649            name: toolCall.name,2650            call_id: toolCall.id,2651            result: [2652                { type: 'text', text: 'instrument.jpg' },2653                {2654                    type: 'image',2655                    mime_type: 'image/jpeg',2656                    data: base64ImageData,2657                }2658            ]2659        }]2660    });26612662    console.log(finalInteraction.output_text);26632664### Java26652666    import com.google.genai.Client;2667    import com.google.genai.gaos.models.interactions.CreateModelInteraction;2668    import com.google.genai.gaos.models.interactions.Function;2669    import com.google.genai.gaos.models.interactions.FunctionCallStep;2670    import com.google.genai.gaos.models.interactions.FunctionResultStep;2671    import com.google.genai.gaos.models.interactions.FunctionResultStepResultUnion;2672    import com.google.genai.gaos.models.interactions.FunctionResultSubcontent;2673    import com.google.genai.gaos.models.interactions.ImageContent;2674    import com.google.genai.gaos.models.interactions.ImageContentMimeType;2675    import com.google.genai.gaos.models.interactions.Interaction;2676    import com.google.genai.gaos.models.interactions.InteractionsInput;2677    import com.google.genai.gaos.models.interactions.Model;2678    import com.google.genai.gaos.models.interactions.Step;2679    import com.google.genai.gaos.models.interactions.TextContent;2680    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;2681    import java.util.Arrays;2682    import java.util.HashMap;2683    import java.util.Map;26842685    Client client = new Client();26862687    Map<String, Object> parameters = new HashMap<>();2688    parameters.put("type", "object");26892690    Function getInstrumentImage =2691        Function.builder()2692            .name("get_instrument_image")2693            .description("Gets an image of an instrument.")2694            .parameters(parameters)2695            .build();26962697    CreateModelInteraction params =2698        CreateModelInteraction.builder()2699            .model(Model.of("gemini-3.8-flash"))2700            .input(InteractionsInput.of("Show me the instrument."))2701            .tools(Arrays.asList(getInstrumentImage))2702            .build();27032704    Interaction interaction =2705        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();27062707    FunctionCallStep toolCall = null;2708    if (interaction.steps().isPresent()) {2709      for (Step step : interaction.steps().get()) {2710        if (step instanceof FunctionCallStep) {2711          toolCall = (FunctionCallStep) step;2712          break;2713        }2714      }2715    }27162717    if (toolCall != null) {2718      String base64ImageData = "BASE64_IMAGE_DATA";27192720      FunctionResultStep resultStep =2721          FunctionResultStep.builder()2722              .name(toolCall.name().orElse(""))2723              .callId(toolCall.id().orElse(""))2724              .result(2725                  FunctionResultStepResultUnion.of(2726                      Arrays.<FunctionResultSubcontent>asList(2727                          TextContent.builder().text("instrument.jpg").build(),2728                          ImageContent.builder()2729                              .mimeType(ImageContentMimeType.IMAGE_JPEG)2730                              .data(base64ImageData)2731                              .build())))2732              .build();27332734      CreateModelInteraction finalParams =2735          CreateModelInteraction.builder()2736              .model(Model.of("gemini-3.8-flash"))2737              .previousInteractionId(interaction.id().orElse(""))2738              .input(InteractionsInput.ofStep(Arrays.<Step>asList(resultStep)))2739              .build();27402741      Interaction finalInteraction =2742          client2743              .interactions2744              .create(CreateInteractionRequestBody.of(finalParams))2745              .interaction()2746              .get();27472748      System.out.println(finalInteraction.outputText().orElse(""));2749    }27502751### Go27522753    package main27542755    import (2756        "context"2757        "fmt"2758        "io"2759        "log"2760        "net/http"27612762        "google.golang.org/genai"2763    )27642765    func main() {2766        ctx := context.Background()2767        client, err := genai.NewClient(ctx, nil)2768        if err != nil {2769            log.Fatal(err)2770        }27712772        // 1. Define the function tool2773        getImageDeclaration := &genai.FunctionDeclaration{2774            Name:        "get_image",2775            Description: "Retrieves the image file reference for a specific order item.",2776            Parameters: &genai.Schema{2777                Type: genai.TypeObject,2778                Properties: map[string]*genai.Schema{2779                    "item_name": {2780                        Type:        genai.TypeString,2781                        Description: "The name or description of the item ordered (e.g., 'instrument').",2782                    },2783                },2784                Required: []string{"item_name"},2785            },2786        }27872788        tools := []*genai.Tool{2789            {FunctionDeclarations: []*genai.FunctionDeclaration{getImageDeclaration}},2790        }27912792        // 2. Send a message that triggers the tool2793        prompt := "Show me the instrument I ordered last month."2794        response1, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", genai.Text(prompt), &genai.GenerateContentConfig{2795            Tools: tools,2796        })2797        if err != nil {2798            log.Fatal(err)2799        }28002801        // 3. Handle the function call2802        functionCall := response1.FunctionCalls()[0]2803        requestedItem := functionCall.Args["item_name"]2804        fmt.Printf("Model wants to call: %s\n", functionCall.Name)2805        fmt.Printf("Calling external tool for: %v\n", requestedItem)28062807        resp, err := http.Get("https://goo.gle/instrument-img")2808        if err != nil {2809            log.Fatal(err)2810        }2811        defer resp.Body.Close()2812        imageBytes, err := io.ReadAll(resp.Body)2813        if err != nil {2814            log.Fatal(err)2815        }28162817        functionResponseData := map[string]any{2818            "image_ref": map[string]any{"$ref": "instrument.jpg"},2819        }28202821        functionResponseMultimodalData := &genai.FunctionResponsePart{2822            InlineData: &genai.FunctionResponseBlob{2823                MIMEType:    "image/jpeg",2824                DisplayName: "instrument.jpg",2825                Data:        imageBytes,2826            },2827        }28282829        // 4. Send the tool's result back2830        history := []*genai.Content{2831            genai.NewContentFromText(prompt, genai.RoleUser),2832            response1.Candidates[0].Content,2833            {2834                Role: genai.RoleUser,2835                Parts: []*genai.Part{2836                    {2837                        FunctionResponse: &genai.FunctionResponse{2838                            ID:       functionCall.ID,2839                            Name:     functionCall.Name,2840                            Response: functionResponseData,2841                            Parts:    []*genai.FunctionResponsePart{functionResponseMultimodalData},2842                        },2843                    },2844                },2845            },2846        }28472848        response2, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", history, &genai.GenerateContentConfig{2849            Tools: tools,2850            ThinkingConfig: &genai.ThinkingConfig{2851                IncludeThoughts: true,2852            },2853        })2854        if err != nil {2855            log.Fatal(err)2856        }28572858        fmt.Printf("\nFinal model response: %s\n", response2.Text())2859    }28602861### REST28622863    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \2864      -H "x-goog-api-key: $GEMINI_API_KEY" \2865      -H 'Content-Type: application/json' \2866      -d '{2867        "model": "gemini-3.8-flash",2868        "previous_interaction_id": "INTERACTION_ID",2869        "input": [2870          {2871            "type": "function_result",2872            "name": "get_image",2873            "call_id": "call_123",2874            "result": [2875              {"type": "text", "text": "instrument.jpg"},2876              {2877                "type": "image",2878                "mime_type": "image/jpeg",2879                "data": "BASE64_IMAGE_DATA"2880              }2881            ]2882          }2883        ]2884      }'28852886## Function calling with Structured output28872888For Gemini 3 series models, combine function calling with2889[structured output](https://ai.google.dev/gemini-api/docs/structured-output) for2890consistently formatted responses.28912892## Remote MCP (Model Context Protocol)28932894Interactions API supports connecting to remote MCP servers to give the model access to external tools and services. You provide the server `name` and `url` in the tools configuration.28952896When using Remote MCP, be aware of the following constraints:28972898- **Server types**: Remote MCP only works with Streamable HTTP servers. SSE (Server-Sent Events) servers are not supported.2899- **Naming** : MCP server names should not include the `-` character. Use `snake_case` server names instead.29002901| Field | Type | Required | Description |2902|---|---|---|---|2903| `type` | `string` | Yes | Must be `"mcp_server"`. |2904| `name` | `string` | No | A display name for the MCP server. |2905| `url` | `string` | No | The full URL for the MCP server endpoint. |2906| `headers` | `object` | No | Key-value pairs sent as HTTP headers with every request to the server (for example, authentication tokens). |2907| `allowed_tools` | `array` | No | Restrict which tools from the server the agent may call. |29082909### Example29102911### Python29122913    from google import genai29142915    client = genai.Client()29162917    interaction = client.interactions.create(2918        model="gemini-3.8-flash",2919        input="Check the weather in San Francisco.",2920        tools=[2921            {2922                "type": "mcp_server",2923                "name": "weather",2924                "url": "https://gemini-api-demos.uc.r.appspot.com/mcp",2925            }2926        ]2927    )29282929### JavaScript29302931    import { GoogleGenAI } from '@google/genai';29322933    const client = new GoogleGenAI({});29342935    const interaction = await client.interactions.create({2936        model: 'gemini-3.8-flash',2937        input: 'Check the weather in San Francisco.',2938        tools: [2939            {2940                type: 'mcp_server',2941                name: 'weather',2942                url: 'https://gemini-api-demos.uc.r.appspot.com/mcp'2943            }2944        ]2945    });29462947### Java29482949    import com.google.genai.Client;2950    import com.google.genai.gaos.models.interactions.CreateModelInteraction;2951    import com.google.genai.gaos.models.interactions.Interaction;2952    import com.google.genai.gaos.models.interactions.InteractionsInput;2953    import com.google.genai.gaos.models.interactions.MCPServer;2954    import com.google.genai.gaos.models.interactions.Model;2955    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;2956    import java.util.Arrays;29572958    Client client = new Client();29592960    CreateModelInteraction params =2961        CreateModelInteraction.builder()2962            .model(Model.of("gemini-3.8-flash"))2963            .input(InteractionsInput.of("Check the weather in San Francisco."))2964            .tools(2965                Arrays.asList(2966                    MCPServer.builder()2967                        .name("weather")2968                        .url("https://gemini-api-demos.uc.r.appspot.com/mcp")2969                        .build()))2970            .build();29712972    Interaction interaction =2973        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();29742975### REST29762977    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \2978      -H "Content-Type: application/json" \2979      -H "x-goog-api-key: $GEMINI_API_KEY" \2980    -d '{2981        "model": "gemini-3.8-flash",2982        "input": "Check the weather in San Francisco.",2983        "tools": [2984            {2985                "type": "mcp_server",2986                "name": "weather",2987                "url": "https://gemini-api-demos.uc.r.appspot.com/mcp"2988            }2989        ]2990    }'29912992## Stream tool calls29932994When using tools with streaming, the model generates function calls as a2995sequence of `step.delta` events on the stream. Tool arguments can be streamed2996as partial arguments using `arguments`. You must aggregate these deltas to2997reconstruct the complete tool calls before executing them.29982999### Python30003001    import json3002    from google import genai30033004    client = genai.Client()30053006    weather_tool = {3007        "type": "function",3008        "name": "get_weather",3009        "description": "Gets the weather for a given location.",3010        "parameters": {3011            "type": "object",3012            "properties": {3013                "location": {"type": "string", "description": "The city and state"}3014            },3015            "required": ["location"]3016        }3017    }30183019    stream = client.interactions.create(3020        model="gemini-3.8-flash",3021        input="What is the weather in Paris?",3022        tools=[weather_tool],3023        stream=True3024    )30253026    current_calls = {}3027    tool_calls = []30283029    for event in stream:3030        if event.event_type == "step.start":3031            if event.step.type == "function_call":3032                current_calls[event.index] = {3033                    "id": event.step.id,3034                    "name": event.step.name,3035                    "arguments": ""3036                }3037                if hasattr(event.step, "arguments") and event.step.arguments:3038                    if isinstance(event.step.arguments, dict):3039                        current_calls[event.index]["arguments"] = json.dumps(event.step.arguments)3040                    else:3041                        current_calls[event.index]["arguments"] = event.step.arguments3042        elif event.event_type == "step.delta":3043            if event.delta.type == "arguments":3044                if event.index in current_calls:3045                    current_calls[event.index]["arguments"] += event.delta.partial_arguments3046            elif event.delta.type == "text":3047                print(event.delta.text, end="", flush=True)30483049        elif event.event_type == "interaction.completed":3050            for index, call in current_calls.items():3051                args = call["arguments"]3052                if args:3053                    args = json.loads(args)3054                else:3055                    args = {}30563057                tool_calls.append({3058                    "type": "function_call",3059                    "id": call["id"],3060                    "name": call["name"],3061                    "arguments": args3062                })30633064            print(f"\nFinal tool calls ready to execute:")3065            print(json.dumps(tool_calls, indent=2))30663067### JavaScript30683069    import { GoogleGenAI } from '@google/genai';30703071    const client = new GoogleGenAI({});30723073    const weatherTool = {3074        type: 'function',3075        name: 'get_weather',3076        description: 'Gets the weather for a given location.',3077        parameters: {3078            type: 'object',3079            properties: {3080                location: { type: 'string', description: 'The city and state' }3081            },3082            required: ['location']3083        }3084    };30853086    const stream = await client.interactions.create({3087        model: 'gemini-3.8-flash',3088        input: 'What is the weather in Paris?',3089        tools: [weatherTool],3090        stream: true,3091    });30923093    const currentCalls = new Map();3094    let toolCalls = [];30953096    for await (const event of stream) {3097        const evType = event.event_type;3098        if (evType === 'step.start') {3099            if (event.step.type === 'function_call') {3100                currentCalls.set(event.index, {3101                    id: event.step.id,3102                    name: event.step.name,3103                    arguments: ''3104                });3105                if (event.step.arguments) {3106                    if (typeof event.step.arguments === 'object') {3107                        currentCalls.get(event.index).arguments = JSON.stringify(event.step.arguments);3108                    } else {3109                        currentCalls.get(event.index).arguments = event.step.arguments;3110                    }3111                }3112            }3113        } else if (evType === 'step.delta') {3114            if (event.delta.type === 'arguments') {3115                if (currentCalls.has(event.index)) {3116                    currentCalls.get(event.index).arguments += event.delta.partial_arguments;3117                }3118            } else if (event.delta.type === 'text') {3119                process.stdout.write(event.delta.text);3120            }3121        } else if (evType === 'interaction.completed' || evType === 'interaction.complete') {3122            toolCalls = Array.from(currentCalls.values()).map(call => ({3123                type: 'function_call',3124                id: call.id,3125                name: call.name,3126                arguments: call.arguments ? JSON.parse(call.arguments) : {}3127            }));3128            console.log('\nFinal tool calls ready to execute:');3129            console.log(JSON.stringify(toolCalls, null, 2));3130        }3131    }31323133### Java31343135    import com.google.genai.Client;3136    import com.google.genai.gaos.models.interactions.ArgumentsDelta;3137    import com.google.genai.gaos.models.interactions.CreateModelInteraction;3138    import com.google.genai.gaos.models.interactions.Function;3139    import com.google.genai.gaos.models.interactions.FunctionCallStep;3140    import com.google.genai.gaos.models.interactions.InteractionCompletedEvent;3141    import com.google.genai.gaos.models.interactions.InteractionSSEEvent;3142    import com.google.genai.gaos.models.interactions.InteractionSSEStreamEvent;3143    import com.google.genai.gaos.models.interactions.InteractionsInput;3144    import com.google.genai.gaos.models.interactions.Model;3145    import com.google.genai.gaos.models.interactions.Step;3146    import com.google.genai.gaos.models.interactions.StepDelta;3147    import com.google.genai.gaos.models.interactions.StepDeltaData;3148    import com.google.genai.gaos.models.interactions.StepStart;3149    import com.google.genai.gaos.models.interactions.TextDelta;3150    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;3151    import com.google.genai.gaos.models.operations.CreateInteractionResponse;3152    import com.google.genai.gaos.utils.EventStream;3153    import java.util.ArrayList;3154    import java.util.Arrays;3155    import java.util.HashMap;3156    import java.util.List;3157    import java.util.Map;31583159    Client client = new Client();31603161    Map<String, Object> locationProp = new HashMap<>();3162    locationProp.put("type", "string");3163    locationProp.put("description", "The city and state");31643165    Map<String, Object> properties = new HashMap<>();3166    properties.put("location", locationProp);31673168    Map<String, Object> parameters = new HashMap<>();3169    parameters.put("type", "object");3170    parameters.put("properties", properties);3171    parameters.put("required", Arrays.asList("location"));31723173    Function weatherTool =3174        Function.builder()3175            .name("get_weather")3176            .description("Gets the weather for a given location.")3177            .parameters(parameters)3178            .build();31793180    CreateModelInteraction params =3181        CreateModelInteraction.builder()3182            .model(Model.of("gemini-3.8-flash"))3183            .input(InteractionsInput.of("What is the weather in Paris?"))3184            .tools(Arrays.asList(weatherTool))3185            .stream(true)3186            .build();31873188    CreateInteractionResponse response =3189        client.interactions.create(CreateInteractionRequestBody.of(params));31903191    Map<Integer, Map<String, Object>> currentCalls = new HashMap<>();3192    List<Map<String, Object>> toolCalls = new ArrayList<>();31933194    try (EventStream<InteractionSSEStreamEvent> events = response.events()) {3195      for (InteractionSSEStreamEvent streamEvent : events) {3196        InteractionSSEEvent event = streamEvent.data().orElse(null);3197        if (event instanceof StepStart) {3198          StepStart stepStart = (StepStart) event;3199          Step step = stepStart.step().orElse(null);3200          if (step instanceof FunctionCallStep) {3201            FunctionCallStep fcStep = (FunctionCallStep) step;3202            int idx = stepStart.index().orElse(0);3203            Map<String, Object> callInfo = new HashMap<>();3204            callInfo.put("id", fcStep.id().orElse(""));3205            callInfo.put("name", fcStep.name().orElse(""));3206            callInfo.put("arguments", new StringBuilder());3207            if (fcStep.arguments().isPresent() && !fcStep.arguments().get().isEmpty()) {3208              ((StringBuilder) callInfo.get("arguments")).append(fcStep.arguments().get().toString());3209            }3210            currentCalls.put(idx, callInfo);3211          }3212        } else if (event instanceof StepDelta) {3213          StepDelta stepDelta = (StepDelta) event;3214          StepDeltaData delta = stepDelta.delta().orElse(null);3215          int idx = stepDelta.index().orElse(0);3216          if (delta instanceof ArgumentsDelta) {3217            String partialArgs = ((ArgumentsDelta) delta).arguments().orElse("");3218            if (currentCalls.containsKey(idx)) {3219              ((StringBuilder) currentCalls.get(idx).get("arguments")).append(partialArgs);3220            }3221          } else if (delta instanceof TextDelta) {3222            ((TextDelta) delta).text().ifPresent(System.out::print);3223          }3224        } else if (event instanceof InteractionCompletedEvent) {3225          for (Map<String, Object> call : currentCalls.values()) {3226            Map<String, Object> finishedCall = new HashMap<>();3227            finishedCall.put("type", "function_call");3228            finishedCall.put("id", call.get("id"));3229            finishedCall.put("name", call.get("name"));3230            finishedCall.put("arguments", call.get("arguments").toString());3231            toolCalls.add(finishedCall);3232          }3233          System.out.println("\nFinal tool calls ready to execute:");3234          System.out.println(toolCalls);3235        }3236      }3237    }32383239### Go32403241    package main32423243    import (3244        "context"3245        "fmt"3246        "log"32473248        "google.golang.org/genai"3249    )32503251    func main() {3252        ctx := context.Background()3253        client, err := genai.NewClient(ctx, nil)3254        if err != nil {3255            log.Fatal(err)3256        }32573258        getWeather := &genai.FunctionDeclaration{3259            Name:        "get_weather",3260            Description: "Gets the weather for a given location.",3261            Parameters: &genai.Schema{3262                Type: genai.TypeObject,3263                Properties: map[string]*genai.Schema{3264                    "location": {3265                        Type:        genai.TypeString,3266                        Description: "The city and state",3267                    },3268                },3269                Required: []string{"location"},3270            },3271        }32723273        config := &genai.GenerateContentConfig{3274            Tools: []*genai.Tool{3275                {FunctionDeclarations: []*genai.FunctionDeclaration{getWeather}},3276            },3277        }32783279        for resp, err := range client.Models.GenerateContentStream(3280            ctx,3281            "gemini-3.8-flash",3282            genai.Text("What is the weather in Paris?"),3283            config,3284        ) {3285            if err != nil {3286                log.Fatal(err)3287            }3288            for _, fc := range resp.FunctionCalls() {3289                fmt.Printf("Function to call: %s\n", fc.Name)3290                fmt.Printf("Arguments: %v\n", fc.Args)3291            }3292        }3293    }32943295### REST32963297    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \3298      -H "Content-Type: application/json" \3299      -H "x-goog-api-key: $GEMINI_API_KEY" \3300    -d '{3301        "model": "gemini-3.8-flash",3302        "input": "What is the weather in Paris?",3303        "tools": [{3304            "type": "function",3305            "name": "get_weather",3306            "description": "Gets the weather for a given location.",3307            "parameters": {3308                "type": "object",3309                "properties": {3310                    "location": {"type": "string", "description": "The city and state"}3311                },3312                "required": ["location"]3313            }3314        }],3315        "stream": true3316    }'33173318## Best practices33193320- **Function and Parameter Descriptions:** Be clear and specific.3321- **Naming:** Use descriptive names without spaces or special characters.3322- **Strong Typing:** Use specific types (integer, string, enum).3323- **Tool Selection:** Keep active set to 10-20 tools maximum.3324- **Prompt Engineering:** Provide context and instructions.3325- **Validation:** Validate function calls before executing.3326- **Error Handling:** Implement robust error handling.3327- **Security:** Use appropriate authentication for external APIs.33283329## Workarounds for pre-tool text requirements33303331**Issue:** If your prompt requires the model to output structured text (XML, YAML, JSON, etc.) (e.g., `<UPDATE>...</UPDATE>`) immediately before making a tool call, the tool call may occasionally fail with `Malformed_Function_Call`.33323333**Solutions:** The following workarounds resolve this issue:33343335- **PREFERRED:** Instruct the model to put its pre-tool notes inside a dedicated `update()` function call instead of raw text (details below).3336- Instruct the model to write notes as Markdown headers (`# UPDATE`, `## PLAN`) instead of structured text.3337- Do not require the model to output text before tool calls.33383339### Preferred workaround: Wrap working notes in a dedicated function call33403341Instead of the original instruction:33423343    Before calling a tool, in every response you MUST first output a single `<UPDATE>` part as specified, don't skip this part or any of required sub-tags within `<UPDATE>`.33443345Use this updated instruction:33463347    Before calling any other tool, in every response you MUST first call `update` with all required parameters (previous_step, plan, next_step, external).33483349And update all references to the old `<UPDATE>` XML format in the customer request. Then add the corresponding function declaration for the update function:33503351    {3352      "name": "update",3353      "description": "Update working notes (previous step analysis, plan, next step, external note).",3354      "parameters": {3355        "type": "OBJECT",3356        "properties": {3357          "previous_step": {3358            "type": "STRING",3359            "description": "Key findings and outcomes since the previous step."3360          },3361          "plan": {3362            "type": "STRING",3363            "description": "The current status of the plan."3364          },3365          "next_step": {3366            "type": "STRING",3367            "description": "Brief explanation of the immediate next action according to the plan."3368          },3369          "external": {3370            "type": "STRING",3371            "description": "A short, plain-language note shown to the User about what you are ABOUT TO DO next."3372          }3373        },3374        "required": [3375          "previous_step",3376          "plan",3377          "next_step",3378          "external"3379        ]3380      }3381    }33823383Then the model will make two calls in the same step: the `update()` call that replaces the structured XML, and the actual function call it wants to make.33843385## Notes and limitations33863387- Only a [subset of the OpenAPI schema](https://ai.google.dev/api/rest/v1beta/cachedContents#FunctionDeclaration) is supported.3388- For `any` mode, the API may reject very large or deeply nested schemas.3389- Supported parameter types in Python are limited.
Files main
Menu

Theme