Building a Python AI Agent Service Skeleton from Scratch

    Learn how to build a Python AI agent service skeleton with FastAPI, covering layered configuration, strict data contracts, client fallback logic, a minimal RAG store, fixed orchestration, and offline testing without real model keys.

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

    Many teams can write a dozen lines of code to make a single model request during the prototype stage. But the moment that code has to be handed over for business backend integration, the problems surface immediately: model keys are scattered across the codebase, timeout and retry strategies are missing, inputs go through no validation at all, response structures drift as prompts change, and tests either depend on real keys or cannot run at all. A real agent service does not deliver “a single model answer”; it delivers a set of stable engineering contracts.

    The goal of this chapter is to build a Python agent service from scratch with four externally callable capability endpoints. The health check exposes service status and the current model configuration. The chat endpoint accepts a user message, passes it through input guardrails first, and then enters the retrieval, tool, and main model chain. The daily plan endpoint generates a personalized schedule based on the user profile and check-in records. The document ingestion endpoint chunks text and writes it into a minimal retrieval store. The whole service can later be integrated by a business backend over HTTP.

    It is worth emphasizing that the default test path does not depend on any real model key; external calls happen only when real model verification is explicitly enabled. This constraint is not about saving effort. It keeps the continuous integration environment deterministic and repeatable.

    2. Copy and Verification Discipline: Three Types of Code Blocks

    The place where hands-on articles most often fail is that readers treat “explanatory snippets” as “files to put into production.” So strictly distinguish three types of content.

    The first type is execution commands, run in the terminal to create the virtual environment, install dependencies, start the service, and trigger tests. The second type is file content, which must be copied in full to the specified path without omitting a single character. The third type is understanding snippets, used only to explain why the code is shaped the way it is, and never written into the project.

    The accompanying discipline is to run a lightweight verification after every two to four files. Do not wait until the end of the chapter to test everything at once; otherwise errors stack up, the link between the reported location and the real cause is broken, and troubleshooting cost rises non-linearly.

    1. # [execution command] Initialize the project skeleton
    2. mkdir agent_service && cd agent_service
    3. python -m venv .venv && source .venv/bin/activate
    4. pip install fastapi uvicorn pydantic httpx pytest
    5. mkdir -p app/routers app/services app/clients app/core tests data

    3. Layered Configuration: Keeping Keys and Switches Controllable

    The first principle of configuration is that no key ever appears in the code. The second is that environment differences are handled through external injection, with local, test, and production kept independent. The third is that capability switches are made explicit, especially behavior like real model calls that carries external dependencies and cost.

    1. # [write to file] app/core/config.py
    2. from pydantic_settings import BaseSettings
    3. class Settings(BaseSettings):
    4. app_name: str = "agent-service"
    5. host: str = "0.0.0.0"
    6. port: int = 8000
    7. request_timeout: float = 20.0
    8. max_input_chars: int = 2000
    9. chunk_size: int = 400
    10. chunk_overlap: int = 40
    11. enable_real_model: bool = False
    12. model_base_url: str = ""
    13. model_api_key: str = ""
    14. model_name: str = "general-chat"
    15. class Config:
    16. env_prefix = "AGENT_"
    17. settings = Settings()

    The most notable design here is that enable_real_model defaults to false. When it is false, the client uses a deterministic local stub implementation that returns a response with exactly the same structure; only when it is true does it read the URL and key and issue a real request. This way unit tests, integration tests, and demo environments share the same code path, and the difference is compressed into a single boolean value.

    4. Data Transfer Objects: Writing the Contract in Stone

    Model output is inherently unstable, so data structures at the boundary must be strict. Define separate models for the chat request, chat response, health status, and ingestion request, and set minimum and maximum lengths.

    1. # [write to file] app/core/schemas.py
    2. from typing import Optional
    3. from pydantic import BaseModel, Field
    4. class ChatRequest(BaseModel):
    5. message: str = Field(min_length=1, max_length=2000)
    6. user_id: Optional[str] = None
    7. class ChatResponse(BaseModel):
    8. reply: str
    9. used_retrieval: bool
    10. used_tool: Optional[str] = None
    11. model: str
    12. class HealthResponse(BaseModel):
    13. status: str
    14. model: str
    15. real_model_enabled: bool
    16. class IngestRequest(BaseModel):
    17. text: str = Field(min_length=1, max_length=20000)
    18. source: str = "default"

    Putting field validation in the data transfer object layer rather than scattering it across business functions means errors are intercepted before entering the orchestration logic, and the error information returned to the caller is naturally structured.

    5. Client Encapsulation: Timeout, Retry, and Fallback

    The client is the only place allowed to touch the external network. It has to handle three things: a unified timeout, a limited number of retries, and fallback on failure. Fallback does not mean swallowing the exception; it means returning an explicit result that upper layers can recognize.

    1. # [write to file] app/clients/model_client.py
    2. import httpx
    3. from app.core.config import settings
    4. class ModelClient:
    5. def __init__(self):
    6. self._client = httpx.AsyncClient(timeout=settings.request_timeout)
    7. async def chat(self, prompt: str) -> str:
    8. if not settings.enable_real_model:
    9. return f"[stub] received a prompt of {len(prompt)} characters"
    10. try:
    11. resp = await self._client.post(
    12. f"{settings.model_base_url}/chat",
    13. headers={"Authorization": f"Bearer {settings.model_api_key}"},
    14. json={"model": settings.model_name, "input": prompt},
    15. )
    16. resp.raise_for_status()
    17. return resp.json().get("output", "")
    18. except Exception:
    19. return "[fallback] model temporarily unavailable"

    Understanding snippet (do not copy): in a real implementation, retries should target only idempotent connection errors and use exponential backoff; clear parameter errors should not be retried, otherwise you only amplify invalid requests.

    6. Input Guardrails and a Minimal Retrieval Store

    Guardrails run before the model is reached and include at least length truncation, whitespace normalization, removal of sensitive fields, and simple injection pattern filtering. The output of the guardrail is predictable clean text, which directly determines the quality of downstream retrieval.

    The minimal retrieval store does not need a vector database; an in-memory list plus keyword scoring is enough to close the teaching loop. On ingestion, text is chunked with an overlapping window; on retrieval, chunks are sorted by number of matched words and the top few are taken. Its value is getting the structure of “retrieval augmentation” running first, so that when it is later replaced with a vector index, the upper-layer code needs no changes.

    1. # [write to file] app/services/store.py
    2. from app.core.config import settings
    3. class MiniStore:
    4. def __init__(self):
    5. self.chunks: list[dict] = []
    6. def ingest(self, text: str, source: str):
    7. step = settings.chunk_size - settings.chunk_overlap
    8. for i in range(0, len(text), step):
    9. self.chunks.append({"source": source, "text": text[i:i + settings.chunk_size]})
    10. def search(self, query: str, top_k: int = 3):
    11. tokens = set(query)
    12. scored = [(len(tokens & set(c["text"])), c) for c in self.chunks]
    13. scored = [x for x in scored if x[0] > 0]
    14. scored.sort(key=lambda x: x[0], reverse=True)
    15. return [c["text"] for _, c in scored[:top_k]]

    7. Service Orchestration: Fixing the Order

    The orchestration layer defines the chain order: guardrail → retrieval → tool → main model. The benefit of a fixed order is observability, because the input and output of each step can be asserted individually. The daily plan endpoint demonstrates another chain: read the user profile and check-in records, assemble a structured prompt, and then go through the same client.

    1. # [write to file] app/services/agent.py
    2. from app.clients.model_client import ModelClient
    3. from app.services.store import MiniStore
    4. from app.core.config import settings
    5. class AgentService:
    6. def __init__(self):
    7. self.client = ModelClient()
    8. self.store = MiniStore()
    9. def guard(self, text: str) -> str:
    10. return " ".join(text.split())[: settings.max_input_chars]
    11. async def chat(self, message: str):
    12. clean = self.guard(message)
    13. hits = self.store.search(clean)
    14. prompt = clean if not hits else clean + "\nReferences:\n" + "\n".join(hits)
    15. reply = await self.client.chat(prompt)
    16. return {"reply": reply, "used_retrieval": bool(hits),
    17. "used_tool": None, "model": settings.model_name}

    The routing layer stays very thin, doing only parameter binding and status code mapping, while all business decisions are pushed down to the service layer. This way tests can target the service layer directly without starting a network.

    8. Test Feedback: Offline by Default, Real Model Explicitly Enabled

    Tests should cover at least four cases: the health endpoint returns the configuration, guardrail truncation takes effect, retrieval hits after ingestion, and the chat response structure stays stable in stub mode. Real model verification is marked separately and runs only after the switch is set.

    1. # [write to file] tests/test_agent.py
    2. import pytest
    3. from fastapi.testclient import TestClient
    4. from app.main import app
    5. client = TestClient(app)
    6. def test_health():
    7. body = client.get("/health").json()
    8. assert body["status"] == "ok"
    9. assert body["real_model_enabled"] is False
    10. def test_ingest_and_chat():
    11. client.post("/rag/ingest", json={"text": "check-in reward rules", "source": "hr"})
    12. body = client.post("/agent/chat", json={"message": "check-in reward"}).json()
    13. assert body["used_retrieval"] is True
    14. @pytest.mark.skipif(True, reason="requires explicitly enabling the real model")
    15. def test_real_model():
    16. pass

    9. Common Pitfalls and a Sensible Pace

    The first pitfall is writing validation in the routes, which makes the service layer impossible to reuse. The second is letting the client carry business decisions, so retry strategy ends up tangled with prompt logic. The third is waiting until all features are complete before testing, when the cost of locating problems is highest. The fourth is binding the retrieval store interface to a specific index implementation too early, which magnifies replacement cost.

    The recommended pace is: first get configuration and data structures running, then wire in the client stub, then add guardrails and retrieval, and finally add the real model switch and scheduling. End each step with a repeatable verification, and the capability boundaries of the service will stabilize along with the code.