thanhnv2323 commited on
Commit
33340fe
·
1 Parent(s): 545ecb3

chore: update doc

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +11 -0
  2. docs/.gitkeep +0 -0
  3. docs/README.md +12 -0
  4. docs/images/ai persona - Functional diagram rag.png +0 -0
  5. docs/images/ai persona - System Architecture Overview.png +0 -0
  6. docs/images/ai persona -Functional diagram peft.png +0 -0
  7. docs/images/ai persona-Functional diagram overview.png +0 -0
  8. docs/images/functional_diagram.png +0 -0
  9. docs/md/design.md +214 -0
  10. docs/md/design/application/auth_service.md +41 -0
  11. docs/md/design/application/ingestion_service.md +48 -0
  12. docs/md/design/application/persona_configuration_service.md +43 -0
  13. docs/md/design/application/qa_service.md +42 -0
  14. docs/md/design/application/report_service.md +42 -0
  15. docs/md/design/application/rest_api_server.md +424 -0
  16. docs/md/design/application/rest_api_swagger.md +39 -0
  17. docs/md/design/communication/cache_client.md +47 -0
  18. docs/md/design/communication/event_broker.md +45 -0
  19. docs/md/design/communication/rpc_client.md +41 -0
  20. docs/md/design/core/conversation_memory.md +40 -0
  21. docs/md/design/core/explanation.md +41 -0
  22. docs/md/design/core/input_handler.md +35 -0
  23. docs/md/design/core/mcp_client.md +30 -0
  24. docs/md/design/core/mcp_server.md +47 -0
  25. docs/md/design/core/orchestrator.md +102 -0
  26. docs/md/design/core/persona_registry.md +38 -0
  27. docs/md/design/core/persona_router.md +39 -0
  28. docs/md/design/core/prompt_builder.md +56 -0
  29. docs/md/design/core/rag_pipeline.md +44 -0
  30. docs/md/design/core/system_prompt.md +44 -0
  31. docs/md/design/data_pipeline/document_ingestion_pipeline.md +39 -0
  32. docs/md/design/data_pipeline/extract_raw_models.md +27 -0
  33. docs/md/design/data_pipeline/extract_raw_utils.md +39 -0
  34. docs/md/design/data_pipeline/indicator_rag.md +58 -0
  35. docs/md/design/data_pipeline/pdf_renderer.md +46 -0
  36. docs/md/design/data_pipeline/persona_extraction_config.md +63 -0
  37. docs/md/design/data_pipeline/persona_extraction_pipeline.md +71 -0
  38. docs/md/design/data_pipeline/persona_merger.md +64 -0
  39. docs/md/design/data_pipeline/persona_reasoner.md +58 -0
  40. docs/md/design/data_pipeline/prompts.md +34 -0
  41. docs/md/design/data_pipeline/run_persona_extraction_cli.md +36 -0
  42. docs/md/design/data_pipeline/schema.md +51 -0
  43. docs/md/design/data_pipeline/vllm_openai_extractor.md +59 -0
  44. docs/md/design/frontend/chat_frontend.md +45 -0
  45. docs/md/design/integration/end_to_end_flow.md +38 -0
  46. docs/md/design/integration/index.md +11 -0
  47. docs/md/design/integration/local_dev_configuration.md +40 -0
  48. docs/md/design/integration/running_local_chat.md +47 -0
  49. docs/md/design/integration/running_persona_extraction.md +42 -0
  50. docs/md/design/integration/wiring_rag_into_orchestrator.md +48 -0
README.md CHANGED
@@ -1,3 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
1
  # 2025-P3-AI-Personas - Team 1
2
 
3
  <a target="_blank" href="https://cookiecutter-data-science.drivendata.org/">
 
1
+ ---
2
+ title: AI Persona Backend
3
+ emoji: "🤖"
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ base_path: /docs
9
+ pinned: false
10
+ ---
11
+
12
  # 2025-P3-AI-Personas - Team 1
13
 
14
  <a target="_blank" href="https://cookiecutter-data-science.drivendata.org/">
