
How to Build Your First AI Application With Python
Architect and implement a production-grade Python AI service featuring structured outputs, resilient RAG pipelines, fallback systems, and OpenTelemetry.
Moving an AI prototype from a Jupyter notebook to an enterprise-grade production service is one of the most critical transitions a software engineering team can make. While fetching a response from an LLM API requires just three lines of code, building a system capable of handling strict latency SLAs, unpredictable provider outages, non-deterministic outputs, and compliance standards requires robust software engineering patterns.
In this guide, we will walk through building a production-grade AI microservice in Python 3.11+. We will cover schema enforcement, resilient orchestration, context retrieval, observability, and defensive engineering strategies necessary for mission-critical enterprise systems.
1. Enterprise AI System Architecture
Before writing code, we must define the architectural boundary. An enterprise AI application is not just an API wrapper—it is a distributed processing engine that handles state, retrieval, model execution, and validation.
Below is the standard topology for a decoupled, production-grade AI application:
+-----------------------+
| API Gateway / REST |
+-----------+-----------+
|
v
+-----------------------+
| FastAPI Orchestrator |
+-----+-----------+-----+
| |
+---------------------------+ +---------------------------+
| |
v v
+-----------------------+ +-----------------------+
| Context Pipeline | | Execution Engine |
| (Vector DB / Cache) | | (Retry / Fallback) |
+-----------+-----------+ +-----------+-----------+
| |
v v
+-----------------------+ +-----------------------+
| Qdrant / pgvector | | Primary & Secondary |
| Vector Database | | LLM APIs (OpenAI/Anth)|
+-----------------------+ +-----------+-----------+
|
v
+-----------------------+
| Output Guardrails & |
| Schema Enforcement |
+-----------+-----------+
|
v
+-----------------------+
| OpenTelemetry Sink |
| (Jaeger / Datadog) |
+-----------------------+
Key Components
- Orchestration Layer: Handles HTTP requests, authentication, request validation, and rate limiting.
- Context Engine: Retrieves semantically relevant data from vector stores or traditional database systems to populate the prompt context window.
- Execution Engine: Manages model providers, async pool management, transient failure retries, and multi-model fallback execution.
- Guardrails & Schema Validation: Transforms probabilistic string outputs from the LLM into strictly typed, verified JSON objects using Pydantic.
- Telemetry Layer: Emits traces, metrics, and token usage statistics to enterprise monitoring tools via OpenTelemetry.
2. Setting Up the Enterprise Python Environment
Enterprise services require explicit environment isolation, static analysis, and strict dependency pinning.
Create a new project using uv (or poetry) for dependency management:
uv init enterprise-ai-service
cd enterprise-ai-service
uv add fastapi uvicorn pydantic pydantic-settings openai tenacity qdrant-client opentelemetry-api opentelemetry-sdk structlog
Directory Structure
enterprise_ai/
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── core/
│ │ ├── config.py
│ │ ├── exceptions.py
│ │ └── telemetry.py
│ ├── schemas/
│ │ └── extraction.py
│ ├── services/
│ │ ├── llm_client.py
│ │ └── vector_store.py
│ └── api/
│ └── v1/
│ └── router.py
├── tests/
├── Dockerfile
└── pyproject.toml
3. Enforcing Determinism: Schema Validation & Structured Outputs
The biggest challenge in enterprise LLM engineering is non-determinism. Traditional downstream services expect rigid APIs (JSON schemas, SQL records). LLMs produce unstructured text by default.
To fix this, we enforce structured outputs at both the API level and model integration layer using Pydantic v2 and OpenAI’s Structured Outputs (JSON Schema mode).
Defining the Schema
Create app/schemas/extraction.py:
from enum import Enum
from typing import List, Optional
from pydantic import BaseModel, Field, ConfigDict
class RiskSeverity(str, Enum):
LOW = "LOW"
MEDIUM = "MEDIUM"
HIGH = "HIGH"
CRITICAL = "CRITICAL"
class IdentifiedRisk(BaseModel):
model_config = ConfigDict(extra="forbid")
category: str = Field(description="The functional domain of the risk (e.g., Security, Legal, Operational).")
description: str = Field(description="Concise analysis detailing the potential risk.")
severity: RiskSeverity = Field(description="Assessed severity level based on enterprise impact.")
mitigation_strategy: Optional[str] = Field(
default=None,
description="Recommended action item to reduce risk exposure."
)
class ContractAnalysisResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
document_id: str = Field(description="Unique identifier of the target document.")
executive_summary: str = Field(description="High-level overview of contract terms.")
overall_risk_score: float = Field(ge=0.0, le=10.0, description="Normalized risk score from 0.0 to 10.0.")
identified_risks: List[IdentifiedRisk] = Field(description="List of all extracted risk vectors.")
Engineering Note: Setting
extra="forbid"inConfigDictforces the model to adhere strictly to the declared JSON schema without introducing hallucinated top-level keys.
4. Building the Resilient Execution Engine
In production environments, remote APIs fail. Network timeouts, 429 rate limit errors, and 503 provider outages will happen. The LLM execution engine must implement exponential backoff with jitter and multi-provider fallbacks.
Configuration Management
Create app/core/config.py:
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
PROJECT_NAME: str = "Enterprise AI Analysis Engine"
ENVIRONMENT: str = "production"
# LLM Configuration
OPENAI_API_KEY: str
PRIMARY_MODEL: str = "gpt-4o"
FALLBACK_MODEL: str = "gpt-4o-mini"
MAX_RETRIES: int = 3
TIMEOUT_SECONDS: float = 30.0
settings = Settings()
Implementing the Resilience Engine
Create app/services/llm_client.py:
import structlog
from typing import Type, TypeVar
from pydantic import BaseModel
from openai import AsyncOpenAI, APIError, RateLimitError, APITimeoutError
from tenacity import (
retry,
stop_after_attempt,
wait_random_exponential,
retry_if_exception_type,
before_sleep_log
)
from app.core.config import settings
from app.core.exceptions import AIExecutionException
logger = structlog.get_logger(__name__)
T = TypeVar("T", bound=BaseModel)
class ResilientLLMClient:
"""Production wrapper for OpenAI API with retry logic, structured parsing, and multi-model fallback."""
def __init__(self):
self.client = AsyncOpenAI(
api_key=settings.OPENAI_API_KEY,
timeout=settings.TIMEOUT_SECONDS
)
@retry(
reraise=True,
stop=stop_after_attempt(settings.MAX_RETRIES),
wait=wait_random_exponential(min=1, max=10),
retry=retry_if_exception_type((RateLimitError, APITimeoutError)),
before_sleep=before_sleep_log(logger, log_level=10) # DEBUG
)
async def _execute_with_retry(
self,
model: str,
system_prompt: str,
user_prompt: str,
response_format: Type[T]
) -> T:
"""Executes API call with exponential backoff and jitter."""
response = await self.client.beta.chat.completions.parse(
model=model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
response_format=response_format,
temperature=0.1, # Low temperature for analytical precision
)
return response.choices[0].message.parsed
async def generate_structured_output(
self,
system_prompt: str,
user_prompt: str,
response_format: Type[T]
) -> T:
"""Executes LLM request using primary model, falling back to secondary model upon critical failure."""
try:
logger.info("Executing primary model invocation", model=settings.PRIMARY_MODEL)
return await self._execute_with_retry(
model=settings.PRIMARY_MODEL,
system_prompt=system_prompt,
user_prompt=user_prompt,
response_format=response_format
)
except APIError as primary_err:
logger.error(
"Primary model execution failed. Triggering fallback model execution.",
primary_model=settings.PRIMARY_MODEL,
fallback_model=settings.FALLBACK_MODEL,
error=str(primary_err)
)
try:
return await self._execute_with_retry(
model=settings.FALLBACK_MODEL,
system_prompt=system_prompt,
user_prompt=user_prompt,
response_format=response_format
)
except Exception as fallback_err:
logger.critical("Both primary and fallback models failed.", error=str(fallback_err))
raise AIExecutionException("Critical failure in execution engine.") from fallback_err
5. Integrating Retrieval-Augmented Generation (RAG)
In an enterprise environment, LLMs must answer questions based on internal domain context (e.g., enterprise documentation, internal wikis, or database records).
Here is how to set up an asynchronous context vector pipeline using Qdrant.
Vector Store Service Implementation
Create app/services/vector_store.py:
from typing import List
from qdrant_client import AsyncQdrantClient
from qdrant_client.http import models
from openai import AsyncOpenAI
from app.core.config import settings
class ContextRetrievalService:
"""Service to handle embedding generation and vector store retrieval operations."""
def __init__(self, qdrant_url: str = "http://localhost:6333"):
self.qdrant_client = AsyncQdrantClient(url=qdrant_url)
self.openai_client = AsyncOpenAI(api_key=settings.OPENAI_API_KEY)
self.embedding_model = "text-embedding-3-small"
async def generate_embeddings(self, text: str) -> List[float]:
"""Generate dense vector embeddings using OpenAI API."""
response = await self.openai_client.embeddings.create(
input=text,
model=self.embedding_model
)
return response.data[0].embedding
async def retrieve_context(self, collection_name: str, query: str, limit: int = 3) -> str:
"""Search vector database for top matching semantic context fragments."""
query_vector = await self.generate_embeddings(query)
search_result = await self.qdrant_client.search(
collection_name=collection_name,
query_vector=query_vector,
limit=limit
)
context_blocks = []
for hit in search_result:
payload_text = hit.payload.get("text_content", "")
context_blocks.append(f"[Document Chunk ID: {hit.id}]\n{payload_text}")
return "\n\n---\n\n".join(context_blocks)
6. Enterprise Observability: Distributed Tracing with OpenTelemetry
You cannot optimize what you do not measure. Enterprise AI systems need visibility into prompt tokens, completion tokens, overall latency, and retries.
Adding OpenTelemetry Instrumentation
Create app/core/telemetry.py:
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
from opentelemetry.sdk.resources import Resource
def setup_telemetry(service_name: str = "ai-analysis-service"):
resource = Resource.create(attributes={"service.name": service_name})
provider = TracerProvider(resource=resource)
# In production, swap ConsoleSpanExporter for OTLPSpanExporter (e.g. Datadog, Jaeger, Dynatrace)
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("enterprise_ai.tracer")
7. Putting It All Together: The FastAPI Microservice
Now, let’s assemble our schemas, execution engine, RAG pipeline, and observability layer into a production-grade FastAPI endpoint.
Create app/main.py:
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, Field
from app.core.config import settings
from app.core.telemetry import setup_telemetry, tracer
from app.schemas.extraction import ContractAnalysisResponse
from app.services.llm_client import ResilientLLMClient
from app.services.vector_store import ContextRetrievalService
from app.core.exceptions import AIExecutionException
# Initialize Telemetry
setup_telemetry()
app = FastAPI(
title=settings.PROJECT_NAME,
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# Dependency Injection Containers
def get_llm_client() -> ResilientLLMClient:
return ResilientLLMClient()
def get_vector_service() -> ContextRetrievalService:
return ContextRetrievalService()
class AnalysisRequest(BaseModel):
document_id: str = Field(..., example="doc_contract_9921")
user_query: str = Field(..., example="Extract key liability risks from this contract.")
@app.post(
"/api/v1/analyze-contract",
response_model=ContractAnalysisResponse,
status_code=200
)
async def analyze_contract(
request: AnalysisRequest,
llm_client: ResilientLLMClient = Depends(get_llm_client),
vector_service: ContextRetrievalService = Depends(get_vector_service)
):
"""Analyzes enterprise documents for operational risk factors using RAG and structured LLM outputs."""
with tracer.start_as_current_span("analyze_contract_transaction") as span:
span.set_attribute("document_id", request.document_id)
# 1. Fetch Relevant Context Vector Chunks
with tracer.start_as_current_span("retrieve_vector_context"):
retrieved_context = await vector_service.retrieve_context(
collection_name="enterprise_contracts",
query=request.user_query
)
if not retrieved_context:
raise HTTPException(status_code=404, detail="No relevant document context found.")
# 2. Construct Dynamic Prompt Strategy
system_prompt = (
"You are a Senior Risk Analyst for an enterprise organization. Analyze the provided contract context "
"and extract structured risk metrics strictly according to the defined JSON schema. "
"Do not hallucinate facts outside the provided document blocks."
)
user_prompt = f"Document Identifier: {request.document_id}\n\n" \
f"Context Information:\n{retrieved_context}\n\n" \
f"User Query Directive: {request.user_query}"
# 3. Execute Structured LLM Request with Guardrails
try:
with tracer.start_as_current_span("llm_structured_execution"):
result = await llm_client.generate_structured_output(
system_prompt=system_prompt,
user_prompt=user_prompt,
response_format=ContractAnalysisResponse
)
span.set_attribute("overall_risk_score", result.overall_risk_score)
return result
except AIExecutionException as e:
span.record_exception(e)
raise HTTPException(status_code=502, detail="AI processing upstream failure.")
8. Defensive Engineering: Sanitization & Security
Enterprise AI applications must be defended against prompt injection, data exfiltration, and context overflow attack vectors.
1. Data Anonymization (PII Scrubbing)
Before passing user input or DB records to an external LLM API, sensitive data (Social Security Numbers, Credit Card details, internal IP addresses) should be sanitized:
import re
def scrub_pii(text: str) -> str:
"""Basic regular expression pattern scrubbing for sensitive data before external transit."""
# Scrub SSN
text = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[REDACTED_SSN]', text)
# Scrub IPv4 Addresses
text = re.sub(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b', '[REDACTED_IP]', text)
return text
2. Token Budgeting Guardrails
Uncontrolled prompt length can exhaust your API quota or trigger high latencies. Truncate inputs dynamically to fit within safe working memory limits:
import tiktoken
def truncate_tokens(text: str, max_tokens: int = 4000, model: str = "gpt-4o") -> str:
"""Truncates text string to strict maximum token length."""
encoding = tiktoken.encoding_for_model(model)
tokens = encoding.encode(text)
if len(tokens) > max_tokens:
return encoding.decode(tokens[:max_tokens])
return text
9. Containerization for Production Deployment
To package your AI application for deployment to AWS ECS, Kubernetes (EKS), or Azure Container Instances, use multi-stage Docker builds to keep image sizes small and secure:
# Build Stage
FROM python:3.11-slim AS builder
WORKDIR /app
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1
RUN apt-get update && apt-get install -y --no-install-recommends build-essential && rm -rf /var/lib/apt/lists/*
RUN pip install uv
COPY pyproject.toml uv.lock ./
RUN uv pip install --system --no-cache -r pyproject.toml
# Production Final Stage
FROM python:3.11-slim AS runner
WORKDIR /app
# Run non-root user for enterprise runtime security
RUN addgroup --system appgroup && adduser --system --group appuser
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
COPY app ./app
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/docs || exit 1
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
10. Summary Checklist for Enterprise AI Applications
Moving from prototype to production requires passing these foundational engineering checkpoints:
| Engineering Pillar | Implementation Requirement |
|---|---|
| Output Determinism | Enforce schema validation using Pydantic models and Native JSON Schema capabilities (ConfigDict(extra="forbid")). |
| Resilience & SLAs | Use exponential backoff, jitter, and fallback model chains (e.g., GPT-4o $\rightarrow$ GPT-4o-mini). |
| Contextual Relevance | Implement asynchronous hybrid vector retrieval pipelines with strict token budgeting. |
| Observability | Emit distributed OpenTelemetry traces mapping total model execution time, prompt tokens, and completion costs. |
| Security & Compliance | Sanitize PII using input-scrubbing pre-processors and containerize services under non-root profiles. |
By following this architectural framework, you can build Python-based AI applications that are reliable, secure, observable, and ready for production enterprise workloads.