How didilili/shopkeeper-agent works
1. Repository purpose
- This is an end-to-end “e-commerce analytics question answering” system.
- Users ask natural-language questions, the backend retrieves relevant metadata, the agent generates and validates SQL, runs it against a data warehouse MySQL, and streams progress/results back to the UI.
2. Two main runtime paths
- Offline metadata knowledge build: extracts table/column/metric/value knowledge from source schemas and stores it in MySQL, Qdrant, and Elasticsearch.
- Online question answering: takes a user query, performs multi-stage retrieval and reasoning with LangGraph, generates SQL, executes it, and returns streamed events.
3. Backend API boundary
- app/api is the HTTP boundary, centered on query_router.py.
- The query endpoint exposes a streaming interaction model using SSE-style messages, with message types for progress, result, and error.
- FastAPI lifespan/dependency wiring is isolated in lifespan.py and dependencies.py.
4. Agent orchestration layer
- app/agent contains the LangGraph workflow that drives the question-answering pipeline.
- graph.py defines the overall state machine; state.py and context.py hold the agent state and request context.
- The workflow is decomposed into nodes under app/agent/nodes, each handling one step such as keyword extraction, retrieval, filtering, SQL generation, validation, correction, and execution.
5. Retrieval strategy and its boundaries
- The system uses hybrid retrieval rather than direct SQL generation from the LLM.
- Qdrant is used for semantic retrieval of column and metric knowledge.
- Elasticsearch is used for keyword/full-text retrieval of concrete field values.
- MySQL metadata tables remain the authoritative store for structured metadata and mappings.
6. Metadata knowledge subsystem
- app/services/meta_knowledge_service.py coordinates building and syncing the knowledge base.
- app/repositories/mysql/meta writes structured metadata into the meta database.
- app/repositories/qdrant stores embeddings for columns and metrics.
- app/repositories/es stores field values for text search.
- app/scripts/build_meta_knowledge.py is the main offline entrypoint for this pipeline.
7. Execution subsystem
- app/repositories/mysql/dw/dw_mysql_repository.py handles SQL execution against the teaching data warehouse MySQL.
- The agent does not just synthesize SQL; it validates and may correct it before execution.
- This keeps the “reasoning” part in the graph layer and the “data access” part in repository code.
8. Configuration and infrastructure
- Runtime settings live in conf/app_config.yaml and conf/meta_config.yaml, with .env used for secrets like the LLM API key.
- app/conf loads app and metadata config; app/core/context.py and app/core/log.py provide request-scoped logging support.
- Docker Compose under docker/docker-compose.yaml brings up MySQL, Elasticsearch, Qdrant, Kibana, and the embedding service.
9. LLM and embedding integration
- app/agent/llm.py and app/clients/embedding_client_manager.py abstract model access.
- The README indicates an OpenAI-compatible LLM endpoint and a TEI-based embedding service using BAAI/bge-large-zh-v1.5.
- This separation keeps model/provider choice out of the agent workflow itself.
10. Repository and domain model layering
- app/models contains SQLAlchemy ORM entities for persisted metadata.
- app/entities contains business-facing data objects used across services and agent nodes.
- app/repositories isolates storage-specific logic, while app/services composes repositories into application use cases.
11. Frontend boundary
- frontend/ is a separate React + Vite + Tailwind app.
- It sends queries to the backend API and renders both the conversational flow and tabular results.
- Components like StepRail, MessageBubble, and ResultTable suggest the UI is designed to visualize the agent’s execution steps, not just the final answer.
12. Overall data flow for a user query
- User input enters the FastAPI query endpoint.
- The agent extracts keywords, recalls columns/metrics/values, merges and filters context, generates SQL, validates/corrects it, then executes it on the warehouse.
- The response is streamed back to the frontend, which displays both intermediate progress and the final result.
13. Key architectural boundary to diagram
- Draw a clear split between:
- Offline knowledge construction: source schema/value extraction → meta stores/indexes
- Online inference and execution: API → LangGraph agent → SQL execution → streamed UI
- That separation is the core design of the repository.
14. What matters most for an architecture diagram
- External systems: MySQL (meta + DW), Qdrant, Elasticsearch, LLM API, embedding service.
- Internal layers: FastAPI API, LangGraph agent nodes, services/repositories, and the React frontend.
- The system is a pipeline-oriented AI application, not a simple chat app: retrieval, reasoning, SQL generation, validation, and execution are distinct stages.
Main entry points: recall_column.py Recall Data · meta_knowledge_service.py Meta Service · query_router.py Query Router · graph.py Agent Graph
Components 23
Presentation
Frontend client that visualizes the conversational workflow and results.
- Frontend App · React/Vite/Tailwind client that sends queries and renders steps, messages, and tables.
frontend/src/App.tsx - API Client · Browser-side query client and response formatting helpers.
frontend/src/lib/agentApi.ts
API Layer
FastAPI boundary for streaming question answering requests.
- Query Router · Streaming query endpoint and SSE-style message boundary.
app/api/routers/query_router.py - API Wiring · Dependency injection and lifespan initialization for the HTTP application.
app/api/dependencies.py - Query Schema · Request and response message schemas for query streaming.
app/api/schemas/query_schema.py - Stream Result · Streams progress, result, and error messages back to the client.
app/api/schemas/query_schema.py
Agent Runtime
LangGraph-based reasoning pipeline for retrieval, SQL generation, validation, and execution.
- Query Service · Application service that coordinates the online question-answering flow.
app/services/query_service.py - Agent Graph · Overall workflow definition for the question-answering pipeline.
app/agent/graph.py - Agent State · Mutable state carried across retrieval, generation, validation, and execution steps.
app/agent/state.py - Agent Context · Per-request context and execution metadata shared by nodes.
app/agent/context.py - Extract Keywords · Derives search terms from the user question.
app/agent/nodes/extract_keywords.py - Recall Data · Hybrid retrieval stage that gathers column, metric, and value candidates.
app/agent/nodes/recall_column.py - Filter & Merge · Narrows candidates and merges retrieved evidence into usable context.
app/agent/nodes/filter_table.py - SQL Reasoning · Generates SQL, validates it, and applies corrections when needed.
app/agent/nodes/generate_sql.py - Run SQL · Executes the final SQL against the warehouse.
app/agent/nodes/run_sql.py
Knowledge Build
Offline pipeline that builds and syncs metadata knowledge into search and vector stores.
- Meta Service · Coordinates extraction, syncing, and persistence of metadata knowledge.
app/services/meta_knowledge_service.py - Build Script · Main offline entrypoint for building metadata knowledge.
app/scripts/build_meta_knowledge.py
Storage & External
Persistent stores and external services used by the system.
- Meta MySQL · Stores structured tables, columns, metrics, and mappings in the metadata database.
app/repositories/mysql/meta/meta_mysql_repository.py - Qdrant Repos · Stores and retrieves embeddings for columns and metrics.
app/repositories/qdrant/column_qdrant_repository.py - Value Search · Stores field values for keyword and full-text retrieval.
app/repositories/es/value_es_repository.py - DW MySQL · Executes analytical SQL against the teaching data warehouse.
app/repositories/mysql/dw/dw_mysql_repository.py - LLM Client · Abstraction over the chat model used for reasoning and SQL generation.
app/agent/llm.py - Embedding Client · Client manager for the TEI-based embedding service.
app/clients/embedding_client_manager.py
Connections 25
- Frontend App → API Client: calls · UI sends user queries to the client wrapper.
- API Client → Query Router: HTTP request · Browser submits streaming query requests to the API.
- Query Router → API Wiring: uses · Router depends on FastAPI wiring and request-scoped dependencies.
- Query Router → Query Schema: encodes · Endpoint uses typed request and streaming message schemas.
- Query Router → Query Service: delegates · API boundary forwards query handling to the application service.
- Query Service → Agent Graph: drives · Service starts and monitors the LangGraph workflow.
- Agent Graph → Agent State: mutates · Workflow reads and updates shared agent state.
- Agent Graph → Agent Context: reads · Workflow uses request context during execution.
- Agent Graph → Extract Keywords: starts · Pipeline begins by extracting query keywords.
- Extract Keywords → Recall Data: feeds · Extracted terms seed hybrid retrieval.
- Recall Data → Filter & Merge: supplies · Retrieved candidates are filtered and merged into focused context.
- Filter & Merge → SQL Reasoning: prepares · Assembled evidence is used for SQL generation and validation.
- SQL Reasoning → LLM Client: invokes · LLM is used for generation and correction steps.
- SQL Reasoning → Run SQL: passes · Validated SQL is sent for execution.
- Run SQL → DW MySQL: executes on · Warehouse repository runs the SQL against MySQL.
- Run SQL → Stream Result: streams · Execution output is streamed back as progress/result/error messages.
- Stream Result → Frontend App: renders · Frontend displays streamed steps and final results.
- Build Script → Meta Service: runs · Offline entrypoint triggers knowledge construction.
- Meta Service → Meta MySQL: writes · Structured metadata is persisted to the metadata database.
- Meta Service → Qdrant Repos: indexes · Embeddings for columns and metrics are stored for semantic retrieval.
- Meta Service → Value Search: indexes · Concrete field values are stored for text search.
- Meta Service → Embedding Client: embeds · Knowledge build requests embeddings from the embedding service.
- Recall Data → Qdrant Repos: semantic search · Agent retrieves column and metric candidates from Qdrant.
- Recall Data → Value Search: keyword search · Agent retrieves value candidates from Elasticsearch.
- Recall Data → Meta MySQL: structured lookup · Agent consults authoritative metadata mappings in MySQL.