Building a Multi-Tool Gemma 4 Agent with Error Recovery

· Source: MachineLearningMastery.com - Machinelearningmastery.com · Field: Technology & Digital — Artificial Intelligence & Machine Learning, Software Development & Engineering · Depth: Intermediate, long

Summary

The article describes building a resilient multi-tool Gemma 4 agent with error recovery. It transforms a basic tool-calling script into an agent capable of handling failures from misbehaving tools, malformed model outputs, and unavailable services. Key aspects include structuring an iterative agent loop with a MAX_ITERATIONS safety cap and designing tool error messages that guide the model towards recovery. The analysis identifies four distinct failure categories: tool execution errors (e.g., ValueError, TypeError, ToolUnavailableError), malformed tool calls from the model, domain-level errors (e.g., unknown city), and graceful degradation for unavailable tools. The agent dispatches tool calls within try/except blocks, converting errors into model-readable messages, and employs defensive coercion for argument types. The get_local_time tool demonstrates graceful degradation using a TIMEZONE_FALLBACK_CACHE for simulated geocoding outages.

Key takeaway

For AI Engineers building multi-tool agents with Gemma 4 or similar models, prioritize robust error handling to prevent system crashes and improve agent autonomy. You should implement an iterative agent loop with a hard iteration cap and design your tool dispatcher to catch and convert all tool execution errors into informative messages for the model. This approach enables your agent to self-correct from malformed calls, domain errors, and service outages, significantly reducing manual intervention and improving reliability in unsupervised operation.

Key insights

Building resilient agents requires converting tool errors into model-readable messages within an iterative loop for self-correction.

Principles

Method

Implement an iterative agent loop that sends message history to the model, executes tool calls, and appends results. Cap iterations at MAX_ITERATIONS. Dispatch tool calls in try/except blocks, converting exceptions (TypeError, ValueError, ToolUnavailableError, Exception) into structured error messages for the model.

In practice

Topics

Code references

Best for: AI Engineer, Machine Learning Engineer, MLOps Engineer

Related on AIssential

Open in AIssential →

Editorial summary, takeaway, and curation by AIssential. Original article published by MachineLearningMastery.com - Machinelearningmastery.com.