Gemini | Tool Use

Gemini supports function calling (tool use), allowing you to define functions that the model can invoke during a conversation. When Gemini decides to call a function, it returns a functionCall part in its response. You then execute the function and send the result back.

Function Calling Flow

  1. Define function declarations with name, description, and parameters (JSON Schema).
  2. Send a content generation request with function declarations.
  3. Gemini responds with a functionCall part containing the function name and arguments.
  4. Execute the function with the provided arguments.
  5. Send a new request with a functionResponse part containing the result.
  6. Gemini responds with the final answer.

Example

Define a weather function and handle function calling.


Gemini := TsgcHTTP_API_Gemini.Create(nil);
Gemini.GeminiOptions.ApiKey := 'API_KEY';

// Step 1: Create request with function declarations
oRequest := TsgcGeminiClass_Request_GenerateContent.Create;
Try
  oRequest.Model := 'gemini-2.0-flash';
  oRequest.MaxOutputTokens := 4096;

  // Define user message
  SetLength(oContents, 1);
  oContents[0] := TsgcGeminiClass_Request_Content.Create;
  oContents[0].Role := 'user';
  SetLength(oParts, 1);
  oParts[0] := TsgcGeminiClass_Request_Part.Create;
  oParts[0].Text := 'What is the weather in San Francisco?';
  oContents[0].Parts := oParts;
  oRequest.Contents := oContents;

  // Define function
  SetLength(oFunctions, 1);
  oFunctions[0] := TsgcGeminiClass_Request_FunctionDeclaration.Create;
  oFunctions[0].Name := 'get_weather';
  oFunctions[0].Description := 'Get the current weather in a given location';
  oFunctions[0].Parameters :=
    '{"type":"object","properties":{"location":{"type":"string",' +
    '"description":"The city and state"}},"required":["location"]}';
  oRequest.FunctionDeclarations := oFunctions;

  // Step 2: Send request
  oResponse := Gemini.CreateContent(oRequest);
  Try
    // Step 3: Check for function call
    if Length(oResponse.Candidates) > 0 then
    begin
      if Length(oResponse.Candidates[0].Parts) > 0 then
      begin
        if oResponse.Candidates[0].Parts[0].FunctionCallName <> '' then
        begin
          vFunctionName := oResponse.Candidates[0].Parts[0].FunctionCallName;
          vFunctionArgs := oResponse.Candidates[0].Parts[0].FunctionCallArgs;
          // Step 4: Execute function and get result
          vResult := '72 degrees and sunny';
        end;
      end;
    end;
  Finally
    oResponse.Free;
  End;
Finally
  oParts[0].Free;
  oContents[0].Free;
  oFunctions[0].Free;
  oRequest.Free;
End;

Properties