Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 71

Prototyping the Customer Request Lifecycle

Recommended resources

Introduction

Welcome to the final lesson and the capstone project of our course on agentic orchestration. In the previous lesson, we designed a comprehensive architectural blueprint for a production-grade agentic system, emphasizing the separation of concerns between a deterministic control plane and a non-deterministic data plane. We have methodically laid the groundwork, from the core agent loop to advanced reliability patterns. Now, it is time to bring that blueprint to life.

This lesson is entirely focused on implementation. Our goal is to build and test a working prototype of the integrated system we designed, simulating a full customer request lifecycle. You will leverage your experience with distributed systems to construct the core components using industry-standard tools: a FastAPI web server for task ingestion, a Celery/Redis backend for asynchronous task execution, and Docker to containerize and orchestrate the entire system. This hands-on project will synthesize every concept we've covered, transforming our architectural diagrams into running code and providing a tangible demonstration of a robust, scalable agent service.


1. The Asynchronous Foundation: Decoupling Ingestion from Execution

The first principle of our production architecture is that long-running agent tasks must not block the client. An HTTP request-response cycle is ill-suited for workflows that can take minutes to complete due to multiple LLM calls and tool executions. The solution is the asynchronous job pattern, a cornerstone of distributed systems.

Async Agent Workflows: Designing for Long-Running Tasks

To solidify the "why" behind our approach, let's review the core problem with synchronous designs and the standard architectural pattern that solves it. This article by Tian Pan provides a concise and accurate overview.

Read the first two sections, starting from the introduction to the problem, and then the following section on the solution. Pay close attention to the sequence diagram and the simple state machine (pending → working → completed). This is precisely the pattern we are about to implement.

To realize this pattern, we will build a system with three main parts:

  1. API Server (FastAPI): A lightweight web server that exposes an endpoint to receive new tasks. It immediately adds the task to a queue and returns a task_id to the client.
  2. Message Queue (Redis): A broker that holds tasks waiting to be processed. This decouples the API server from the workers.
  3. Agent Worker (Celery): A separate process that consumes tasks from the queue, executes the long-running agent logic, and stores the result.

The following resource provides a nearly complete implementation of this foundation. We will use it as our starting point.

Asynchronous Processing and Message Queues in Agentic AI ...

This article provides the Python code for an asynchronous agent system using FastAPI and Celery. We will adopt this code for our prototype.

Focus on the section "Basic Async Agent Task with Celery." Study the two provided code blocks for tasks.py and api.py. In tasks.py, notice how the execute_agent_workflow function is decorated with @app.task. This registers it as a Celery task. The use of self.update_state is crucial for providing progress updates. In api.py, observe the three endpoints: /execute to submit a task, /status to poll for progress, and /result to retrieve the final output. This directly implements the async job pattern.

Let's set up our project structure based on this. Create a project directory with two files: api.py and tasks.py. Populate them with the code from the reading. For now, you can use the execute_agent_workflow function as-is. We will modify it in the next section to perform our specific customer service task.


2. Implementing the Agent Worker Logic

The execute_agent_workflow function in tasks.py is where our agent's intelligence resides. The provided example simulates a simple research task. Let's adapt it to our "cancel subscription and refund" scenario from the previous lesson.

This involves breaking the task down into a sequence of steps, which mirrors the "plan-then-execute" pattern we discussed. Our agent worker will simulate this process. For this prototype, we'll use simple Python functions with time.sleep() to stand in for actual tool calls and LLM inference latency.

First, let's define our mock tools. Add these functions to your tasks.py file.

# tasks.py

# ... (Celery app setup) ...

# Mock Tools
def get_subscription_details(customer_id: str) -> dict:
    """Mock tool to fetch subscription details from a CRM."""
    print(f"TOOL: Fetching subscription for {customer_id}")
    time.sleep(1) # Simulate API latency
    return {"id": "sub-987", "plan": "premium", "last_charge_amount": 99.00}

def issue_refund(customer_id: str, amount: float) -> dict:
    """Mock tool to issue a refund via a payment gateway."""
    print(f"TOOL: Issuing refund of ${amount} to {customer_id}")
    time.sleep(2) # Simulate API latency
    return {"refund_id": "ref-xyz123", "status": "succeeded"}

def cancel_subscription(subscription_id: str) -> dict:
    """Mock tool to cancel a subscription."""
    print(f"TOOL: Cancelling subscription {subscription_id}")
    time.sleep(1) # Simulate API latency
    return {"subscription_id": subscription_id, "status": "cancelled"}

