Skip to content

About

Distributed multi-agent code orchestration and self-healing engine using LangGraph, Celery, Redis, and Kubernetes.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

πŸ€– Distributed Multi-Agent Code Orchestration & Self-Healing Engine

An asynchronous AI coding system that researches, plans, generates, executes, tests, and automatically repairs Python code using LangGraph, Celery, Redis, and LLMs.

Python LangGraph Celery Redis Docker Kubernetes LangSmith


Overview

This project is a distributed multi-agent coding engine designed to handle programming tasks asynchronously.

Instead of relying on a single LLM response, the system uses a structured workflow to:

  1. πŸ”Ž Research the problem
  2. 🧠 Decompose it into implementation steps
  3. πŸ’» Generate Python code
  4. πŸ§ͺ Execute the generated code
  5. πŸ” Inspect runtime errors
  6. πŸ”§ Automatically repair failed code
  7. βœ… Re-test the corrected implementation
  8. πŸ“Š Produce a final analysis/report

The core idea is simple:

Don't trust generated code blindly. Execute it, observe what happens, and use the real execution feedback to improve it.


System Architecture

                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                         β”‚   Client / Producer   β”‚
                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                    β”‚
                              Celery .delay()
                                    β”‚
                                    β–Ό
                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                         β”‚        Redis         β”‚
                         β”‚   Task Broker        β”‚
                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                    β”‚
                                    β–Ό
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚       Celery Workers         β”‚
                    β”‚                              β”‚
                    β”‚   Worker 1    Worker 2 ...   β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                   β”‚
                                   β–Ό
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚         LangGraph             β”‚
                    β”‚                              β”‚
                    β”‚  Research                    β”‚
                    β”‚      ↓                       β”‚
                    β”‚  Planner                     β”‚
                    β”‚      ↓                       β”‚
                    β”‚  Code Generation             β”‚
                    β”‚      ↓                       β”‚
                    β”‚  Test / Execute              β”‚
                    β”‚      β”‚                       β”‚
                    β”‚      β”œβ”€β”€ ❌ Failure           β”‚
                    β”‚      β”‚      ↓                β”‚
                    β”‚      β”‚   Error Feedback      β”‚
                    β”‚      β”‚      ↓                β”‚
                    β”‚      β”‚   Code Repair         β”‚
                    β”‚      β”‚      ↓                β”‚
                    β”‚      └──── Re-test           β”‚
                    β”‚                              β”‚
                    β”‚      ↓                       β”‚
                    β”‚   Analysis                   β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                   β”‚
                                   β–Ό
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚ Persistence & Observability  β”‚
                    β”‚                              β”‚
                    β”‚ SQLite + LangSmith + Logs    β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Agent Workflow

The LangGraph workflow consists of multiple stages.

1. Research Agent

The research stage gathers useful information before implementation.

It can use semantic memory and external research when additional information is required.

Programming Task
       ↓
   Research
       ↓
Relevant Context

2. Planner Agent

The planner breaks a complex programming problem into smaller implementation steps.

For example:

Build an LRU Cache
       β”‚
       β”œβ”€β”€ Define data structure
       β”œβ”€β”€ Implement get()
       β”œβ”€β”€ Implement put()
       β”œβ”€β”€ Handle eviction
       └── Validate behavior

This gives the Code Agent a structured plan before implementation.


3. πŸ’» Code Agent

The Code Agent generates the Python implementation based on the research and plan.

The generated code is then passed to the Test Agent.


4. Test Agent

The Test Agent doesn't simply ask an LLM whether the generated code is correct.

Instead, it actually executes the generated Python program.

The workflow uses:

  • tempfile
  • subprocess.run
  • Return-code validation
  • stdout capture
  • stderr capture
  • Execution timeout

Simplified flow:

Generated Python Code
        ↓
Temporary .py file
        ↓
Python subprocess
        ↓
   β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”
   ↓         ↓
Success    Failure
   ↓         ↓
 Continue   Capture error
             ↓
          Code Agent

Self-Healing Workflow

The main feature of the system is its self-healing code generation loop.