docs/.gitkeep ADDED
File without changes
docs/README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Generating the docs
2
+ ----------
3
+
4
+ Use [mkdocs](http://www.mkdocs.org/) structure to update the documentation.
5
+
6
+ Build locally with:
7
+
8
+ mkdocs build
9
+
10
+ Serve locally with:
11
+
12
+ mkdocs serve
docs/images/ai persona - Functional diagram rag.png ADDED
docs/images/ai persona - System Architecture Overview.png ADDED
docs/images/ai persona -Functional diagram peft.png ADDED
docs/images/ai persona-Functional diagram overview.png ADDED
docs/images/functional_diagram.png ADDED
docs/md/design.md ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # System design
2
+
3
+ ## Overview
4
+
5
+ The Lavazza AI Personas project is a comprehensive technical initiative undertaken in collaboration with Politecnico di Torino, aiming to transform static consumer segmentation studies into dynamic, conversational AI agents.
6
+
7
+ ## Requirements
8
+
9
+ The Lavazza AI Personas project is a comprehensive technical initiative aimed at creating dynamic, conversational AI agents that authentically represent Lavazza's customer segments.
10
+
11
+ The project requires the development of a bespoke system that balances authentic personality with factual accuracy and transparency, intentionally moving away from the common biases found in large commercial models.
12
+
13
+ ### I. Project Goal (Objective)
14
+
15
+ The overarching goal is to transform **static customer segmentation studies** into **dynamic, conversational AI agents**. These personas will serve as a next-generation consumer insights platform and a dynamic tool for market research, idea validation, and strategic decision-making within Lavazza.
16
+
17
+ Key strategic and ultimate goals include:
18
+
19
+ * **Accelerating Insights:** Providing marketing teams and researchers with a sparring partner to validate concepts, test campaigns, and gather consumer insights in real-time.
20
+ * **Trust and Transparency:** Building the solution **from scratch** to gain greater transparency over the models' logic and reduce the inherent bias found in pre-trained large commercial models (like ChatGPT), which often rely too heavily on generic information rather than proprietary Lavazza data.
21
+ * **Ultimate Deliverable:** Creating a **user-friendly chat frontend** through which internal teams can interact with the synthetic personas.
22
+
23
+ ### II. Key Project Requirements
24
+
25
+ The requirements are divided into functional (what the personas must achieve) and architectural/data (how the system must be built).
26
+
27
+ #### A. Persona Behavior and Functional Requirements
28
+
29
+ The project mandates specific, sophisticated behavioral requirements to ensure the personas are reliable and useful for critical business decisions:
30
+
31
+ | Requirement Category | Specific Mandates |
32
+ | :--- |:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
33
+ | **Factual Accuracy** | The algorithm must find and provide **precise, detailed answers** that are explicitly written within the source documentation. |
34
+ | **Non-Hallucination (Crucial)** | The personas must avoid fabrications or "hallucinations". If the persona lacks sufficient data on a topic, it is explicitly preferred that they answer: **"I don't have enough data on this topic"**. |
35
+ | **Authenticity and Tone** | Responses must be **coherent and consistent** with the specific segment description. The language should reflect the persona's defined style, based on real customer quotes and narratives stored in their profile. |
36
+ | **Critical Thinking** | The persona must be capable of providing **critical, negative feedback** or refusing ideas if they conflict with its profile, rather than simply trying to please the audience. This requires a deliberate engineering effort. |
37
+ | **Transparency (Explainability)** | The solution must allow the user to understand the LLM’s logic. It must have a **connection to the source** of the information, clearly indicating if the answer came from Lavazza's internal documentation or from generic external sources. |
38
+ | **Multimodal Input** | The chat interface must support processing **text, visuals, and PDF documents** (e.g., packaging designs, concept notes). |
39
+ | **Virtual Focus Groups** | The system must be able to simulate a **virtual focus group** by allowing users to interact with and receive simultaneous, separate feedback from multiple AI personas. |
40
+
41
+ #### B. Data and Foundation Requirements
42
+
43
+ The personas must be built on a reliable, proprietary data foundation:
44
+
45
+ 1. **Proprietary Segmentation Studies:** The primary source of qualitative insight is Lavazza's **Customer Segmentation Studies** (in PDF format), detailing nuanced descriptions and motivations of customer segments.
46
+ 2. **Quantitative Market Data:** The system must integrate tabular data, providing the quantitative backbone, including demographic profiles and behavioral patterns like purchase frequency and product preferences.
47
+ 3. **Data Extraction Challenge:** Significant effort is required to extract information from the PDF documentation, which includes numerous images and plots, to make it machine-readable for the LLM.
48
+ 4. **Unified Schema:** Data from heterogeneous sources must be synthesized into a **Unified Persona Profile Schema** (a JSON object) covering demographics, psychographics, behavioral data, and narrative/verbatim excerpts.
49
+
50
+ #### C. Technical and Enterprise Requirements
51
+
52
+ 1. **Architecture:** The recommended architecture is a **Hybrid RAG-Tuning Model** that uses:
53
+ * **Retrieval-Augmented Generation (RAG):** To provide factual grounding from the knowledge base, drastically reducing hallucination and enabling traceability.
54
+ * **Parameter-Efficient Fine-Tuning (PEFT), such as LoRA:** To instill the required personality, critical thinking style, and nuanced voice into the model.
55
+ 2. **Model Choice:** The system should utilize a state-of-the-art **open-source LLM** (e.g., Llama 3 or Mistral families) to ensure full control, prevent vendor lock-in, and maintain data security and privacy through local or private cloud deployment.
56
+
57
+ ## Project Structure
58
+
59
+ Implementation work follows the Cookiecutter Data Science layout already summarized in `README.md`, which keeps experimentation assets, production code, and documentation isolated yet connected. Highlights:
60
+
61
+ - **`adsp/`** – Houses the full implementation stack. Each module aligns with a layer from the architecture:
62
+ - `app/` – persona configuration, ingestion, reporting, Q&A, and auth services.
63
+ - `fe/` – frontend prototypes that connect authentication with the chat UI.
64
+ - `communication/` – RPC, cache, and event broker abstractions.
65
+ - `core/` – modular packages for the orchestrator, input processing, prompt construction, retrieval, persona routing, memory, and MCP-powered tool access.
66
+ - `data_pipeline/` – document ingestion, schema enforcement, transformations, and vector-store builders.
67
+ - `modeling/` – PEFT training utilities plus runtime inference adapters.
68
+ - `monitoring/` – evaluation harnesses and metrics collection.
69
+ - `storage/` / `utils/` – business DB, object storage, vector DB clients, logging, and exceptions.
70
+ - **`data/`** – Canonical storage for raw, interim, processed, and external datasets. It mirrors the ingestion and RAG pipelines by enforcing immutability of `raw/` inputs and reproducibility of downstream artifacts.
71
+ - **`docs/`** – Architectural material, including this design blueprint and `docs/folder_structure.md`, which keeps the README-aligned breakdown of every folder so engineers can quickly locate assets tied to each system capability.
72
+ - **`models/`, `reports/`, and `notebooks/`** – Hold serialized persona checkpoints, generated analysis, and exploratory research notebooks, respectively, ensuring model development and monitoring assets remain auditable.
73
+
74
+ Refer to `docs/folder_structure.md` whenever you need the full tree, naming conventions, or ownership expectations for a given path.
75
+
76
+ ## System Architecture
77
+
78
+ ### System Architecture Overview
79
+
80
+ ![](../images/ai%20persona%20-%20System%20Architecture%20Overview.png)
81
+
82
+ #### **1. User Interface (UI)**
83
+
84
+ The user interface serves as the system’s entry point, built as a **Frontend (FE)** application. It enables users to interact seamlessly with the platform, submit queries, upload data, and view results or reports.
85
+
86
+ #### **2. Application Layer**
87
+
88
+ This layer contains the core application logic and manages all user-driven workflows.
89
+
90
+ Key components include:
91
+
92
+ - **Persona Configuration:** Enables users to select or customize AI personas dynamically.
93
+ - **Ingestion Service:** Handles ingestion of raw data such as PDFs or images and stores them in **S3**.
94
+ - **Report Service:** Generates structured, formatted reports from processed and analyzed data.
95
+ - **Q&A Service:** Manages interactive question-and-answer exchanges with the AI.
96
+ - **Auth Service:** Provides authentication and authorization for users, ensuring secure access and operations.
97
+
98
+
99
+ #### **3. Communication Layer**
100
+
101
+ This layer facilitates efficient communication and coordination among microservices.
102
+
103
+ - **RPC Server:** Enables direct service-to-service communication via Remote Procedure Calls.
104
+ - **Cache:** A high-speed memory layer that stores frequently accessed data to optimize performance.
105
+ - **Event Broker / Message Queue (RabbitMQ or Kafka):** Handles asynchronous communication and event-driven processing across services, ensuring reliability, scalability, and robust monitoring.
106
+
107
+
108
+ #### **4. Core Layer**
109
+
110
+ The intelligence engine of the system—handles AI persona logic, LLM orchestration, and data-driven grounding.
111
+
112
+ - **Orchestrator:** The central coordinator of the Core Layer. When a request arrives, the Orchestrator manages the entire generation process, directing which services to call.
113
+ - **Input Handler:** Preprocesses and normalizes user inputs, including text extraction from PDFs and preparation of image data for AI analysis.
114
+ - **Prompt Construction:** Dynamically builds structured prompts by combining user input, persona rules, and retrieved data.
115
+ - **AI Persona Router:** Selects fine-tuned Large Language Models (LLMs) tailored to embody distinct customer segment personalities, generating output accordingly.
116
+ - **RAG (Retrieval-Augmented Generation):** Provides factual grounding by retrieving relevant information from the **Vector DB**, ensuring responses remain accurate.
117
+ - **Persona Registry:** Stores the static attributes and behavioral definitions of each persona, guiding prompt construction and response tone.
118
+ - **Explanation:** This module allows for an in-depth explanation of the thought process behind the reasoning model and the data used in the thinking process.
119
+ - **MCP Server (Model Context Protocol Server):** Enriches LLM interactions with real-time contextual or external domain data.
120
+ - **Memory:** It stores the recent history of the user's chat, allowing the persona to remember what was said earlier in the conversation and provide context-aware answers.
121
+
122
+
123
+ #### **5. Monitoring and Evaluation**
124
+
125
+ A centralized observability layer that tracks performance, quality, and reliability across all services.
126
+
127
+ - **Evaluation Tools:** Measure the accuracy and quality of AI responses and data processing outcomes.
128
+ - **Metrics & Alerting:** Monitor key indicators such as latency, error rates, resource utilization, and token usage, triggering alerts for anomalies or system degradation.
129
+
130
+
131
+ #### **6. Data Storage Layer**
132
+
133
+ The persistence foundation of the system, designed for scalability, durability, and speed.
134
+
135
+ - **Business Logic Database:** Stores structured data such as user profiles, authentication records, saved reports, and persona definitions.
136
+ - **Object Storage (S3):** Manages large, unstructured data files (e.g., raw PDFs, images, and uploaded datasets).
137
+ - **Vector Database:** Stores embeddings for persona-related documents, historical interactions, and reference materials — powering RAG retrieval and factual grounding.
138
+
139
+ ### Functional Diagram
140
+
141
+ #### 1. Process Flow Overview
142
+
143
+ ![](../images/ai%20persona-Functional%20diagram%20overview.png)
144
+
145
+ ##### 1. User Query Submission
146
+ - User sends a query with optional attached files (image, PDF, etc.) to the **Orchestrator**.
147
+
148
+ ###### 1.1 Orchestrator Analysis
149
+ - The Orchestrator analyzes the query and attachments to decide which services should be used.
150
+
151
+ ##### 2. Memory Integration
152
+ - Extract useful information from **chat history**.
153
+
154
+ ##### 3. Input Preprocessing
155
+ - Inputs are preprocessed before passing to the model.
156
+
157
+ ###### 3.1 Text Input
158
+ - Normalize text to make it easier to handle in later steps.
159
+
160
+ ###### 3.2 PDF Input
161
+ - Parse, process, and extract meaningful information from PDF files.
162
+
163
+ ###### 3.3 Image Input
164
+ - Process images and extract valuable information.
165
+
166
+ ##### 4. Context Retrieval (RAG System)
167
+ - Use the query and relevant input information to retrieve context (e.g., market data) via a **RAG system**.
168
+
169
+ ##### 5. Tool Selection & MCP Server Requests
170
+ - Decide which tools should be used to enrich the context.
171
+ - Send requests to the **MCP server** to gather corresponding context.
172
+
173
+ ###### 5.1 Web Search
174
+ - Extract updated information from the internet (trends, real-time data, missing internal data, etc.).
175
+
176
+ ###### 5.2 Database Query
177
+ - Retrieve useful data from internal or external databases.
178
+
179
+ ###### 5.3 External APIs
180
+ - Call APIs to obtain additional information.
181
+
182
+ ###### 5.4 Other Tools
183
+ - Use calculators, simulators, weather data extractors, or other utilities to enrich context.
184
+
185
+ ##### 6. Explanation
186
+ - The explanation module will explain in detail the thought process of the reasoning model and the data used for the thinking process.
187
+
188
+ ##### 7. Prompt Construction
189
+ - The Orchestrator aggregates useful context and passes it to **Prompt Construction**.
190
+
191
+ ##### 8. Persona Selection
192
+ - Apply the selected Persona profile, including:
193
+ - Demographics
194
+ - Behavior Data
195
+ - Transactional Data
196
+
197
+
198
+ ##### 9. Persona Model Routing
199
+ - Route to a fine-tuned Persona model.
200
+ - Pass the enriched prompt and context.
201
+
202
+ ##### 10. Model Response
203
+ - Generate a response with:
204
+ - Specific personality
205
+ - Tone
206
+ - Linguistic style of the Persona
207
+
208
+ #### 2. Background Processing - PEFT AI Personas
209
+
210
+ ![](../images/ai%20persona%20-Functional%20diagram%20peft.png)
211
+
212
+ #### 3. Background Processing - Rag Indexing
213
+
214
+ ![](../images/ai%20persona%20-%20Functional%20diagram%20rag.png)
docs/md/design/application/auth_service.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Application: `AuthService`
2
+
3
+ **Code**: `adsp/app/auth_service.py`
4
+
5
+ ## Purpose
6
+
7
+ `AuthService` provides a minimal authentication/authorization mechanism so UI clients can be gated before invoking persona workflows.
8
+
9
+ ## Responsibilities
10
+
11
+ - Store user → token bindings
12
+ - Validate access with token equality
13
+
14
+ ## Public API
15
+
16
+ ### `register(user: str, token: str) -> None`
17
+
18
+ Stores the token for a user in an in-memory dictionary.
19
+
20
+ ### `is_authorized(user: str, token: str) -> bool`
21
+
22
+ Returns `True` iff `token == stored_token_for_user`.
23
+
24
+ ## Data model
25
+
26
+ - `_tokens: Dict[str, str]` (in-memory)
27
+
28
+ ## Key dependencies / technologies
29
+
30
+ - Python `dataclasses`
31
+ - In-memory storage (`dict`)
32
+
33
+ ## Notes / production hardening
34
+
35
+ The architecture in `docs/md/design.md` expects secure auth; this stub should be replaced with:
36
+
37
+ - Identity provider / SSO integration (OIDC/SAML)
38
+ - Token verification (JWT signature + expiration)
39
+ - Role-based access control (RBAC) for persona sets / documents
40
+ - Persistence in the business database (`adsp/storage/business_db.py` or a real DB)
41
+
docs/md/design/application/ingestion_service.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Application: `IngestionService`
2
+
3
+ **Code**: `adsp/app/ingestion_service.py`
4
+
5
+ ## Purpose
6
+
7
+ `IngestionService` handles user-driven ingestion of files (PDFs/images/structured data). In the architecture, this is the application-layer entrypoint that persists uploads to object storage and triggers downstream processing.
8
+
9
+ ## Responsibilities
10
+
11
+ - Accept uploaded file paths
12
+ - Persist their bytes into object storage
13
+ - (Planned) emit events / enqueue jobs for downstream data pipelines
14
+
15
+ ## Public API
16
+
17
+ ### `ingest_files(files: Iterable[pathlib.Path]) -> None`
18
+
19
+ **Inputs**
20
+ - `files`: iterable of local file paths (already available on the host)
21
+
22
+ **Output**
23
+ - None (side-effect: writes to object store)
24
+
25
+ ## Internal logic (current)
26
+
27
+ For each `file_path`:
28
+ - Calls `adsp.storage.object_store.put(bucket, file_path)`
29
+
30
+ ## Storage interactions
31
+
32
+ - Object storage shim: `adsp/storage/object_store.py`
33
+ - `put(bucket: str, file_path: Path) -> None`
34
+
35
+ ## Key dependencies / technologies
36
+
37
+ - Python `dataclasses`
38
+ - `pathlib.Path`
39
+ - In-memory object store shim (to be replaced by S3/GCS/Azure Blob)
40
+
41
+ ## Notes / production hardening
42
+
43
+ - Add validation (file type, size limits, virus scanning).
44
+ - Replace `object_store` shim with S3-compatible client.
45
+ - Integrate with `EventBroker` / message queue to trigger:
46
+ - persona extraction pipeline
47
+ - RAG indexing pipeline
48
+
docs/md/design/application/persona_configuration_service.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Application: `PersonaConfigurationService`
2
+
3
+ **Code**: `adsp/app/persona_config.py`
4
+
5
+ ## Purpose
6
+
7
+ `PersonaConfigurationService` is the application-layer interface for creating and listing personas available to the system.
8
+
9
+ ## Responsibilities
10
+
11
+ - Register persona definitions (metadata + behavioral configuration)
12
+ - List available personas
13
+ - Retrieve persona definitions by id
14
+
15
+ ## Public API
16
+
17
+ ### `register_persona(persona_id: str, definition: dict) -> None`
18
+
19
+ Stores a persona definition in an in-memory dictionary.
20
+
21
+ ### `list_personas() -> list[str]`
22
+
23
+ Returns sorted persona IDs.
24
+
25
+ ### `get_persona(persona_id: str) -> dict`
26
+
27
+ Returns the persona definition; raises `KeyError` if missing.
28
+
29
+ ## Data model
30
+
31
+ - `_personas: Dict[str, Dict]` (in-memory)
32
+
33
+ ## Key dependencies / technologies
34
+
35
+ - Python `dataclasses`
36
+ - In-memory storage (`dict`)
37
+
38
+ ## Notes / integration
39
+
40
+ - The Core layer has its own `PersonaRegistry` (`adsp/core/persona_registry/__init__.py`). In production you typically unify these:
41
+ - Application layer writes persona definitions to a persistent store (business DB).
42
+ - Core layer loads and caches them for prompt construction + routing.
43
+
docs/md/design/application/qa_service.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Application: `QAService`
2
+
3
+ **Code**: `adsp/app/qa_service.py`
4
+
5
+ ## Purpose
6
+
7
+ `QAService` is the UI-facing entrypoint for interactive persona Q&A. It forwards queries into the Core layer’s orchestrator.
8
+
9
+ ## Responsibilities
10
+
11
+ - Receive `(persona_id, query)` from the frontend
12
+ - Invoke the Core orchestration pipeline and return the final text response
13
+
14
+ ## Public API
15
+
16
+ ### `ask(persona_id: str, query: str) -> str`
17
+
18
+ **Inputs**
19
+ - `persona_id`: persona to use for voice/routing
20
+ - `query`: the user question
21
+
22
+ **Output**
23
+ - `str` response (persona answer)
24
+
25
+ ## Internal logic (current)
26
+
27
+ 1. Creates a new `core.orchestrator.Orchestrator()`
28
+ 2. Calls `Orchestrator.handle_query(persona_id=persona_id, query=query)`
29
+
30
+ ## Key dependencies / technologies
31
+
32
+ - `adsp/core/orchestrator/__init__.py` (`Orchestrator`)
33
+ - Python `dataclasses`
34
+
35
+ ## Notes / production hardening
36
+
37
+ - The current implementation instantiates a new orchestrator per call; in production you would inject a long-lived orchestrator with configured dependencies (vector DB client, persona registry, cache, metrics).
38
+ - Add request metadata:
39
+ - `session_id` (for memory)
40
+ - `attachments` (PDF/image)
41
+ - `requested_personas[]` (for “virtual focus group” multi-persona fan-out)
42
+
docs/md/design/application/report_service.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Application: `ReportService`
2
+
3
+ **Code**: `adsp/app/report_service.py`
4
+
5
+ ## Purpose
6
+
7
+ `ReportService` generates stakeholder-friendly reports from computed persona insights.
8
+
9
+ ## Responsibilities
10
+
11
+ - Accept structured “insights” payloads
12
+ - Write report artifacts (currently markdown) to an output directory
13
+
14
+ ## Public API
15
+
16
+ ### `generate(persona_id: str, insights: dict) -> pathlib.Path`
17
+
18
+ **Inputs**
19
+ - `persona_id`: identifier used to name the report file
20
+ - `insights`: arbitrary dictionary to embed in the report body
21
+
22
+ **Output**
23
+ - Returns the filesystem path where the report was written:
24
+ - `{output_dir}/{persona_id}_report.md`
25
+
26
+ ## Internal logic (current)
27
+
28
+ 1. Constructs `report_path`
29
+ 2. Writes a markdown stub containing the `insights` dict (stringified)
30
+ 3. Returns `report_path`
31
+
32
+ ## Key dependencies / technologies
33
+
34
+ - Python `dataclasses`
35
+ - `pathlib.Path` file IO
36
+
37
+ ## Notes / production hardening
38
+
39
+ - Define a report schema (sections, citations, charts).
40
+ - Export to PDF/HTML and store in object storage.
41
+ - Add provenance: include evidence snippets and page citations from persona indicators.
42
+
docs/md/design/application/rest_api_server.md ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Application: REST API Server (FastAPI)
2
+
3
+ **Code**: `adsp/app/api_server.py`
4
+
5
+ ## Purpose
6
+
7
+ Expose the Application layer over HTTP so external clients (frontend/UI, tools, other services) can interact with:
8
+ - authentication
9
+ - persona discovery
10
+ - persona chat (Q&A)
11
+ - ingestion (upload)
12
+ - reports
13
+
14
+ The server is designed for local development and demos. It wires existing in-process services (`adsp/app/*`) and returns typed JSON responses.
15
+
16
+ ## Key technologies
17
+
18
+ - **FastAPI**: REST framework + OpenAPI generation
19
+ - **Pydantic**: request/response validation (reuses `adsp/core/types.py`)
20
+ - **Uvicorn**: ASGI server
21
+
22
+ Dependencies are declared in `requirements.txt` (`fastapi`, `uvicorn[standard]`).
23
+
24
+ ## Runtime architecture (in-process)
25
+
26
+ On startup, the API server creates and stores service singletons:
27
+
28
+ - `AuthService` (`adsp/app/auth_service.py`)
29
+ - `QAService` (`adsp/app/qa_service.py`) → uses Core orchestrator with local RAG + persona loading
30
+ - `IngestionService` (`adsp/app/ingestion_service.py`) → writes to `object_store` shim
31
+ - `ReportService` (`adsp/app/report_service.py`) → writes markdown to `reports/api/` by default
32
+ - `SurveyManager` (`adsp/core/survey/survey_manager.py`) → stores survey definitions
33
+ - `GroupGenerator` (`adsp/core/survey/group_generator.py`) → creates respondent groups
34
+ - `ResponseSynthesizer` (`adsp/core/survey/response_synthesizer.py`) → runs survey simulations and exports results
35
+
36
+ These are accessible to endpoints via a FastAPI dependency (`get_services()`).
37
+
38
+ ## Authentication model (dev)
39
+
40
+ If `ADSP_REQUIRE_AUTH=true`, protected endpoints require:
41
+ - `X-User: <user>`
42
+ - `X-Token: <token>`
43
+
44
+ Register tokens via:
45
+ - `POST /v1/auth/register`
46
+
47
+ When `ADSP_REQUIRE_AUTH` is unset/false, endpoints are open for local demo convenience.
48
+
49
+ ## Swagger / OpenAPI
50
+
51
+ - Swagger UI: `GET /docs`
52
+ - OpenAPI JSON: `GET /openapi.json`
53
+ - ReDoc: `GET /redoc`
54
+
55
+ ## Endpoints
56
+
57
+ ### System
58
+
59
+ - `GET /health`
60
+ - Response fields:
61
+ - `status`: API health indicator (`ok` when service is up)
62
+ - `version`: API version string
63
+ - `qa_status`: QA service warmup status (`idle|warming|ready|error`)
64
+ - Example:
65
+
66
+ ```bash
67
+ curl -X GET "http://localhost:8000/health"
68
+ ```
69
+
70
+ ### Auth
71
+
72
+ - `POST /v1/auth/register`
73
+ - Request fields:
74
+ - `user`: user identifier
75
+ - `token`: API token assigned to this user
76
+ - Response fields:
77
+ - `status`: registration result (`ok`)
78
+ - Example:
79
+
80
+ ```bash
81
+ curl -X POST "http://localhost:8000/v1/auth/register" \
82
+ -H "Content-Type: application/json" \
83
+ -d '{"user":"demo-user","token":"demo-token-123"}'
84
+ ```
85
+
86
+ - `POST /v1/auth/validate`
87
+ - Request fields:
88
+ - `user`: user identifier to validate
89
+ - `token`: token to validate
90
+ - Response fields:
91
+ - `authorized`: `true` when user/token pair matches registry
92
+ - Example:
93
+
94
+ ```bash
95
+ curl -X POST "http://localhost:8000/v1/auth/validate" \
96
+ -H "Content-Type: application/json" \
97
+ -d '{"user":"demo-user","token":"demo-token-123"}'
98
+ ```
99
+
100
+ ### Personas
101
+
102
+ - `GET /v1/personas`
103
+ - Response fields:
104
+ - `personas`: array of persona summaries
105
+ - `persona_id`: stable persona key
106
+ - `persona_name`: human-readable name
107
+ - `summary_bio`: short profile summary
108
+ - Example:
109
+
110
+ ```bash
111
+ curl -X GET "http://localhost:8000/v1/personas"
112
+ ```
113
+
114
+ - `GET /v1/personas/{persona_id}/profile`
115
+ - Path fields:
116
+ - `persona_id`: persona to retrieve
117
+ - Response fields:
118
+ - Full `PersonaProfileModel` payload (`adsp/data_pipeline/schema.py`)
119
+ - Example:
120
+
121
+ ```bash
122
+ curl -X GET "http://localhost:8000/v1/personas/curious-connoisseurs/profile"
123
+ ```
124
+
125
+ - `GET /v1/personas/{persona_id}/system-prompt`
126
+ - Path fields:
127
+ - `persona_id`: persona to retrieve
128
+ - Response fields:
129
+ - `system_prompt`: generated prompt string used by the orchestrator
130
+ - Example:
131
+
132
+ ```bash
133
+ curl -X GET "http://localhost:8000/v1/personas/curious-connoisseurs/system-prompt"
134
+ ```
135
+
136
+ ### Chat
137
+
138
+ - `POST /v1/chat`
139
+ - Request fields (`ChatRequest`):
140
+ - `persona_id`: target persona id
141
+ - `query`: user question
142
+ - `session_id`: optional session key
143
+ - `persona_display_name`: optional persona label
144
+ - `attachments`: optional list of attachment objects (`type`, `name`, `mime_type`, `payload`)
145
+ - `top_k`: retrieval depth
146
+ - `use_tools`: enable/disable tool use
147
+ - Response fields (`response: ChatResponse`):
148
+ - `persona_id`: persona used to answer
149
+ - `answer`: generated response text
150
+ - `context`: assembled retrieval context
151
+ - `citations`: evidence list
152
+ - `tool_calls`: tool execution trace
153
+ - Example:
154
+
155
+ ```bash
156
+ curl -X POST "http://localhost:8000/v1/chat" \
157
+ -H "Content-Type: application/json" \
158
+ -d '{
159
+ "persona_id":"curious-connoisseurs",
160
+ "query":"What matters most when buying coffee?",
161
+ "top_k":5,
162
+ "use_tools":false
163
+ }'
164
+ ```
165
+
166
+ ### Ingestion
167
+
168
+ - `POST /v1/ingestion/upload`
169
+ - Request fields:
170
+ - `filename`: target object key
171
+ - `content_base64`: Base64-encoded file payload
172
+ - `bucket`: optional destination bucket override
173
+ - Response fields:
174
+ - `bucket`: storage bucket used
175
+ - `key`: object key written
176
+ - `size_bytes`: decoded payload size
177
+ - Example:
178
+
179
+ ```bash
180
+ curl -X POST "http://localhost:8000/v1/ingestion/upload" \
181
+ -H "Content-Type: application/json" \
182
+ -d '{
183
+ "filename":"notes.txt",
184
+ "content_base64":"SGVsbG8gTGF2YXp6YSBBSSBQZXJzb25hcyE=",
185
+ "bucket":"uploads"
186
+ }'
187
+ ```
188
+
189
+ ### Reports
190
+
191
+ - `POST /v1/reports/{persona_id}`
192
+ - Path fields:
193
+ - `persona_id`: persona key used to name output report
194
+ - Request fields:
195
+ - `insights`: free-form insights object rendered to markdown
196
+ - Response fields:
197
+ - `path`: generated report path
198
+ - Example:
199
+
200
+ ```bash
201
+ curl -X POST "http://localhost:8000/v1/reports/curious-connoisseurs" \
202
+ -H "Content-Type: application/json" \
203
+ -d '{
204
+ "insights":{
205
+ "top_drivers":["taste","price","brand trust"],
206
+ "summary":"Segment values consistent quality and practical pricing."
207
+ }
208
+ }'
209
+ ```
210
+
211
+ ### Survey Simulation
212
+
213
+ - `GET /api/surveys`
214
+ - Query fields:
215
+ - `page`: 1-based page number (default `1`)
216
+ - `page_size`: items per page (default `20`, max `200`)
217
+ - Response fields:
218
+ - `items`: paged survey list (`survey_id`, `title`, `description`, `created_at`, `questions`)
219
+ - `paging`: metadata (`page`, `page_size`, `total_items`, `total_pages`)
220
+ - Example:
221
+
222
+ ```bash
223
+ curl -X GET "http://localhost:8000/api/surveys?page=1&page_size=20"
224
+ ```
225
+
226
+ - `POST /api/surveys`
227
+ - Request fields:
228
+ - `survey_id`: optional id (auto-generated if omitted)
229
+ - `title`: survey title
230
+ - `description`: survey objective
231
+ - `questions`: question array (`question_id`, `text`, `type`, optional `options`, optional `metadata`)
232
+ - Response fields:
233
+ - `survey_id`, `title`, `description`, `created_at`, `questions`
234
+ - Example:
235
+
236
+ ```bash
237
+ curl -X POST "http://localhost:8000/api/surveys" \
238
+ -H "Content-Type: application/json" \
239
+ -d '{
240
+ "survey_id":"coffee-pref-2026-q1",
241
+ "title":"Coffee Preference Survey",
242
+ "description":"Capture coffee purchase preferences.",
243
+ "questions":[
244
+ {
245
+ "question_id":"q1",
246
+ "text":"Which product claim matters most?",
247
+ "type":"multiple_choice",
248
+ "options":["Great taste","Affordable price","Sustainable sourcing"]
249
+ },
250
+ {
251
+ "question_id":"q2",
252
+ "text":"How likely are you to try a new blend?",
253
+ "type":"rating",
254
+ "metadata":{"scale":"1-5"}
255
+ }
256
+ ]
257
+ }'
258
+ ```
259
+
260
+ - `GET /api/surveys/{survey_id}`
261
+ - Path fields:
262
+ - `survey_id`: survey identifier
263
+ - Response fields:
264
+ - `survey_id`, `title`, `description`, `created_at`, `questions`
265
+ - `simulations`: all simulation runs for this survey
266
+ - `simulation_id`, `group_id`, `status`, `started_at`, `completed_at`
267
+ - `progress` (`completed`, `pending`)
268
+ - `responses_count`, `responses`, `statistics_ready`
269
+ - Example:
270
+
271
+ ```bash
272
+ curl -X GET "http://localhost:8000/api/surveys/coffee-pref-2026-q1"
273
+ ```
274
+
275
+ - `POST /api/groups`
276
+ - Request fields:
277
+ - `composition`: list of group parts (`persona_id`, `count`)
278
+ - `mode`: `random` or `llm`
279
+ - `sampling_ratio`: trait sampling ratio
280
+ - `include_names`: generate synthetic names flag
281
+ - `countries`: optional list of allowed countries (for example `["italy","france"]`)
282
+ - `seed`: optional deterministic seed
283
+ - Response fields:
284
+ - `group_id`, `created_at`, `total_respondents`, `composition`, `generation_method`, `sample_profiles`
285
+ - each generated profile includes `name`, `country`, `gender`, and `ethnicity`
286
+ - Example:
287
+
288
+ ```bash
289
+ curl -X POST "http://localhost:8000/api/groups" \
290
+ -H "Content-Type: application/json" \
291
+ -d '{
292
+ "composition":[
293
+ {"persona_id":"curious-connoisseurs","count":25},
294
+ {"persona_id":"conscious-explorers","count":15}
295
+ ],
296
+ "mode":"random",
297
+ "sampling_ratio":0.7,
298
+ "include_names":true,
299
+ "countries":["italy","france"],
300
+ "seed":42
301
+ }'
302
+ ```
303
+
304
+ - `GET /api/groups/countries`
305
+ - Purpose:
306
+ - Lists every country id supported by `POST /api/groups` in `countries`
307
+ - Response fields:
308
+ - `countries[]`: `country_id`, `display_name`, `description`
309
+ - Example:
310
+
311
+ ```bash
312
+ curl -X GET "http://localhost:8000/api/groups/countries"
313
+ ```
314
+
315
+ - `GET /api/groups`
316
+ - Query fields:
317
+ - `page`: 1-based page number (default `1`)
318
+ - `page_size`: items per page (default `20`, max `200`)
319
+ - Response fields:
320
+ - `items`: paged group list (`group_id`, `created_at`, `total_respondents`, `composition`, `generation_method`, `sample_profiles`)
321
+ - `paging`: metadata (`page`, `page_size`, `total_items`, `total_pages`)
322
+ - Example:
323
+
324
+ ```bash
325
+ curl -X GET "http://localhost:8000/api/groups?page=1&page_size=20"
326
+ ```
327
+
328
+ - `GET /api/groups/{group_id}`
329
+ - Path fields:
330
+ - `group_id`: group identifier
331
+ - Query fields:
332
+ - `include_full_profiles`: `true` to include full respondent payloads
333
+ - Response fields:
334
+ - `group_id`, `created_at`, `total_respondents`, `composition`, `generation_method`, `respondents`, `sample_profiles`
335
+ - Example:
336
+
337
+ ```bash
338
+ curl -X GET "http://localhost:8000/api/groups/group-ab12cd34?include_full_profiles=false"
339
+ ```
340
+
341
+ - `POST /api/surveys/{survey_id}/simulate`
342
+ - Path fields:
343
+ - `survey_id`: target survey id
344
+ - Query fields:
345
+ - `background`: when `true` (default), starts async run and returns immediately
346
+ - Request fields:
347
+ - `group_id`: source respondent group
348
+ - `batch_size`: processing batch size
349
+ - `format`: output format hint
350
+ - Response fields:
351
+ - `simulation_id`, `status`, `total_respondents`, `progress`, `estimated_time_minutes`
352
+ - `status` is `processing` while running and becomes `completed` after finish
353
+ - Example:
354
+
355
+ ```bash
356
+ curl -X POST "http://localhost:8000/api/surveys/coffee-pref-2026-q1/simulate?background=true" \
357
+ -H "Content-Type: application/json" \
358
+ -d '{
359
+ "group_id":"group-ab12cd34",
360
+ "batch_size":10,
361
+ "format":"json"
362
+ }'
363
+ ```
364
+
365
+ - `GET /api/surveys/{survey_id}/responses`
366
+ - Path fields:
367
+ - `survey_id`: target survey id
368
+ - Query fields:
369
+ - `simulation_id`: optional simulation id (latest when omitted)
370
+ - `format`: `csv` or `json`
371
+ - Response:
372
+ - File download (`text/csv` for `format=csv`, `application/json` for `format=json`)
373
+ - Example:
374
+
375
+ ```bash
376
+ curl -L -X GET "http://localhost:8000/api/surveys/coffee-pref-2026-q1/responses?format=csv" -o responses.csv
377
+ ```
378
+
379
+ - `GET /api/surveys/{survey_id}/statistics`
380
+ - Path fields:
381
+ - `survey_id`: target survey id
382
+ - Query fields:
383
+ - `simulation_id`: optional simulation id (latest when omitted)
384
+ - Notes:
385
+ - Statistics are computed only for `completed` simulations.
386
+ - The first computation is stored as cache per simulation and reused on subsequent calls.
387
+ - Response fields:
388
+ - `survey_id`, `simulation_id`, `total_respondents`, `total_responses`, `computed_at`, `questions`
389
+ - Per-question fields:
390
+ - `question_id`, `text`, `type`, `answered_count`, `response_rate`
391
+ - `choice_distribution` (`multiple_choice`)
392
+ - `rating_distribution`, `rating_average`, `rating_min`, `rating_max` (`rating`)
393
+ - `text_response_count`, `sample_text_responses` (`open_ended`)
394
+ - Example:
395
+
396
+ ```bash
397
+ curl -X GET "http://localhost:8000/api/surveys/coffee-pref-2026-q1/statistics?simulation_id=sim-1234abcd"
398
+ ```
399
+
400
+ ## How to run locally
401
+
402
+ ```bash
403
+ make install
404
+ python scripts/run_api.py
405
+ ```
406
+
407
+ Then open:
408
+ - `http://localhost:8000/docs`
409
+
410
+ ## Configuration
411
+
412
+ Environment variables (see `.env.example`):
413
+
414
+ - API:
415
+ - `ADSP_API_HOST` (default `0.0.0.0`)
416
+ - `ADSP_API_PORT` (default `8000`)
417
+ - `ADSP_API_RELOAD` (default `true`)
418
+ - `ADSP_REQUIRE_AUTH` (default `false`)
419
+ - Data paths:
420
+ - `ADSP_PERSONAS_DIR`
421
+ - `ADSP_PERSONA_TRAITS_DIR`
422
+ - Runtime LLM backend (optional):
423
+ - `ADSP_LLM_BACKEND=stub|openai`
424
+ - `ADSP_LLM_BASE_URL`, `ADSP_LLM_MODEL`, `ADSP_LLM_API_KEY`
docs/md/design/application/rest_api_swagger.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # REST API Swagger (OpenAPI)
2
+
3
+ The REST server is implemented with FastAPI, which generates the Swagger/OpenAPI specification at runtime:
4
+
5
+ - Swagger UI: `http://localhost:8000/docs`
6
+ - OpenAPI JSON: `http://localhost:8000/openapi.json`
7
+
8
+ ## Quick export (optional)
9
+
10
+ Once dependencies are installed, you can export the OpenAPI JSON to a file:
11
+
12
+ ```bash
13
+ python -c "from adsp.app.api_server import app; import json; print(json.dumps(app.openapi(), indent=2))" > openapi.json
14
+ ```
15
+
16
+ ## Contract summary
17
+
18
+ For the authoritative schema, use `/openapi.json`. The key routes are:
19
+
20
+ - `GET /health`
21
+ - `POST /v1/auth/register`
22
+ - `POST /v1/auth/validate`
23
+ - `GET /v1/personas`
24
+ - `GET /v1/personas/{persona_id}/profile`
25
+ - `GET /v1/personas/{persona_id}/system-prompt`
26
+ - `POST /v1/chat`
27
+ - `POST /v1/ingestion/upload`
28
+ - `POST /v1/reports/{persona_id}`
29
+ - `GET /api/surveys`
30
+ - `POST /api/surveys`
31
+ - `GET /api/surveys/{survey_id}`
32
+ - `GET /api/groups`
33
+ - `POST /api/groups`
34
+ - `GET /api/groups/countries`
35
+ - `GET /api/groups/{group_id}`
36
+ - `POST /api/surveys/{survey_id}/simulate`
37
+ - `GET /api/surveys/{survey_id}/responses`
38
+
39
+ All request/response fields now expose descriptions and examples directly in Swagger UI.
docs/md/design/communication/cache_client.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Communication: `CacheClient`
2
+
3
+ **Code**: `adsp/communication/cache.py`
4
+
5
+ ## Purpose
6
+
7
+ `CacheClient` provides a low-latency caching layer for frequently repeated computations (e.g., repeated persona answers for identical prompts).
8
+
9
+ ## Responsibilities
10
+
11
+ - Store computed values by string key
12
+ - Retrieve cached values
13
+
14
+ ## Public API
15
+
16
+ ### `get(key: str) -> Any | None`
17
+
18
+ Returns the cached value if present; otherwise `None`.
19
+
20
+ ### `set(key: str, value: Any) -> None`
21
+
22
+ Stores `value` under `key`.
23
+
24
+ ## Data model
25
+
26
+ - `_entries: Dict[str, Any]` (in-memory)
27
+
28
+ ## Current usage
29
+
30
+ Used by the Core orchestrator:
31
+ - `adsp/core/orchestrator/__init__.py` caches responses by `f"{persona_id}:{query}"`
32
+
33
+ ## Key dependencies / technologies
34
+
35
+ - Python `dataclasses`
36
+ - In-memory `dict`
37
+
38
+ ## Notes / production hardening
39
+
40
+ Replace the in-memory implementation with:
41
+ - Redis / Memcached
42
+ - Cache key strategy including:
43
+ - persona version / adapter version
44
+ - prompt template version
45
+ - retrieval context hash (to prevent stale grounding)
46
+ - TTLs and cache invalidation policies
47
+
docs/md/design/communication/event_broker.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Communication: `EventBroker`
2
+
3
+ **Code**: `adsp/communication/event_broker.py`
4
+
5
+ ## Purpose
6
+
7
+ `EventBroker` models the event-driven part of the architecture (`docs/md/design.md`) where ingestion and background jobs communicate asynchronously.
8
+
9
+ ## Responsibilities
10
+
11
+ - Allow subscribers to register callbacks for a topic
12
+ - Publish a payload to all subscribers for a topic
13
+
14
+ ## Public API
15
+
16
+ ### `subscribe(topic: str, handler: Callable) -> None`
17
+
18
+ Registers a handler to be called when `topic` receives a message.
19
+
20
+ ### `publish(topic: str, payload: dict) -> None`
21
+
22
+ Invokes all registered handlers for `topic` with `payload`.
23
+
24
+ ## Data model
25
+
26
+ - `_subscribers: DefaultDict[str, List[Callable]]` (in-memory)
27
+
28
+ ## Key dependencies / technologies
29
+
30
+ - Python `dataclasses`
31
+ - `collections.defaultdict`
32
+
33
+ ## Notes / production hardening
34
+
35
+ The architecture suggests RabbitMQ/Kafka. A production broker should provide:
36
+ - Durable queues/topics
37
+ - Retries, dead-letter queues
38
+ - Consumer groups / backpressure
39
+ - Observability (lag, throughput, failure counts)
40
+
41
+ Typical events in this system:
42
+ - `file_ingested` (object store key + metadata)
43
+ - `persona_extraction_requested` / `persona_extraction_completed`
44
+ - `rag_indexing_requested` / `rag_indexing_completed`
45
+
docs/md/design/communication/rpc_client.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Communication: `RPCClient`
2
+
3
+ **Code**: `adsp/communication/rpc.py`
4
+
5
+ ## Purpose
6
+
7
+ `RPCClient` is a placeholder for synchronous service-to-service calls (RPC/gRPC/HTTP) inside the platform.
8
+
9
+ ## Responsibilities
10
+
11
+ - Route a `(service, payload)` request to a resolved handler
12
+ - Return the handler’s response
13
+
14
+ ## Public API
15
+
16
+ ### `call(service: str, payload: dict) -> Any`
17
+
18
+ **Inputs**
19
+ - `service`: logical service name
20
+ - `payload`: request payload
21
+
22
+ **Output**
23
+ - Any response returned by the resolved handler
24
+
25
+ ## Internal logic (current)
26
+
27
+ 1. Calls `_resolver(service)` to get a callable handler
28
+ 2. Calls `handler(payload)` and returns the result
29
+
30
+ ## Key dependencies / technologies
31
+
32
+ - Python `dataclasses`
33
+ - Callable injection for `_resolver`
34
+
35
+ ## Notes / production hardening
36
+
37
+ Replace with:
38
+ - HTTP (FastAPI) or gRPC client stubs
39
+ - Typed request/response models (Pydantic/Protobuf)
40
+ - Timeouts, retries, tracing propagation
41
+
docs/md/design/core/conversation_memory.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: `ConversationMemory`
2
+
3
+ **Code**: `adsp/core/memory/__init__.py`
4
+
5
+ ## Purpose
6
+
7
+ `ConversationMemory` stores recent chat history so the persona can behave consistently across turns.
8
+
9
+ ## Responsibilities
10
+
11
+ - Append messages per persona
12
+ - Enforce a maximum history length
13
+ - Return history for context building (not yet wired into prompt construction)
14
+
15
+ ## Public API
16
+
17
+ ### `store(persona_id: str, message: dict) -> None`
18
+
19
+ Appends the message; evicts oldest entries once `max_items` is exceeded.
20
+
21
+ ### `get_history(persona_id: str) -> list[dict]`
22
+
23
+ Returns a copy of the history list for the persona.
24
+
25
+ ## Data model
26
+
27
+ - `_messages: DefaultDict[str, List[dict]]` (in-memory)
28
+ - `max_items: int` (default `10`)
29
+
30
+ ## Key dependencies / technologies
31
+
32
+ - Python `dataclasses`
33
+ - `collections.defaultdict`
34
+
35
+ ## Notes / production hardening
36
+
37
+ - Memory should be keyed by conversation/session (not only persona_id).
38
+ - Persist in a database for auditability and multi-instance deployments.
39
+ - Add summarization to fit token budgets.
40
+
docs/md/design/core/explanation.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: Explanation Module (Design)
2
+
3
+ **Architecture reference**: `docs/md/design.md` lists an “Explanation” module for transparency and traceability.
4
+
5
+ ## Purpose
6
+
7
+ The Explanation module provides user-visible justification for outputs:
8
+ - what evidence was retrieved (citations)
9
+ - what persona rules were applied
10
+ - what tool calls (MCP) were made
11
+ - why the system refused / said “not enough data” (non-hallucination)
12
+
13
+ ## Recommended API
14
+
15
+ Expose an explanation payload alongside the answer:
16
+
17
+ ```json
18
+ {
19
+ "answer": "string",
20
+ "citations": [
21
+ { "doc_id": "string", "pages": [1, 2], "snippet": "string", "score": 0.0 }
22
+ ],
23
+ "persona": { "persona_id": "string", "version": "string?" },
24
+ "retrieval": { "k": 5, "source": "vector_db|indicator_rag", "query": "string" },
25
+ "tool_calls": [ { "tool": "string", "payload": {}, "result_summary": "string" } ],
26
+ "safety": { "refusal": false, "not_enough_data": false }
27
+ }
28
+ ```
29
+
30
+ ## Integration points
31
+
32
+ - `Orchestrator.handle_query()` should return a structured response (not only a string) so explanation can be returned to the UI.
33
+ - `RAGPipeline` should return structured citations (doc/page) rather than only a context string.
34
+ - `MCPServer` should log tool calls and cache keys.
35
+
36
+ ## Key technologies (recommended)
37
+
38
+ - Typed models: Pydantic
39
+ - Logging/tracing: OpenTelemetry
40
+ - UI rendering: expandable “Evidence” panel showing citations and tool outputs
41
+
docs/md/design/core/input_handler.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: `InputHandler`
2
+
3
+ **Code**: `adsp/core/input_handler/__init__.py`
4
+
5
+ ## Purpose
6
+
7
+ `InputHandler` normalizes user inputs before retrieval and prompt building.
8
+
9
+ ## Responsibilities
10
+
11
+ - Normalize text input (current)
12
+ - (Planned) route and preprocess multimodal inputs:
13
+ - PDF text extraction + page selection
14
+ - Image preprocessing and OCR / captioning
15
+
16
+ ## Public API
17
+
18
+ ### `normalize(text: str) -> str`
19
+
20
+ **Input**
21
+ - raw text string
22
+
23
+ **Output**
24
+ - stripped text string (`text.strip()`)
25
+
26
+ ## Key dependencies / technologies
27
+
28
+ - Python `dataclasses`
29
+
30
+ ## Notes / production hardening
31
+
32
+ To meet `docs/md/design.md` multimodal requirements, expand this component with:
33
+ - PDF extraction via `pymupdf` (`fitz`) or `pdf2image` + OCR
34
+ - Attachment routing into the pipeline used in `adsp/data_pipeline/persona_data_pipeline/extract_raw/`
35
+
docs/md/design/core/mcp_client.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: `MCPClient`
2
+
3
+ **Code**: `adsp/core/mcp_server/tools/mcp_client.py`
4
+
5
+ ## Purpose
6
+
7
+ `MCPClient` is the client-side interface to request tool execution. Today it is a mock that echoes the request.
8
+
9
+ ## Responsibilities
10
+
11
+ - Provide a simple `request(tool, payload)` function
12
+ - (Planned) communicate with external tool servers/processes
13
+
14
+ ## Public API
15
+
16
+ ### `request(tool: str, payload: dict) -> dict`
17
+
18
+ Returns `{ "tool": tool, "payload": payload }`.
19
+
20
+ ## Key dependencies / technologies
21
+
22
+ - Python `dataclasses`
23
+
24
+ ## Notes / production hardening
25
+
26
+ Replace with:
27
+ - MCP-compatible transport (HTTP/websocket/stdin-stdio)
28
+ - Tool registry and authentication
29
+ - Structured tool schemas for safe calling
30
+
docs/md/design/core/mcp_server.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: `MCPServer`
2
+
3
+ **Code**: `adsp/core/mcp_server/__init__.py`, `adsp/core/mcp_server/tools/mcp_client.py`
4
+
5
+ ## Purpose
6
+
7
+ `MCPServer` is the Core component responsible for calling external “tools” via a Model Context Protocol-style interface and caching their responses.
8
+
9
+ In the architecture (`docs/md/design.md`), tool calls are used to enrich the model context with:
10
+ - web search
11
+ - database queries
12
+ - external APIs
13
+ - utilities (calculators, simulators, etc.)
14
+
15
+ ## Responsibilities
16
+
17
+ - Provide `run(tool, payload)` interface
18
+ - Cache tool responses by a deterministic key
19
+
20
+ ## Public API
21
+
22
+ ### `run(tool: str, payload: dict) -> dict`
23
+
24
+ **Inputs**
25
+ - `tool`: tool name (string identifier)
26
+ - `payload`: tool request payload
27
+
28
+ **Output**
29
+ - Tool response dict (cached for identical requests)
30
+
31
+ ## Internal logic (current)
32
+
33
+ 1. Creates `cache_key = f"{tool}:{tuple(sorted(payload.items()))}"`
34
+ 2. If `cache_key` not present, calls `MCPClient.request(tool, payload)` and stores the result
35
+ 3. Returns cached result
36
+
37
+ ## Key dependencies / technologies
38
+
39
+ - Python `dataclasses`
40
+ - Simple in-process caching (`dict`)
41
+
42
+ ## Notes / production hardening
43
+
44
+ - Deterministic keying should handle nested payloads and non-hashable types (current implementation assumes flat payload).
45
+ - Add timeouts, retries, rate limiting.
46
+ - Persist tool-call traces for explainability (“why did the model say this?”).
47
+
docs/md/design/core/orchestrator.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: `Orchestrator`
2
+
3
+ **Code**: `adsp/core/orchestrator/__init__.py`
4
+
5
+ ## Purpose
6
+
7
+ The Orchestrator is the Core layer’s coordinator. It turns a user query into a grounded, persona-voiced response by chaining preprocessing, retrieval, prompt construction, model routing, memory, and caching.
8
+
9
+ ## Responsibilities
10
+
11
+ - Provide a single “handle query” entrypoint to the Application layer (`QAService`)
12
+ - Orchestrate:
13
+ - input normalization
14
+ - retrieval (RAG)
15
+ - prompt construction
16
+ - persona model routing
17
+ - conversation memory writeback
18
+ - response caching
19
+
20
+ ## Public API
21
+
22
+ ### `handle_query(persona_id: str, query: str) -> str`
23
+
24
+ **Inputs**
25
+ - `persona_id`: persona identifier used for retrieval + routing
26
+ - `query`: raw user question text (current implementation assumes text-only)
27
+
28
+ **Output**
29
+ - Persona response string
30
+
31
+ ## Internal logic (current)
32
+
33
+ 1. **Cache lookup**
34
+ - `cache_key = f"{persona_id}:{session_id}:{query}"`
35
+ - Return cached value if present (`CacheClient.get`)
36
+ 2. **Normalize**
37
+ - `normalized = InputHandler.normalize(query)`
38
+ 3. **Retrieve context**
39
+ - `retrieved = RAGPipeline.retrieve_with_metadata(persona_id=persona_id, query=normalized, k=top_k)`
40
+ 4. **Filter for relevance**
41
+ - Filter conversation history and retrieved context down to what is relevant for the current question
42
+ - `filtered_history = ConversationContextFilter.filter_history(history, normalized)`
43
+ - `filtered_retrieved = ConversationContextFilter.filter_retrieved(retrieved, normalized)`
44
+ 5. **Build prompt**
45
+ - `prompt = PromptBuilder.build(persona_id=persona_id, query=normalized, context=filtered_retrieved.context, history=filtered_history)`
46
+ 6. **Dispatch to persona model**
47
+ - `response = PersonaRouter.dispatch(persona_id=persona_id, prompt=prompt)`
48
+ 7. **Persist memory**
49
+ - `ConversationMemory.store(persona_id=persona_id, message={"query": query, "response": response})`
50
+ 8. **Cache write**
51
+ - `CacheClient.set(cache_key, response)`
52
+
53
+ ## Inputs/outputs and extension points
54
+
55
+ The architecture (`docs/md/design.md`) calls for multimodal inputs (PDF/image). The orchestrator is the correct place to expand the request contract to:
56
+ - `attachments: list[{type, bytes|path|object_store_key}]`
57
+ - `session_id` or `conversation_id` (for memory)
58
+ - `requested_personas: list[str]` (virtual focus group fan-out)
59
+
60
+ ## Key dependencies / technologies
61
+
62
+ - Python `dataclasses`
63
+ - Core subcomponents:
64
+ - `adsp/core/input_handler/__init__.py` (`InputHandler`)
65
+ - `adsp/core/context_filter.py` (`ConversationContextFilter`)
66
+ - `adsp/core/rag/__init__.py` (`RAGPipeline`)
67
+ - `adsp/core/prompt_builder/__init__.py` (`PromptBuilder`)
68
+ - `adsp/core/ai_persona_router/__init__.py` (`PersonaRouter`)
69
+ - `adsp/core/memory/__init__.py` (`ConversationMemory`)
70
+ - Communication:
71
+ - `adsp/communication/cache.py` (`CacheClient`)
72
+
73
+ ## Observability / monitoring (recommended)
74
+
75
+ Wire `MetricsCollector` to capture:
76
+ - cache hit/miss
77
+ - retrieval latency and top-k
78
+ - model latency and token usage
79
+ - error counts by stage
80
+
81
+ ## Failure modes (current)
82
+
83
+ - Missing persona in `PersonaRegistry` → `KeyError` during prompt build
84
+ - Unconfigured model backend in the inference engine (stub today)
85
+ - Retrieval returns empty context (currently allowed; may degrade factuality)
86
+
87
+ ## Relevance filtering (config)
88
+
89
+ Relevance filtering is enabled by default and can be configured via environment variables:
90
+
91
+ - `ADSP_CONTEXT_FILTER_ENABLED`: `true`/`false` (default: `true`)
92
+ - `ADSP_CONTEXT_FILTER_BACKEND`: `heuristic` (default) or `openai`
93
+ - `ADSP_CONTEXT_FILTER_MAX_HISTORY`: max history turns to include (default: `4`)
94
+ - `ADSP_CONTEXT_FILTER_MAX_BLOCKS`: max retrieved context blocks to include (default: `3`)
95
+ - `ADSP_CONTEXT_FILTER_MIN_COVERAGE`: minimum token coverage threshold (default: `0.2`)
96
+ - `ADSP_CONTEXT_FILTER_TIMEOUT`: LLM selection timeout in seconds (default: `20`)
97
+
98
+ Optional OpenAI-compatible backend settings (when `ADSP_CONTEXT_FILTER_BACKEND=openai`):
99
+
100
+ - `ADSP_CONTEXT_FILTER_BASE_URL` (defaults to `ADSP_LLM_BASE_URL` / `VLLM_BASE_URL`)
101
+ - `ADSP_CONTEXT_FILTER_MODEL` (defaults to `ADSP_LLM_MODEL` / `VLLM_MODEL`)
102
+ - `ADSP_CONTEXT_FILTER_API_KEY` (defaults to `ADSP_LLM_API_KEY` / `VLLM_API_KEY`)
docs/md/design/core/persona_registry.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: `PersonaRegistry`
2
+
3
+ **Code**: `adsp/core/persona_registry/__init__.py`
4
+
5
+ ## Purpose
6
+
7
+ `PersonaRegistry` stores persona metadata used by the Core layer for prompt construction and routing decisions.
8
+
9
+ ## Responsibilities
10
+
11
+ - Maintain a catalog of persona metadata keyed by `persona_id`
12
+ - Provide read access for prompt building
13
+
14
+ ## Public API
15
+
16
+ ### `get(persona_id: str) -> dict`
17
+
18
+ Returns persona metadata dict, raises `KeyError` if missing.
19
+
20
+ ### `upsert(persona_id: str, metadata: dict) -> None`
21
+
22
+ Stores/replaces metadata for the persona.
23
+
24
+ ## Default persona
25
+
26
+ On initialization, the registry contains:
27
+ - `default`: `{ "preamble": "You are a Lavazza persona who is transparent and data-grounded." }`
28
+
29
+ ## Key dependencies / technologies
30
+
31
+ - Python `dataclasses`
32
+ - In-memory `dict`
33
+
34
+ ## Notes / integration
35
+
36
+ Production architecture typically sources persona definitions from the extracted persona profile JSON (`data/processed/personas/`) or a business database. A common pattern is:
37
+ - Load persona profiles at startup (or on demand) and `upsert` them into the registry.
38
+
docs/md/design/core/persona_router.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: `PersonaRouter`
2
+
3
+ **Code**: `adsp/core/ai_persona_router/__init__.py`
4
+
5
+ ## Purpose
6
+
7
+ `PersonaRouter` selects the appropriate model or adapter for a given persona and dispatches the prompt to the inference engine.
8
+
9
+ ## Responsibilities
10
+
11
+ - Choose an inference path per `persona_id`
12
+ - Send prompt to the runtime inference engine
13
+
14
+ ## Public API
15
+
16
+ ### `dispatch(persona_id: str, prompt: str) -> str`
17
+
18
+ **Inputs**
19
+ - `persona_id`: used to select adapter/model
20
+ - `prompt`: prompt string produced by `PromptBuilder`
21
+
22
+ **Output**
23
+ - persona response string
24
+
25
+ ## Internal logic (current)
26
+
27
+ - Delegates to `PersonaInferenceEngine.generate(persona_id, prompt)`
28
+
29
+ ## Key dependencies / technologies
30
+
31
+ - `adsp/modeling/inference.py` (`PersonaInferenceEngine`)
32
+
33
+ ## Notes / production hardening
34
+
35
+ In production, this component typically:
36
+ - maps `persona_id` → adapter checkpoint (LoRA) or fine-tuned model endpoint
37
+ - supports multiple backends (local `transformers`, vLLM, TGI, etc.)
38
+ - applies safety and decoding policies consistently
39
+
docs/md/design/core/prompt_builder.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: `PromptBuilder`
2
+
3
+ **Code**: `adsp/core/prompt_builder/__init__.py`, `adsp/core/prompt_builder/system_prompt.py`
4
+
5
+ ## Purpose
6
+
7
+ `PromptBuilder` constructs the final prompt sent to a persona model by combining:
8
+ - persona rules/traits
9
+ - retrieved grounding context
10
+ - user question
11
+
12
+ ## Responsibilities
13
+
14
+ - Retrieve persona metadata from `PersonaRegistry`
15
+ - Convert persona profiles into a system prompt (including reasoning traits when present)
16
+ - Assemble a single string prompt for the model
17
+
18
+ ## Public API
19
+
20
+ ### `build(persona_id: str, query: str, context: str) -> str`
21
+
22
+ **Inputs**
23
+ - `persona_id`: persona to load from the registry
24
+ - `query`: normalized user question
25
+ - `context`: retrieval grounding text (already formatted)
26
+
27
+ **Output**
28
+ - String prompt:
29
+ - system prompt + `Context:` + `Question:`
30
+
31
+ ## Internal logic (current)
32
+
33
+ 1. `persona = PersonaRegistry.get(persona_id)`
34
+ 2. `system_prompt = _system_prompt_for_persona(persona)`
35
+ 3. Returns:
36
+ - `{system_prompt}\n\nContext:\n{context}\n\nQuestion:\n{query}`
37
+
38
+ ## Persona profile handling
39
+
40
+ `_system_prompt_for_persona()` supports:
41
+ - `PersonaProfileModel` (Pydantic) → `persona_to_system_prompt(profile)`
42
+ - `dict`:
43
+ - if it looks like a profile with reasoning traits, attempt to validate as `PersonaProfileModel`
44
+ - else fallback to `persona["preamble"]` or `"You are an AI persona."`
45
+
46
+ ## Key dependencies / technologies
47
+
48
+ - `pydantic` (`ValidationError`)
49
+ - `adsp/data_pipeline/schema.py` (`PersonaProfileModel`)
50
+ - `PersonaRegistry` (`adsp/core/persona_registry/__init__.py`)
51
+
52
+ ## Notes / production hardening
53
+
54
+ - Return structured prompt objects (`{system, user, context}`) rather than concatenated strings to better support chat-based LLM APIs.
55
+ - Add citation formatting to ensure explainability requirements are met (page refs + doc ids).
56
+
docs/md/design/core/rag_pipeline.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: `RAGPipeline`
2
+
3
+ **Code**: `adsp/core/rag/__init__.py`
4
+
5
+ ## Purpose
6
+
7
+ `RAGPipeline` provides factual grounding by retrieving relevant context from the vector store given `(persona_id, query)`.
8
+
9
+ ## Responsibilities
10
+
11
+ - Query the vector store for relevant evidence
12
+ - Return a context string to inject into prompt construction
13
+
14
+ ## Public API
15
+
16
+ ### `retrieve(persona_id: str, query: str) -> str`
17
+
18
+ **Inputs**
19
+ - `persona_id`: persona scope for retrieval
20
+ - `query`: normalized user query
21
+
22
+ **Output**
23
+ - context string
24
+
25
+ ## Internal logic (current)
26
+
27
+ - Delegates to `VectorDatabase.search(persona_id, query)`
28
+
29
+ ## Key dependencies / technologies
30
+
31
+ - `adsp/storage/vector_db.py` (`VectorDatabase`) — currently an in-memory stub
32
+
33
+ ## Recommended upgrade path
34
+
35
+ This repo also contains a more realistic RAG component (LangChain-based):
36
+ - `adsp/data_pipeline/persona_data_pipeline/rag/indicator.py` (`PersonaIndicatorRAG`)
37
+
38
+ A practical integration pattern:
39
+ 1. Load persona profiles (`PersonaProfileModel`) and index indicators into a vector store.
40
+ 2. At query time, run similarity search and convert `Document[]` to a prompt-ready context string.
41
+ 3. Return both context and structured citations for explainability.
42
+
43
+ See: `docs/md/design/integration/wiring_rag_into_orchestrator.md`
44
+
docs/md/design/core/system_prompt.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core: `persona_to_system_prompt`
2
+
3
+ **Code**: `adsp/core/prompt_builder/system_prompt.py`
4
+
5
+ ## Purpose
6
+
7
+ `persona_to_system_prompt()` converts a persona profile (including optional reasoning traits) into an LLM system prompt that steers voice, values, and guardrails.
8
+
9
+ ## Responsibilities
10
+
11
+ - Generate consistent persona “system” instructions
12
+ - Encode:
13
+ - voice/style (`style_profile`)
14
+ - value priorities (`value_frame`)
15
+ - reasoning tradeoffs (`reasoning_policies`)
16
+ - content guardrails (`content_filters`)
17
+
18
+ ## Public API
19
+
20
+ ### `persona_to_system_prompt(persona: PersonaProfileModel) -> str`
21
+
22
+ **Input**
23
+ - `PersonaProfileModel` (see `adsp/data_pipeline/schema.py`)
24
+
25
+ **Output**
26
+ - Multi-section system prompt string
27
+
28
+ ## Sections emitted
29
+
30
+ - Header: persona label and `summary_bio`
31
+ - `Voice:` section (if `style_profile` present)
32
+ - `Value frame:` section (if `value_frame` present)
33
+ - `Reasoning policies:` section (if `reasoning_policies` present)
34
+ - `Content filters:` section (if `content_filters` present)
35
+
36
+ ## Key dependencies / technologies
37
+
38
+ - `pydantic` models from `adsp/data_pipeline/schema.py`
39
+
40
+ ## Notes
41
+
42
+ - This function is intentionally strict about missing data: if a trait section is absent, it is omitted from the prompt instead of being fabricated.
43
+ - If the reasoning enrichment pipeline is disabled, prompts will contain only the baseline persona header unless other fields are present.
44
+
docs/md/design/data_pipeline/document_ingestion_pipeline.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: `DocumentIngestionPipeline`
2
+
3
+ **Code**: `adsp/data_pipeline/ingestion.py`
4
+
5
+ ## Purpose
6
+
7
+ `DocumentIngestionPipeline` is a minimal ingestion pipeline that persists uploaded files into object storage. It matches the first step of the platform’s background processing: turning UI uploads into durable artifacts for extraction/indexing.
8
+
9
+ ## Responsibilities
10
+
11
+ - Accept a set of file paths
12
+ - Store each file in object storage under the configured bucket
13
+
14
+ ## Public API
15
+
16
+ ### `run(files: Iterable[pathlib.Path]) -> None`
17
+
18
+ **Inputs**
19
+ - `files`: iterable of local filesystem paths
20
+
21
+ **Outputs**
22
+ - None (side effect: object store write)
23
+
24
+ ## Internal logic (current)
25
+
26
+ For each file:
27
+ - `adsp.storage.object_store.put(bucket, file_path)`
28
+
29
+ ## Key dependencies / technologies
30
+
31
+ - Python `dataclasses`
32
+ - `pathlib.Path`
33
+ - `adsp/storage/object_store.py`
34
+
35
+ ## Notes / production hardening
36
+
37
+ - In a real deployment, this pipeline would likely be invoked asynchronously from an event broker after `IngestionService` emits an event.
38
+ - Add metadata capture (doc_id, upload time, uploader, checksum) and store it in the business database.
39
+
docs/md/design/data_pipeline/extract_raw_models.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: Page Models (`PageImage`, `PageExtractionResult`)
2
+
3
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/models.py`
4
+
5
+ ## Purpose
6
+
7
+ Provides minimal typed containers for:
8
+ - rendered page images
9
+ - extraction results per page
10
+
11
+ ## Models
12
+
13
+ ### `PageImage`
14
+
15
+ Fields:
16
+ - `page_number: int` (1-based)
17
+ - `image_path: Path`
18
+ - `width: int`, `height: int`
19
+
20
+ ### `PageExtractionResult`
21
+
22
+ Fields:
23
+ - `page_number: int`
24
+ - `raw_text: str` (raw model output)
25
+ - `parsed: dict | None` (best-effort parsed JSON payload)
26
+ - `error: str | None` (capture parsing/extraction failures)
27
+
docs/md/design/data_pipeline/extract_raw_utils.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: Extraction Utilities
2
+
3
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/utils.py`
4
+
5
+ ## Purpose
6
+
7
+ Helper functions used by the extraction pipeline to improve model interoperability and robustness.
8
+
9
+ ## `strip_json_markdown(text: str) -> str`
10
+
11
+ **Goal**
12
+ - Models frequently return JSON wrapped in markdown fences (```json ... ```). This helper extracts the JSON body.
13
+
14
+ **Behavior**
15
+ - If no fences: returns stripped text
16
+ - If fences present:
17
+ - splits on ``` blocks
18
+ - prefers a block starting with `{` or `[` (or the largest block)
19
+
20
+ ## `encode_image_base64(image_path: Path, max_bytes: int | None) -> (str, str)`
21
+
22
+ **Goal**
23
+ - Encode images as base64 for OpenAI “image_url” content.
24
+ - Compress to stay under request payload limits.
25
+
26
+ **Behavior**
27
+ - If raw PNG bytes <= `max_bytes`, return base64 PNG
28
+ - Else:
29
+ - try converting to JPEG at decreasing quality
30
+ - if still too large, downscale gradually and re-encode
31
+ - fallback to raw PNG on any errors
32
+
33
+ **Output**
34
+ - `(base64_string, mime_type)` where mime is `"image/png"` or `"image/jpeg"`
35
+
36
+ **Dependencies**
37
+ - Uses `Pillow` when compression is needed
38
+ - Logs decisions via `loguru`
39
+
docs/md/design/data_pipeline/indicator_rag.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: `PersonaIndicatorRAG`
2
+
3
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/rag/indicator.py`
4
+
5
+ ## Purpose
6
+
7
+ `PersonaIndicatorRAG` provides a retrieval system over persona indicators using LangChain primitives. It is a more realistic implementation of the RAG concept than the Core `VectorDatabase` stub.
8
+
9
+ ## Responsibilities
10
+
11
+ - Render each persona’s indicators into text “documents”
12
+ - Embed and store them in a vector store
13
+ - Provide similarity search and retriever interfaces
14
+ - Convert retrieved documents into a prompt-ready context string
15
+
16
+ ## Public API
17
+
18
+ ### `index_persona(persona: PersonaProfileModel) -> list[str]`
19
+
20
+ Adds a persona’s indicators to the vector store and returns vector store ids.
21
+
22
+ ### `index_personas(personas: Iterable[PersonaProfileModel) -> list[str]`
23
+
24
+ Batch indexing helper.
25
+
26
+ ### `search(query: str, k: int = 5) -> list[Document]`
27
+
28
+ Returns top-k similar documents.
29
+
30
+ ### `as_retriever(k: int = 5) -> VectorStoreRetriever`
31
+
32
+ Returns a retriever wrapper for LangChain chains.
33
+
34
+ ### `documents_to_context_prompt(documents: Iterable[Document]) -> str`
35
+
36
+ Renders a list of `Document` results to a single context string with headers, separated by `---`.
37
+
38
+ ## Inputs/outputs
39
+
40
+ **Inputs**
41
+ - `embeddings: langchain_core.embeddings.Embeddings` (caller supplies the embedding model)
42
+ - personas: `PersonaProfileModel` objects (typed schema)
43
+
44
+ **Outputs**
45
+ - Retrieval: `langchain_core.documents.Document[]`
46
+ - Context: `str` suitable for injection into prompt builder
47
+
48
+ ## Key dependencies / technologies
49
+
50
+ - `langchain_community.vectorstores.FAISS`
51
+ - `langchain_core.documents.Document`
52
+ - `langchain_core.embeddings.Embeddings`
53
+
54
+ ## Notes / production hardening
55
+
56
+ - Swap the default FAISS index with a persistent vector store for production.
57
+ - Add metadata filters to enforce persona scoping at retrieval time.
58
+ - Preserve `sources` (doc_id/pages) and emit citations in addition to context text.
docs/md/design/data_pipeline/pdf_renderer.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: `PDFRenderer`
2
+
3
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/renderer.py`
4
+
5
+ ## Purpose
6
+
7
+ `PDFRenderer` converts a PDF into page images used as inputs to the vision extractor.
8
+
9
+ ## Responsibilities
10
+
11
+ - Render PDF pages as PNG images to an output directory
12
+ - Reuse previously rendered images when possible (cache)
13
+ - Return typed `PageImage` metadata objects
14
+
15
+ ## Public API
16
+
17
+ ### `render(pdf_path: Path, output_dir: Path, page_range: (int,int) | None, reuse_existing_images: bool) -> list[PageImage]`
18
+
19
+ **Inputs**
20
+ - `pdf_path`: path to PDF
21
+ - `output_dir`: directory for rendered images (`page_XXXX.png`)
22
+ - `page_range`: optional inclusive 1-based page range
23
+ - `reuse_existing_images`: if `True`, reuse existing PNGs when readable
24
+
25
+ **Output**
26
+ - List of `PageImage` objects with:
27
+ - `page_number`, `image_path`, `width`, `height`
28
+
29
+ ## Rendering backends
30
+
31
+ 1. **Primary**: PyMuPDF (`fitz`)
32
+ - Efficient rendering via `page.get_pixmap(dpi=...)`
33
+ 2. **Fallback**: `pdf2image`
34
+ - Can render per page or entire doc
35
+
36
+ ## Key dependencies / technologies
37
+
38
+ - `pymupdf` (`fitz`) OR `pdf2image`
39
+ - `Pillow` (`PIL.Image`) for reading existing images (cache reuse)
40
+ - `loguru` logging
41
+
42
+ ## Failure modes
43
+
44
+ - Missing PDF → `FileNotFoundError` raised by the pipeline before render
45
+ - Missing render dependencies → `ImportError` with install guidance
46
+
docs/md/design/data_pipeline/persona_extraction_config.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: `PersonaExtractionConfig`
2
+
3
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/config.py`
4
+
5
+ ## Purpose
6
+
7
+ Central configuration object for the persona extraction pipeline, including:
8
+ - file paths for inputs/outputs
9
+ - model endpoints and decoding params
10
+ - caching / concurrency settings
11
+ - reasoning enrichment toggles
12
+
13
+ ## Key configuration groups
14
+
15
+ ### Input/output paths
16
+
17
+ Defaults are derived from `adsp/config.py` directory constants:
18
+ - `pdf_path` (default raw PDF under `data/raw/...`)
19
+ - `page_images_dir`, `raw_responses_dir` (interim outputs)
20
+ - `merged_output_path`, `persona_output_dir` (processed persona profiles)
21
+ - `reasoning_output_dir` (processed reasoning traits)
22
+ - `qa_report_path`, `structured_pages_output_path` (interim artifacts)
23
+
24
+ ### Rendering
25
+
26
+ - `dpi`: resolution for page image render (default `300`)
27
+ - `page_range`: optional inclusive `(start, end)` 1-based
28
+ - `context_window`: number of adjacent pages to send as context for each extraction call
29
+
30
+ ### Vision extraction (OpenAI-compatible)
31
+
32
+ Environment variables:
33
+ - `VLLM_BASE_URL` (default `http://localhost:8000/v1`)
34
+ - `VLLM_MODEL` (required)
35
+ - `VLLM_API_KEY` (default `EMPTY`)
36
+
37
+ Parameters:
38
+ - `temperature`, `top_p`
39
+ - `max_tokens`, `response_timeout`
40
+ - `max_concurrent_requests`, `max_retries`, `backoff_seconds`
41
+ - `max_image_bytes` (compress images to remain under payload limits)
42
+
43
+ ### Reasoning enrichment (optional)
44
+
45
+ Toggle:
46
+ - `generate_reasoning_profiles` (default `True`)
47
+
48
+ Environment variables:
49
+ - `REASONING_BASE_URL` (defaults to `VLLM_BASE_URL`)
50
+ - `REASONING_MODEL` (optional; falls back to `VLLM_MODEL`)
51
+ - `REASONING_API_KEY` (defaults to `VLLM_API_KEY`)
52
+
53
+ Parameters:
54
+ - `reasoning_temperature`, `reasoning_top_p`
55
+ - `reasoning_max_tokens`
56
+ - `reasoning_max_input_chars` (chunking control)
57
+ - `reasoning_max_concurrent`
58
+
59
+ ## Notes
60
+
61
+ - Use `scripts/run_persona_extraction.py` to override config values via CLI flags.
62
+ - For deterministic extraction, the defaults set `temperature=0.0` and very low `top_p`.
63
+
docs/md/design/data_pipeline/persona_extraction_pipeline.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: `PersonaExtractionPipeline`
2
+
3
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/pipeline.py`
4
+
5
+ ## Purpose
6
+
7
+ `PersonaExtractionPipeline` converts a PDF segmentation study into:
8
+ - structured page-level JSON outputs
9
+ - merged persona profiles (`personas.json` + per-persona files)
10
+ - optional reasoning enrichment artifacts (style/value/guardrails per persona)
11
+
12
+ This is the “PDF → structured persona JSON” backbone referenced in `docs/md/design.md` and `docs/md/persona_extraction_pipeline.md`.
13
+
14
+ ## High-level stages
15
+
16
+ The pipeline is implemented as a LangChain `RunnableSequence`:
17
+
18
+ 1. Render PDF pages to images (`PDFRenderer`)
19
+ 2. Plan extraction, optionally reusing cached page responses
20
+ 3. Extract structured JSON per page using a vision-capable model (`VLLMOpenAIExtractor`)
21
+ 4. Merge page outputs into persona profiles (`PersonaMerger`)
22
+ 5. (Optional) Reason over salient indicators to derive persona traits (`PersonaReasoner`)
23
+
24
+ ## Public API
25
+
26
+ ### `run() -> dict[str, Any]`
27
+
28
+ Returns the final state dict containing:
29
+ - `personas`: list of persona payloads
30
+ - `personas_map`: persona_id → payload dict
31
+ - `general_content`: extracted general content blocks
32
+ - `pages`: raw page payloads
33
+ - `page_results`: list of `PageExtractionResult`
34
+
35
+ ### Helper: `run_persona_extraction_pipeline(config: PersonaExtractionConfig | None) -> dict`
36
+
37
+ Convenience wrapper to create and run the pipeline.
38
+
39
+ ## Inputs
40
+
41
+ Configured via `PersonaExtractionConfig` (see `docs/md/design/data_pipeline/persona_extraction_config.md`), including:
42
+ - `pdf_path`
43
+ - optional `page_range`
44
+ - vLLM/OpenAI-compatible model endpoint + model name
45
+ - output paths for interim and processed artifacts
46
+
47
+ ## Outputs (filesystem)
48
+
49
+ Defaults (see config) write to:
50
+ - **Interim**
51
+ - rendered pages: `data/interim/persona_extraction/page_images/page_XXXX.png`
52
+ - raw page outputs: `data/interim/persona_extraction/pages/page_XXXX.json`
53
+ - QA report: `data/interim/persona_extraction/qa_report.json`
54
+ - optional structured dump: `data/interim/persona_extraction/pages_structured.json`
55
+ - **Processed**
56
+ - merged personas bundle: `data/processed/personas/personas.json`
57
+ - per-persona profiles: `data/processed/personas/individual/{persona_id}.json`
58
+ - reasoning traits: `data/processed/personas/common_traits/{persona_id}.json`
59
+
60
+ ## Caching behavior
61
+
62
+ When `reuse_cache=True`:
63
+ - The pipeline loads existing `pages/page_XXXX.json` files and skips re-extraction for pages without errors.
64
+ - Reasoning enrichment also reuses existing `{persona_id}.json` trait outputs if present.
65
+
66
+ ## Key dependencies / technologies
67
+
68
+ - `langchain_core.runnables` for pipeline composition (`RunnableLambda`, `RunnableSequence`)
69
+ - `loguru` logging
70
+ - Vision + reasoning model calls via the `openai` Python client configured with `base_url` to a vLLM/OpenAI-compatible server
71
+
docs/md/design/data_pipeline/persona_merger.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: `PersonaMerger`
2
+
3
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/merger.py`
4
+
5
+ ## Purpose
6
+
7
+ `PersonaMerger` aggregates page-level extraction results into:
8
+ - a merged persona bundle (`personas.json`)
9
+ - per-persona profile files (`individual/{persona_id}.json`)
10
+ - QA report for validation and parse failures
11
+
12
+ ## Responsibilities
13
+
14
+ - Consume `PageExtractionResult` objects and merge their `parsed` payloads
15
+ - Resolve and stabilize `persona_id` values (slugify)
16
+ - Stamp indicator sources with doc_id + page references for traceability
17
+ - Merge repeated indicators/fields across pages
18
+ - Emit QA report (missing persona_name, parse failures, etc.)
19
+
20
+ ## Key behaviors
21
+
22
+ ### Persona ID resolution
23
+
24
+ For each `persona_data` dict on a page:
25
+ - Prefer `persona_id`, else `persona_name`, else fallback `persona-page-{page_number}-{n}`
26
+ - Normalize via `_slugify()` (lowercase + kebab-case)
27
+
28
+ ### Source stamping
29
+
30
+ `_stamp_indicator_sources()` ensures every indicator has:
31
+ - `sources[].doc_id` set (defaults to `document_name`)
32
+ - `sources[].pages` includes the current page number
33
+
34
+ ### Deep merge strategy
35
+
36
+ `_deep_merge(target, incoming, parent_path)` merges dicts/lists/scalars with simple rules:
37
+ - Scalars default to “fill” (only write if missing) unless `merge_strategy[path]="overwrite"`
38
+ - Lists default to append + deduplicate (unless overwritten)
39
+ - `indicators` lists receive special merge logic to merge by indicator key (`id` / `indicator_id` / `label`)
40
+
41
+ The `merge_strategy` dict is a dotted-path override (e.g., `"summary_bio": "overwrite"`).
42
+
43
+ ## Public API
44
+
45
+ ### `apply_page_result(result: PageExtractionResult) -> None`
46
+
47
+ Applies a single page result into the internal aggregate state:
48
+ - `personas` map
49
+ - `general_content`
50
+ - `pages`
51
+ - `parse_failures`
52
+
53
+ ### `write_outputs(output_path: Path, qa_report_path: Path, page_results: Sequence[PageExtractionResult], persona_output_dir: Path | None) -> None`
54
+
55
+ Writes:
56
+ - merged payload to `output_path`
57
+ - individual persona JSON files to `persona_output_dir` (if provided)
58
+ - QA report to `qa_report_path`
59
+
60
+ ## Key dependencies / technologies
61
+
62
+ - `json` for output writing
63
+ - `loguru` logging
64
+
docs/md/design/data_pipeline/persona_reasoner.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: `PersonaReasoner`
2
+
3
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/reasoner.py`
4
+
5
+ ## Purpose
6
+
7
+ `PersonaReasoner` enriches extracted persona profiles with reasoning traits:
8
+ - how the persona speaks (`style_profile`)
9
+ - what the persona values (`value_frame`)
10
+ - decision rules (`reasoning_policies`)
11
+ - guardrails (`content_filters`)
12
+
13
+ This supports the “authenticity + critical thinking” requirements in `docs/md/design.md`.
14
+
15
+ ## Responsibilities
16
+
17
+ - Collect salient evidence (`salience.is_salient == true`) from persona indicators
18
+ - Build a prompt to a reasoning-capable text model (OpenAI-compatible)
19
+ - Parse JSON output into trait sections
20
+ - Chunk large evidence sets and merge partial trait outputs
21
+ - Cache results per persona on disk
22
+
23
+ ## Public API
24
+
25
+ ### `process(personas: dict[str, dict], output_dir: Path, reuse_cache: bool = True) -> dict[str, dict]`
26
+
27
+ **Inputs**
28
+ - `personas`: persona_id → extracted persona profile dict (from the merger)
29
+ - `output_dir`: directory where `{persona_id}.json` trait files are written
30
+ - `reuse_cache`: reuse existing `{persona_id}.json` results if present
31
+
32
+ **Output**
33
+ - Map of persona_id → reasoning payload written
34
+
35
+ ## Internal logic (current)
36
+
37
+ For each persona (concurrently via thread pool):
38
+ 1. If cached traits exist and reuse enabled, load and return them
39
+ 2. Build `key_indicators[]` by filtering statements with `salience.is_salient`
40
+ 3. Chunk indicators by `reasoning_max_input_chars`
41
+ 4. For each chunk:
42
+ - Fill `ALIGNMENT_USER_TEMPLATE` (see prompts doc)
43
+ - Call the model via `openai` client
44
+ - Parse JSON and merge into the aggregated profile
45
+ 5. Write `{persona_id}.json` to disk
46
+
47
+ ## Key dependencies / technologies
48
+
49
+ - `openai` Python client (OpenAI-compatible endpoint)
50
+ - `concurrent.futures.ThreadPoolExecutor`
51
+ - `loguru` logging
52
+
53
+ ## Failure modes
54
+
55
+ - If reasoning is disabled (`generate_reasoning_profiles=False`) → returns `{}` and skips.
56
+ - If there are no salient indicators → returns `{}` (no enrichment).
57
+ - If model output is not valid JSON → the chunk is skipped and the profile may be partial.
58
+
docs/md/design/data_pipeline/prompts.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: Prompt Templates
2
+
3
+ This pipeline uses two prompt families:
4
+
5
+ 1. **Vision extraction prompt** (page → structured JSON)
6
+ 2. **Alignment/reasoning prompt** (salient evidence → traits)
7
+
8
+ ## Vision extraction prompt
9
+
10
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/prompts.py` (`SYSTEM_PROMPT`)
11
+
12
+ Key requirements enforced by the prompt:
13
+ - Detect persona vs general market pages
14
+ - Separate multiple personas on the same page without cross-contamination
15
+ - Emit hierarchical data:
16
+ - Indicator → Statements → Metrics
17
+ - Include traceability and cross-page linkage hints
18
+ - Output strict JSON (no markdown fences)
19
+
20
+ ## Reasoning/alignment prompts
21
+
22
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/alignment_prompts.py`
23
+
24
+ - `ALIGNMENT_SYSTEM_PROMPT`: instructs “use evidence only” and output strict JSON sections.
25
+ - `ALIGNMENT_USER_TEMPLATE`: provides:
26
+ - persona identity
27
+ - current partial profile (for chunking)
28
+ - salient `key_indicators` evidence
29
+ - explicit required JSON schema for `style_profile`, `value_frame`, `reasoning_policies`, `content_filters`
30
+
31
+ ## Notes
32
+
33
+ - Both prompts are designed for determinism and schema compliance. When using non-deterministic decoding, schema violations increase and should be caught by QA validation.
34
+
docs/md/design/data_pipeline/run_persona_extraction_cli.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: Running Persona Extraction (CLI)
2
+
3
+ **Code**: `scripts/run_persona_extraction.py`
4
+
5
+ ## Purpose
6
+
7
+ Provides a CLI wrapper around `PersonaExtractionPipeline` so engineers can run extraction locally and control config values without editing code.
8
+
9
+ ## Basic usage
10
+
11
+ ```bash
12
+ python scripts/run_persona_extraction.py --vllm-model <vision-model-name>
13
+ ```
14
+
15
+ ## Required environment / dependencies
16
+
17
+ - Python deps installed (`openai`, `pymupdf` or `pdf2image`, `Pillow`, `loguru`, `langchain-core`)
18
+ - An OpenAI-compatible server for the vision model (commonly vLLM), configured via:
19
+ - `--vllm-base-url` / `VLLM_BASE_URL`
20
+ - `--vllm-model` / `VLLM_MODEL`
21
+
22
+ Optional reasoning enrichment requires a text model:
23
+ - `--reasoning-model` / `REASONING_MODEL` (or reuse the vision model if it supports text)
24
+
25
+ ## What it writes
26
+
27
+ See `docs/md/design/data_pipeline/persona_extraction_pipeline.md` for the default output locations (interim + processed).
28
+
29
+ ## Common flags (high value)
30
+
31
+ - `--pdf-path`: input PDF
32
+ - `--page-range start,end`: limit run to a subset of pages
33
+ - `--no-cache`: re-run extraction even if cached page outputs exist
34
+ - `--concurrency`: parallel extraction calls
35
+ - `--disable-reasoning-profiles`: skip enrichment step
36
+
docs/md/design/data_pipeline/schema.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: Persona Schema (`PersonaProfileModel`)
2
+
3
+ **Code**: `adsp/data_pipeline/schema.py`
4
+
5
+ ## Purpose
6
+
7
+ Defines the canonical typed schema for persona profiles produced by extraction and consumed by prompt construction and retrieval/indexing.
8
+
9
+ ## Responsibilities
10
+
11
+ - Provide Pydantic models for:
12
+ - page sources, metrics, salience, influences
13
+ - indicators and statements
14
+ - reasoning enrichment traits (style/value/policies/filters)
15
+ - Support parsing JSON payloads into typed objects
16
+
17
+ ## Key models
18
+
19
+ - `PersonaProfileModel`
20
+ - `Indicator` → `Statement` → `Metric`
21
+ - `Salience`, `Influences`
22
+ - Reasoning enrichment:
23
+ - `StyleProfile`
24
+ - `ValueFrame`
25
+ - `ReasoningPolicies` (with `PurchaseAdvice`, `ProductEvaluation`, `InformationProcessing`)
26
+ - `ContentFilters`
27
+
28
+ ## Important schema behaviors
29
+
30
+ - `extra = "allow"` on all models:
31
+ - The pipeline can accept additional fields without breaking parsing.
32
+ - Good for iterative schema evolution, but can hide unexpected upstream changes; add validation checks in QA reports if strictness is needed.
33
+
34
+ ## Public helper
35
+
36
+ ### `load_persona_profile(path: str | Path) -> PersonaProfileModel`
37
+
38
+ **Input**
39
+ - Path to a persona profile JSON file
40
+
41
+ **Output**
42
+ - Parsed `PersonaProfileModel`
43
+
44
+ **Failure modes**
45
+ - Raises `FileNotFoundError` if file does not exist
46
+ - Raises `pydantic.ValidationError` if payload cannot be parsed into the model
47
+
48
+ ## Related documentation
49
+
50
+ - Human-readable schema description: `docs/md/persona_profile_schema.md`
51
+
docs/md/design/data_pipeline/vllm_openai_extractor.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Pipeline: `VLLMOpenAIExtractor`
2
+
3
+ **Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/extractor.py`
4
+
5
+ ## Purpose
6
+
7
+ Extracts structured JSON from page images using a vision-capable model exposed via an OpenAI-compatible API (commonly vLLM).
8
+
9
+ ## Responsibilities
10
+
11
+ - Build a multimodal request payload (text + image(s))
12
+ - Call `chat.completions.create(...)` against an OpenAI-compatible server
13
+ - Parse model output into JSON (with guardrails for markdown fences and malformed output)
14
+ - Run page extraction concurrently (thread pool)
15
+ - Retry with backoff on failures
16
+
17
+ ## Public API
18
+
19
+ ### `extract_pages(pages: Sequence[PageImage], *, all_pages: Sequence[PageImage] | None, context_window: int | None, on_result: Callable | None) -> list[PageExtractionResult]`
20
+
21
+ **Inputs**
22
+ - `pages`: list of primary pages to extract
23
+ - `all_pages`: used to look up adjacent pages for context windows
24
+ - `context_window`: number of neighboring pages to include on each side
25
+ - `on_result`: optional callback invoked after each page completes (used to persist intermediates)
26
+
27
+ **Output**
28
+ - Sorted list of `PageExtractionResult { page_number, raw_text, parsed, error }`
29
+
30
+ ## Request construction
31
+
32
+ Messages:
33
+ - `system`: `SYSTEM_PROMPT` (see `docs/md/design/data_pipeline/prompts.md`)
34
+ - `user`: list of content blocks:
35
+ - text preface indicating the primary page number
36
+ - one or more image blocks in OpenAI “image_url” format with `data:{mime};base64,...`
37
+
38
+ Images are base64-encoded and optionally compressed via `encode_image_base64()` to stay under payload limits.
39
+
40
+ ## Parsing strategy
41
+
42
+ 1. Strip markdown fences (`strip_json_markdown`)
43
+ 2. Try parsing:
44
+ - full cleaned content
45
+ - best-effort substring `{...}` and `[...]`
46
+ 3. If output is a list, select the item matching the requested page number (fallback to first dict)
47
+
48
+ ## Key dependencies / technologies
49
+
50
+ - `openai` Python client (configured with `base_url` for OpenAI-compatible servers)
51
+ - `concurrent.futures.ThreadPoolExecutor`
52
+ - `loguru` logging
53
+
54
+ ## Failure modes
55
+
56
+ - `VLLM_MODEL` missing → `ValueError` on initialization
57
+ - Non-JSON output → `PageExtractionResult.error` contains message; page is skipped during caching reuse
58
+ - Server/API errors → retried up to `max_retries` with `backoff_seconds * attempt`
59
+
docs/md/design/frontend/chat_frontend.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Frontend: `ChatFrontend`
2
+
3
+ **Code**: `adsp/fe/chat_frontend.py`
4
+
5
+ ## Purpose
6
+
7
+ `ChatFrontend` is a minimal UI-layer adapter that represents the “chat app” entrypoint in the system architecture. It wires authentication to the Q&A workflow.
8
+
9
+ ## Responsibilities
10
+
11
+ - Validate that a user is authorized to chat.
12
+ - Forward an authorized message to the Q&A service.
13
+
14
+ ## Public API
15
+
16
+ ### `send_message(user: str, token: str, persona_id: str, message: str) -> str`
17
+
18
+ **Inputs**
19
+ - `user`: user identifier (string)
20
+ - `token`: auth token (string)
21
+ - `persona_id`: persona identifier to route the request
22
+ - `message`: user question / input
23
+
24
+ **Outputs**
25
+ - Returns `"Unauthorized"` if `AuthService.is_authorized()` fails
26
+ - Otherwise returns the string response from `QAService.ask()`
27
+
28
+ ## Internal logic (current)
29
+
30
+ 1. Calls `auth_service.is_authorized(user, token)`
31
+ 2. If unauthorized, returns `"Unauthorized"`
32
+ 3. If authorized, calls `qa_service.ask(persona_id=persona_id, query=message)` and returns its result
33
+
34
+ ## Key dependencies / technologies
35
+
36
+ - Python `dataclasses`
37
+ - Application-layer services:
38
+ - `adsp/app/auth_service.py` (`AuthService`)
39
+ - `adsp/app/qa_service.py` (`QAService`)
40
+
41
+ ## Notes / production hardening
42
+
43
+ - In production, this layer would typically be a real UI (e.g., Streamlit/React) calling an HTTP API, not in-process Python objects.
44
+ - Add attachment support (PDF/image) by extending the API to accept files and forwarding them to the orchestrator input handler.
45
+
docs/md/design/integration/end_to_end_flow.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # End-to-End Flow (Frontend → Core)
2
+
3
+ This describes the current in-process execution path for a single chat message.
4
+
5
+ ## Call flow
6
+
7
+ 1. `ChatFrontend.send_message(user, token, persona_id, message)`
8
+ 2. `AuthService.is_authorized(user, token)`
9
+ 3. `QAService.ask(persona_id, query)`
10
+ 4. `Orchestrator.handle_query(persona_id, query)`
11
+ - `InputHandler.normalize(query)`
12
+ - `RAGPipeline.retrieve(persona_id, normalized_query)`
13
+ - `PromptBuilder.build(persona_id, normalized_query, context)`
14
+ - `PersonaRouter.dispatch(persona_id, prompt)`
15
+ - `ConversationMemory.store(persona_id, {"query": ..., "response": ...})`
16
+ - `CacheClient.get/set(cache_key)`
17
+
18
+ ## Minimal usage example
19
+
20
+ ```python
21
+ from adsp.app import AuthService, QAService
22
+ from adsp.fe import ChatFrontend
23
+
24
+ auth = AuthService()
25
+ auth.register("alice", "token123")
26
+
27
+ frontend = ChatFrontend(qa_service=QAService(), auth_service=auth)
28
+ print(frontend.send_message("alice", "token123", "default", "What do you think about this idea?"))
29
+ ```
30
+
31
+ ## How to extend (recommended)
32
+
33
+ - Add `session_id` to `ConversationMemory` so multiple conversations don’t collide under the same persona_id.
34
+ - Change `Orchestrator.handle_query()` to return a structured response (answer + citations + explanation) to support transparency.
35
+ - Implement “virtual focus group” fan-out:
36
+ - accept `persona_ids: list[str]`
37
+ - run orchestrator per persona and return an aggregated result
38
+
docs/md/design/integration/index.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Integration Guides
2
+
3
+ This folder documents how to run workflows end-to-end and how components connect across layers.
4
+
5
+ ## Guides
6
+
7
+ - End-to-end runtime flow: `docs/md/design/integration/end_to_end_flow.md`
8
+ - Run local chat: `docs/md/design/integration/running_local_chat.md`
9
+ - Run persona extraction: `docs/md/design/integration/running_persona_extraction.md`
10
+ - Wire LangChain RAG into the orchestrator: `docs/md/design/integration/wiring_rag_into_orchestrator.md`
11
+ - Local configuration and environment variables: `docs/md/design/integration/local_dev_configuration.md`
docs/md/design/integration/local_dev_configuration.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Local Dev Configuration
2
+
3
+ ## Project paths
4
+
5
+ `adsp/config.py` defines canonical paths relative to the repo root:
6
+ - `DATA_DIR`, `RAW_DATA_DIR`, `INTERIM_DATA_DIR`, `PROCESSED_DATA_DIR`
7
+ - `MODELS_DIR`
8
+ - `REPORTS_DIR`, `FIGURES_DIR`
9
+
10
+ These defaults are used by:
11
+ - persona extraction pipeline config (`PersonaExtractionConfig`)
12
+ - modeling CLIs (`train`, `predict`)
13
+
14
+ ## Environment variables
15
+
16
+ `.env` is loaded at import time via `python-dotenv` in `adsp/config.py`.
17
+
18
+ Create it from the provided template:
19
+ - `cp .env.example .env`
20
+
21
+ Common variables:
22
+ - `VLLM_BASE_URL`, `VLLM_MODEL`, `VLLM_API_KEY`
23
+ - `REASONING_BASE_URL`, `REASONING_MODEL`, `REASONING_API_KEY`
24
+ - Runtime chat backend:
25
+ - `ADSP_LLM_BACKEND` (`stub` or `openai`)
26
+ - `ADSP_LLM_BASE_URL`, `ADSP_LLM_MODEL`, `ADSP_LLM_API_KEY`
27
+ - Persona data paths:
28
+ - `ADSP_PERSONAS_DIR`
29
+ - `ADSP_PERSONA_TRAITS_DIR`
30
+
31
+ ## Useful commands
32
+
33
+ - Install deps: `make install`
34
+ - Lint: `make lint`
35
+ - Format: `make format`
36
+ - Run chat: `make chat` or `python scripts/run_chat.py chat --persona-id basic-traditional`
37
+
38
+ ## Notes on current repo state
39
+
40
+ - Several components are stubs (in-memory storage, placeholder inference/training). The design docs call out recommended production replacements.
docs/md/design/integration/running_local_chat.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Running Local Chat
2
+
3
+ This repo includes a runnable local chat loop that exercises the full FE → App → Core flow using:
4
+ - extracted persona profiles under `data/processed/personas/`
5
+ - local RAG over persona indicators (no external embedding model downloads)
6
+ - a stub generator by default (optional OpenAI-compatible backend)
7
+
8
+ ## Prerequisites
9
+
10
+ - Install deps: `make install`
11
+ - (Optional) create a `.env`: `cp .env.example .env`
12
+
13
+ ## List personas
14
+
15
+ ```bash
16
+ python scripts/run_chat.py list-personas
17
+ ```
18
+
19
+ ## Interactive chat
20
+
21
+ ```bash
22
+ python scripts/run_chat.py chat --persona-id basic-traditional
23
+ ```
24
+
25
+ ## One-shot ask
26
+
27
+ ```bash
28
+ python scripts/run_chat.py ask "What do you value most?" --persona-id basic-traditional --top-k 5
29
+ ```
30
+
31
+ ## Using an OpenAI-compatible backend (optional)
32
+
33
+ If you have a local server (e.g., vLLM) exposing `/v1`:
34
+
35
+ ```bash
36
+ export ADSP_LLM_BACKEND=openai
37
+ export ADSP_LLM_BASE_URL=http://localhost:8000/v1
38
+ export ADSP_LLM_MODEL=<your-model>
39
+ export ADSP_LLM_API_KEY=EMPTY
40
+ python scripts/run_chat.py chat --persona-id basic-traditional
41
+ ```
42
+
43
+ ## Notes
44
+
45
+ - Persona files are loaded from `ADSP_PERSONAS_DIR` (default: `data/processed/personas/individual`).
46
+ - Reasoning traits are loaded from `ADSP_PERSONA_TRAITS_DIR` (default: `data/processed/personas/common_traits`).
47
+
docs/md/design/integration/running_persona_extraction.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Running Persona Extraction (PDF → Personas)
2
+
3
+ The persona extraction pipeline renders PDF pages, calls a vision model to extract structured JSON, merges into persona profiles, and optionally runs a reasoning model to derive traits.
4
+
5
+ ## Prerequisites
6
+
7
+ - Python environment with dependencies from `requirements.txt`
8
+ - A running OpenAI-compatible model server (commonly vLLM) that supports image inputs
9
+
10
+ ## Configure model endpoint
11
+
12
+ You can provide config via CLI flags or environment variables:
13
+
14
+ - `VLLM_BASE_URL` (default `http://localhost:8000/v1`)
15
+ - `VLLM_MODEL` (required)
16
+ - `VLLM_API_KEY` (default `EMPTY`)
17
+
18
+ Optional reasoning model:
19
+ - `REASONING_BASE_URL` (defaults to `VLLM_BASE_URL`)
20
+ - `REASONING_MODEL` (optional; defaults to `VLLM_MODEL`)
21
+ - `REASONING_API_KEY` (defaults to `VLLM_API_KEY`)
22
+
23
+ ## Run
24
+
25
+ ```bash
26
+ python scripts/run_persona_extraction.py \
27
+ --pdf-path "data/raw/lavazza/customer-segmentation/2023 03_FR_Consumers Segmentation France.pdf" \
28
+ --vllm-model "<your-vision-model>" \
29
+ --page-range 1,10
30
+ ```
31
+
32
+ ## Outputs
33
+
34
+ Default outputs are documented in:
35
+ - `docs/md/design/data_pipeline/persona_extraction_pipeline.md`
36
+
37
+ ## Debugging tips
38
+
39
+ - Use `--no-cache` to force re-extraction of pages (ignores cached `pages/page_XXXX.json`).
40
+ - Use `--debug` to write raw model text to `data/interim/persona_extraction/debug/`.
41
+ - If model output is not parseable JSON, inspect `pages/page_XXXX.json` (`raw_text` and `error`).
42
+
docs/md/design/integration/wiring_rag_into_orchestrator.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wiring LangChain RAG into the Orchestrator
2
+
3
+ The Core `RAGPipeline` currently delegates to an in-memory stub `VectorDatabase` and returns only a context string. This guide describes how to wire the LangChain-based indicator retriever into runtime query handling.
4
+
5
+ ## Target behavior
6
+
7
+ - Index persona indicators into a vector store at startup (or after extraction).
8
+ - At query time:
9
+ - retrieve top-k relevant indicator documents
10
+ - format them into a context string for the prompt
11
+ - return structured citations (doc_id/pages) for explainability
12
+
13
+ ## Building the index
14
+
15
+ Inputs:
16
+ - persona profiles: `data/processed/personas/individual/*.json`
17
+ - schema loader: `adsp.data_pipeline.schema.load_persona_profile`
18
+
19
+ Retriever:
20
+ - `adsp.data_pipeline.persona_data_pipeline.rag.PersonaIndicatorRAG`
21
+
22
+ Embeddings:
23
+ - Provide any `langchain_core.embeddings.Embeddings` implementation.
24
+ - This repo includes `langchain-huggingface` + `sentence-transformers` in `requirements.txt`.
25
+
26
+ ## Query-time retrieval
27
+
28
+ 1. `docs = indicator_rag.search(query, k=5)`
29
+ 2. `context = documents_to_context_prompt(docs)`
30
+ 3. Build prompt: `PromptBuilder.build(..., context=context)`
31
+
32
+ ## Integrating with `Orchestrator`
33
+
34
+ Recommended approach:
35
+ - Replace `RAGPipeline.retrieve()` to return both:
36
+ - `context: str`
37
+ - `citations: list[dict]` (derived from `Document.metadata` + `sources`)
38
+ - Update `Orchestrator.handle_query()` to return a structured response including citations.
39
+
40
+ If you keep the current string-only API:
41
+ - You can still return `context` built from `documents_to_context_prompt()`, but citations will be lost unless added elsewhere.
42
+
43
+ ## Related docs
44
+
45
+ - `docs/md/design/data_pipeline/indicator_rag.md`
46
+ - `docs/md/design/core/rag_pipeline.md`
47
+ - `docs/md/design/core/explanation.md`
48
+