File size: 12,450 Bytes
d4ea4e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# Gradio-hackathon : Generalist self-evolving ai agent inspired by Alita 
This is my team project for the gradio hackathon 2025
This Project is inspired by research paper : `https://arxiv.org/abs/2505.20286`

# 📁 Structure du projet
```bash

alita_agent/


├── main.py                           # Point d'entrée principal : exécute un TaskPrompt via le ManagerAgent

├── manager_agent.py                  # Logique de coordination centrale, il orchestre tous les composants

├── task_prompt.py                    # Définit la classe TaskPrompt, contenant la requête utilisateur initiale


├── components/                       # Contient tous les composants fonctionnels modulaires

│   ├── __init__.py                   # Rends le dossier importable comme un package

│   ├── script_generator.py           # Génère dynamiquement du code Python à partir d'un MCPToolSpec

│   ├── code_runner.py                # Exécute un script dans un environnement isolé et capture le résultat

│   ├── mcp_registry.py               # Gère l'enregistrement, la recherche et la réutilisation des outils MCP

│   ├── web_agent.py                  # Effectue des recherches web ou GitHub pour aider à la génération de code

│   └── mcp_brainstormer.py           # Génère des MCPToolSpec en analysant la tâche utilisateur


├── models/                           # Contient les classes de données (dataclasses) utilisées dans tout le système

│   ├── __init__.py                   # Rends le dossier importable comme un package

│   ├── mcp_tool_spec.py              # Définition de MCPToolSpec (dataclass) : nom, schémas I/O, description, pseudo-code, etc.

│   └── mcp_execution_result.py       # Définition de MCPExecutionResult (dataclass) : succès, sortie, logs, erreur


├── tests/                            # Contient les tests unitaires pour chaque module

│   ├── __init__.py                   # Rends le dossier importable comme un package

│   ├── test_script_generator.py      # Tests pour vérifier la génération correcte de code et d'environnements

│   ├── test_code_runner.py           # Tests pour s'assurer de la bonne exécution des scripts et gestion d'erreurs

│   ├── test_mcp_registry.py          # Tests de l'enregistrement, recherche et appel d'outils dans le registre MCP

│   └── test_manager_agent.py         # Tests d'intégration sur le comportement global du ManagerAgent


└── README.md                         # Documentation du projet, instructions, pipeline, inspirations et lien vers le papier

```

# Project Pipeline 

#### 🔄 Le flux complet avec vérification de l'existence
1. L'utilisateur envoie un TaskPrompt
2. Le Manager Agent demande au MCPBrainstormer : "Quels outils faudrait-il pour résoudre cette tâche ?"
3. Le Brainstormer propose une ou plusieurs specs (MCPToolSpec)
4. Le Manager Agent consulte le MCPRegistry : "Ai-je déjà un outil enregistré dont le nom + I/O matchent cette spec ?"
   - Oui ? ➜ réutilise l'outil existant
   - Non ? ➜ il appel le web agent pour une recherche d'outils open-source pour implementer. Puis, le Manager prend la recherche et la donne a Brainstormer pour commencer la construction.

#### 🔍 Comment détecter que l'outil existe déjà ?
Par matching sur la spec MCPToolSpec :
- Nom exact (ou identifiant unique comme un hash)

- Ou plus intelligemment :
    - même structure input_schema

    - même output_schema
    - mêmes rôles ou description proche (avec embedding / vector search)

```python

def check_existing_tool(spec: MCPToolSpec, registry: MCPRegistry) -> Optional[str]:

    for registered_spec in registry.list_tools():

        if registered_spec.input_schema == spec.input_schema and \

           registered_spec.output_schema == spec.output_schema:

            return registry.get_tool_endpoint(registered_spec.name)

    return None

```

#### 💬 Que fait l'agent s'il le trouve ?
Il ne régénère rien :
- Il ajoute l'appel de l'outil MCP existant dans son plan
- Il formate l'entrée JSON
- Il appelle POST /predict directement
- Il utilise la réponse dans la suite de son raisonnement

