@ai.ntellect/core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.FR.md ADDED
@@ -0,0 +1,303 @@
1
+ # AI.ntellect Core Framework
2
+
3
+ ## Table des matières
4
+
5
+ 1. [Composants principaux](#composants-principaux)
6
+ - [Orchestrator](#orchestrator)
7
+ - [Queue Manager](#queue-manager)
8
+ - [Synthétiseur](#synthétiseur)
9
+ - [Mémoire Cache (CAG)](#mémoire-cache-cag)
10
+ 2. [Création et gestion des actions](#création-et-gestion-des-actions)
11
+ 3. [Exécution du Workflow](#exécution-du-workflow)
12
+ 4. [Appels API et côté client](#appels-api-et-côté-client)
13
+ 5. [WIP (Work in Progress)](#wip-work-in-progress)
14
+
15
+ ---
16
+
17
+ ## 1. Composants principaux
18
+
19
+ Le système repose sur plusieurs composants clés qui assurent une gestion fluide et efficace des actions et du processus global de workflow.
20
+
21
+ ### Orchestrator
22
+
23
+ L'orchestrateur est responsable de la gestion de l'exécution des actions dans un workflow. Il analyse les besoins en fonction des entrées (comme le prompt utilisateur) et décide de l'ordre des actions à effectuer. Il interagit avec les autres composants comme la mémoire cache et les événements pour organiser l'exécution des tâches.
24
+
25
+ - **Rôle principal** : Organiser et diriger l'exécution des actions.
26
+ - **Interactions** :
27
+ - Demande des actions à exécuter.
28
+ - Utilise la mémoire cache pour éviter la redondance.
29
+ - Émet des événements pour informer les autres composants de l'état du workflow.
30
+
31
+ ### Queue Manager
32
+
33
+ Le gestionnaire de la file d'attente (Queue Manager) organise les actions à exécuter et gère leur ordre d'exécution. Il permet de maintenir un flux fluide d'exécution, en ajoutant les actions à la file d'attente selon les priorités définies par l'orchestrateur.
34
+
35
+ - **Rôle principal** : Gérer la file d'attente des actions et s'assurer qu'elles sont exécutées dans le bon ordre.
36
+ - **Fonctions principales** :
37
+ - Ajouter de nouvelles actions à la file d'attente.
38
+ - Gérer les priorités des actions.
39
+ - Assurer une exécution correcte et en temps voulu des actions.
40
+
41
+ ### Synthétiseur
42
+
43
+ Le synthétiseur est responsable de la génération des réponses et de l'analyse des actions en fonction des résultats obtenus dans le workflow. Il peut créer des résumés ou des réponses plus complexes à partir des résultats bruts obtenus lors de l'exécution des actions.
44
+
45
+ - **Rôle principal** : Transformer les résultats des actions en une sortie compréhensible et structurée.
46
+ - **Interactions** :
47
+ - Prend les résultats des actions exécutées.
48
+ - Crée des résumés ou des réponses adaptées.
49
+
50
+ ### Cache Augmented Generation (CAG)
51
+
52
+ Le CAG (Cache Augmented Generation) joue un rôle clé dans l'optimisation des workflows en stockant les résultats intermédiaires des actions effectuées. Cela permet de les réutiliser lors des workflows futurs, évitant ainsi des répétitions inutiles et améliorant l'efficacité globale du système.
53
+
54
+ Dans le contexte de notre projet, le CAG sert principalement de **mémoire procédurale**, un type spécifique de mémoire qui se concentre sur la réutilisation des résultats intermédiaires dans des contextes similaires. Contrairement à d'autres types de mémoire, comme la mémoire **épisodique** (qui conserve les expériences passées) ou la mémoire **sémantique** (qui stocke des connaissances générales), la mémoire procédurale est axée sur l'exécution de tâches répétitives ou d'actions précédemment effectuées.
55
+
56
+ #### Rôle principal :
57
+
58
+ - Sauvegarder les résultats des actions pour les réutiliser lors d'exécutions futures.
59
+
60
+ #### Fonctions principales :
61
+
62
+ - **Sauvegarde des résultats des actions** : Les résultats des actions sont stockés de manière à être facilement accessibles lorsque nécessaire.
63
+ - **Réutilisation des résultats** : Les résultats peuvent être fournis à la demande, ce qui évite des recalculs inutiles.
64
+ - **Optimisation des workflows** : En réutilisant des actions déjà exécutées, la mémoire cache optimise les workflows en éliminant les étapes redondantes.
65
+
66
+ La mémoire procédurale permet de renforcer l'efficacité du système en réduisant le temps de calcul et en garantissant que les processus répétitifs sont traités plus rapidement et plus efficacement.
67
+
68
+ ---
69
+
70
+ ## 2. Création et gestion des actions
71
+
72
+ Les actions sont des tâches spécifiques à réaliser dans le cadre du workflow. Elles peuvent être des interactions avec des APIs, des transactions blockchain, ou toute autre opération nécessaire.
73
+
74
+ Chaque action est définie comme un objet contenant un nom, une description, des paramètres, et une fonction d'exécution.
75
+
76
+ ### Exemple d'action
77
+
78
+ ```typescript
79
+ import { networkConfigs } from "@config/network";
80
+ import { parseEther } from "ethers";
81
+ import { z } from "zod";
82
+
83
+ export const prepareTransaction = {
84
+ name: "prepare-transaction",
85
+ description: "Préparer un transfert pour que l'utilisateur la signe.",
86
+ parameters: z.object({
87
+ walletAddress: z.string(),
88
+ amount: z.string().describe("Montant à envoyer"),
89
+ networkId: z
90
+ .string()
91
+ .describe("Réseau cible (par exemple, ethereum, arbitrum)"),
92
+ }),
93
+ execute: async ({
94
+ walletAddress,
95
+ amount,
96
+ network,
97
+ }: {
98
+ walletAddress: string;
99
+ amount: string;
100
+ networkId: string;
101
+ }) => {
102
+ try {
103
+ const networkConfig = networkConfigs[networkId];
104
+ if (!networkConfig) {
105
+ throw new Error(`Réseau ${network} non trouvé`);
106
+ }
107
+
108
+ return {
109
+ to: walletAddress,
110
+ value: parseEther(amount).toString(),
111
+ chain: {
112
+ id: networkConfig.id,
113
+ rpc: networkConfig.rpc,
114
+ },
115
+ type: "transfer",
116
+ };
117
+ } catch (error) {
118
+ return "Erreur lors de la préparation de la transaction";
119
+ }
120
+ },
121
+ };
122
+ ```
123
+
124
+ ### Comment définir une action :
125
+
126
+ 1. **Nom** : Identifiant unique pour l'action.
127
+ 2. **Description** : Brève description de ce que fait l'action.
128
+ 3. **Paramètres** : Les paramètres nécessaires pour l'exécution de l'action, validés par `zod`.
129
+ 4. **Exécution** : Fonction `execute` qui effectue l'action.
130
+
131
+ ---
132
+
133
+ ## 3. Exécution du workflow
134
+
135
+ Le workflow représente l'ensemble du processus d'exécution d'un certain nombre d'actions définies. Lorsqu'un utilisateur envoie un prompt, l'orchestrateur détermine les actions à exécuter en fonction des besoins.
136
+
137
+ ### Exemple de création d'un workflow :
138
+
139
+ ```typescript
140
+ const tools = [
141
+ prepareEvmTransaction,
142
+ getNews, // Exemple d'action pour obtenir les dernières nouvelles
143
+ ];
144
+
145
+ const orchestrator = new Orchestrator(tools);
146
+
147
+ const workflow = new Workflow(
148
+ { id: from }, // ID utilisateur ou contexte
149
+ { orchestrator, memoryCache, eventEmitter } // Composants nécessaires
150
+ );
151
+ ```
152
+
153
+ - **Orchestrator** : Gestion de l'ordre des actions.
154
+ - **MemoryCache** : Réutilisation des résultats précédents.
155
+ - **EventEmitter** : Suivi et notification de l'état du workflow.
156
+
157
+ ### Processus du workflow :
158
+
159
+ 1. Le prompt utilisateur est analysé.
160
+ 2. L'orchestrateur décide des actions nécessaires et leur ordre.
161
+ 3. Les actions sont exécutées.
162
+ 4. Les résultats sont synthétisés et renvoyés à l'utilisateur.
163
+
164
+ ---
165
+
166
+ ## 4. Appels API et côté client
167
+
168
+ ```typescript
169
+ fastify.post("/api/chat", {
170
+ preHandler: requireAuth,
171
+ handler: async (request, reply) => {
172
+ const { messages, from } = request.body;
173
+ const latestMessage = messages[messages.length - 1];
174
+
175
+ const workflow = new Workflow(
176
+ { id: from },
177
+ { orchestrator, memoryCache, eventEmitter }
178
+ );
179
+ return workflow.start(latestMessage.content, messages);
180
+ },
181
+ });
182
+ ```
183
+
184
+ ```typescript
185
+ export function Chat({ id, initialMessages }) {
186
+ const { messages, setMessages, handleSubmit, input, setInput } = useChat({
187
+ api: "/api/chat",
188
+ body: { id, from: activeAccount?.address },
189
+ });
190
+
191
+ return (
192
+ <div>
193
+ <div>{messages}</div>
194
+ <input
195
+ type="text"
196
+ value={input}
197
+ onChange={(e) => setInput(e.target.value)}
198
+ />
199
+ <button onClick={handleSubmit}>Envoyer</button>
200
+ </div>
201
+ );
202
+ }
203
+ ```
204
+
205
+ ---
206
+
207
+ ## 5. WIP (Work in Progress)
208
+
209
+ Voici les éléments actuellement en développement ou à améliorer :
210
+
211
+ - Voici la version corrigée avec les titres en minuscules et des checklists en français sous chaque section :
212
+
213
+ ---
214
+
215
+ ## Mémoire et RAG (Retrieval Augmented Generation)
216
+
217
+ **Objectif** : Créer un système de mémoire persistante qui conserve le contexte à travers les sessions et améliore l'apprentissage de l'agent au fil du temps en intégrant des sources de connaissances externes.
218
+
219
+ **Intérêt** :
220
+
221
+ - La mémoire à long terme permet à l'agent de se souvenir des interactions passées et d'accéder à des connaissances externes pertinentes.
222
+ - Des réponses plus contextuelles et personnalisées.
223
+ - Amélioration de l'efficacité et de la précision des interactions.
224
+ - Réduction des réponses incorrectes ou obsolètes.
225
+ - Permet un apprentissage et une adaptation continus.
226
+
227
+ **Étapes à mettre en place** :
228
+
229
+ **Infrastructure de mémoire** :
230
+
231
+ - [x] Intégration d'une base de données vectorielle.
232
+ - [x] Système de récupération basé sur la pertinence.
233
+ - [ ] Consolidation et nettoyage automatique de la mémoire.
234
+ - [ ] Hiérarchie de la mémoire (working/long-term memory).
235
+
236
+ **Intégration des connaissances** :
237
+
238
+ - [ ] Pipeline de traitement des documents.
239
+ - [ ] Intégration de la base de connaissances.
240
+ - [ ] Système de vérification des sources.
241
+ - [ ] Récupération contextuelle.
242
+ - [ ] Capacités de recherche sémantique.
243
+
244
+ **Types de mémoire** :
245
+
246
+ - [ ] Épisodique : Interactions et expériences passées.
247
+ - [ ] Sémantique : Connaissances et faits externes.
248
+ - [x] Procédurale : Modèles et workflows appris.
249
+
250
+ **Statut** : Implémentation de base avec Redis terminée, intégration de la base de données vectorielle et pipeline RAG en cours. Conception de l'architecture finalisée, avec une implémentation initiale lancée.
251
+
252
+ ---
253
+
254
+ ## Collaboration multi-agent
255
+
256
+ **Objectif** : Permettre à plusieurs agents de collaborer sur des tâches complexes avec spécialisation et coordination.
257
+
258
+ **Intérêt** : La collaboration entre agents permet de diviser les tâches complexes en sous-tâches spécialisées, améliorant ainsi l'efficacité et la qualité des résultats. Elle permet également une meilleure gestion des ressources et une adaptation plus rapide aux changements.
259
+
260
+ **Étapes à réaliser** :
261
+
262
+ - [ ] Mise en place d'un cadre de délégation des tâches.
263
+ - [ ] Gestion partagée du contexte.
264
+ - [ ] Établissement de protocoles de résolution des conflits.
265
+
266
+ **Statut** : Phase de recherche, planification architecturale en cours.
267
+
268
+ ---
269
+
270
+ ## Gestion des interactions complexes on-chain
271
+
272
+ **Objectif** : Créer un modèle pour la reconnaissance des interactions on-chain et la création de workflows pour des interactions complexes.
273
+
274
+ **Intérêt** : Cette fonctionnalité permet à l'agent de comprendre et d'interagir avec des contrats intelligents de manière plus intuitive, facilitant ainsi l'exécution d'actions complexes sur la blockchain. Cela améliore l'accessibilité et l'efficacité des interactions avec les contrats intelligents.
275
+
276
+ **Étapes à réaliser** :
277
+
278
+ - [ ] Extraction et traitement des ABI des contrats pertinents.
279
+ - [ ] Filtrage des fonctions pertinentes.
280
+ - [ ] Génération de requêtes hypothétiques en langage naturel.
281
+ - [ ] Conversion des requêtes en embeddings vectoriels.
282
+ - [ ] Stockage des embeddings et des requêtes associées.
283
+ - [ ] Recherche de similarité basée sur le cosine.
284
+ - [ ] Classement des résultats en fonction de la pertinence.
285
+
286
+ **Statut** : Étude en cours pour déterminer la meilleure approche et les technologies à utiliser.
287
+
288
+ ---
289
+
290
+ ## Implémentation du Lit Protocol
291
+
292
+ **Objectif** : Ajouter la possibilité d'exécuter des actions Lit, permettant de déployer et d'exécuter des calculs décentralisés et sécurisés sur le réseau Lit.
293
+
294
+ **Intérêt** : L'intégration du Lit Protocol permet d'exécuter des actions Lit de manière décentralisée, en utilisant des clés cryptographiques pour valider les opérations. Ces actions peuvent être utilisées pour exécuter des scripts JavaScript dans un environnement décentralisé, ce qui permet une grande transparence, car toutes les interactions sont enregistrées sur la blockchain. L'un des principaux avantages réside dans l'automatisation et la sécurité des processus tout en préservant la confidentialité des utilisateurs, ce qui renforce la confiance dans les interactions on-chain.
295
+
296
+ **Étapes à réaliser** :
297
+
298
+ - [x] Étudier la documentation du Lit Protocol, en particulier la section sur les actions Lit et leur mise en œuvre.
299
+ - [ ] Intégrer le protocole dans l'architecture existante pour permettre l'exécution des actions Lit.
300
+ - [ ] Développer des modules pour l'exécution des actions Lit, incluant la gestion des signatures et l'exécution des scripts dans un environnement sécurisé.
301
+ - [ ] Tester l'intégration, la sécurité et la transparence des actions Lit pour garantir leur bon fonctionnement.
302
+
303
+ **Statut** : En cours d'étude pour déterminer la faisabilité et les implications techniques, notamment en ce qui concerne l'intégration de la décentralisation dans le système existant.
package/README.md ADDED
@@ -0,0 +1,299 @@
1
+ # AI.ntellect Core Framework
2
+
3
+ ## Table of Contents
4
+
5
+ 1. [Main Components](#main-components)
6
+ - [Orchestrator](#orchestrator)
7
+ - [Queue Manager](#queue-manager)
8
+ - [Synthesizer](#synthesizer)
9
+ - [Cache Memory (CAG)](#cache-memory-cag)
10
+ 2. [Action Creation and Management](#action-creation-and-management)
11
+ 3. [Workflow Execution](#workflow-execution)
12
+ 4. [API Calls and Client Side](#api-calls-and-client-side)
13
+ 5. [WIP (Work in Progress)](#wip-work-in-progress)
14
+
15
+ ---
16
+
17
+ ## 1. Main Components
18
+
19
+ The system relies on several key components that ensure smooth and efficient management of actions and the overall workflow process.
20
+
21
+ ### Orchestrator
22
+
23
+ The orchestrator is responsible for managing the execution of actions within a workflow. It analyzes the needs based on inputs (like the user prompt) and decides the order of actions to be performed. It interacts with other components like the cache memory and events to organize the execution of tasks.
24
+
25
+ - **Main Role**: Organize and direct the execution of actions.
26
+ - **Interactions**:
27
+ - Requests actions to be executed.
28
+ - Uses cache memory to avoid redundancy.
29
+ - Emits events to inform other components about the state of the workflow.
30
+
31
+ ### Queue Manager
32
+
33
+ The queue manager organizes the actions to be executed and manages their execution order. It ensures a smooth flow of execution by adding actions to the queue based on the priorities defined by the orchestrator.
34
+
35
+ - **Main Role**: Manage the action queue and ensure actions are executed in the correct order.
36
+ - **Main Functions**:
37
+ - Add new actions to the queue.
38
+ - Manage action priorities.
39
+ - Ensure proper and timely execution of actions.
40
+
41
+ ### Synthesizer
42
+
43
+ The synthesizer is responsible for generating responses and analyzing actions based on the results obtained in the workflow. It can create summaries or more complex responses from the raw results obtained during the execution of actions.
44
+
45
+ - **Main Role**: Transform the results of actions into a comprehensible and structured output.
46
+ - **Interactions**:
47
+ - Takes the results of executed actions.
48
+ - Creates summaries or tailored responses.
49
+
50
+ ### Cache Augmented Generation (CAG)
51
+
52
+ CAG plays a crucial role in optimizing workflows by storing intermediate results from executed actions. This allows them to be reused in future workflows, avoiding unnecessary repetitions and improving the overall system efficiency.
53
+
54
+ In the context of our project, CAG primarily serves as **procedural memory**, a specific type of memory focused on reusing intermediate results in similar contexts. Unlike other types of memory, such as **episodic** (which stores past experiences) or **semantic** (which stores general knowledge), procedural memory is centered on performing repetitive tasks or previously executed actions.
55
+
56
+ #### Main Role:
57
+
58
+ - Save the results of actions for reuse in future executions.
59
+
60
+ #### Main Functions:
61
+
62
+ - **Store action results**: Action results are stored in a way that they can be easily accessed when needed.
63
+ - **Reuse results**: Results can be provided on demand, avoiding unnecessary recalculations.
64
+ - **Optimize workflows**: By reusing previously executed actions, cache memory optimizes workflows by eliminating redundant steps.
65
+
66
+ Procedural memory enhances the system's efficiency by reducing computation time and ensuring that repetitive processes are handled more quickly and effectively.
67
+
68
+ ---
69
+
70
+ ## 2. Action Creation and Management
71
+
72
+ Actions are specific tasks to be performed within a workflow. They can involve interactions with APIs, blockchain transactions, or any other necessary operations.
73
+
74
+ Each action is defined as an object containing a name, description, parameters, and an execution function.
75
+
76
+ ### Example of an Action
77
+
78
+ ```typescript
79
+ import { networkConfigs } from "@config/network";
80
+ import { parseEther } from "ethers";
81
+ import { z } from "zod";
82
+
83
+ export const prepareTransaction = {
84
+ name: "prepare-transaction",
85
+ description: "Prepare a transfer for the user to sign.",
86
+ parameters: z.object({
87
+ walletAddress: z.string(),
88
+ amount: z.string().describe("Amount to send"),
89
+ networkId: z.string().describe("Target network (e.g., ethereum, arbitrum)"),
90
+ }),
91
+ execute: async ({
92
+ walletAddress,
93
+ amount,
94
+ network,
95
+ }: {
96
+ walletAddress: string;
97
+ amount: string;
98
+ networkId: string;
99
+ }) => {
100
+ try {
101
+ const networkConfig = networkConfigs[networkId];
102
+ if (!networkConfig) {
103
+ throw new Error(`Network ${network} not found`);
104
+ }
105
+
106
+ return {
107
+ to: walletAddress,
108
+ value: parseEther(amount).toString(),
109
+ chain: {
110
+ id: networkConfig.id,
111
+ rpc: networkConfig.rpc,
112
+ },
113
+ type: "transfer",
114
+ };
115
+ } catch (error) {
116
+ return "Error preparing the transaction";
117
+ }
118
+ },
119
+ };
120
+ ```
121
+
122
+ ### How to Define an Action:
123
+
124
+ 1. **Name**: Unique identifier for the action.
125
+ 2. **Description**: Brief description of what the action does.
126
+ 3. **Parameters**: Parameters required to execute the action, validated by `zod`.
127
+ 4. **Execution**: `execute` function that performs the action.
128
+
129
+ ---
130
+
131
+ ## 3. Workflow Execution
132
+
133
+ The workflow represents the entire process of executing a number of defined actions. When a user sends a prompt, the orchestrator determines which actions to perform based on the needs.
134
+
135
+ ### Example of Creating a Workflow:
136
+
137
+ ```typescript
138
+ const tools = [
139
+ prepareEvmTransaction,
140
+ getNews, // Example action to fetch the latest news
141
+ ];
142
+
143
+ const orchestrator = new Orchestrator(tools);
144
+
145
+ const workflow = new Workflow(
146
+ { id: from }, // User ID or context
147
+ { orchestrator, memoryCache, eventEmitter } // Required components
148
+ );
149
+ ```
150
+
151
+ - **Orchestrator**: Manages the order of actions.
152
+ - **MemoryCache**: Reuses previous results.
153
+ - **EventEmitter**: Tracks and notifies the state of the workflow.
154
+
155
+ ### Workflow Process:
156
+
157
+ 1. The user’s prompt is analyzed.
158
+ 2. The orchestrator decides which actions are needed and their order.
159
+ 3. Actions are executed.
160
+ 4. Results are synthesized and returned to the user.
161
+
162
+ ---
163
+
164
+ ## 4. API Calls and Client Side
165
+
166
+ ```typescript
167
+ fastify.post("/api/chat", {
168
+ preHandler: requireAuth,
169
+ handler: async (request, reply) => {
170
+ const { messages, from } = request.body;
171
+ const latestMessage = messages[messages.length - 1];
172
+
173
+ const workflow = new Workflow(
174
+ { id: from },
175
+ { orchestrator, memoryCache, eventEmitter }
176
+ );
177
+ return workflow.start(latestMessage.content, messages);
178
+ },
179
+ });
180
+ ```
181
+
182
+ ```typescript
183
+ export function Chat({ id, initialMessages }) {
184
+ const { messages, setMessages, handleSubmit, input, setInput } = useChat({
185
+ api: "/api/chat",
186
+ body: { id, from: activeAccount?.address },
187
+ });
188
+
189
+ return (
190
+ <div>
191
+ <div>{messages}</div>
192
+ <input
193
+ type="text"
194
+ value={input}
195
+ onChange={(e) => setInput(e.target.value)}
196
+ />
197
+ <button onClick={handleSubmit}>Send</button>
198
+ </div>
199
+ );
200
+ }
201
+ ```
202
+
203
+ ---
204
+
205
+ ## 5. WIP (Work in Progress)
206
+
207
+ Here are the elements currently in development or improvement:
208
+
209
+ ---
210
+
211
+ ## Memory and RAG (Retrieval Augmented Generation)
212
+
213
+ **Objective**: Create a persistent memory system that retains context across sessions and improves the agent’s learning over time by integrating external knowledge sources.
214
+
215
+ **Interest**:
216
+
217
+ - Long-term memory allows the agent to remember past interactions and access relevant external knowledge.
218
+ - More contextual and personalized responses.
219
+ - Improved efficiency and accuracy of interactions.
220
+ - Reduction of incorrect or outdated responses.
221
+ - Enables continuous learning and adaptation.
222
+
223
+ **Steps to Implement**:
224
+
225
+ **Memory Infrastructure**:
226
+
227
+ - [x] Integration of a vector database.
228
+ - [x] Relevance-based retrieval system.
229
+ - [ ] Automatic memory consolidation and cleaning.
230
+ - [ ] Memory hierarchy (working/long-term memory).
231
+
232
+ **Knowledge Integration**:
233
+
234
+ - [ ] Document processing pipeline.
235
+ - [ ] Integration of knowledge base.
236
+ - [ ] Source verification system.
237
+ - [ ] Contextual retrieval.
238
+ - [ ] Semantic search capabilities.
239
+
240
+ **Memory Types**:
241
+
242
+ - [ ] Episodic: Past interactions and experiences.
243
+ - [ ] Semantic: External knowledge and facts.
244
+ - [x] Procedural: Learned models and workflows.
245
+
246
+ **Status**: Basic implementation with Redis complete, vector database integration and RAG pipeline in progress. Architecture design finalized, with initial implementation launched.
247
+
248
+ ---
249
+
250
+ ## Multi-Agent Collaboration
251
+
252
+ **Objective**: Enable multiple agents to collaborate on complex tasks with specialization and coordination.
253
+
254
+ **Interest**: Collaboration between agents allows breaking down complex tasks into specialized subtasks, enhancing the efficiency and quality of results. It also enables better resource management and faster adaptation to changes.
255
+
256
+ **Steps to Implement**:
257
+
258
+ - [ ] Task delegation framework.
259
+ - [ ] Shared context management.
260
+ - [ ] Conflict resolution protocols.
261
+
262
+ **Status**: Research phase, architectural planning in progress.
263
+
264
+ ---
265
+
266
+ ## Complex On-Chain Interactions Management
267
+
268
+ **Objective**: Create a model for recognizing on-chain interactions and creating workflows for complex interactions.
269
+
270
+ **Interest**: This feature allows the agent to understand and interact with smart contracts more intuitively, facilitating the execution of complex actions on the blockchain. It improves accessibility and efficiency in interacting with smart contracts.
271
+
272
+ **Steps to Implement**:
273
+
274
+ - [ ] Extraction and processing of relevant contract ABIs.
275
+ - [ ] Filtering of relevant functions.
276
+ - [ ] Generation of hypothetical queries in natural language.
277
+ - [ ] Conversion of queries into vector embeddings.
278
+ - [ ] Storing embeddings and associated queries.
279
+ - [ ] Similarity search based on cosine.
280
+ - [ ] Ranking results based on relevance.
281
+
282
+ **Status**: Ongoing study to determine the best approach and technologies to use.
283
+
284
+ ---
285
+
286
+ ## Lit Protocol Implementation
287
+
288
+ **Objective**: Add the ability to execute Lit actions, enabling decentralized and secure calculations on the Lit network.
289
+
290
+ **Interest**: Integrating the Lit Protocol allows executing Lit actions in a decentralized manner, using cryptographic keys to validate operations. These actions can be used to run JavaScript scripts in a decentralized environment, offering transparency as all interactions are recorded on the blockchain. The main benefit lies in automation and security while preserving user privacy, which enhances trust in on-chain interactions.
291
+
292
+ **Steps to Implement**:
293
+
294
+ - [x] Study Lit Protocol documentation, especially the section on Lit actions and their implementation.
295
+ - [ ] Integrate the protocol into the existing architecture to allow execution of Lit actions.
296
+ - [ ] Develop modules for executing Lit actions, including signature management and secure script execution.
297
+ - [ ] Test the integration, security, and transparency of Lit actions to ensure they function properly.
298
+
299
+ **Status**: Under study to determine feasibility and technical implications, particularly regarding integrating decentralization into the existing system.
@@ -0,0 +1,35 @@
1
+ import { z } from "zod";
2
+ import { ActionSchema } from "../../types";
3
+
4
+ export const orchestratorContext = {
5
+ role: "You are the gateway agent, you are the first agent to be called. You are the one who will decide if the user request is clear and if it's possible to achieve the goal.",
6
+ guidelines: {
7
+ important: [
8
+ "IMPORTANT: If there is no action to do, you must answer in the 'answer' field.",
9
+ "IMPORTANT: If there are actions to do, you must explain why you are doing them in the 'answer' field.",
10
+ "IMPORTANT: If user ask for a analysis of the market or a cryptocurrency, use the maximum of useful tools to have a global view of the market (fundamental analysis vs technical analysis).",
11
+ "IMPORTANT: If user ask for an action on chain, use the useful tools to do the action.",
12
+ "IMPORTANT: You allow to provide an analysis without providing any financial advice.",
13
+ "IMPORTANT: ALWAYS use the same language as user request. (If it's English, use English, if it's French, use French, etc.)",
14
+ ],
15
+ },
16
+ compose: (tools: ActionSchema[]) => {
17
+ return `
18
+ ${orchestratorContext.role}
19
+
20
+ ${orchestratorContext.guidelines.important.join("\n")}
21
+
22
+ If this is an action, extract the parameters required to execute the action.
23
+ IMPORTANT: If some parameters are not clear or missing, YOU MUST ask the user for them.
24
+
25
+ The actions are: ${tools.map((action) => {
26
+ const parameters = action.parameters as z.ZodObject<any>;
27
+ const schemaShape = Object.keys(parameters._def.shape()).join(
28
+ ", "
29
+ );
30
+ const actionString = `Name: ${action.name}, Description: ${action.description}, Arguments: { ${schemaShape} }`;
31
+ return actionString;
32
+ })}
33
+ `;
34
+ },
35
+ };
@@ -0,0 +1,33 @@
1
+ import { openai } from "@ai-sdk/openai";
2
+ import { generateObject } from "ai";
3
+ import { z } from "zod";
4
+ import { ActionSchema, Agent } from "../../types";
5
+ import { orchestratorContext } from "./context";
6
+
7
+ export class Orchestrator implements Agent {
8
+ private readonly model = openai("gpt-4o-mini");
9
+ public tools: ActionSchema[];
10
+
11
+ constructor(tools: ActionSchema[]) {
12
+ this.tools = tools;
13
+ }
14
+
15
+ async process(prompt: string): Promise<any> {
16
+ const response = await generateObject({
17
+ model: this.model,
18
+ schema: z.object({
19
+ actions: z.array(
20
+ z.object({
21
+ name: z.string(),
22
+ parameters: z.record(z.string(), z.any()),
23
+ })
24
+ ),
25
+ answer: z.string(),
26
+ }),
27
+ prompt: prompt,
28
+ system: orchestratorContext.compose(this.tools),
29
+ });
30
+
31
+ return response.object;
32
+ }
33
+ }