When generated code fails during execution, the runtime error is captured and returned to the Code Agent.

        Generate Code
             β”‚
             β–Ό
        Execute Code
             β”‚
       β”Œβ”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”
       β”‚           β”‚
    Success      Failure
       β”‚           β”‚
       β–Ό           β–Ό
    Continue    Capture
                traceback
                   β”‚
                   β–Ό
              Code Agent
                   β”‚
                   β–Ό
             Fix the code
                   β”‚
                   β–Ό
               Re-test

This allows the system to respond to real execution errors such as:

  • Missing imports
  • Type errors
  • Index errors
  • Runtime exceptions
  • Incorrect implementation logic
  • Invalid API usage

The retry process is bounded so that the workflow does not continue indefinitely.


Code Execution & Verification

The system uses isolated subprocess execution to verify generated Python code.

A temporary Python file is created and executed independently.

Example:

result = subprocess.run(
    ["python", temp_file],
    capture_output=True,
    text=True,
    timeout=5
)

The Test Agent checks:

returncode == 0

and captures:

stdout
stderr

A 5-second timeout prevents a generated program from running indefinitely.

This is subprocess-based execution and timeout protection. It should not be considered a hardened security sandbox for arbitrary untrusted code.


Distributed Task Processing

The system uses Celery + Redis to process tasks asynchronously.

Instead of keeping the producer blocked while the complete AI workflow executes:

Client
  β”‚
  β”‚ submit task
  β–Ό
Redis
  β”‚
  β–Ό
Celery Worker
  β”‚
  β–Ό
LangGraph
  β”‚
  β–Ό
Final Result

Tasks are placed into the queue and processed by workers.

Example:

run_agent_task.delay(
    "Write a Python function to implement binary search."
)

This architecture separates:

  • Task submission
  • Task queuing
  • Task execution
  • AI workflow processing

LLM Rate-Limit Handling

LLM APIs can temporarily reject requests because of rate limits.

The project includes mechanisms to handle HTTP 429 responses.

Celery Task Pacing

Tasks can be rate-limited at the worker level:

rate_limit = "15/m"

This helps control how quickly tasks are consumed.

Dynamic Backoff

The safe_llm_call wrapper detects rate-limit errors and waits before retrying.

LLM Request
    β”‚
    β”œβ”€β”€ Success ──► Continue
    β”‚
    └── 429
         β”‚
         β–Ό
     Read retry delay
         β”‚
         β–Ό
        Wait
         β”‚
         β–Ό
       Retry

This helps prevent repeated requests from immediately triggering additional rate-limit failures.


Kubernetes Configuration

The project includes Kubernetes manifests for the distributed worker architecture.

k8s/
β”œβ”€β”€ redis-deployment.yaml
β”œβ”€β”€ celery-worker-deployment.yaml
└── hpa.yaml

Redis Deployment

Runs Redis inside Kubernetes and exposes it through an internal Kubernetes Service.

Celery Worker
      β”‚
      β–Ό
redis-service:6379
      β”‚
      β–Ό
 Redis Pod

Celery Worker Deployment

Defines how Celery worker containers should run.

The configuration includes:

  • Worker replicas
  • Container image
  • Environment variables
  • Kubernetes Secrets
  • CPU/memory requests
  • CPU/memory limits
  • Liveness probes
  • Readiness probes

Horizontal Pod Autoscaler

The HPA can dynamically adjust the number of worker Pods based on CPU and memory utilization.

Low workload
     ↓
2 workers

High workload
     ↓
3 β†’ 4 β†’ 5 ... workers

Maximum
     ↓
10 workers

The current configuration defines:

Minimum replicas: 2
Maximum replicas: 10

The repository contains Kubernetes deployment and scaling configuration. Actual deployment to a Kubernetes cluster depends on the target environment.


Benchmark Results

1. Distributed Load Test

The system was tested by dispatching 30 asynchronous programming tasks through Celery and Redis.

Metric Result
Tasks dispatched 30
Successful completions 30/30
Completion rate 100%
Total execution time 823.49 seconds
Worker concurrency 2 threads
Average throughput ~0.036 tasks/sec

What this test demonstrates

The test demonstrates that the asynchronous task pipeline successfully processed all 30 tasks in that test run without unhandled task failures.

30/30 is a task completion result for this benchmark. It is not a claim of general AI accuracy.


Custom Coding Benchmark

The generated-code pipeline was also evaluated on five custom programming tasks.