#### 💡 Cas pratiques
Differents cas et Réaction attendue de l'agent 

| Situation réelle                          | Réaction de l'agent                                                      |
| ----------------------------------------- | ------------------------------------------------------------------------ |
| L'outil `"SubtitleExtractor"` existe déjà | L'agent appelle directement l'endpoint                                   |
| Le spec est proche mais pas identique     | L'agent peut quand même le réutiliser (avec adaptation)                  |
| L'outil existe mais a échoué              | L'agent peut **fallback** vers génération d'un nouvel outil MCP          |
| L'outil existe mais est obsolète          | Le Registry peut signaler une mise à jour ou déclencher une régénération |


#### Fonctions attendues 

| Classe               | Méthode attendue                           | Présente ? | Commentaire |
| -------------------- | ------------------------------------------ | ---------- | ----------- |
| `ManagerAgent`       | `run_task(prompt)`                         | ✅          | OK          |
| `MCPBrainstormer`    | `brainstorm(prompt)`                       | ✅          | OK          |
| `WebAgent`           | `search_github`, `retrieve_readme`         | ✅          | OK          |
| `ScriptGenerator`    | `generate_code`, `generate_env_script`     | ✅          | OK          |
| `CodeRunner`         | `execute`, `setup_environment`             | ✅          | OK          |
| `MCPRegistry`        | `register_tool`, `list_tools`, `call_tool` | ✅          | OK          |
| `MCPExecutionResult` | attributs `success`, `output`, `logs`      | ✅          | OK          |
| `MCPToolSpec`        | `name`, `input_schema`, etc.               | ✅          | OK          |

Ici Le ManagerAgent coordonne tout. Il délègue à :
- MCPBrainstormer → pour générer des specs d'outils.
- ScriptGenerator → pour générer du code.
- CodeRunner → pour tester le code.
- WebAgent → pour récupérer du contexte externe.
- MCPRegistry → pour enregistrer et réutiliser les outils.


![](alitaDiagram.svg)


```sh

plantuml -tsvg README.md

```

<div hidden>
<details>
<summary>Voir le script PlantUML</summary>
```plantuml

@startuml alitaDiagram



skinparam classAttributeIconSize 0



' === Classes de données ===

class TaskPrompt {

    - text: str

}



class MCPToolSpec {

    - name: str

    - input_schema: dict

    - output_schema: dict

    - description: str

    - pseudo_code: str

    - source_hint: str

}



class MCPExecutionResult {

    - success: bool

    - output: dict

    - logs: str

    - error_message: str

}



class ToolCall {

  - tool_name: str

  - input_data: dict

  - result: dict

}





' === Agents principaux ===

class ManagerAgent {

    - brainstormer: MCPBrainstormer

    - web_agent: WebAgent

    - generator: ScriptGenerator

    - runner: CodeRunner

    - registry: MCPRegistry

    + run_task(prompt: TaskPrompt): dict

    + check_existing_tool(spec: MCPToolSpec) -> Optional[str]

}



class MCPBrainstormer {

    + brainstorm(prompt: TaskPrompt): List<MCPToolSpec>

}



class WebAgent {

    + search_github(query: str): str

    + retrieve_readme(repo_url: str): str

}



class ScriptGenerator {

    + generate_code(spec: MCPToolSpec): str

    + generate_env_script(spec: MCPToolSpec): str

}



class CodeRunner {

    + execute(script: str): MCPExecutionResult

    + setup_environment(env_script: str): bool

}



class MCPRegistry {

    + register_tool(spec: MCPToolSpec, endpoint_url: str): void

    + list_tools(): List<MCPToolSpec>

    + call_tool(tool: str): object

}







' === Relations avec types + cardinalités ===



' Le Manager reçoit une tâche utilisateur

TaskPrompt --> "1" ManagerAgent : provides query



' Manager appelle le Brainstormer

ManagerAgent --> "1" MCPBrainstormer : calls



' Manager utilise WebAgent

ManagerAgent "1" <--> "1" WebAgent : queries/answers



' Brainstormer appelle ScriptGenerator et CodeRunner

MCPBrainstormer --> "1" ScriptGenerator : plans

MCPBrainstormer --> "1" CodeRunner : validates



' Manager consulte ou enregistre dans le Registry

ManagerAgent --> "1" MCPRegistry : checks/updates



' Manager construit un plan d'appel d'outils

ManagerAgent --> "0..*" ToolCall : creates



' Brainstormer retourne des MCPToolSpec

MCPBrainstormer --> "1..*" MCPToolSpec : returns



' ScriptGenerator utilise MCPToolSpec pour générer

ScriptGenerator --> "1" MCPToolSpec : consumes



' Registry enregistre des ToolSpecs

MCPRegistry --> "0..*" MCPToolSpec : stores



' CodeRunner renvoie un résultat d'exécution

CodeRunner --> "1" MCPExecutionResult : returns



' CodeRunner peut utiliser des outils enregistrés

CodeRunner --> "0..*" MCPRegistry : queries





@enduml

```
</details> 
</div>

