How asm313/base_code_for_agentic_ai works
1. Overall shape
- This is a single Python backend service organized as a layered monolith, not a set of microservices.
- The runtime app lives under src/, while evals/ is a separate offline evaluation pipeline and grafana/ + prometheus/ are deployment-time observability configs.
2. Request entrypoint and API boundary
- src/main.py is the FastAPI bootstrap: it wires middleware, CORS, rate limiting, router registration, and startup/shutdown lifecycle.
- src/interface/router.py is the HTTP aggregation layer, and src/interface/auth.py plus src/interface/interaction.py hold the route handlers for auth and chat/agent interactions.
- This is the main boundary between external clients and the rest of the system.
3. Configuration and environment management
- src/config/settings.py centralizes environment-driven config: model selection, JWT secrets, database connection details, rate limits, and observability settings.
- The repo is designed to run across development/staging/production with different .env files and Docker Compose wiring.
4. Security and request safeguards
- Security is enforced before business logic through src/system/middleware.py, src/system/rate_limit.py, and src/utils/sanitization.py.
- src/utils/auth.py handles JWT minting and verification, while src/interface/auth.py uses those utilities to protect user/session operations.
- The architecture assumes per-request abuse control, input sanitation, and context-aware auth checks.
5. Data persistence layer
- src/data/models/ contains the persistence entities: user.py, session.py, thread.py, plus shared base/database definitions.
- src/data/schemas/ contains Pydantic DTOs for API contracts, keeping external payloads separate from database models.
- src/data/db_manager.py is the persistence boundary: connection/session management and CRUD coordination.
- schema.sql suggests the database can also be provisioned explicitly outside the ORM path.
6. Conversation and memory model
- The app distinguishes between users, chat sessions, and LangGraph threads/checkpoints.
- session is the user-facing conversation container; thread is the lower-level state anchor for graph persistence.
- This separation matters for architecture: user identity, chat history, and agent execution state are not the same thing.
7. Agent orchestration
- src/agent/workflow.py is the core agent graph/orchestration layer.
- src/agent/prompts/system.md holds the system prompt as a separate asset.
- src/agent/tools/web_search.py exposes an external tool for the agent, which means the agent can branch into tool execution rather than only generating text.
- The agent layer is responsible for prompt assembly, context handling, and tool-driven reasoning.
8. LLM service abstraction
- src/services/llm_provider.py is the model-facing service boundary.
- It isolates the rest of the app from direct provider calls, which is where retry/fallback behavior, model choice, and generation settings belong.
- In the overall flow, the agent does not call the provider directly; it goes through this service layer.
9. System utilities and observability
- src/system/logs.py provides structured logging, src/system/telemetry.py likely connects tracing/metrics, and src/system/middleware.py is where request context is attached.
- The repo is observability-heavy: the runtime path emits logs/metrics/traces so the agent behavior and system health can be monitored together.
- This aligns with the included langfuse, Prometheus, and Grafana support in the repo.
10. External services and infrastructure
- The main external dependencies that affect architecture are OpenAI for LLM inference, PostgreSQL for persistence, Langfuse for tracing/evaluation, and DuckDuckGo search for the web tool.
- The Docker setup uses a Postgres image with vector support in the README narrative, which implies the database is also part of long-term memory/state infrastructure.
- docker-compose.yml, Dockerfile, and the scripts/ folder show this project is meant to run as a containerized stack with supporting services.
11. Offline evaluation pipeline
- evals/ is separate from request serving and should be drawn as an asynchronous quality-control subsystem.
- evals/evaluator.py, evals/helpers.py, evals/main.py, and evals/metrics/prompts/*.md implement LLM-as-a-judge scoring over traces.
- The evaluation loop consumes observability data, computes quality metrics like helpfulness/relevancy/hallucination/toxicity, and reports results back into the monitoring workflow.
12. Monitoring and dashboards
- prometheus/prometheus.yml configures scraping, and grafana/dashboards/ defines dashboards as code.
- Operationally, metrics flow from the FastAPI service into Prometheus, then into Grafana for visualization.
- This is separate from app logic, but it is part of the production architecture because it closes the feedback loop on latency, reliability, and agent quality.
13. Typical end-to-end runtime flow
- A client request enters FastAPI → middleware applies logging/rate limiting/metrics → interface route validates auth/session → service layer fetches data and config → agent workflow prepares prompt/state/tools → LLM provider generates a response → results are returned to the client and persisted/traced.
- Separately, the eval pipeline can read traces and score them offline without being on the request path.
14. How to draw the diagram
- Use one central application box for src/.
- Draw four major internal lanes: interface/API, system/security, agent/LLM, and data persistence.
- Add external boxes for PostgreSQL, OpenAI, DuckDuckGo, Langfuse, Prometheus, and Grafana.
- Show evals/ as a sidecar/offline subsystem consuming traces rather than serving live traffic.
Main entry points: main.py FastAPI app · auth.py Auth routes · interaction.py Chat routes · workflow.py Agent workflow
Components 27
Runtime app
Live FastAPI service under src/
- FastAPI app · Wires middleware, routers, and lifecycle
src/main.py - API router · Aggregates public HTTP routes
src/interface/router.py - Auth routes · Login and session/user endpoints
src/interface/auth.py - Chat routes · Conversation and agent interaction endpoints
src/interface/interaction.py - Middleware · Request context, logging, and pre-processing
src/system/middleware.py - Rate limit · Per-request throttling and protection
src/system/rate_limit.py - Logging · Structured application logs
src/system/logs.py - Settings · Environment-driven app configuration
src/config/settings.py - JWT utils · Token minting and verification
src/utils/auth.py - Sanitization · Input cleanup and validation helpers
src/utils/sanitization.py - DB manager · Connection management and CRUD coordination
src/data/db_manager.py - Models · User, session, thread, and base database models
src/data/models - DTOs · Pydantic request and response contracts
src/data/schemas - Agent workflow · Prompt assembly, context handling, and tool use
src/agent/workflow.py - System prompt · Default system instructions for the agent
src/agent/prompts/system.md - Web search · External search tool for agent reasoning
src/agent/tools/web_search.py - LLM provider · Provider abstraction for generation calls
src/services/llm_provider.py
Offline evals
Asynchronous quality-control pipeline
- Eval runner · Entry point for trace-based evaluations
evals/main.py - Evaluator · Scores traces with LLM-as-judge metrics
evals/evaluator.py - Eval helpers · Shared evaluation utilities
evals/helpers.py
Observability
Metrics, dashboards, and tracing support
- Telemetry · Tracing and metrics hooks
src/system/telemetry.py - Prometheus · Scrapes service metrics
prometheus/prometheus.yml - Grafana · Operational dashboards as code
grafana/dashboards
Other components
- PostgreSQL · Persistent store for users, sessions, and threads
- OpenAI · External model inference provider
- DuckDuckGo · External web search backend
- Langfuse · Tracing and eval data backend
Connections 34
- FastAPI app → API router: registers
- FastAPI app → Middleware: installs
- FastAPI app → Rate limit: adds
- FastAPI app → Settings: loads
- FastAPI app → Telemetry: initializes
- Middleware → Logging: emits
- Middleware → Telemetry: attaches context
- API router → Auth routes: routes to
- API router → Chat routes: routes to
- Auth routes → JWT utils: verifies
- Auth routes → Sanitization: sanitizes
- Auth routes → DB manager: reads/writes
- Chat routes → Sanitization: sanitizes
- Chat routes → DB manager: reads/writes
- Chat routes → Agent workflow: invokes
- DB manager → Models: persists
- DB manager → PostgreSQL: stores in
- Models → PostgreSQL: schema for
- Auth routes → DTOs: uses
- Chat routes → DTOs: uses
- Agent workflow → System prompt: loads
- Agent workflow → Web search: tool use
- Agent workflow → LLM provider: calls
- Agent workflow → DB manager: fetches context
- LLM provider → OpenAI: requests generation
- Web search → DuckDuckGo: searches
- Telemetry → Langfuse: traces to
- Telemetry → Prometheus: exposes metrics
- Prometheus → Grafana: feeds
- Eval runner → Evaluator: runs
- Eval runner → Eval helpers: uses
- Eval runner → Langfuse: consumes traces
- Evaluator → OpenAI: judges with
- Evaluator → Langfuse: reports to