Tasks included

  1. ISO 8601 date parsing without third-party libraries
  2. Custom JSON encoding for datetime and UUID
  3. LRU cache implementation using OrderedDict
  4. Semantic version comparison
  5. Nested bracket matching

Result

Tasks evaluated: 5
Tasks passed:    5
Pass rate:       100%

The solutions were executed through the automated code execution/testing workflow.

Important

This is a custom 5-task evaluation, not a standardized benchmark such as HumanEval or MBPP.


What This Project Demonstrates

This project combines several areas of modern AI engineering:

AI & LLMs

  • LLM-powered code generation
  • Agentic workflows
  • Multi-agent orchestration
  • Prompt-based reasoning
  • Self-healing workflows
  • Semantic memory

Backend & Distributed Systems

  • Python
  • Celery
  • Redis
  • Asynchronous processing
  • Worker pools
  • Task queues
  • Retry/backoff mechanisms

AI Infrastructure

  • Docker
  • Kubernetes
  • Horizontal Pod Autoscaling
  • Health probes
  • Resource management
  • Kubernetes Secrets

Observability

  • LangSmith
  • Structured logging
  • Workflow tracing
  • Node-level execution monitoring

Evaluation

  • Automated code execution
  • Runtime validation
  • Load testing
  • Custom coding benchmarks
  • Pass-rate measurement

πŸ› οΈ Technology Stack

Technology Purpose
Python 3.11 Core application
LangGraph AI workflow orchestration
Celery Distributed task execution
Redis Message broker / task backend
FAISS Semantic vector search
FastEmbed Embedding generation
Groq / LLM API LLM inference
LangSmith AI workflow observability
SQLite State/checkpoint persistence
Docker Containerization
Kubernetes Container orchestration
Subprocess Generated-code execution

Project Structure

multi-agent-orchestrator/
β”‚
β”œβ”€β”€ k8s/
β”‚   β”œβ”€β”€ redis-deployment.yaml
β”‚   β”œβ”€β”€ celery-worker-deployment.yaml
β”‚   └── hpa.yaml
β”‚
β”œβ”€β”€ main.py
β”‚   └── LangGraph workflow and agent nodes
β”‚
β”œβ”€β”€ celery_tasks.py
β”‚   └── Celery application and task definitions
β”‚
β”œβ”€β”€ state.py
β”‚   └── AgentTaskState schema
β”‚
β”œβ”€β”€ memory.py
β”‚   └── FAISS semantic memory
β”‚
β”œβ”€β”€ run_load_test.py
β”‚   └── Distributed 30-task load test
β”‚
β”œβ”€β”€ run_accuracy_via_celery.py
β”‚   └── Custom coding evaluation
β”‚
β”œβ”€β”€ benchmark_accuracy.py
β”‚   └── Benchmark harness
β”‚
β”œβ”€β”€ Dockerfile
β”‚   └── Container definition
β”‚
β”œβ”€β”€ requirements.txt
β”‚   └── Python dependencies
β”‚
└── README.md

Getting Started

Prerequisites

  • Python 3.11+
  • Redis
  • Groq API key
  • LangSmith API key (optional)
  • Docker (optional)
  • Kubernetes cluster (optional)

1. Clone the Repository

git clone https://github.com/<your-username>/multi-agent-orchestrator.git

cd multi-agent-orchestrator

2. Create Virtual Environment

Windows

python -m venv venv

.\venv\Scripts\activate

Linux / macOS

python -m venv venv

source venv/bin/activate

3. Install Dependencies

pip install -r requirements.txt

4. Configure Environment Variables

Create a .env file:

GROQ_API_KEY=your_groq_api_key

REDIS_URL=redis://localhost:6379/0

LANGCHAIN_TRACING_V2=true
LANGCHAIN_PROJECT=multi-agent-orchestrator
LANGCHAIN_ENDPOINT=https://api.smith.langchain.com
LANGCHAIN_API_KEY=your_langsmith_api_key

Add .env to .gitignore:

.env
venv/
__pycache__/
*.pyc

Never commit API keys to GitHub.


β–Ά Running Locally

Start Redis and make sure it is available at:

localhost:6379

Then start the Celery worker:

celery -A celery_tasks worker --loglevel=info --pool=threads --concurrency=2

Tasks can then be dispatched asynchronously:

run_agent_task.delay(
    "Write a Python function to implement binary search."
)

Docker

Build the image:

