File size: 8,214 Bytes
2eef9ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Architecture Overview

## System Design

The Multi-Agent System uses LangGraph to orchestrate a collaborative workflow of specialized AI agents that work together to decompose and execute complex tasks.

```
User Request
    β”‚
    β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    LangGraph Workflow                   β”‚
β”‚                                                         β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚    Memory    │───▢│   Planner    │─▢│  Executor β”‚   β”‚
β”‚  β”‚  Retrieval   β”‚    β”‚    Agent     β”‚  β”‚   Agent    β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                           β–²                   β”‚         β”‚
β”‚                           β”‚ replan            β”‚ loop    β”‚
β”‚                      β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”        β”Œβ”€β”€β”€β”€β”€β”΄β”€β”€β”      β”‚
β”‚                      β”‚  Critic │◀───────Executor β”‚     β”‚   
β”‚                      β”‚  Agent  β”‚        β”‚ Tools  β”‚     β”‚
β”‚                      β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜        β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β”‚
β”‚                           β”‚ approve                    β”‚
β”‚                           β–Ό                            β”‚
β”‚                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                    β”‚
β”‚                    β”‚    Memory    β”‚                    β”‚
β”‚                    β”‚    Store     β”‚                    β”‚
β”‚                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
    β”‚
    β–Ό
  Response
```

## Components

### 1. Agents

#### Memory Agent
- **Purpose**: Retrieve relevant past experiences
- **Model**: gpt-4o-mini
- **Pattern**: Two-tier retrieval (Redis hot cache + SQLite cold storage)
- **Output**: List of relevant past learnings

#### Planner Agent
- **Purpose**: Decompose tasks into executable steps
- **Model**: gpt-4
- **Pattern**: Function calling with structured JSON output
- **Output**: Ordered plan with dependencies

#### Executor Agent
- **Purpose**: Execute individual steps with available tools
- **Model**: gpt-4
- **Pattern**: Tool use with retry logic and backoff
- **Output**: Step results with traceability

#### Critic Agent
- **Purpose**: Evaluate task completion quality
- **Model**: gpt-4
- **Pattern**: Separate evaluator prevents self-bias
- **Output**: Approval or rejection with feedback

#### Memory Store
- **Purpose**: Persist learnings for future tasks
- **Model**: gpt-4o-mini
- **Pattern**: Extract semantic and episodic knowledge
- **Storage**: Hybrid Redis + SQLite

### 2. Tools

Available tools for the Executor agent:

| Tool | Type | Description | Rate Limited |
|------|------|-------------|--------------|
| `web_search` | External | DuckDuckGo search | Yes |
| `fetch_url` | External | Read URL content | Yes |
| `calculate` | Local | Safe math evaluation | No |
| `run_python` | Sandboxed | Execute Python code | Yes |

### 3. State Management

```python
# Task state throughout the workflow
{
    "task_id": "uuid",
    "task": "original task",
    "status": TaskStatus.PENDING,
    "plan": [...],
    "steps_completed": 0,
    "current_step": None,
    "result": None,
    "errors": [],
    "events": [],
    "total_tokens": 0,
    "memory_context": []
}
```

### 4. Database Schema

#### PostgreSQL (Production)

```sql
-- Tasks table
CREATE TABLE tasks (
    id UUID PRIMARY KEY,
    task TEXT,
    status VARCHAR(50),
    result JSONB,
    created_at TIMESTAMP,
    updated_at TIMESTAMP,
    deleted_at TIMESTAMP
);

-- Memory entries
CREATE TABLE memories (
    id UUID PRIMARY KEY,
    task_id UUID REFERENCES tasks(id),
    content TEXT,
    embedding VECTOR(1536),  -- OpenAI embeddings
    memory_type VARCHAR(50),  -- episodic, semantic
    created_at TIMESTAMP
);
```

#### Redis (Caching)

```
Key patterns:
- task:{task_id}:state     β†’ Current state
- task:{task_id}:status    β†’ Quick status lookup
- memory:{task_type}       β†’ Hot memory cache
- queue:pending            β†’ Task queue
```

### 5. API Architecture

