UniterRouter
API ReferenceGoogle Compatible

Function Calling

Gemini Function Calling API - Enable Gemini Pro to call external tools and APIs. Build AI agents with tool use for automated workflows and integrations.

Function Calling (Tools)

Function calling allows Gemini models to interact with external systems by generating structured function calls. The model doesn't execute functions directly—it generates the parameters, and your code executes them.

Supported Models: All Gemini 1.5+ models support function calling.

How It Works

  1. Define functions with JSON schemas
  2. Send the definitions with your request
  3. Model decides if/which function to call
  4. Model generates function parameters
  5. Your code executes the function
  6. Send the result back to the model

Defining Functions

curl -X POST "https://api.uniterouter.ai/v1beta/models/gemini-2.0-flash:generateContent" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $UNITEROUTER_API_KEY" \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [{"text": "What is the weather in Tokyo?"}]
      }
    ],
    "tools": [
      {
        "functionDeclarations": [
          {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "City name, e.g., Tokyo, New York"
                },
                "unit": {
                  "type": "string",
                  "enum": ["celsius", "fahrenheit"],
                  "description": "Temperature unit"
                }
              },
              "required": ["location"]
            }
          }
        ]
      }
    ]
  }'
import google.generativeai as genai

genai.configure(
    api_key="your_uniterouter_api_key",
    transport="rest",
    client_options={"api_endpoint": "api.uniterouter.ai"}
)

# Define the function
def get_weather(location: str, unit: str = "celsius") -> dict:
    """Get weather for a location (mock implementation)"""
    return {
        "location": location,
        "temperature": 22,
        "unit": unit,
        "condition": "sunny"
    }

# Create model with tools
model = genai.GenerativeModel(
    "gemini-2.0-flash",
    tools=[get_weather]
)

# Start chat
chat = model.start_chat(enable_automatic_function_calling=True)
response = chat.send_message("What's the weather in Tokyo?")
print(response.text)
import { GoogleGenerativeAI, FunctionDeclarationSchemaType } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI("your_uniterouter_api_key", {
  baseUrl: "https://api.uniterouter.ai"
});

const model = genAI.getGenerativeModel({
  model: "gemini-2.0-flash",
  tools: [{
    functionDeclarations: [{
      name: "get_weather",
      description: "Get the current weather for a location",
      parameters: {
        type: FunctionDeclarationSchemaType.OBJECT,
        properties: {
          location: {
            type: FunctionDeclarationSchemaType.STRING,
            description: "City name"
          },
          unit: {
            type: FunctionDeclarationSchemaType.STRING,
            enum: ["celsius", "fahrenheit"]
          }
        },
        required: ["location"]
      }
    }]
  }]
});

const result = await model.generateContent("What's the weather in Tokyo?");
const call = result.response.functionCalls()?.[0];

if (call) {
  console.log("Function:", call.name);
  console.log("Args:", call.args);
}

Function Call Response

When the model decides to call a function:

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "functionCall": {
              "name": "get_weather",
              "args": {
                "location": "Tokyo",
                "unit": "celsius"
              }
            }
          }
        ],
        "role": "model"
      }
    }
  ]
}

Sending Function Results

After executing the function, send the result back:

# Execute the function
result = get_weather("Tokyo", "celsius")

# Send result back
response = chat.send_message(
    genai.protos.Content(
        parts=[
            genai.protos.Part(
                function_response=genai.protos.FunctionResponse(
                    name="get_weather",
                    response={"result": result}
                )
            )
        ]
    )
)
print(response.text)  # "The weather in Tokyo is 22°C and sunny."

Tool Config

Control function calling behavior:

{
  "toolConfig": {
    "functionCallingConfig": {
      "mode": "AUTO",
      "allowedFunctionNames": ["get_weather", "get_time"]
    }
  }
}
ModeDescription
AUTOModel decides when to call functions
ANYModel must call at least one function
NONEDisable function calling

Multiple Functions

tools = [
    {
        "functionDeclarations": [
            {
                "name": "get_weather",
                "description": "Get current weather",
                "parameters": {...}
            },
            {
                "name": "get_time",
                "description": "Get current time in a timezone",
                "parameters": {...}
            },
            {
                "name": "search_web",
                "description": "Search the web for information",
                "parameters": {...}
            }
        ]
    }
]

Parallel Function Calls

Gemini can call multiple functions in parallel:

{
  "candidates": [{
    "content": {
      "parts": [
        {
          "functionCall": {
            "name": "get_weather",
            "args": {"location": "Tokyo"}
          }
        },
        {
          "functionCall": {
            "name": "get_weather",
            "args": {"location": "New York"}
          }
        }
      ]
    }
  }]
}

Best Practices

  1. Clear descriptions - Write detailed function and parameter descriptions
  2. Use enums - Constrain parameter values when possible
  3. Handle errors - Always handle function execution errors gracefully
  4. Validate inputs - Validate parameters before executing functions
  5. Keep it simple - Fewer, focused functions work better than many generic ones

How is this guide?