# ... (Celery task definition) ...

Now, let's modify the execute_agent_workflow Celery task to use these tools. This implementation follows the logic of a simple, from-scratch agent that processes a request through a series of steps. The video "Intro to Agents - Create an Agent from Scratch" provides a good mental model for this kind of direct, non-framework implementation.

# tasks.py

@app.task(bind=True, max_retries=3)
def execute_agent_workflow(self, customer_id: str, objective: str) -> Dict[str, Any]:
    """
    Executes a customer service workflow for cancelling a subscription and issuing a refund.
    """
    try:
        # Step 1: Planning (Simulated LLM call)
        self.update_state(state='PROCESSING', meta={'step': 'Planning', 'progress': 10})
        print(f"AGENT: Received objective '{objective}' for customer {customer_id}. Generating plan.")
        time.sleep(1.5) # Simulate LLM planning latency
        plan = [
            "get_subscription_details",
            "issue_refund",
            "cancel_subscription"
        ]
        self.update_state(state='PROCESSING', meta={'step': 'Planning Complete', 'plan': plan, 'progress': 25})

        # Step 2: Tool Execution
        tool_outputs = {}

        # Execute get_subscription_details
        self.update_state(state='PROCESSING', meta={'step': 'Executing: get_subscription_details', 'progress': 40})
        sub_details = get_subscription_details(customer_id)
        tool_outputs['subscription'] = sub_details

        # Execute issue_refund
        self.update_state(state='PROCESSING', meta={'step': 'Executing: issue_refund', 'progress': 60})
        refund_amount = sub_details.get("last_charge_amount", 0)
        refund_details = issue_refund(customer_id, refund_amount)
        tool_outputs['refund'] = refund_details

        # Execute cancel_subscription
        self.update_state(state='PROCESSING', meta={'step': 'Executing: cancel_subscription', 'progress': 80})
        sub_id = sub_details.get("id")
        cancellation_details = cancel_subscription(sub_id)
        tool_outputs['cancellation'] = cancellation_details

        # Step 3: Final Synthesis (Simulated LLM call)
        self.update_state(state='PROCESSING', meta={'step': 'Synthesizing Response', 'progress': 90})
        print("AGENT: All tools executed. Synthesizing final response.")
        time.sleep(1) # Simulate LLM synthesis latency
        final_response_text = f"Successfully processed the request for {customer_id}. " \
                              f"A refund of ${refund_amount} has been issued (ID: {refund_details['refund_id']}). " \
                              f"Subscription {sub_id} has been cancelled."

        # Complete
        self.update_state(state='SUCCESS', meta={'step': 'Complete', 'progress': 100})
        return {
            'status': 'success',
            'result': final_response_text,
            'metadata': {
                'tools_used': plan,
                'tool_outputs': tool_outputs
            }
        }

    except Exception as exc:
        self.update_state(state='FAILURE', meta={'error': str(exc)})
        # Celery's retry mechanism with exponential backoff
        raise self.retry(exc=exc, countdown=60 * (2 ** self.request.retries))

In your api.py, you'll also need to adjust the AgentRequest model and the call to execute_agent_workflow.delay to pass customer_id and objective instead of query and context.

This worker now embodies a simple agent. It receives an objective, forms a plan, executes a sequence of tools, and synthesizes a final result, all while reporting its progress back to the Celery backend.


3. Containerizing the System with Docker

With our api.py and tasks.py files defined, we can now package our entire system for deployment using Docker. This aligns with your experience in container orchestration and is standard practice for production systems. We will use Docker Compose to define and run our multi-container application.

Asynchronous Processing and Message Queues in Agentic AI ...

The same resource we used for the code provides a complete Docker deployment setup.

Study the section "Production Deployment with Docker." You will need three files from this section: docker-compose.yml, Dockerfile, and requirements.txt. requirements.txt: This lists all the Python dependencies for our project. Dockerfile: This provides the instructions to build a container image for our Python application. It installs dependencies and sets up the runtime environment. docker-compose.yml: This is the orchestrator. It defines the services that make up our application: redis, the celery_worker, and the api. Notice how it links them together using environment variables and depends_on.

Create these three files in your project directory. For the docker-compose.yml, you can omit the postgres, celery_beat, and flower services to keep the prototype simple. Your final docker-compose.yml should look something like this:

# docker-compose.yml
version: '3.8'

