convez.ai
AgenteAutomaçãoIntermediário
SpearHead07

Claude Multi-Tool Agent

SpearHead07/claude-multi-tool-agent

Agent robusto Claude+LangGraph com multi-tools, CLI e logging estruturado

Ver no GitHub
InicialPluginScore · de 0 a 100

Agent de produção em Python com Anthropic Claude e LangGraph que implementa raciocínio multi-ferramenta, roteamento inteligente de tools, recuperação de erros e logging estruturado. Inclui CLI para consultas únicas ou chat interativo com observabilidade completa.

Instalação

$npx convez-ai SpearHead07/claude-multi-tool-agent

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
0
Acompanhando
0
Saúde
28%
Último commit
há 6 meses
Versão
—
Issues abertas
0
Contribuidores
2

Casos de uso

  • Construir agents de produção com raciocínio sobre múltiplas ferramentas
  • Implementar roteamento de tools baseado em schemas descritivos
  • Aprender padrões de state machines com LangGraph
  • Estruturar logs e observabilidade em sistemas com LLM

Veredito

Implementação sólida e educativa de um agent em produção. Padrões bem estruturados (state machine, tool routing, error handling) servem como referência. Começador em IA multiagentes aprenderá muito; desenvolvedor Python experiente verá boas práticas de engenharia, não apenas tutorial.

README

A tradução para o português deste README ainda está na fila.

Claude Multi-Tool Agent

A production-ready AI agent built with Anthropic Claude and LangGraph — supports multi-tool reasoning, graceful error recovery, and full observability via structured logging. Ships with a CLI for single queries, interactive chat, and verbose debugging.

Python LangGraph Anthropic License


Overview

Most LLM tutorials show you how to call an API. Few show you how to build an agent that handles failure gracefully, routes between multiple tools intelligently, and produces structured logs you can debug in production.

This project is a from-scratch implementation of a multi-tool agent using Anthropic's Claude API and LangGraph. It demonstrates the core patterns — tool routing via descriptions, errors-as-conversation, graph-based state management, and modular code structure — that production agent systems are built on.

The agent currently supports two tools (calculator and date) but the architecture is designed so that adding a new tool is a 4-line change, with no modifications to the agent loop, the graph, or the CLI.


Architecture

Architecture

The agent is a LangGraph state machine with two nodes and one router:

  • call_model sends the conversation to Claude with bound tool schemas
  • execute_tools is LangGraph's built-in ToolNode, wired to a tool registry
  • should_continue is the router — checks the last message for tool calls, routes to either execute_tools or END

State flows through the graph as a typed messages list, using add_messages as a reducer so updates append rather than replace.


Tech Stack

  • Language — Python 3.10+
  • LLM — Anthropic Claude (Opus 4.5)
  • Framework — LangGraph for state machine, LangChain Anthropic for model binding
  • CLI — argparse (standard library)
  • Logging — Python logging module with module-named loggers
  • Config — python-dotenv for environment variable loading

Quick Start

# 1. Clone the repo
git clone https://github.com/YOUR_USERNAME/claude-multi-tool-agent.git
cd claude-multi-tool-agent

# 2. Install dependencies
pip install -r requirements.txt

# 3. Set up your API key
cp .env.example .env
# Open .env and paste your ANTHROPIC_API_KEY

# 4. Run a single query
python main.py --query "what is 25 * 4 and what's today's date"

# Or start an interactive chat session
python main.py --interactive

# Or run with verbose mode to see every step
python main.py -q "what is 12 * 12" -v

CLI Reference

python main.py --help
FlagShortDescription
--query "..."-qRun a single query and exit
--interactive-iStart an interactive chat session
--verbose-vStream intermediate steps (every node execution)
--help-hShow usage docs

Project Structure

Each file has a single responsibility. The dependency arrow flows one way: main → src → tools. Adding a new tool is a 4-line change — one new file in tools/, three lines in tools/__init__.py. No agent or graph code changes.


How Tool Routing Works

There is no if/else routing logic in this codebase. Claude reads the description field on each tool's JSON schema and decides which tool to call. Sharp descriptions = correct routing. Vague descriptions = wrong tool calls.

Each description follows a "use when / do NOT use when" pattern:

"description": (
    "Performs mathematical calculations. Use this when the user asks to compute, "
    "add, subtract, multiply, divide, or evaluate any math expression. "
    "Do NOT use for date or text questions."
)

The "Do NOT use for…" clause measurably improves routing accuracy, especially on ambiguous queries.


Error Handling Philosophy

Errors are not crashes — they are conversational turns. When a tool fails, it returns the error as a string instead of raising an exception. Claude reads the error message in the next turn and reasons about what to do — retry with different input, ask the user for clarification, or apologise and stop.

This means the agent loop never breaks on tool failures. It just continues with new context.

try:
    result = eval(expression)
    return f"{expression} = {result}"
except Exception as e:
    log.error(f"calculator failed: {e}")
    return f"Error: {str(e)}"   # returned as a string, not raised

Logging

Every tool call, model invocation, and routing decision is logged with a timestamp, severity level, and module name:

This is the agent's nervous system — debugging without it is impossible. Severity levels: INFO for normal flow, WARNING for unusual inputs (rejected expressions, empty results), ERROR for failures.


What I Learned

  • Tool descriptions are the routing layer. Claude picks tools by reading text, not running code. Sharpening descriptions with explicit "use when / do NOT use when" clauses dramatically improves routing accuracy.
  • Errors are conversational turns, not crashes. Returning errors as strings (instead of raising) lets the agent self-correct on the next turn. The loop never dies.
  • Graphs replace loops once complexity grows. A while True loop works for one tool. With multiple tools, conditional routing, and future human-in-the-loop, LangGraph's State + Nodes + Edges scales where loops break.
  • Modular structure matters more than line count. Splitting a 200-line script into 12 small files with single responsibilities makes the same code dramatically easier to extend, test, and explain.
  • Centralised config + structured logging are not optional. They cost 30 minutes to set up and save hours later. Every production codebase has them — there's a reason.

API Usage

The agent can be exposed as a FastAPI web service.

Start the server

uvicorn src.api:app --port 8000

Visit http://127.0.0.1:8000/docs for the interactive Swagger UI.

Endpoints

MethodPathDescription
GET/Health check
GET/docsInteractive API documentation (Swagger UI)
POST/chatSend a query, get a JSON response
POST/chat/streamSend a query, stream tokens via Server-Sent Events

Example: synchronous chat

curl -X POST http://127.0.0.1:8000/chat \
  -H "Content-Type: application/json" \
  -d '{"query": "what is 25 * 4"}'

Response:

{
  "answer": "25*4 = 100",
  "model": "claude-opus-4-5"
}

Example: streaming chat

curl -N -X POST http://127.0.0.1:8000/chat/stream \
  -H "Content-Type: application/json" \
  -d '{"query": "write a short poem"}'

Response: a stream of data: events, terminated by event: done.


License

MIT — see LICENSE file.


Author

Built by Ashish as part of a 30-day journey to AI Engineer.

🔗 LinkedIn · GitHub

Ver o original no GitHub

Bom para

Relacionados