A containerized, production-grade multi-agent system with dynamic orchestration, self-improving evaluation loop, adversarial robustness testing, and real-time SSE streaming.
# 1. Clone and enter the directory
cd multi_agent_system
# 2. Create .env with your OpenAI API key
echo "OPENAI_API_KEY=sk-..." > .env
# 3. Start everything
docker compose up --buildServices started:
| Service | URL | Description |
|---|---|---|
| API | http://localhost:8000 | FastAPI application |
| API Docs | http://localhost:8000/docs | Interactive Swagger UI |
| Log UI | http://localhost:8001 | RedisInsight log query interface |
| PostgreSQL | localhost:5432 | Database |
| Redis | localhost:6379 | Celery broker + SSE pub/sub |
Optional environment variables (add to .env):
BRAVE_SEARCH_API_KEY=... # Real web search via Brave API
SERPER_API_KEY=... # Real web search via Serper (Google)
LLM_MODEL=gpt-4o # Override the LLM model
POSTGRES_USER=user
POSTGRES_PASSWORD=password
POSTGRES_DB=multiagent
If no search API key is provided, the system uses a deterministic stub that generates plausible-looking results for testing purposes.
┌─────────────────────────────────────────────────────────────────────┐
│ CLIENT │
│ POST /query ──────────────────────────────────────────────────┐ │
│ GET /query/{id}/stream ◄── SSE events (real-time) │ │
└─────────────────────────────────────────────────────────────────┼───┘
│
┌──────────────────────────────────────────────────────────────────▼───┐
│ FastAPI (api/) │
│ /query /traces /evals/latest /prompts/review /evals/targeted │
└──────────────────────────────────────────────────────────────────┬───┘
│ enqueue │ SSE subscribe
▼ ▼
┌───────────────────────────┐ ┌──────────────────────────┐
│ Celery Worker (worker/) │ │ Redis pub/sub │
│ process_agent_job() │──publish─► job:{id}:events │
└───────────────┬───────────┘ └──────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────────────┐
│ Orchestrator (core/orchestrator.py) │
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ SharedContext (core/context.py) │ │
│ │ job_id, query, history, sub_tasks, retrieved_chunks, │ │
│ │ claim_scores, final_answer, provenance_map, │ │
│ │ tool_call_logs, routing_log, policy_violations │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ LLM routing decision ──► next_agent + justification │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────┐ ┌──────────┐ │
│ │Decomposition │ │ Retrieval │ │ Critique │ │Synthesis │ │
│ │ Agent │ │ Agent │ │ Agent │ │ Agent │ │
│ │ │ │ │ │ │ │ │ │
│ │ Breaks query │ │ Multi-hop │ │ Per-claim│ │ Merges │ │
│ │ into DAG of │ │ retrieval │ │ scoring │ │ outputs, │ │
│ │ typed tasks │ │ (2+ hops) │ │ + span │ │ resolves │ │
│ │ with deps │ │ with chunk │ │ flagging │ │ contrad. │ │
│ │ │ │ citations │ │ │ │ provenance│ │
│ └──────────────┘ └──────┬───────┘ └──────────┘ └──────────┘ │
└──────────────────────────┼────────────────────────────────────────┘
│
┌─────────────▼──────────────┐
│ Tool Registry │
│ (tools/registry.py) │
│ │
│ web_search ──► Brave/ │
│ Serper/ │
│ stub │
│ execute_python ──► sandbox │
│ db_lookup ──► Postgres │
│ self_reflect ──► LLM │
└─────────────────────────────┘
│
┌─────────────▼──────────────┐
│ PostgreSQL │
│ jobs, execution_traces, │
│ eval_runs, proposed_prompts│
│ prompt_performance_deltas │
└─────────────────────────────┘
│
┌─────────────▼──────────────┐
│ Eval Harness (eval/) │
│ 15 test cases: │
│ 5 baseline + 5 ambiguous │
│ + 5 adversarial │
│ 6 scoring dimensions │
└─────────────────────────────┘
│
┌─────────────▼──────────────┐
│ Meta-Agent (meta/) │
│ Reads failures → proposes │
│ prompt rewrite → human │
│ approves → re-eval → delta │
└─────────────────────────────┘
Decision boundary: Routes between agents only. Never produces content directly.
Uses structured LLM reasoning to decide the next agent at each turn. Every routing decision is logged with justification, turn number, and context budget status. Routing follows these rules:
- Simple factual: retrieval → critique → synthesis → finish
- Complex/ambiguous: decomposition → retrieval → critique → synthesis → finish
- Never loops back to an already-run agent
- Stops when synthesis has produced a final answer
Decision boundary: Breaks queries into sub-tasks. Does not solve them.
Produces a DAG of typed sub-tasks (factual, analytical, code, comparison). Each task declares its dependencies — dependent tasks must not execute until their prerequisites resolve. For simple queries, produces 1-2 tasks.
Decision boundary: Fetches and grounds information. Does not synthesize.
Performs exactly two retrieval hops:
- First hop: searches based on the original query
- Second hop: LLM determines what follow-up query fills the gaps from hop 1
Every retrieved chunk is tagged with its hop number and relevance score. The agent cites which chunk contributed to which part of the answer.
Decision boundary: Evaluates claims. Does not rewrite content.
Reviews all agent outputs and assigns per-claim confidence scores (0.0–1.0). Flags specific spans of text (not whole outputs) with reasons. Claims with confidence < 0.6 are always flagged.
Decision boundary: Merges and resolves. Produces the final answer.
Takes all agent outputs, critique scores, and retrieved evidence. Resolves contradictions flagged by the critique agent internally — never surfaces them to the user. Produces a provenance map linking each sentence to its source agent and source chunk.
All tools have defined failure contracts:
| Tool | Timeout | Empty | Malformed |
|---|---|---|---|
web_search |
raises TimeoutError |
{"results": [], "status": "empty"} |
raises ValueError |
execute_python |
raises TimeoutError (5s) |
exit_code=0, stdout="" |
raises ValueError |
db_lookup |
DB timeout → error dict | {"rows": [], "status": "empty"} |
raises ValueError |
self_reflect |
LLM timeout → error dict | {"contradictions": []} |
raises ValueError |
Each tool call is logged with: tool name, attempt number, input kwargs, output, latency_ms, status, accepted (bool), and rejection reason if rejected.
Agents can retry a tool up to 2 times. Each retry is logged separately.
The ContextWindowManager tracks token consumption per agent per turn:
| Agent | Budget |
|---|---|
| orchestrator | 4,000 tokens |
| decomposition | 2,000 tokens |
| retrieval | 6,000 tokens |
| critique | 4,000 tokens |
| synthesis | 6,000 tokens |
Agents call check_budget() before adding to context. If an agent exceeds its
budget, a PolicyViolation is logged — the overflow is never silently truncated.
History compression is triggered automatically when budget drops below 20%.
15 test cases across 3 categories:
Baseline (5): Capital of France, water formula, Hamlet author, 17×23, CPython language.
Ambiguous (5): "Tell me about the bank", "How do I fix the issue?", "Compare the two approaches", "What happened recently?", "Explain the process step by step."
Adversarial (5):
- Prompt injection: attempts to override agent instructions
- Wrong premise (flat Earth): factually confident but incorrect
- Jailbreak (DAN): attempts to bypass safety
- Wrong premise (Python 1850): incorrect historical claim
- Contradiction forcing: demands two contradictory answers
Scoring dimensions:
| Dimension | Weight | What it measures |
|---|---|---|
| answer_correctness | 30% | Factual accuracy, premise correction, injection resistance |
| citation_accuracy | 15% | Chunks cited and linked to answer parts |
| contradiction_resolution | 15% | Flagged contradictions resolved in final answer |
| tool_selection_efficiency | 15% | Unnecessary tool calls penalized |
| context_budget_compliance | 15% | Budget overflow violations |
| critique_agreement_rate | 10% | Critique agreement with final output |
Every eval run stores: exact prompts per agent, exact tool calls, exact outputs, all scores with justifications, and timestamps. Re-running on the same inputs produces a diff-able output.
After each eval run, the meta-agent:
- Reads all failure cases (score < 0.6)
- Identifies the worst-performing dimension
- Maps the dimension to the responsible agent
- Proposes a rewritten prompt with a unified diff and justification
- Stores the proposal in
proposed_promptstable (status: pending)
A human reviews via POST /prompts/{id}/review with {"action": "approve"}.
If approved:
- The new prompt is applied to the agent at runtime
- The eval re-runs on previously failed cases only
- The performance delta (score_before, score_after, delta) is stored in
prompt_performance_deltas
Every proposal, approval/rejection, and delta is stored with timestamps and is queryable.
Submit a query. Returns job_id and stream_url.
{"query": "What is the capital of France?"}SSE stream. Events: orchestrator_start, routing_decision, agent_start,
tool_call, agent_output, orchestrator_done, job_complete, job_error.
Full execution trace: ordered agent decisions, tool calls, handoffs.
Latest eval summary by category and scoring dimension.
Approve or reject a pending prompt rewrite.
{"action": "approve", "reviewer_note": "Looks good"}Re-run eval on failed cases.
{"run_id": "run_abc123", "case_ids": ["b1", "adv2"]}Code sandbox: Uses subprocess inside the Docker container rather than
spawning sibling containers via Docker-in-Docker. This is sufficient for
safe computation but not for arbitrary untrusted code in production.
Retrieval: Uses a deterministic stub when no search API key is configured. Real multi-hop retrieval requires a Brave or Serper API key. The stub generates plausible-looking results but does not fetch real web content.
Self-reflection tool: Calls the LLM synchronously from a sync context, which works but is not ideal for high-concurrency scenarios.
Meta-agent prompt patching: Applies prompt rewrites to in-memory module globals. In a multi-worker deployment, each worker process would need to reload the prompt from the database on startup for the change to be consistent.
Eval scoring: answer_correctness uses keyword matching for baseline cases.
This is fast and deterministic but misses paraphrased correct answers. A
production system would use an LLM-as-judge for this dimension.
Context compression: The compression agent uses a simple "keep first + last 3" heuristic. A production system would use a dedicated summarization model.
Does:
- Identify the worst-performing agent/dimension after each eval run
- Generate a targeted prompt rewrite with a unified diff
- Store the proposal for human review
- Apply the approved prompt and measure the delta on previously failed cases
- Log the full audit trail (proposals, approvals, deltas) with timestamps
Does not:
- Automatically apply rewrites without human approval
- Guarantee improvement (the LLM-generated rewrite may not help)
- Persist prompt changes across container restarts (stored in DB but requires explicit reload on startup in multi-worker deployments)
- Run continuous background improvement (triggered per eval run)
- LLM-as-judge scoring for
answer_correctnessto replace keyword matching - Docker-in-Docker sandbox for truly isolated code execution
- Vector database (pgvector or Qdrant) for real semantic retrieval instead of web search stubs
- Prompt versioning with automatic reload from DB on worker startup
- Distributed tracing with OpenTelemetry for cross-service latency visibility
- Rate limiting and auth on the API endpoints
- Streaming synthesis — pipe the synthesis agent's LLM stream directly to SSE so the final answer appears token-by-token in real time
- A/B testing framework for prompt rewrites — run old and new prompts in parallel on the same inputs before committing to the rewrite