AI
AI Certified
Professional AI Certification
Get Started
39lesson.complete • 7/18
Courses›Google Gemini Pro›Advanced Gemini Development
📖 Advanced Gemini Development

Function Calling and Tool Use

⏱ 15 min·Lesson 7 of 18FREE

Function Calling and Tool Use

Overview

Function calling allows Gemini to interact with external systems — databases, APIs, calculators, and any tool you define. Instead of making up answers, the model can request real data. This is the foundation of building agents and intelligent automation pipelines.

How Function Calling Works

  1. You define function declarations (name, description, parameters)
  2. You send a prompt with those declarations
  3. Gemini decides if a function call is needed and returns a structured call request
  4. You execute the function and return the result
  5. Gemini uses the result to generate its final response

Defining Functions

typescript
import {
  GoogleGenerativeAI,
  FunctionDeclarationSchemaType,
} from '@google/generative-ai';

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);

const tools = [
  {
    functionDeclarations: [
      {
        name: 'get_weather',
        description: 'Get the current weather for a given city',
        parameters: {
          type: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            city: {
              type: FunctionDeclarationSchemaType.STRING,
              description: 'The city name, e.g. London',
            },
            unit: {
              type: FunctionDeclarationSchemaType.STRING,
              enum: ['celsius', 'fahrenheit'],
              description: 'Temperature unit',
            },
          },
          required: ['city'],
        },
      },
      {
        name: 'search_database',
        description: 'Search the product database for items matching a query',
        parameters: {
          type: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            query: {
              type: FunctionDeclarationSchemaType.STRING,
              description: 'Search query string',
            },
            limit: {
              type: FunctionDeclarationSchemaType.NUMBER,
              description: 'Maximum number of results',
            },
          },
          required: ['query'],
        },
      },
    ],
  },
];

Handling Function Calls

typescript
const model = genAI.getGenerativeModel({
  model: 'gemini-2.5-flash',
  tools,
});

// Simulated function implementations
function getWeather(city: string, unit = 'celsius') {
  return { city, temperature: 18, unit, condition: 'Partly cloudy' };
}

function searchDatabase(query: string, limit = 5) {
  return { results: [`Product matching "${query}"`], count: 1 };
}

async function runWithTools(userMessage: string) {
  const chat = model.startChat();
  let response = await chat.sendMessage(userMessage);

  // Agentic loop — keep processing until no more tool calls
  while (true) {
    const candidate = response.response.candidates?.[0];
    const functionCallParts = candidate?.content.parts.filter(p => p.functionCall);

    if (!functionCallParts || functionCallParts.length === 0) break;

    const functionResponses = functionCallParts.map(part => {
      const { name, args } = part.functionCall!;

      let result: any;
      if (name === 'get_weather') {
        result = getWeather(args.city, args.unit);
      } else if (name === 'search_database') {
        result = searchDatabase(args.query, args.limit);
      }

      return {
        functionResponse: { name, response: { result } },
      };
    });

    response = await chat.sendMessage(functionResponses);
  }

  return response.response.text();
}

const answer = await runWithTools("What's the weather in London and do we sell umbrellas?");
console.log(answer);

Python Implementation

python
import google.generativeai as genai

def get_weather(city: str, unit: str = "celsius") -> dict:
    return {"city": city, "temperature": 18, "unit": unit}

weather_tool = genai.protos.Tool(
    function_declarations=[
        genai.protos.FunctionDeclaration(
            name="get_weather",
            description="Get current weather for a city",
            parameters=genai.protos.Schema(
                type=genai.protos.Type.OBJECT,
                properties={
                    "city": genai.protos.Schema(type=genai.protos.Type.STRING),
                },
                required=["city"],
            ),
        )
    ]
)

model = genai.GenerativeModel("gemini-2.5-flash", tools=[weather_tool])
response = model.generate_content("What's the weather in Paris?")

# Handle function call
if response.candidates[0].content.parts[0].function_call:
    fc = response.candidates[0].content.parts[0].function_call
    result = get_weather(**dict(fc.args))
    print(result)

Tool Configuration Modes

You can control how Gemini uses tools:

  • AUTO (default): Model decides when to call functions
  • ANY: Model must call at least one function
  • NONE: Model won't call functions
typescript
const model = genAI.getGenerativeModel({
  model: 'gemini-2.5-flash',
  tools,
  toolConfig: { functionCallingConfig: { mode: 'AUTO' } },
});

Key Takeaways

  • Function calling enables Gemini to interact with real-world data and systems
  • Always implement an agentic loop to handle sequential function calls
  • Use descriptive function names and parameter descriptions — the model uses them to decide when to call
  • Tool configuration modes let you control calling behaviour precisely
🎓

Enjoyed this lesson?

Unlock all 18 lessons for a one-time payment.

Get Full Access — £29 →