```
FastAPI Application
β”œβ”€β”€ /health          β†’ Health checks
β”œβ”€β”€ /tasks           β†’ Task management
β”‚   β”œβ”€β”€ POST /       β†’ Create task
β”‚   β”œβ”€β”€ GET /{id}    β†’ Get status
β”‚   └── DELETE /{id} β†’ Cancel
β”œβ”€β”€ /workflows       β†’ Workflow execution
β”‚   β”œβ”€β”€ POST /execute β†’ Run workflow
β”‚   └── GET /{id}/status β†’ Status
└── /docs            β†’ Interactive docs
```

## Data Flow

### Task Execution Flow

1. **Input**: User submits task via API
2. **Memory**: Retrieve relevant past experience
3. **Planning**: Decompose into steps
4. **Execution Loop**:
   - Select next step
   - Choose tool/approach
   - Execute with retry logic
   - Store intermediate result
   - Check completion
5. **Evaluation**: Critic validates solution
6. **Feedback**:
   - If approved β†’ Store learnings
   - If rejected β†’ Replan
7. **Output**: Return results to user

### State Transitions

```
PENDING
  β”‚
  β”œβ”€β–Ά PLANNING (Planner agent)
  β”‚     β”‚
  β”‚     β”œβ”€β–Ά EXECUTING (Executor agent)
  β”‚     β”‚     β”‚
  β”‚     β”‚     β”œβ”€β–Ά EVALUATING (Critic agent)
  β”‚     β”‚     β”‚     β”‚
  β”‚     β”‚     β”‚     β”œβ”€β–Ά REPLANNING (loop back)
  β”‚     β”‚     β”‚     └─▢ STORING (Memory agent)
  β”‚     β”‚     β”‚           β”‚
  β”‚     β”‚     β”‚           └─▢ COMPLETED
  β”‚     β”‚     β”‚
  β”‚     β”‚     └─▢ FAILED
  β”‚     β”‚
  β”‚     └─▢ FAILED
  β”‚
  └─▢ FAILED
```

## Performance Considerations

### Latency

- **First response**: 2-5 seconds (planning phase)
- **Per step**: 1-3 seconds (execution)
- **Evaluation**: 1-2 seconds
- **Total typical task**: 30-120 seconds

### Memory Usage

- Base: ~200MB
- Per concurrent task: ~50MB
- Redis memory: ~100MB default
- Database: Depends on data volume

### Scaling Limits

- **Requests/second**: Limited by LLM API rate limits
- **Concurrent tasks**: ~10-100 (depends on compute)
- **Database**: 1M+ tasks (PostgreSQL)
- **Cache**: Millions of memories (Redis)

## Error Handling

### Retry Strategy

```python
# Exponential backoff with jitter
max_retries = 3
base_delay = 1.0
max_delay = 32.0

delay = min(base_delay * (2 ** attempt) + random(0, 1), max_delay)
```

### Fallback Strategies

1. **Tool failure**: Try alternative tool or manual approach
2. **Step failure**: Skip or add to error log
3. **Planning failure**: Use simpler, direct approach
4. **Critic rejection**: Auto-replan or escalate

## Security Architecture

### API Security

- API Key authentication (future)
- Rate limiting per user
- Request validation (Pydantic)
- CORS enabled for frontend only

### Data Security

- Environment variables for secrets
- Encrypted database connections
- No sensitive data in logs
- Memory isolation between tasks

## Monitoring & Observability

### Metrics

- `task_total` - Total tasks processed
- `task_duration_seconds` - Execution time
- `agent_calls_total` - Agent invocations
- `api_requests_total` - API endpoints hit
- `memory_hit_ratio` - Cache effectiveness

### Logs

- Structured JSON logging
- Trace IDs for request tracking
- Agent decision tracking
- Tool execution logs

### Health Checks

- Database connectivity
- Redis connectivity
- LLM API availability
- API responsiveness

## Deployment Patterns

### Development
- SQLite local storage
- In-memory cache
- Console logging
- Hot reload

### Production
- PostgreSQL database
- Redis cache cluster
- Centralized logging (ELK/Datadog)
- Load balancer
- Auto-scaling