Building a Python AI Agent Service from Scratch

    This article walks through building a production-ready Python AI agent service, moving beyond a simple model call to a structured backend service. It covers why a working prototype is not a deliverable service, how to organize code blocks and verification steps, a recommended directory structure with layered configuration, defining stable data contracts with Pydantic schemas, wrapping the model client to handle uncertainty, adding input guardrails and a fixed orchestration pipeline, building a minimal retrieval store, and a three-layer testing strategy with an evolution roadmap. Readers will learn how to keep contracts stable, boundaries clear, the service observable, and tests free of real model costs.

    1. Why “Calling a Model” Is Not the Same as “Delivering a Service”

    Many teams can run a single model request in a few dozen lines of code during the prototype stage. But when it is time to hand that capability to a business backend, the problems surface all at once: API keys scattered across the code, unstable response structures, no health checks, exceptions that are impossible to trace, and tests that depend on real quota. The core judgment here is accurate: the goal of this chapter is not to make the model “say a sentence,” but to place the model call inside an engineering structure.

    An agent service that a backend can call must satisfy at least four conditions. First, a stable contract: callers depend only on fixed paths and data structures. Second, clear boundaries: input passes through guardrails before it reaches the model. Third, observability: health checks expose the service status and the current model configuration. Fourth, testability: the default path does not consume real model quota.

    The recommended minimal service therefore includes four endpoints: health check, general chat, daily plan generation, and text ingestion with retrieval. They correspond to status exposure, the orchestration pipeline, business-level encapsulation, and knowledge preparation, forming a complete loop.

    2. Three Types of Code Blocks and the Verification Rhythm

    To avoid “pasting code in the wrong place,” the project documentation should clearly distinguish three types of content:

    • Commands to run: executed in the terminal to create a virtual environment, install dependencies, start the service, and run tests.
    • Files to write: written in full to the specified path, with no omitted fragments allowed.
    • Fragments to understand: used only to explain design motivation; they do not go into the project.

    As for rhythm, do a lightweight verification (import check, unit test, or health check request) after every 2 to 4 files. Errors are worst when they pile up: waiting until the end of the chapter to debug all at once often makes it impossible to tell which step introduced the problem.

    3. Directory Structure and Layered Configuration

    A recommended structure (illustrative):

    1. agent_service/
    2. app/
    3. main.py # Application entry point and route registration
    4. config.py # Configuration loading and validation
    5. schemas.py # Data transfer objects
    6. clients/
    7. model.py # Model client wrapper
    8. services/
    9. guard.py # Input guardrails
    10. rag.py # Minimal retrieval store
    11. orchestrator.py# Main pipeline orchestration
    12. stores/
    13. vector_store.py
    14. tests/
    15. requirements.txt

    The key to layered configuration is “environment variables first, safe defaults.” Real model keys must be injected through the environment, and real calls are disabled by default. If a required item is missing when the service starts, it should fail fast with a readable error rather than crash on the first request.

    1. # Fragment to understand, do not copy: the core of configuration is validate before use
    2. class Settings:
    3. real_model_enabled: bool = False
    4. model_name: str = "general-chat"
    5. api_key: str | None = None

    4. Data Transfer Objects: Fix the Contract First

    Defining the structures before writing business logic can significantly reduce rework. The minimal set includes: chat request (session identifier, user message, optional context), chat response (reply text, matched fragments, elapsed time, whether degraded), ingestion request (text, source identifier), ingestion response (number of chunks, elapsed time), and health response (status, model configuration summary).

    Illustrative:

    1. # File to write: schemas.py
    2. from pydantic import BaseModel
    3. class ChatIn(BaseModel):
    4. session_id: str
    5. message: str
    6. class ChatOut(BaseModel):
    7. reply: str
    8. hits: int
    9. degraded: bool
    10. class HealthOut(BaseModel):
    11. status: str
    12. model: str
    13. real_enabled: bool

    Once the contract is stable, the backend depends only on the structures and does not need to care whether retrieval is used internally or whether the service degrades.

    5. The Model Client: Confining Uncertainty

    Model calls inherently involve timeouts, rate limiting, and format drift. The client layer should handle three things uniformly: timeout and retry limits, structured output parsing, and predictable exception types on failure. The key principle is that the upper layers do not perceive the raw error text; they receive only normalized exceptions, making it easier for the orchestration layer to decide on a degradation strategy.

    1. # File to write: clients/model.py (illustrative)
    2. class ModelClient:
    3. def __init__(self, settings):
    4. self.s = settings
    5. def complete(self, prompt: str) -> str:
    6. if not self.s.real_model_enabled:
    7. return "[Mock reply]" + prompt[:20]
    8. # Real calls must be explicitly enabled, with unified timeout and exception normalization here
    9. raise RuntimeError("real model disabled")

    Defaulting to the mock branch is the key design that keeps “tests from burning quota”; real testing is turned on through an explicit switch to avoid accidental triggering.

    6. Input Guardrails and the Orchestration Pipeline

    Guardrails are not optional. The minimal implementation includes a length limit, filtering of empty content and pure symbols, coarse screening for sensitive instruction patterns, and validation of session identifier legitimacy. The guardrail returns a structured result (whether to allow passage, and a reason code), and the orchestration layer uses it to return a clear error rather than sending dirty data into the model.

    The main pipeline order should be fixed as: guardrail → retrieval recall → tool call (optional) → main model generation → result assembly. The value of a fixed order is reproducibility: the same input under the same configuration should produce an explainable path record.

    1. # File to write: services/orchestrator.py (illustrative)
    2. def chat(msg: str, settings, client, store):
    3. g = guard(msg)
    4. if not g.ok:
    5. return {"reply": "Input failed validation", "hits": 0, "degraded": True}
    6. hits = store.search(msg, top_k=3)
    7. reply = client.complete(build_prompt(msg, hits))
    8. return {"reply": reply, "hits": len(hits), "degraded": False}

    7. Minimal Retrieval Store and the Daily Plan

    The minimal retrieval store does not need to pursue complex algorithms: text chunking, term-matching scoring, and taking the top few chunks by score are enough for a demo and integration testing. The focus is a stable interface, so it can later be smoothly replaced with a more complete vector retrieval approach without affecting the upper layers.

    The daily plan endpoint demonstrates “business-level encapsulation”: it assembles a prompt based on the user profile and check-in records and outputs structured suggestions. It reuses the same orchestration pipeline with only a different input assembly method, which proves the reuse value of the layered design.

    8. Testing Strategy and Evolution Roadmap

    Tests are divided into three layers: the structure layer (imports and configuration validation), the contract layer (endpoint input and output), and the pipeline layer (guardrail interception and degradation paths). All run offline by default; real model tests are marked separately and executed only when explicitly enabled.

    The suggested evolution roadmap: first add logging and metrics (such as call latency and degradation rate), then introduce caching and rate limiting, and finally replace the retrieval implementation. Each step keeps the endpoint contract unchanged, so the backend gains improved capability without any changes.