Skip to main content

Gemini Function Calling Patterns

Implement Gemini function calling with tool declarations, parallel function calls, multi-turn conversations, and error handling for building AI agents.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
You are a Gemini AI integration expert. Help me implement function calling with the Gemini API for a customer support chatbot application using Python with google-generativeai.

Step 1: Define 8 function declarations for the Gemini Tools configuration. Each function should have a clear name, description (that helps Gemini decide when to call it), and a JSON Schema for parameters. Cover these use cases: search knowledge base, check order status, create ticket, transfer to agent. Structure declarations following Gemini best practices: use descriptive parameter names, add enum constraints where applicable, mark required vs optional parameters, and include example values in descriptions.

Step 2: Implement the function calling loop in Python with google-generativeai. Send the user prompt to Gemini with the tool declarations. Parse the response: if it contains a function call, extract the function name and arguments, execute the corresponding local function, and send the result back to Gemini as a function response. Handle the case where Gemini requests 3 parallel function calls in a single response by executing them concurrently and returning all results.

Step 3: Build a multi-turn conversation handler that maintains context across 20 turns. Store the conversation history (user messages, model responses, function calls, and function results) and send the complete history with each request. Implement context window management: when the history exceeds 30,000 tokens, summarize older turns while preserving the most recent function call results.

Step 4: Implement robust error handling for function execution failures. When a local function fails (network error, validation error, permission denied), return a structured error response to Gemini with the error type and message. Gemini should then either retry with different parameters, try an alternative approach, or inform the user about the limitation. Set a maximum retry count of 2 per function call.

Step 5: Add function call validation and safety guardrails. Before executing any function call, validate that the arguments match the schema, sanitize inputs to prevent injection attacks, check that the function is in the allowed list for the current user role (customer, agent, admin), and log the call for audit purposes. Implement rate limiting of 50 function calls per conversation to prevent runaway loops.

Step 6: Create integration tests for 10 scenarios: Gemini correctly selects the right function for ambiguous prompts, handles missing optional parameters with defaults, chains multiple function calls to answer complex queries, gracefully handles function failures, and respects the function calling mode configuration (auto, any, none). Mock the Gemini API responses for deterministic testing.

What this prompt does

This prompt implements Gemini function calling end to end, focusing on the hard parts: the calling loop, parallel calls, retries, and safety guardrails rather than the happy path. It runs through six steps: defining function declarations, implementing the calling loop, building multi-turn conversation handling, adding error handling, applying validation and safety guardrails, and writing integration tests. It scaffolds the validation, rate limiting, and audit logging you would otherwise hand-write every time you build an agent.

The variables tailor it to your agent. [sdk_language] sets the implementation language, [function_count] and [use_cases] define the tool declarations, and [parallel_calls] controls concurrency. [max_turns] and [max_tokens] shape conversation context management, [max_retries] bounds retries, [user_roles] and [rate_limit] enforce access and loop limits, and [test_count] sizes the integration test suite. The allow-list keyed on [user_roles] is the guardrail that keeps an agent from doing something it shouldn't, and it sits alongside argument validation and audit logging so every call is checked before it runs. These are the parts of agent development that are tedious to write by hand yet essential to get right.

When to use it

  • You are building an AI agent where function calling is the core mechanism.
  • You need a robust calling loop that executes tools and feeds results back to Gemini.
  • You want concurrent execution when Gemini requests parallel function calls.
  • You need multi-turn context management that summarizes older turns under a token cap.
  • You want validation, role-based allow-lists, rate limiting, and audit logging built in.
  • You need integration tests covering ambiguous prompts and function-failure handling.

Example output

Expect [function_count] function declarations with JSON Schema parameters, enum constraints, and required/optional markers covering your [use_cases]. The implementation steps produce a [sdk_language] calling loop that parses function calls and returns results, concurrent execution for up to [parallel_calls] calls, multi-turn history management with summarization beyond [max_tokens], and structured error responses with retries up to [max_retries]. Guardrails enforcing [user_roles] and [rate_limit] plus [test_count] integration tests with mocked Gemini responses round it out. It is mostly working code, with the loop, error handling, and safety checks treated as the core of the agent rather than optional extras.

Pro tips

  • Write tight function descriptions; Gemini decides when to call each one, so vague descriptions on your [function_count] tools cause wrong selections.
  • Use enum constraints and clear required-vs-optional markers in the schemas so arguments stay well-formed.
  • Cap [parallel_calls] to what your backend can actually run concurrently to avoid overload.
  • Implement the allow-list and injection checks yourself with care; the [user_roles] guardrail is where real agents get dangerous.
  • Set [rate_limit] to prevent runaway loops, and pair it with [max_retries] so failures don't spin forever.
  • Mock Gemini responses for the [test_count] scenarios so tests stay deterministic across runs instead of depending on live API behavior.

Frequently Asked Questions

Does this handle parallel function calls?
Yes. Step 2 handles the case where Gemini requests up to `[parallel_calls]` parallel function calls in one response, executing them concurrently and returning all results. You should cap `[parallel_calls]` at what your backend can run safely without overloading downstream services.
How does it manage long conversations?
Step 3 maintains conversation history across `[max_turns]` turns and sends the full history with each request. When history exceeds `[max_tokens]` tokens, it summarizes older turns while preserving the most recent function-call results, which keeps context coherent without unbounded token growth.
What safety measures are included?
Step 5 validates arguments against the schema, sanitizes inputs to prevent injection, checks each call against an allow-list for the current `[user_roles]`, logs calls for audit, and rate-limits to `[rate_limit]` calls per conversation. The prompt notes you should implement the allow-list and injection checks carefully yourself.
What language and SDK does it target?
Whatever you set in `[sdk_language]`; the default is Python with google-generativeai. The calling loop, error handling, and tests are generated for that language, so set it accurately to get idiomatic code rather than pseudo-code you must translate.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in Gemini AI Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support