docker build -t multi-agent-orchestrator:latest .

Run the worker:

docker run --env-file .env multi-agent-orchestrator:latest

The Docker image is configured to start a Celery worker by default.


Kubernetes

Apply the Redis configuration:

kubectl apply -f k8s/redis-deployment.yaml

Apply the Celery worker deployment:

kubectl apply -f k8s/celery-worker-deployment.yaml

Apply the HPA:

kubectl apply -f k8s/hpa.yaml

Check running Pods:

kubectl get pods

Check Deployments:

kubectl get deployments

Check autoscaling:

kubectl get hpa

View worker logs:

kubectl logs <pod-name>

Observability

The project supports LangSmith tracing to inspect the AI workflow.

Tracing can help monitor:

  • Agent execution
  • LangGraph nodes
  • LLM calls
  • Workflow transitions
  • Latency
  • Errors
  • Token usage where available

This is particularly useful when debugging multi-step agentic workflows.


Reliability Features

The system includes several mechanisms to improve reliability:

Asynchronous Processing

Celery and Redis separate task submission from long-running AI execution.

Runtime Verification

Generated code is executed and checked instead of being blindly trusted.

Error Feedback

Actual runtime errors are returned to the Code Agent for correction.

Bounded Retries

The self-healing loop has retry limits to prevent infinite execution.

Rate-Limit Handling

HTTP 429 errors can trigger controlled waiting and retry behavior.

Health Checks

Kubernetes liveness and readiness probes can monitor worker health.

Resource Limits

Kubernetes CPU and memory requests/limits provide resource boundaries for worker Pods.


Engineering Challenges

Challenge 1 β€” Long-running AI workflows

Problem: LLM workflows can take significant time to complete.

Solution: Celery + Redis provide asynchronous task processing.


Challenge 2 β€” Generated code can fail

Problem: LLM-generated code may contain runtime or implementation errors.

Solution: Execute the code and provide real traceback information back to the Code Agent.


Challenge 3 β€” API rate limits

Problem: LLM providers can temporarily reject requests.

Solution: Task pacing and retry/backoff handling.


Challenge 4 β€” Distributed workers

Problem: Multiple workers need a shared task queue.

Solution: Redis acts as the broker while Celery manages distributed workers.


Challenge 5 β€” Debugging agent workflows

Problem: Multi-step agent systems can be difficult to debug.

Solution: LangSmith tracing and structured application logging.


Challenge 6 β€” Scaling workers

Problem: Worker capacity may need to increase as workload grows.

Solution: Kubernetes Deployment + Horizontal Pod Autoscaler configuration.


Future Improvements

  • Evaluate on standardized benchmarks such as HumanEval
  • Add stronger container-level code isolation
  • Add broader automated test coverage
  • Add FastAPI API layer
  • Add Prometheus/Grafana monitoring
  • Add CI/CD pipeline
  • Add authentication and authorization
  • Deploy to a managed Kubernetes cluster
  • Compare multiple LLM providers
  • Expand benchmark dataset
  • Compare single-pass generation against self-healing generation

Current Verified Results

╔══════════════════════════════════════════╗
β•‘          DISTRIBUTED LOAD TEST           β•‘
╠══════════════════════════════════════════╣
β•‘ Tasks dispatched:       30               β•‘
β•‘ Successful completions: 30 / 30         β•‘
β•‘ Completion rate:        100%             β•‘
β•‘ Execution time:         823.49 seconds   β•‘
β•‘ Worker concurrency:     2                β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•


╔══════════════════════════════════════════╗
β•‘       CUSTOM CODING EVALUATION           β•‘
╠══════════════════════════════════════════╣
β•‘ Tasks evaluated:        5                β•‘
β•‘ Tasks passed:           5                β•‘
β•‘ Pass rate:              100%             β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

These results represent the specific test runs performed on this project. They are not intended to represent general model accuracy, production SLA, or standardized benchmark performance.


Author

Imad Ud Din

AI Engineer | AI Agents | Generative AI | RAG | LangGraph | Python

Interested in building practical AI systems, agentic workflows, LLM applications, and AI-powered automation.


Support

If you find this project interesting, consider giving the repository a ⭐.


About

Distributed multi-agent code orchestration and self-healing engine using LangGraph, Celery, Redis, and Kubernetes.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages