Wiki IA
LLM et IA Générative

Agents Autonomes

Nouvelle génération d'agents IA - Devin, Claude Computer Use, Auto-GPT et systèmes d'agents auto-dirigés

Agents Autonomes

Les agents autonomes représentent une évolution majeure : des IA capables d'accomplir des tâches complexes de bout en bout, avec un minimum d'intervention humaine.

Évolution vers l'autonomie

┌─────────────────────────────────────────────────────────────────┐
│              ÉVOLUTION DES AGENTS IA                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  2022: CHATBOTS                                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │  User ────► LLM ────► Réponse                           │   │
│  │  Conversation simple, pas d'actions                      │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                  │
│  2023: AGENTS AVEC TOOLS                                        │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │  User ────► LLM ────► Tools ────► Résultat              │   │
│  │  Function calling, actions limitées, supervisé          │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                  │
│  2024: AGENTS AUTONOMES                                         │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │  User ────► Agent ────┬────► Planification              │   │
│  │    ▲                  ├────► Exécution multi-étapes     │   │
│  │    │                  ├────► Auto-correction            │   │
│  │    │                  └────► Résultat final             │   │
│  │    └────────────────────────────────────────────────────│   │
│  │  Boucle autonome avec checkpoint humain occasionnel     │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Devin (Cognition Labs)

Le premier "AI Software Engineer"

┌─────────────────────────────────────────────────────────────────┐
│                         DEVIN                                    │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  "Resolve this GitHub issue"                                    │
│               │                                                  │
│               ▼                                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │              ENVIRONNEMENT DEVIN                         │   │
│  │                                                          │   │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐             │   │
│  │  │  Shell   │  │  Editor  │  │ Browser  │             │   │
│  │  │  (bash)  │  │  (code)  │  │  (web)   │             │   │
│  │  └────┬─────┘  └────┬─────┘  └────┬─────┘             │   │
│  │       │             │             │                    │   │
│  │       └─────────────┼─────────────┘                    │   │
│  │                     │                                   │   │
│  │               ┌─────▼─────┐                            │   │
│  │               │   AGENT   │                            │   │
│  │               │   CORE    │                            │   │
│  │               │           │                            │   │
│  │               │ • Plan    │                            │   │
│  │               │ • Execute │                            │   │
│  │               │ • Debug   │                            │   │
│  │               │ • Iterate │                            │   │
│  │               └───────────┘                            │   │
│  │                                                          │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                  │
│  CAPACITÉS:                                                     │
│  ✓ Clone repos, navigue le code                                │
│  ✓ Écrit et modifie des fichiers                               │
│  ✓ Exécute des tests                                           │
│  ✓ Recherche documentation en ligne                            │
│  ✓ Crée des PR complètes                                       │
│                                                                  │
│  BENCHMARK SWE-bench: 13.86% → Plus que la moyenne dev         │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Architecture conceptuelle

# Architecture simplifiée type Devin
from dataclasses import dataclass
from enum import Enum

class ToolType(Enum):
    SHELL = "shell"
    EDITOR = "editor"
    BROWSER = "browser"

@dataclass
class ExecutionState:
    """État de l'environnement d'exécution"""
    files: dict[str, str]  # path -> content
    shell_history: list[str]
    browser_state: dict
    current_plan: list[str]
    completed_steps: list[str]

class AutonomousAgent:
    def __init__(self, llm, tools: dict[ToolType, callable]):
        self.llm = llm
        self.tools = tools
        self.state = ExecutionState(
            files={},
            shell_history=[],
            browser_state={},
            current_plan=[],
            completed_steps=[]
        )
        self.max_iterations = 50

    def solve(self, task: str) -> str:
        """Résout une tâche de bout en bout"""
        # 1. Planification initiale
        self.state.current_plan = self._plan(task)

        for iteration in range(self.max_iterations):
            # 2. Choisir la prochaine action
            action = self._decide_action()

            if action["type"] == "complete":
                return action["result"]

            # 3. Exécuter l'action
            result = self._execute(action)

            # 4. Mettre à jour l'état
            self._update_state(action, result)

            # 5. Re-planifier si nécessaire
            if self._needs_replanning(result):
                self.state.current_plan = self._replan()

        return "Max iterations reached"

    def _plan(self, task: str) -> list[str]:
        """Génère un plan d'action"""
        prompt = f"""
        Task: {task}

        Create a step-by-step plan to complete this task.
        Consider: code exploration, implementation, testing, debugging.

        Plan:
        """
        response = self.llm.generate(prompt)
        return self._parse_plan(response)

    def _decide_action(self) -> dict:
        """Décide la prochaine action basée sur l'état"""
        prompt = f"""
        Current state:
        - Plan: {self.state.current_plan}
        - Completed: {self.state.completed_steps}
        - Recent shell output: {self.state.shell_history[-3:]}

        What should be the next action?
        Options: shell_command, edit_file, browse_url, complete

        Response format:
        {{"type": "...", "details": "..."}}
        """
        return self.llm.generate_json(prompt)

    def _execute(self, action: dict) -> str:
        """Exécute une action avec le tool approprié"""
        tool_type = ToolType(action["type"])
        tool = self.tools[tool_type]
        return tool(action["details"])

