Building a Multi-Tool Gemma 4 Agent with Error Recovery
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
- Convert all tool failures into model-readable messages.
- Implement iterative agent loops with a MAX_ITERATIONS safety cap.
- Design error messages to teach the model how to recover.
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
- Wrap tool calls in try/except to return errors.
- Implement defensive type coercion for model arguments.
- Provide specific error messages with valid alternatives.
Topics
- Gemma 4
- Tool Calling
- Agent Error Recovery
- Iterative Agent Loop
- Ollama API
- Defensive Programming
Code references
Best for: AI Engineer, Machine Learning Engineer, MLOps Engineer
Related on AIssential
Editorial summary, takeaway, and curation by AIssential. Original article published by MachineLearningMastery.com - Machinelearningmastery.com.