← Tous les articles

Agents avec Claude — Tool use, agentic loops et exemple end-to-end

Comment construire un agent avec Claude : définir les tools, implémenter tool-use, gérer les loops de feedback.

Agents avec Claude — Tool use, agentic loops et exemple end-to-end

Comment Claude fait du tool-use

Step 1 : Vous définissez les tools

{
  "tools": [
    {
      "name": "get_user_info",
      "description": "Fetch user profile by email",
      "input_schema": {
        "type": "object",
        "properties": {
          "email": {"type": "string"}
        }
      }
    },
    {
      "name": "send_email",
      "description": "Send email to user",
      "input_schema": {
        "type": "object",
        "properties": {
          "to": {"type": "string"},
          "subject": {"type": "string"},
          "body": {"type": "string"}
        }
      }
    }
  ]
}

Step 2 : Claude décide d'utiliser une tool

User: "Email mon contact avec address bob@example.com"

Claude pense : 
"Je dois chercher l'info de Bob, puis envoyer un email.
Mes tools : get_user_info, send_email.

Je vais d'abord appeler get_user_info(email=bob@example.com)"

Claude output :
{
  "type": "tool_use",
  "id": "call_123",
  "name": "get_user_info",
  "input": {"email": "bob@example.com"}
}

Step 3 : Vous exécutez la tool

Votre code :

if tool_use.name == "get_user_info":
    user = db.query(email=tool_use.input.email)
    result = {"name": "Bob", "phone": "555-1234", ...}
    # Envoyez le résultat à Claude

Step 4 : Claude continue

Claude reçoit : {"name": "Bob", "phone": "555-1234"}

Claude pense :
"Ok j'ai l'info de Bob. Maintenant j'envoie l'email."

Claude appelle : send_email(to="bob@example.com", subject="...", body="...")

Step 5 : Boucle jusqu'à done

Cette boucle répète jusqu'à Claude dit "fait" (type: "text").

Architecture simple : Agentic loop

def agent_loop(user_query, tools_available, max_iterations=10):
    messages = [{"role": "user", "content": user_query}]
    
    for i in range(max_iterations):
        # Call Claude
        response = claude.messages.create(
            model="claude-3.5-sonnet",
            max_tokens=1024,
            tools=tools_available,
            messages=messages
        )
        
        # Check if Claude is done
        if response.stop_reason == "end_turn":
            return response.content  # Final answer
        
        # Claude wants to use a tool
        for block in response.content:
            if block.type == "tool_use":
                # Execute the tool
                result = execute_tool(block.name, block.input)
                
                # Add to messages for next iteration
                messages.append({
                    "role": "assistant",
                    "content": response.content
                })
                messages.append({
                    "role": "user",
                    "content": {
                        "type": "tool_result",
                        "tool_use_id": block.id,
                        "content": str(result)
                    }
                })
    
    return "Max iterations reached"

Exemple complet : Agent de support client

Tools defined :
- lookup_customer(email) → {id, name, plan}
- lookup_order(order_id) → {id, date, status, items}
- get_kb_article(topic) → {content}
- send_email(to, subject, body) → {sent: true}

User query:
"Hi, I'm Bob (bob@example.com). My order #12345 hasn't arrived."

Agent loop :

Iteration 1 :
  Claude : "I'll help. Let me look up Bob's customer info"
  Tool : lookup_customer(email="bob@example.com")
  Result : {id: 999, name: "Bob", plan: "premium"}

Iteration 2 :
  Claude : "Now let me check the order status"
  Tool : lookup_order(order_id="12345")
  Result : {id: 12345, date: "2026-08-01", status: "shipped", items: [...]}

Iteration 3 :
  Claude : "Order is shipped. Let me find relevant KB article about shipping delays"
  Tool : get_kb_article(topic="shipping_delays")
  Result : {content: "If not received in 3 weeks, contact support..."}

Final :
  Claude outputs :
  "Hi Bob! I found your premium account and order #12345.
   It was shipped on Aug 1 and is in transit. 
   If it doesn't arrive by Aug 22, contact us and we'll reship.
   [KB article link]"

Best practices

1. Clear tool descriptions

❌ Bad: "get data"
✅ Good: "Retrieve customer profile including name, email, subscription status, and total spending. Requires valid email address."

2. Handle tool errors gracefully

try:
    result = execute_tool(...)
except Exception as e:
    # Tell Claude what went wrong
    error_message = f"Tool {tool_name} failed: {str(e)}"
    messages.append({
        "role": "user",
        "content": f"Tool call failed. {error_message}"
    })

3. Limit iterations

Always set max_iterations to avoid infinite loops.

4. Log everything

Track every tool call for debugging + audit.

À lire ensuite : Cas d'usage : Agents en production — Automatisation, supervision et scaling

Voir tout le parcours du tutoriel →

Envie d'aller plus loin avec l'IA ?

Nos formations sont live, pratiques et certifiantes — appliquées à ton métier.

Voir les formations