Claude Computer Use

Contrôle natif de l'ordinateur

┌─────────────────────────────────────────────────────────────────┐
│              CLAUDE COMPUTER USE                                 │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  Architecture:                                                   │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                                                          │   │
│  │  ┌──────────────┐      ┌──────────────────────────┐    │   │
│  │  │   Claude     │      │     Virtual Desktop       │    │   │
│  │  │   (Vision)   │─────►│     (Linux/Windows)       │    │   │
│  │  │              │      │                           │    │   │
│  │  │  "Je vois    │      │   ┌─────────────────┐    │    │   │
│  │  │   l'écran"   │◄─────│   │   Screenshot    │    │    │   │
│  │  └──────────────┘      │   └─────────────────┘    │    │   │
│  │         │              │                           │    │   │
│  │         │              │   Actions:                │    │   │
│  │         ▼              │   • mouse_move(x, y)     │    │   │
│  │  ┌──────────────┐      │   • click(button)        │    │   │
│  │  │  Tool Use:   │─────►│   • type(text)           │    │   │
│  │  │  computer    │      │   • key(combo)           │    │   │
│  │  └──────────────┘      │   • screenshot()         │    │   │
│  │                        │                           │    │   │
│  │                        └──────────────────────────┘    │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                  │
│  DIFFÉRENCE CLÉE:                                               │
│  Pas d'API - Interagit comme un humain via l'interface         │
│  graphique. Peut utiliser N'IMPORTE QUELLE application.        │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Utilisation de Computer Use

import anthropic
import base64
from PIL import Image

client = anthropic.Anthropic()

def run_computer_use_agent(task: str):
    """Agent utilisant Claude Computer Use"""
    messages = [{
        "role": "user",
        "content": task
    }]

    # Boucle d'agent
    while True:
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=4096,
            tools=[
                {
                    "type": "computer_20241022",
                    "name": "computer",
                    "display_width_px": 1920,
                    "display_height_px": 1080,
                    "display_number": 1,
                },
                {
                    "type": "text_editor_20241022",
                    "name": "str_replace_editor",
                },
                {
                    "type": "bash_20241022",
                    "name": "bash",
                },
            ],
            messages=messages,
            betas=["computer-use-2024-10-22"],
        )

        # Traiter la réponse
        if response.stop_reason == "end_turn":
            return extract_final_response(response)

        # Exécuter les tool calls
        tool_results = []
        for block in response.content:
            if block.type == "tool_use":
                result = execute_tool(block.name, block.input)
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": result,
                })

        # Continuer la conversation
        messages.append({"role": "assistant", "content": response.content})
        messages.append({"role": "user", "content": tool_results})

def execute_tool(name: str, input: dict) -> str:
    """Exécute un tool et retourne le résultat"""
    if name == "computer":
        action = input["action"]
        if action == "screenshot":
            # Capture d'écran
            screenshot = take_screenshot()
            return [{
                "type": "image",
                "source": {
                    "type": "base64",
                    "media_type": "image/png",
                    "data": base64.b64encode(screenshot).decode(),
                }
            }]
        elif action == "mouse_move":
            move_mouse(input["coordinate"])
        elif action == "click":
            click_mouse(input.get("button", "left"))
        elif action == "type":
            type_text(input["text"])
        elif action == "key":
            press_key(input["key"])
        return "Action completed"

    elif name == "bash":
        return run_bash_command(input["command"])

    elif name == "str_replace_editor":
        return edit_file(input)

