# didilili/shopkeeper-agent architecture

> Architecture diagram of the GitHub repository didilili/shopkeeper-agent, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-27). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/didilili/shopkeeper-agent
- Repository: https://github.com/didilili/shopkeeper-agent

## Overview

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: [`app/agent/nodes/recall_column.py`](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/recall_column.py) (Recall Data), [`app/services/meta_knowledge_service.py`](https://github.com/didilili/shopkeeper-agent/blob/main/app/services/meta_knowledge_service.py) (Meta Service), [`app/api/routers/query_router.py`](https://github.com/didilili/shopkeeper-agent/blob/main/app/api/routers/query_router.py) (Query Router), [`app/agent/graph.py`](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/graph.py) (Agent Graph)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_presentation["Presentation"]
  node_frontend_app["Frontend App<br/>react UI<br/>[App.tsx]"]
  node_frontend_api["API Client<br/>ui client<br/>[agentApi.ts]"]
end

subgraph group_api["API Layer"]
  node_query_router["Query Router<br/>http stream<br/>[query_router.py]"]
  node_api_wiring["API Wiring<br/>fastapi setup<br/>[dependencies.py]"]
  node_query_schema["Query Schema<br/>api contract<br/>[query_schema.py]"]
  node_query_result["Stream Result<br/>response stream<br/>[query_schema.py]"]
end

subgraph group_agent["Agent Runtime"]
  node_query_service["Query Service<br/>orchestration<br/>[query_service.py]"]
  node_agent_graph["Agent Graph<br/>langgraph state machine<br/>[graph.py]"]
  node_agent_state["Agent State<br/>workflow state<br/>[state.py]"]
  node_agent_context["Agent Context<br/>request context<br/>[context.py]"]
  node_extract_keywords["Extract Keywords<br/>node"]
  node_recall_data["Recall Data<br/>retrieval stage<br/>[recall_column.py]"]
  node_filter_merge["Filter & Merge<br/>context assembly<br/>[filter_table.py]"]
  node_generate_validate["SQL Reasoning<br/>sql pipeline<br/>[generate_sql.py]"]
  node_run_sql["Run SQL<br/>execution<br/>[run_sql.py]"]
end

subgraph group_knowledge["Knowledge Build"]
  node_meta_service["Meta Service<br/>knowledge builder"]
  node_meta_build_script["Build Script<br/>offline entrypoint"]
end

subgraph group_storage["Storage & External"]
  node_meta_mysql_repo[("Meta MySQL<br/>metadata store")]
  node_qdrant_repos[("Qdrant Repos<br/>vector index")]
  node_es_repo[("Value Search<br/>text index")]
  node_dw_mysql_repo[("DW MySQL<br/>sql warehouse")]
  node_llm_client["LLM Client<br/>model access<br/>[llm.py]"]
  node_embedding_client["Embedding Client<br/>embedding access"]
end

node_frontend_app -->|"calls"| node_frontend_api
node_frontend_api -->|"HTTP request"| node_query_router
node_query_router -->|"uses"| node_api_wiring
node_query_router -->|"encodes"| node_query_schema
node_query_router -->|"delegates"| node_query_service
node_query_service -->|"drives"| node_agent_graph
node_agent_graph -->|"mutates"| node_agent_state
node_agent_graph -->|"reads"| node_agent_context
node_agent_graph -->|"starts"| node_extract_keywords
node_extract_keywords -->|"feeds"| node_recall_data
node_recall_data -->|"supplies"| node_filter_merge
node_filter_merge -->|"prepares"| node_generate_validate
node_generate_validate -->|"invokes"| node_llm_client
node_generate_validate -->|"passes"| node_run_sql
node_run_sql -->|"executes on"| node_dw_mysql_repo
node_run_sql -->|"streams"| node_query_result
node_query_result -->|"renders"| node_frontend_app
node_meta_build_script -->|"runs"| node_meta_service
node_meta_service -->|"writes"| node_meta_mysql_repo
node_meta_service -->|"indexes"| node_qdrant_repos
node_meta_service -->|"indexes"| node_es_repo
node_meta_service -->|"embeds"| node_embedding_client
node_recall_data -->|"semantic search"| node_qdrant_repos
node_recall_data -->|"keyword search"| node_es_repo
node_recall_data -->|"structured lookup"| node_meta_mysql_repo

click node_frontend_app "https://github.com/didilili/shopkeeper-agent/blob/main/frontend/src/App.tsx"
click node_frontend_api "https://github.com/didilili/shopkeeper-agent/blob/main/frontend/src/lib/agentApi.ts"
click node_query_router "https://github.com/didilili/shopkeeper-agent/blob/main/app/api/routers/query_router.py"
click node_api_wiring "https://github.com/didilili/shopkeeper-agent/blob/main/app/api/dependencies.py"
click node_query_schema "https://github.com/didilili/shopkeeper-agent/blob/main/app/api/schemas/query_schema.py"
click node_query_service "https://github.com/didilili/shopkeeper-agent/blob/main/app/services/query_service.py"
click node_agent_graph "https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/graph.py"
click node_agent_state "https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/state.py"
click node_agent_context "https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/context.py"
click node_extract_keywords "https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/extract_keywords.py"
click node_recall_data "https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/recall_column.py"
click node_filter_merge "https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/filter_table.py"
click node_generate_validate "https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/generate_sql.py"
click node_run_sql "https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/run_sql.py"
click node_query_result "https://github.com/didilili/shopkeeper-agent/blob/main/app/api/schemas/query_schema.py"
click node_meta_service "https://github.com/didilili/shopkeeper-agent/blob/main/app/services/meta_knowledge_service.py"
click node_meta_build_script "https://github.com/didilili/shopkeeper-agent/blob/main/app/scripts/build_meta_knowledge.py"
click node_meta_mysql_repo "https://github.com/didilili/shopkeeper-agent/blob/main/app/repositories/mysql/meta/meta_mysql_repository.py"
click node_qdrant_repos "https://github.com/didilili/shopkeeper-agent/blob/main/app/repositories/qdrant/column_qdrant_repository.py"
click node_es_repo "https://github.com/didilili/shopkeeper-agent/blob/main/app/repositories/es/value_es_repository.py"
click node_dw_mysql_repo "https://github.com/didilili/shopkeeper-agent/blob/main/app/repositories/mysql/dw/dw_mysql_repository.py"
click node_llm_client "https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/llm.py"
click node_embedding_client "https://github.com/didilili/shopkeeper-agent/blob/main/app/clients/embedding_client_manager.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_frontend_app,node_frontend_api toneBlue
class node_query_router,node_api_wiring,node_query_schema,node_query_result toneAmber
class node_query_service,node_agent_graph,node_agent_state,node_agent_context,node_extract_keywords,node_recall_data,node_filter_merge,node_generate_validate,node_run_sql toneMint
class node_meta_service,node_meta_build_script toneRose
class node_meta_mysql_repo,node_qdrant_repos,node_es_repo,node_dw_mysql_repo,node_llm_client,node_embedding_client toneIndigo
```

## Components

### Presentation

Frontend client that visualizes the conversational workflow and results.

- [Frontend App](https://github.com/didilili/shopkeeper-agent/blob/main/frontend/src/App.tsx): react UI · React/Vite/Tailwind client that sends queries and renders steps, messages, and tables. · `frontend/src/App.tsx`
- [API Client](https://github.com/didilili/shopkeeper-agent/blob/main/frontend/src/lib/agentApi.ts): ui 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](https://github.com/didilili/shopkeeper-agent/blob/main/app/api/routers/query_router.py): http stream · Streaming query endpoint and SSE-style message boundary. · `app/api/routers/query_router.py`
- [API Wiring](https://github.com/didilili/shopkeeper-agent/blob/main/app/api/dependencies.py): fastapi setup · Dependency injection and lifespan initialization for the HTTP application. · `app/api/dependencies.py`
- [Query Schema](https://github.com/didilili/shopkeeper-agent/blob/main/app/api/schemas/query_schema.py): api contract · Request and response message schemas for query streaming. · `app/api/schemas/query_schema.py`
- [Stream Result](https://github.com/didilili/shopkeeper-agent/blob/main/app/api/schemas/query_schema.py): response stream · 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](https://github.com/didilili/shopkeeper-agent/blob/main/app/services/query_service.py): orchestration · Application service that coordinates the online question-answering flow. · `app/services/query_service.py`
- [Agent Graph](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/graph.py): langgraph state machine · Overall workflow definition for the question-answering pipeline. · `app/agent/graph.py`
- [Agent State](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/state.py): workflow state · Mutable state carried across retrieval, generation, validation, and execution steps. · `app/agent/state.py`
- [Agent Context](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/context.py): request context · Per-request context and execution metadata shared by nodes. · `app/agent/context.py`
- [Extract Keywords](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/extract_keywords.py): node · Derives search terms from the user question. · `app/agent/nodes/extract_keywords.py`
- [Recall Data](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/recall_column.py): retrieval stage · Hybrid retrieval stage that gathers column, metric, and value candidates. · `app/agent/nodes/recall_column.py`
- [Filter & Merge](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/filter_table.py): context assembly · Narrows candidates and merges retrieved evidence into usable context. · `app/agent/nodes/filter_table.py`
- [SQL Reasoning](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/generate_sql.py): sql pipeline · Generates SQL, validates it, and applies corrections when needed. · `app/agent/nodes/generate_sql.py`
- [Run SQL](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/nodes/run_sql.py): execution · 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](https://github.com/didilili/shopkeeper-agent/blob/main/app/services/meta_knowledge_service.py): knowledge builder · Coordinates extraction, syncing, and persistence of metadata knowledge. · `app/services/meta_knowledge_service.py`
- [Build Script](https://github.com/didilili/shopkeeper-agent/blob/main/app/scripts/build_meta_knowledge.py): offline entrypoint · 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](https://github.com/didilili/shopkeeper-agent/blob/main/app/repositories/mysql/meta/meta_mysql_repository.py): metadata store · Stores structured tables, columns, metrics, and mappings in the metadata database. · `app/repositories/mysql/meta/meta_mysql_repository.py`
- [Qdrant Repos](https://github.com/didilili/shopkeeper-agent/blob/main/app/repositories/qdrant/column_qdrant_repository.py): vector index · Stores and retrieves embeddings for columns and metrics. · `app/repositories/qdrant/column_qdrant_repository.py`
- [Value Search](https://github.com/didilili/shopkeeper-agent/blob/main/app/repositories/es/value_es_repository.py): text index · Stores field values for keyword and full-text retrieval. · `app/repositories/es/value_es_repository.py`
- [DW MySQL](https://github.com/didilili/shopkeeper-agent/blob/main/app/repositories/mysql/dw/dw_mysql_repository.py): sql warehouse · Executes analytical SQL against the teaching data warehouse. · `app/repositories/mysql/dw/dw_mysql_repository.py`
- [LLM Client](https://github.com/didilili/shopkeeper-agent/blob/main/app/agent/llm.py): model access · Abstraction over the chat model used for reasoning and SQL generation. · `app/agent/llm.py`
- [Embedding Client](https://github.com/didilili/shopkeeper-agent/blob/main/app/clients/embedding_client_manager.py): embedding access · Client manager for the TEI-based embedding service. · `app/clients/embedding_client_manager.py`

## Connections

- 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.
