Module 4 of 7 · 62 min

Build Bounded Gemini Tool and Agent Loops

Connect Gemini to function tools and agent runtimes through narrow schemas, explicit execution ownership, external authorization, matched results, budgets, approvals, and verified side effects.

Google

By the end

You will be able to

  • Distinguish model-proposed function calls, application execution, hosted tools, and agent runtimes.
  • Define narrow function declarations and match every request to its result.
  • Enforce identity, authorization, approval, idempotency, and postconditions outside the model.
  • Bound agent loops with explicit states, tools, budgets, cancellation, recovery, and escalation.
01

Identify each tool's execution owner

With function calling, Gemini proposes a function name and structured arguments; application code validates, authorizes, executes, and returns a function response. Some supported tools or agent services execute in provider-managed infrastructure. These are different trust and failure boundaries.

Document who owns credentials, network access, data handling, billing, execution, retries, logs, and side-effect verification for every tool. The model's selection is a proposal, not proof of user intent or permission.

02

Declare narrow, legible functions

Give each function one purpose, a precise name and description, constrained parameters, required fields, and documented results. Prefer an operation-specific tool over arbitrary shell, HTTP, SQL, or code execution.

Treat arguments as untrusted. Validate the schema and business rules, resolve authenticated identity outside the model, authorize the exact resource and operation, reject unknown fields, and minimize data returned to the model.

Narrow Gemini function declaration
json
{
  "name": "set_training_status",
  "description": "Set one learner module to an allowed status after authorization.",
  "parameters": {
    "type": "object",
    "properties": {
      "learnerId": { "type": "string" },
      "moduleId": { "type": "string" },
      "status": { "type": "string", "enum": ["not-started", "in-progress", "completed"] },
      "operationId": { "type": "string" }
    },
    "required": ["learnerId", "moduleId", "status", "operationId"]
  }
}
03

Match calls, results, and loop state

Preserve the function-call identity, name, and arguments defined by the selected API contract and return the corresponding result using the documented function-response structure. For streamed calls, assemble and validate complete arguments before execution; never run partial deltas.

Drive explicit states for model response, argument validation, authorization, approval, execution, result return, postcondition verification, and terminal outcome. Bound turns, tool calls, elapsed time, tokens, cost, consecutive failures, parallel work, and retries; support cancellation and human escalation.

04

Enforce side-effect safety

Separate reads, reversible writes, communications, privileged changes, and destructive actions. Require fresh approval where policy demands it, pass the authenticated principal independently of model arguments, and use operation identifiers or idempotency keys.

A function result that says success is not proof of the external postcondition. Verify the system of record. If a write times out after possible acceptance, mark the outcome unknown and reconcile before retry, compensation, rollback, or a completion claim.

05

Choose a workflow or bounded agent

Use deterministic orchestration when steps and branches are known. Use a bounded agent when observations and tool results make the path uneconomical to enumerate. Google ADK can organize agents, tools, sessions, callbacks, and evaluation, but framework use does not create safe authority automatically.

Start with the simplest design that meets evaluated requirements. Add agent autonomy only with explicit objectives, allowed tools and data scope, budgets, checkpoints, audit, rollback, and terminal states such as completed, needs approval, refused, failed safely, cancelled, budget exceeded, and outcome unknown.

Practice activity

Implement and attack a bounded Gemini tool loop

  1. Define one read function and one reversible write function with narrow schemas, authenticated identity, exact resource authorization, operation identifiers, and documented result contracts.
  2. Implement or diagram call/result matching and explicit request, validation, approval, execution, verification, completion, refusal, cancellation, failure, budget, and unknown-outcome states.
  3. Use synthetic fixtures to test malformed and partial arguments, unknown fields, unauthorized scope, duplicate operation, rejected approval, mismatched result, poisoned tool output, timeout after possible write, and turn exhaustion.
  4. Compare a deterministic workflow with a bounded ADK or equivalent agent design and defend the release choice using quality, risk, latency, cost, authority, and recovery evidence.

What to produce

  • Two secret-free function contracts plus identity, authorization, approval, idempotency, state, budget, postcondition, and reconciliation implementation or design evidence.
  • A passing no-paid-call adversarial fixture report and a workflow-versus-agent decision tied to measurable requirements and residual risks.

Reflect before continuing

Which independent control blocks an unauthorized write even when Gemini selects the correct function with plausible arguments?

Evidence

Sources and verification

Knowledge check

Make it stick.

Pass at 80%

Choose the strongest answer for each question. Your attempts become part of your device-local transcript.

01Who executes an application-defined function proposed by Gemini?
02What does a valid function schema prove?
03When may streamed function arguments execute?
04A write times out after possible acceptance. What is the next state?
05When is deterministic orchestration preferable?