# Exemple d'utilisation
result = run_computer_use_agent(
    "Ouvre Firefox, va sur Google, et recherche 'weather Paris'"
)

Auto-GPT et agents open source

Architecture Auto-GPT

┌─────────────────────────────────────────────────────────────────┐
│                      AUTO-GPT                                    │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  GOAL: "Create a market research report on AI startups"         │
│                                                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    AGENT LOOP                            │   │
│  │                                                          │   │
│  │  1. THINK                                                │   │
│  │     "What do I need to do next?"                        │   │
│  │     └──► GPT-4 generates reasoning                      │   │
│  │                                                          │   │
│  │  2. PLAN                                                 │   │
│  │     "How should I approach this?"                       │   │
│  │     └──► Creates sub-tasks                              │   │
│  │                                                          │   │
│  │  3. CRITICIZE                                            │   │
│  │     "Is this plan good?"                                │   │
│  │     └──► Self-evaluation                                │   │
│  │                                                          │   │
│  │  4. ACT                                                  │   │
│  │     Execute chosen command                               │   │
│  │     └──► web_search, write_file, execute_code...        │   │
│  │                                                          │   │
│  │  5. READ                                                 │   │
│  │     Process results                                      │   │
│  │     └──► Update memory                                  │   │
│  │                                                          │   │
│  │         ↓                                                │   │
│  │     Repeat until goal achieved                          │   │
│  │                                                          │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                  │
│  MÉMOIRE:                                                       │
│  • Short-term: Contexte conversation                           │
│  • Long-term: Base vectorielle (Pinecone/Weaviate)             │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Autres frameworks d'agents autonomes

# 1. CREWAI - Équipes d'agents collaboratifs
from crewai import Agent, Task, Crew

researcher = Agent(
    role="Senior Research Analyst",
    goal="Research AI trends for 2024",
    backstory="Expert in AI industry analysis",
    tools=[search_tool, scrape_tool],
    llm=llm,
)

writer = Agent(
    role="Content Writer",
    goal="Write engaging articles",
    backstory="Experienced tech journalist",
    tools=[write_tool],
    llm=llm,
)

research_task = Task(
    description="Research top 10 AI trends in 2024",
    agent=researcher,
    expected_output="Detailed analysis with sources"
)

writing_task = Task(
    description="Write article from research",
    agent=writer,
    expected_output="Blog post ready for publication",
    context=[research_task]  # Dépend de research_task
)

crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, writing_task],
    verbose=True,
)

result = crew.kickoff()


# 2. LANGCHAIN AGENTS
from langchain.agents import create_react_agent, AgentExecutor
from langchain_openai import ChatOpenAI
from langchain.tools import Tool

tools = [
    Tool(
        name="Search",
        func=search_function,
        description="Search the web"
    ),
    Tool(
        name="Calculator",
        func=calculator_function,
        description="Perform calculations"
    ),
]

llm = ChatOpenAI(model="gpt-4")
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    max_iterations=10,
)

result = agent_executor.invoke({
    "input": "What is the population of France multiplied by 2?"
})


# 3. AUTOGEN (Microsoft)
from autogen import AssistantAgent, UserProxyAgent

assistant = AssistantAgent(
    name="assistant",
    llm_config={"model": "gpt-4"},
)

user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="TERMINATE",  # Demande validation humaine
    code_execution_config={
        "work_dir": "coding",
        "use_docker": True,  # Sandbox sécurisé
    },
)

# L'agent code et exécute automatiquement
user_proxy.initiate_chat(
    assistant,
    message="Create a plot of stock prices for AAPL"
)

Patterns d'agents autonomes

ReAct (Reasoning + Acting)

┌─────────────────────────────────────────────────────────────────┐
│                    PATTERN REACT                                 │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  Question: "Quel âge a le président français ?"                │
│                                                                  │
│  Thought 1: Je dois chercher qui est le président français     │
│  Action 1: search("président France 2024")                     │
│  Observation 1: Emmanuel Macron est le président               │
│                                                                  │
│  Thought 2: Maintenant je dois trouver sa date de naissance    │
│  Action 2: search("Emmanuel Macron date naissance")            │
│  Observation 2: Né le 21 décembre 1977                         │
│                                                                  │
│  Thought 3: Je peux calculer son âge                           │
│  Action 3: calculate(2024 - 1977)                              │
│  Observation 3: 47                                              │
│                                                                  │
│  Thought 4: J'ai la réponse                                    │
│  Answer: Emmanuel Macron a 47 ans                               │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Plan-and-Execute

