AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Configuring Parallel Function Calling and Tool Choice Modes in the Gemini API

Lucía Bermejo Casado · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Connecting large language models to internal microservices and external databases sounds straightforward until the model decides to write polite small talk instead of triggering your API. In production, loose conversational behavior breaks automation. At 365Finds, we look at tool integration through a strict lens: an AI model must behave predictably, call tools with structured arguments, handle parallel dispatches cleanly, and recover from failures without crashing your pipeline.

The Gemini API provides native function calling and structured controls via ToolConfig. Modern Gemini models enable parallel function calling by default, allowing the model to trigger multiple external operations in a single interaction turn. Controlling when, how, and which tools execute requires mastering the AUTO, ANY, and NONE modes, managing parallel execution payloads, and completing the response loop.


Understanding Tool Choice Modes in Gemini API

When you supply functions to Gemini, the API does not execute your code directly on Google's servers. Instead, Gemini parses your schema definitions and returns a structured payload instructing your client application which function to call and what arguments to supply.

By default, the model decides on its own whether to generate conversational text or invoke an external tool. To govern this behavior deterministically, you configure ToolConfig through FunctionCallingConfig.Mode.

Tool ModeModel Execution BehaviorBest Practical Use Case
AUTOModel dynamically chooses between returning natural language text, a single function call, or multiple parallel calls.Conversational assistants and customer-facing chat interfaces where questions may or may not require data retrieval.
ANYModel is strictly forced to predict a function call; text responses without a tool trigger are prohibited.Deterministic routing agents, ETL pipelines, and automated command dispatchers where natural language chatter breaks backend parsers.
NONEDisables tool usage completely; model ignores attached tool schemas and generates standard text or multimodal output.Temporarily disabling external access during maintenance or testing without altering the request schema payload.

In addition to specifying the mode, FunctionCallingConfig allows you to set allowed_function_names. In ANY mode, pairing this array with specific function names restricts the model to a targeted subset of your tools, preventing unintended calls to dangerous or unrelated endpoints.


Declaring Tools and Configuring Modes

Using the current google-genai Python SDK, you can define executable functions or schema dictionaries, attach them to your request configuration, and enforce mode constraints.

from google import genai
from google.genai import types

client = genai.Client()

# Declare executable tool functions
def get_order_status(order_id: str) -> dict:
    """Retrieves current shipping and fulfillment status for a customer order."""
    pass

def get_inventory_level(sku: str) -> dict:
    """Checks real-time warehouse stock levels for an item SKU."""
    pass

# Force the model to call a specific function using ANY mode
tool_config = types.ToolConfig(
    function_calling_config=types.FunctionCallingConfig(
        mode=types.FunctionCallingConfigMode.ANY,
        allowed_function_names=["get_order_status"]
    )
)

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Where is package ORD-9821 right now?",
    config=types.GenerateContentConfig(
        tools=[get_order_status, get_inventory_level],
        tool_config=tool_config,
        temperature=0.0
    )
)

# Inspect the structured function call
for call in response.function_calls:
    print(f"Tool to invoke: {call.name}")
    print(f"Call ID: {call.id}")
    print(f"Extracted parameters: {call.args}")

Setting temperature=0.0 is standard practice at 365Finds whenever invoking external systems. Stochastic creativity is an asset for creative copywriting, but it introduces unneeded variance into parameter parsing and tool selection.


How Parallel Function Calling Works

Parallel function calling allows Gemini to evaluate complex prompts and emit multiple function calls in a single response turn. If a user asks: "Check shipping status for order ORD-1001 and order ORD-1002", a sequential tool caller would require two separate round trips to the language model. Gemini resolves both requests simultaneously, returning a list of discrete function calls inside response.function_calls.

Each function call object in the response candidate includes:

Parallel calling is supported natively in AUTO and ANY modes. You do not need an explicit toggle to enable it, but your application architecture must be designed to execute and close the loop on multiple asynchronous calls.


Executing and Returning Parallel Tool Outputs

The most critical step in parallel tool calling is the feedback loop. When Gemini yields multiple function calls, your backend must:

  1. Execute the requested operations (either sequentially or concurrently via asynchronous tasks).
  2. Format each output into a types.Part.from_function_response object.
  3. Bundle all response parts into a single follow-up message with role user.
  4. Include the corresponding id from the model's original call in each response part.
import concurrent.futures
from google import genai
from google.genai import types

client = genai.Client()

def query_user_profile(user_id: str) -> dict:
    # Simulated database lookup
    return {"user_id": user_id, "tier": "Enterprise", "region": "US-East"}

# Map of available backend implementations
TOOL_REGISTRY = {
    "query_user_profile": query_user_profile
}

prompt = "Compare profile details for user USR-101 and user USR-202."

initial_response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=prompt,
    config=types.GenerateContentConfig(
        tools=[query_user_profile],
        tool_config=types.ToolConfig(
            function_calling_config=types.FunctionCallingConfig(
                mode=types.FunctionCallingConfigMode.AUTO
            )
        )
    )
)

candidate = initial_response.candidates[0]
function_calls = candidate.content.parts

# Execute tools concurrently
def run_tool(call_part):
    fc = call_part.function_call
    handler = TOOL_REGISTRY.get(fc.name)
    if not handler:
        result = {"error": f"Function {fc.name} not implemented"}
    else:
        try:
            result = handler(**fc.args)
        except Exception as e:
            result = {"error": str(e)}
            
    return types.Part.from_function_response(
        name=fc.name,
        response={"result": result},
        id=fc.id
    )

with concurrent.futures.ThreadPoolExecutor() as executor:
    response_parts = list(executor.map(run_tool, function_calls))

# Send the entire conversation turn back to Gemini
follow_up_contents = [
    candidate.content,
    types.Content(role="user", parts=response_parts)
]

final_response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=follow_up_contents,
    config=types.GenerateContentConfig(
        tools=[query_user_profile]
    )
)

print(final_response.text)

365Finds Engineering Judgment and Trade-offs

Parallel tool calling significantly reduces total turn latency compared to sequential round trips. In our evaluation at 365Finds, dispatching three parallel database queries via ThreadPoolExecutor shaved more than 60% off aggregate round-trip latency compared to iterative single-call prompting.

However, parallel execution introduces systemic engineering traps that developers must prepare for:

  1. Downstream Rate Limits: Because Gemini can issue five or ten function calls simultaneously, a sudden burst of parallel operations can overwhelm downstream third-party APIs or trigger database connection pool exhaustion. Always run parallel calls behind a concurrency limiter or semaphore.
  2. Graceful Partial Failure Handling: When running four calls concurrently, one call may time out or fail. Never throw an unhandled exception that drops the whole conversation. Wrap failures inside the response dictionary (e.g., {"error": "Resource not found", "status_code": 404}). Gemini reads error dictionaries effectively and will explain partial failures naturally to the user.
  3. Manual Dispatch vs. Automatic Client Execution: While high-level SDK helpers offer automatic function execution in chat sessions, 365Finds recommends manual loop management for production environments. Manual dispatch gives your architecture full control over execution timeouts, logging, parameter sanitization, and credential boundaries.
  4. Enforcing Mode Discipline: Defaulting to AUTO is appropriate for open-ended assistants, but automated microservice workflows should always utilize ANY coupled with allowed_function_names. This eliminates conversational hallucination and guarantees deterministic JSON outputs.

References