services:
  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    command: redis-server --appendonly yes

  celery_worker:
    build: .
    command: celery -A tasks worker --loglevel=info
    depends_on:
      - redis
    environment:
      - CELERY_BROKER_URL=redis://redis:6379/0
      - CELERY_RESULT_BACKEND=redis://redis:6379/0
    volumes:
      - ./:/app
    restart: unless-stopped

  api:
    build: .
    command: uvicorn api:app_api --host 0.0.0.0 --port 8000
    ports:
      - "8000:8000"
    depends_on:
      - redis
    environment:
      - CELERY_BROKER_URL=redis://redis:6379/0
    volumes:
      - ./:/app
    restart: unless-stopped

With these files in place, you can build and start the entire system with a single command: docker-compose up --build -d.


4. Simulating the Full Customer Request Lifecycle

Our integrated system is now running. It's time to test it by simulating a full customer request from start to finish. Our test process will mirror the "Agent Testing" methodology, where we act as a simulated user interacting with our agent, which in turn uses simulated tools.

This diagram shows a robust agent testing methodology. Our end-to-end test will follow this pattern, with a client script acting as the "Simulated User (Actor)" and our mock functions serving as the "Simulated Tools (Mock Server)".

This diagram shows a robust agent testing methodology. Our end-to-end test will follow this pattern, with a client script acting as the "Simulated User (Actor)" and our mock functions serving as the "Simulated Tools (Mock Server)".

We will use a simple Python script with the requests library to act as our client. This script will perform the three key actions of the async job pattern: submit, poll, and retrieve.

Create a new file named test_client.py:

# test_client.py
import requests
import time
import json

API_URL = "http://localhost:8000"

def run_test():
    # 1. Submit the task
    print("--- Submitting Task ---")
    task_payload = {
        "customer_id": "cust-456",
        "objective": "Please cancel my subscription and refund my last payment."
    }
    response = requests.post(f"{API_URL}/agent/execute", json=task_payload)
    
    if response.status_code != 200:
        print(f"Error submitting task: {response.text}")
        return

    task_id = response.json()['task_id']
    print(f"Task submitted successfully. Task ID: {task_id}\n")

    # 2. Poll for status
    print("--- Polling for Status ---")
    while True:
        status_response = requests.get(f"{API_URL}/agent/status/{task_id}")
        status_data = status_response.json()
        
        current_state = status_data.get('state')
        current_step = status_data.get('current_step', 'N/A')
        
        print(f"State: {current_state}, Current Step: {current_step}")

        if current_state in ['SUCCESS', 'FAILURE']:
            break
        
        time.sleep(2)
    
    print("\n--- Task Finished ---")

    # 3. Retrieve the final result
    result_response = requests.get(f"{API_URL}/agent/result/{task_id}")
    final_result = result_response.json()

    print("Final Result:")
    print(json.dumps(final_result, indent=2))


if __name__ == "__main__":
    run_test()

Before running the client, open a new terminal and view the logs from your Celery worker to see the agent's internal monologue and tool execution prints: docker-compose logs -f celery_worker.

Now, run the test client: python test_client.py.

You should see the client submit the task, then print status updates as the worker progresses through "Planning", "Executing tools", and "Synthesizing Response". Simultaneously, in the worker logs, you will see the print statements from our agent and mock tools. Finally, the client will print the complete, structured result from the agent. You have just successfully simulated an end-to-end customer request through your distributed agentic system.


Conclusion

Congratulations on completing the course and this capstone project. We have journeyed from the fundamental building blocks of LLM interaction to designing and now implementing a sophisticated, production-grade agentic architecture. This final lesson has brought all our theoretical knowledge into practice, culminating in a tangible, working system.

Key Takeaways:

  • From Blueprint to Reality: We successfully translated the architectural blueprint from the previous lesson into a functional prototype using FastAPI, Celery, and Docker.
  • Asynchronous by Design: The async job pattern is not an add-on but the fundamental structure for building reliable agent services that handle long-running tasks.
  • The Power of First Principles: By building the orchestration layer from scratch, you have gained a deep, transferable understanding of how agentic systems operate, manage state, and handle tasks—knowledge that transcends any specific framework.
  • Integrated Testing: Simulating an end-to-end request lifecycle is critical for validating that all components of a distributed system—API, queue, and workers—are correctly integrated and functioning as a cohesive whole.

This course has equipped you with the first-principles engineering knowledge to architect, build, and deploy complex, reliable agentic systems. The patterns and techniques you have mastered are at the forefront of AI engineering. The journey of building truly intelligent and robust agents is just beginning, and you are now well-prepared to lead it.