class PlanAndExecuteAgent:
    """Agent avec planification explicite"""

    def __init__(self, llm, executor):
        self.planner = llm
        self.executor = executor

    def run(self, objective: str):
        # Phase 1: Planification
        plan = self._create_plan(objective)

        # Phase 2: Exécution séquentielle
        results = []
        for step in plan:
            result = self.executor.execute(step, context=results)
            results.append(result)

            # Re-planification si échec
            if result["status"] == "failed":
                remaining = plan[plan.index(step):]
                plan = remaining[:1] + self._replan(
                    objective, results, remaining[1:]
                )

        return self._synthesize(objective, results)

    def _create_plan(self, objective: str) -> list[str]:
        prompt = f"""
        Objective: {objective}

        Create a numbered plan of concrete steps to achieve this.
        Each step should be independently executable.
        """
        response = self.planner.generate(prompt)
        return self._parse_steps(response)

    def _replan(self, objective, history, remaining):
        prompt = f"""
        Objective: {objective}
        Completed: {history}
        Originally remaining: {remaining}
        Last step failed.

        Create new plan for remaining work.
        """
        return self._parse_steps(self.planner.generate(prompt))

Reflexion

┌─────────────────────────────────────────────────────────────────┐
│                   PATTERN REFLEXION                              │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│                    ┌───────────────┐                            │
│         ┌────────►│    Actor      │                            │
│         │         │   (Agent)     │                            │
│         │         └───────┬───────┘                            │
│         │                 │ Action                              │
│         │                 ▼                                     │
│         │         ┌───────────────┐                            │
│         │         │  Environment  │                            │
│         │         │   (Feedback)  │                            │
│         │         └───────┬───────┘                            │
│         │                 │ Result                              │
│         │                 ▼                                     │
│         │         ┌───────────────┐                            │
│         │         │   Evaluator   │                            │
│         │         │  (Success?)   │                            │
│         │         └───────┬───────┘                            │
│         │                 │                                     │
│         │        ┌────────┴────────┐                           │
│         │        │                 │                            │
│         │      Fail              Success                        │
│         │        │                 │                            │
│         │        ▼                 ▼                            │
│  ┌──────┴────────────┐       ┌──────────┐                      │
│  │    Self-Reflect   │       │  Output  │                      │
│  │                   │       │          │                      │
│  │ "Pourquoi ça n'a  │       └──────────┘                      │
│  │  pas marché?"     │                                         │
│  │                   │                                         │
│  │ Stocke leçon      │                                         │
│  │ dans mémoire      │                                         │
│  └───────────────────┘                                         │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Comparaison des systèmes

SystèmeTypeAutonomieSécuritéOpen Source
DevinSWE AgentTrès hauteSandboxNon
Claude Computer UseGeneralHauteVM requisNon
Auto-GPTGeneralMoyenneLimitéeOui
CrewAIMulti-agentMoyenneConfigurableOui
LangChain AgentsFrameworkVariableConfigurableOui
AutoGenMulti-agentMoyenneDockerOui

Sécurité et contrôle

┌─────────────────────────────────────────────────────────────────┐
│              SÉCURITÉ DES AGENTS AUTONOMES                      │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ⚠ RISQUES MAJEURS:                                            │
│  • Exécution de code malveillant                               │
│  • Accès non autorisé à des ressources                         │
│  • Boucles infinies (coût, ressources)                         │
│  • Actions irréversibles (delete, push)                        │
│  • Exfiltration de données sensibles                           │
│                                                                  │
│  MESURES DE PROTECTION:                                         │
│                                                                  │
│  1. SANDBOXING                                                  │
│     ┌────────────────────────────────────────────────────┐     │
│     │  Docker container / VM isolée                       │     │
│     │  • Pas d'accès réseau (sauf whitelist)             │     │
│     │  • Filesystem limité                                │     │
│     │  • Ressources plafonnées (CPU, RAM, temps)         │     │
│     └────────────────────────────────────────────────────┘     │
│                                                                  │
│  2. HUMAN-IN-THE-LOOP                                          │
│     • Validation avant actions destructives                    │
│     • Checkpoints réguliers                                    │
│     • Budget de tokens/actions                                 │
│                                                                  │
│  3. PERMISSIONS GRANULAIRES                                     │
│     • read_only par défaut                                     │
│     • Whitelist des commandes autorisées                       │
│     • Secrets jamais exposés à l'agent                         │
│                                                                  │
│  4. MONITORING                                                  │
│     • Logs de toutes les actions                               │
│     • Alertes sur comportements anormaux                       │
│     • Kill switch automatique                                   │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Implémentation sécurisée