# ALITA Research Functionality

This README explains how to use the comprehensive research capabilities of the ALITA ManagerAgent.

## Overview

ALITA can now perform deep, autonomous web research using the WebAgent's research functionality. This allows ALITA to gather information from multiple sources, analyze it, and synthesize a comprehensive report on any topic.

## Usage Methods

There are two ways to use the research functionality:

### 1. Direct Research Method

Call the `research` method directly on the ManagerAgent instance:

```python

from manager_agent2 import ManagerAgent

from llama_index.llms.anthropic import Anthropic



# Initialize the LLM and ManagerAgent

llm = Anthropic(model="claude-3-5-sonnet-20241022", api_key="your-api-key")

manager = ManagerAgent(llm=llm)



# Perform research directly

report = manager.research(

    query="What are the latest developments in quantum computing?",

    max_iterations=50,  # Optional: limit the number of research steps

    verbose=True        # Optional: show detailed progress

)



# The report variable now contains a comprehensive research report

print(report)

```

### 2. Tool-Based Research through ReActAgent

Let the ManagerAgent's internal ReActAgent decide when to use research:

```python

from manager_agent2 import ManagerAgent

from models import TaskPrompt

from llama_index.llms.anthropic import Anthropic



# Initialize the LLM and ManagerAgent

llm = Anthropic(model="claude-3-5-sonnet-20241022", api_key="your-api-key")

manager = ManagerAgent(llm=llm)



# Create a task prompt

task_prompt = TaskPrompt(text="I need a comprehensive report on recent developments in quantum computing.")



# Run the task through the agent

response = manager.run_task(task_prompt)



# The response will include the research report if the agent determined research was needed

print(response)

```

The agent will automatically detect when deep research is required based on keywords like "comprehensive," "thorough," "research," etc.

## Running the Test Script

A test script is provided to demonstrate both usage methods:

```bash

python test_research.py

```

Make sure to set your Anthropic API key in the environment or in a `.env` file before running the script.

## System Prompt Configuration

The ManagerAgent's system prompt has been updated to include guidance on when to use the research tool:

- For simple information needs: use 'web_search' for quick answers

- For complex research topics: use 'perform_web_research' for comprehensive autonomous research



## How Research Works



When ALITA performs research:



1. It first analyzes the research query to understand what information is needed

2. It uses web search to gather relevant sources

3. It visits and reads the content of each source

4. It downloads and analyzes relevant documents if needed

5. It evaluates the credibility and relevance of each source

6. It synthesizes the information into a comprehensive report

7. It includes citations and references to the sources used



This enables ALITA to provide high-quality, well-researched answers to complex questions.