Perché Agenti AI Autonomi con Claude?
Ciao a tutti, appassionati di Claude! Se avete armeggiato con l'Anthropic API, sapete che Claude eccelle nel ragionamento, nell'uso degli strumenti e nei task a contesto lungo. Ma cosa succederebbe se potessimo renderlo autonomo—facendolo ciclare attraverso cicli think-act-observe da solo, persino migliorandosi nel tempo?
È questa la magia degli agenti AI. In questo tutorial, ne costruiremo uno da zero usando l'ultima Anthropic SDK (che supporta Claude 3.5 Sonnet, il modello powerhouse attuale). Copriremo esempi in Python e TypeScript, integrazione di strumenti, riflessione per l'auto-miglioramento e consigli per il deployment. Alla fine, avrete un agente pronto per la produzione che può ricercare, calcolare e iterare in modo indipendente.
Perfetto per sviluppatori, team che automatizzano workflow o chiunque stia valutando Claude per agenti enterprise.
Prerequisiti
Prima di tuffarci dentro:
- Anthropic API Key: Iscrivetevi su console.anthropic.com e prendete la vostra chiave.
- Python 3.10+ per la sezione Python.
- Node.js 18+ per TypeScript.
- Familiarità con la programmazione asincrona (la terremo semplice).
- Installate le dipendenze man mano che procediamo.
Useremo Claude 3.5 Sonnet (claude-3-5-sonnet-20241022) per il suo uso superiore degli strumenti e il ragionamento.
Concetti Core: Pattern ReAct + Reflection
Il nostro agente segue il loop ReAct (Reason + Act):
- Observe: Stato attuale/strumenti.
- Think: Claude ragiona sul prossimo passo.
- Act: Chiama strumenti o termina.
- Repeat fino a completamento.
Per l'auto-miglioramento, aggiungeremo un passo di riflessione: Dopo il completamento, Claude critica il suo lavoro e suggerisce miglioramenti per le esecuzioni future (memorizzati in memoria).
Il formato XML degli strumenti di Claude rende tutto fluido—nessun parsing JSON complicato necessario.
Tutorial Python: Costruire l'Agente
Step 1: Installa l'SDK
pip install anthropic
Imposta la tua API key:
import os
os.environ["ANTHROPIC_API_KEY"] = "your-api-key-here"
Step 2: Definisci gli Strumenti
Creeremo due strumenti di esempio: una calcolatrice e una ricerca web mock.
import anthropic
from typing import Any, Dict, List
def calculator(expression: str) -> str:
"""Evaluate a math expression safely."""
try:
# Safe eval for demo; use sympy in prod
result = eval(expression, {"__builtins__": {}})
return f"{result}"
except:
return "Error in calculation."
def web_search(query: str) -> str:
"""Mock web search (replace with SerpAPI or similar)."""
# Simulate results
return f"Search results for '{query}': Claude is great for agents! (Mock data)"
tools = [
{
"name": "calculator",
"description": "Evaluate math expressions like '2+2*(3/4)'",
"input_schema": {
"type": "object",
"properties": {
"expression": {"type": "string"}
}
}
},
{
"name": "web_search",
"description": "Search the web for information",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string"}
}
}
}
]
tool_choice = anthropic.types.ToolChoice(
type="auto",
tool_definitions=[anthropic.types.Tool.from_dict(t) for t in tools]
)
Nota: Gli strumenti usano schemi simili a Pydantic per la validazione.
Step 3: Il Loop dell'Agente Autonomo
Ecco il loop core:
client = anthropic.Anthropic()
async def run_agent(task: str, max_steps: int = 20) -> str:
messages: List[Dict] = [{"role": "user", "content": task}]
memory = [] # For self-improvement
for step in range(max_steps):
response = client.beta.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=messages,
tools=tool_choice.tools,
tool_choice=tool_choice,
)
# Append assistant message
messages.append({"role": "assistant", "content": response.content})
# Handle tool uses
for content_block in response.content:
if content_block.type == "tool_use":
tool_name = content_block.name
tool_args = content_block.input
if tool_name == "calculator":
result = calculator(tool_args["expression"])
elif tool_name == "web_search":
result = web_search(tool_args["query"])
else:
result = "Unknown tool"
# Append tool result
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": content_block.id,
"content": result
}]
})
elif content_block.type == "text":
if "done" in content_block.text.lower() or step > 10:
# Reflection step
reflect_prompt = f"""
Task: {task}
Final output: {content_block.text}
Critique your performance and suggest one improvement for next time."""
reflect_response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=200,
messages=[{"role": "user", "content": reflect_prompt}]
)
memory.append(reflect_response.content[0].text)
return content_block.text + f"\
\
Reflection: {reflect_response.content[0].text}"
return "Max steps reached."
# Usage
result = run_agent("What's 15% of 250? Then search how Claude agents work.")
print(result)
Questo cicla fino a quando Claude dice di aver finito, esegue gli strumenti e aggiunge la riflessione!
Step 4: Eseguilo
Esempio di output:
15% of 250 is 37.5.
Claude agents use ReAct pattern with tools.
Reflection: Good tool use, but could chain searches better next time.
Tutorial TypeScript: Edizione Node.js
Step 1: Setup
mkdir claude-agent-ts
cd claude-agent-ts
npm init -y
npm install @anthropic-ai/sdk
npm install -D typescript @types/node
npx tsc --init
Step 2: Definisci Strumenti & Agente
agent.ts:
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
const tools = [
{
name: 'calculator',
description: 'Evaluate math expressions',
inputSchema: {
type: 'object',
properties: { expression: { type: 'string' } },
},
},
// Add web_search similarly
];
async function runAgent(task: string, maxSteps = 20): Promise<string> {
let messages: any[] = [{ role: 'user', content: task }];
const memory: string[] = [];
for (let step = 0; step < maxSteps; step++) {
const response = await client.beta.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
messages,
tools,
tool_choice: { type: 'auto' },
});
messages.push({ role: 'assistant', content: response.content });
for (const block of response.content) {
if (block.type === 'tool_use') {
// Execute tool (implement calculator, etc.)
let result = 'Tool result'; // Mock
messages.push({
role: 'user',
content: [{
type: 'tool_result',
tool_use_id: block.id,
content: result,
}],
});
} else if (block.type === 'text' && block.text?.includes('done')) {
// Reflection
const reflectRes = await client.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 200,
messages: [{ role: 'user', content: `Task: ${task}\
Output: ${block.text}\
Critique & improve.` }],
});
return `${block.text}\
\
Reflection: ${reflectRes.content[0].text}`;
}
}
}
return 'Max steps reached.';
}
// Run: node agent.js after setting env
console.log(await runAgent('Calculate 2^10 and search Claude tools.'));
TypeScript brilla per gli argomenti degli strumenti type-safe (estendete con Zod per la validazione).
Rendere Autonomo l'Auto-Miglioramento: Memoria Avanzata
Memorizzate le riflessioni in un vector DB come Pinecone o un semplice file:
# After reflection
with open('memory.jsonl', 'a') as f:
f.write(json.dumps({"task": task, "reflection": reflection}) + '\
')
# Load into system prompt for future runs
system_prompt = "You are an improving agent. Past reflections: " + load_memory()
Questo permette all'agente di imparare dagli errori tra le sessioni!
Deployment in Produzione
Python: Server FastAPI
Esposto come API:
from fastapi import FastAPI
app = FastAPI()
@app.post("/agent")
async def agent_endpoint(task: str):
return {"result": await run_agent(task)}
Deploy su Railway o Vercel.
TypeScript: Vercel Serverless
Usate API routes in Next.js per uno scaling istantaneo.
Consigli:
- Rate limits: Batch degli strumenti, usate async.
- Costi: Monitorate i token (~$3/milione input).
- Sicurezza: Strumenti con guardrail e validazione.
- Scala: Aggiungete server MCP per estensioni custom.
Integrate con n8n/Zapier via webhook per workflow.
Esempio del Mondo Reale: Agente di Ricerca
Task: "Research Claude Directory top topics and summarize trends."
Agente: Cerca, calcola statistiche, riflette: "Used search well, but add data viz tool next."
Best Practices & Gotchas
- Max Steps: Prevenite loop infiniti.
- Errori Strumenti: Restituite sempre risultati strutturati.
- Context Window: 200k token—abbastanza per agenti.
- Confronti: Supera GPT-4o nel ragionamento con strumenti (per benchmark).
- Aggiornamenti: Tenete d'occhio il changelog di Anthropic per il beta di computer use.
Conclusione
Ora avete un blueprint per agenti Claude autonomi! Iniziate semplice, iterate con riflessioni, deploy in produzione. Sperimentate con playbook di settore—agenti per screening HR, ricerca vendite, ecc.
Fork su GitHub, condividete i vostri build nei commenti. Domande? Colpite i forum di Claude Directory.
Buon building di agenti! 🚀
(~1450 parole)
Stay ahead of the AI curve
The most important updates, news, and content — delivered in one weekly newsletter.