class SecureAgentExecutor:
    """Exécuteur d'agent avec mesures de sécurité"""

    def __init__(
        self,
        agent,
        allowed_commands: list[str],
        max_iterations: int = 20,
        max_tokens: int = 100000,
        require_approval_for: list[str] = None,
    ):
        self.agent = agent
        self.allowed_commands = set(allowed_commands)
        self.max_iterations = max_iterations
        self.max_tokens = max_tokens
        self.require_approval = set(require_approval_for or [])

        self.iteration_count = 0
        self.token_count = 0

    def run(self, task: str, approval_callback=None):
        """Exécute l'agent avec contrôles de sécurité"""
        while self.iteration_count < self.max_iterations:
            self.iteration_count += 1

            # Obtenir la prochaine action
            action = self.agent.next_action()

            # Vérifier les limites
            if self.token_count > self.max_tokens:
                raise SecurityException("Token budget exceeded")

            # Vérifier si l'action est autorisée
            if not self._is_allowed(action):
                raise SecurityException(f"Action not allowed: {action}")

            # Demander approbation si nécessaire
            if self._requires_approval(action):
                if approval_callback is None:
                    raise SecurityException("Approval required but no callback")
                if not approval_callback(action):
                    continue  # Skip this action

            # Exécuter dans sandbox
            result = self._execute_sandboxed(action)

            # Mettre à jour l'agent
            self.agent.observe(result)
            self.token_count += len(result) // 4  # Approximation

            if self.agent.is_complete():
                return self.agent.get_result()

        raise SecurityException("Max iterations reached")

    def _is_allowed(self, action: dict) -> bool:
        """Vérifie si l'action est dans la whitelist"""
        command = action.get("command", "")
        return any(
            command.startswith(allowed)
            for allowed in self.allowed_commands
        )

    def _requires_approval(self, action: dict) -> bool:
        """Vérifie si l'action nécessite une approbation"""
        command = action.get("command", "")
        return any(
            pattern in command
            for pattern in self.require_approval
        )

    def _execute_sandboxed(self, action: dict) -> str:
        """Exécute l'action dans un environnement isolé"""
        # Utilise Docker ou VM
        import docker
        client = docker.from_env()

        container = client.containers.run(
            "python:3.11-slim",
            command=action["command"],
            mem_limit="512m",
            cpu_period=100000,
            cpu_quota=50000,  # 50% CPU
            network_mode="none",  # Pas de réseau
            remove=True,
            timeout=30,
        )
        return container.decode()

Limites actuelles

┌─────────────────────────────────────────────────────────────────┐
│           LIMITES DES AGENTS AUTONOMES (2024)                   │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ⚠ FIABILITÉ                                                   │
│    - Taux d'échec encore élevé sur tâches complexes            │
│    - Difficultés à récupérer d'erreurs                         │
│    - Comportements imprévisibles                                │
│                                                                  │
│  ⚠ COÛT                                                        │
│    - Très consommateur en tokens                               │
│    - Une tâche Devin peut coûter $10-50                        │
│    - Boucles infinies possibles                                │
│                                                                  │
│  ⚠ LENTEUR                                                     │
│    - Minutes à heures par tâche                                │
│    - Pas adapté pour interactions temps réel                   │
│                                                                  │
│  ⚠ SCOPE LIMITÉ                                                │
│    - Mieux pour tâches bien définies                           │
│    - Difficultés avec ambiguïté                                │
│    - Contexte métier souvent manquant                          │
│                                                                  │
│  BONNES PRATIQUES:                                              │
│  ✓ Commencer par des tâches simples et bien définies          │
│  ✓ Toujours avoir un human-in-the-loop                        │
│  ✓ Définir des budgets stricts (tokens, temps, actions)       │
│  ✓ Monitorer et auditer toutes les actions                    │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Pour aller plus loin

On this page