diff --git a/README.md b/README.md index f6ab55867326332ed4f670c5c0b630b42cb6913a..c9390547747eb184aabc787a1702413c84c26abd 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,14 @@ +--- +title: AI Persona Backend +emoji: "🤖" +colorFrom: blue +colorTo: indigo +sdk: docker +app_port: 7860 +base_path: /docs +pinned: false +--- + # 2025-P3-AI-Personas - Team 1 diff --git a/docs/.gitkeep b/docs/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..79c146859754d65ce1a01add9848026d10bd832c --- /dev/null +++ b/docs/README.md @@ -0,0 +1,12 @@ +Generating the docs +---------- + +Use [mkdocs](http://www.mkdocs.org/) structure to update the documentation. + +Build locally with: + + mkdocs build + +Serve locally with: + + mkdocs serve diff --git a/docs/images/ai persona - Functional diagram rag.png b/docs/images/ai persona - Functional diagram rag.png new file mode 100644 index 0000000000000000000000000000000000000000..6b1f1f8936054ae27fab1799d9dea9a68e2355b9 Binary files /dev/null and b/docs/images/ai persona - Functional diagram rag.png differ diff --git a/docs/images/ai persona - System Architecture Overview.png b/docs/images/ai persona - System Architecture Overview.png new file mode 100644 index 0000000000000000000000000000000000000000..ce9e91dd07608d77074d59fa3804299fa8d676c3 Binary files /dev/null and b/docs/images/ai persona - System Architecture Overview.png differ diff --git a/docs/images/ai persona -Functional diagram peft.png b/docs/images/ai persona -Functional diagram peft.png new file mode 100644 index 0000000000000000000000000000000000000000..6b1b5ccc707f3686a515a7223e16b635dd018375 Binary files /dev/null and b/docs/images/ai persona -Functional diagram peft.png differ diff --git a/docs/images/ai persona-Functional diagram overview.png b/docs/images/ai persona-Functional diagram overview.png new file mode 100644 index 0000000000000000000000000000000000000000..bec242497eac2cd269eac7af866c05cc44f884c9 Binary files /dev/null and b/docs/images/ai persona-Functional diagram overview.png differ diff --git a/docs/images/functional_diagram.png b/docs/images/functional_diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..bd8e672dc483570b2c428822bdcc05f05b40600a Binary files /dev/null and b/docs/images/functional_diagram.png differ diff --git a/docs/md/design.md b/docs/md/design.md new file mode 100644 index 0000000000000000000000000000000000000000..d67e554783bf211d6cb4d20037bac1864bfd81bf --- /dev/null +++ b/docs/md/design.md @@ -0,0 +1,214 @@ +# System design + +## Overview + +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. + +## Requirements + +The Lavazza AI Personas project is a comprehensive technical initiative aimed at creating dynamic, conversational AI agents that authentically represent Lavazza's customer segments. + +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. + +### I. Project Goal (Objective) + +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. + +Key strategic and ultimate goals include: + +* **Accelerating Insights:** Providing marketing teams and researchers with a sparring partner to validate concepts, test campaigns, and gather consumer insights in real-time. +* **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. +* **Ultimate Deliverable:** Creating a **user-friendly chat frontend** through which internal teams can interact with the synthetic personas. + +### II. Key Project Requirements + +The requirements are divided into functional (what the personas must achieve) and architectural/data (how the system must be built). + +#### A. Persona Behavior and Functional Requirements + +The project mandates specific, sophisticated behavioral requirements to ensure the personas are reliable and useful for critical business decisions: + +| Requirement Category | Specific Mandates | +| :--- |:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **Factual Accuracy** | The algorithm must find and provide **precise, detailed answers** that are explicitly written within the source documentation. | +| **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"**. | +| **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. | +| **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. | +| **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. | +| **Multimodal Input** | The chat interface must support processing **text, visuals, and PDF documents** (e.g., packaging designs, concept notes). | +| **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. | + +#### B. Data and Foundation Requirements + +The personas must be built on a reliable, proprietary data foundation: + +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. +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. +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. +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. + +#### C. Technical and Enterprise Requirements + +1. **Architecture:** The recommended architecture is a **Hybrid RAG-Tuning Model** that uses: + * **Retrieval-Augmented Generation (RAG):** To provide factual grounding from the knowledge base, drastically reducing hallucination and enabling traceability. + * **Parameter-Efficient Fine-Tuning (PEFT), such as LoRA:** To instill the required personality, critical thinking style, and nuanced voice into the model. +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. + +## Project Structure + +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: + +- **`adsp/`** – Houses the full implementation stack. Each module aligns with a layer from the architecture: + - `app/` – persona configuration, ingestion, reporting, Q&A, and auth services. + - `fe/` – frontend prototypes that connect authentication with the chat UI. + - `communication/` – RPC, cache, and event broker abstractions. + - `core/` – modular packages for the orchestrator, input processing, prompt construction, retrieval, persona routing, memory, and MCP-powered tool access. + - `data_pipeline/` – document ingestion, schema enforcement, transformations, and vector-store builders. + - `modeling/` – PEFT training utilities plus runtime inference adapters. + - `monitoring/` – evaluation harnesses and metrics collection. + - `storage/` / `utils/` – business DB, object storage, vector DB clients, logging, and exceptions. +- **`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. +- **`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. +- **`models/`, `reports/`, and `notebooks/`** – Hold serialized persona checkpoints, generated analysis, and exploratory research notebooks, respectively, ensuring model development and monitoring assets remain auditable. + +Refer to `docs/folder_structure.md` whenever you need the full tree, naming conventions, or ownership expectations for a given path. + +## System Architecture + +### System Architecture Overview + +![](../images/ai%20persona%20-%20System%20Architecture%20Overview.png) + +#### **1. User Interface (UI)** + +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. + +#### **2. Application Layer** + +This layer contains the core application logic and manages all user-driven workflows. + +Key components include: + +- **Persona Configuration:** Enables users to select or customize AI personas dynamically. +- **Ingestion Service:** Handles ingestion of raw data such as PDFs or images and stores them in **S3**. +- **Report Service:** Generates structured, formatted reports from processed and analyzed data. +- **Q&A Service:** Manages interactive question-and-answer exchanges with the AI. +- **Auth Service:** Provides authentication and authorization for users, ensuring secure access and operations. + + +#### **3. Communication Layer** + +This layer facilitates efficient communication and coordination among microservices. + +- **RPC Server:** Enables direct service-to-service communication via Remote Procedure Calls. +- **Cache:** A high-speed memory layer that stores frequently accessed data to optimize performance. +- **Event Broker / Message Queue (RabbitMQ or Kafka):** Handles asynchronous communication and event-driven processing across services, ensuring reliability, scalability, and robust monitoring. + + +#### **4. Core Layer** + +The intelligence engine of the system—handles AI persona logic, LLM orchestration, and data-driven grounding. + +- **Orchestrator:** The central coordinator of the Core Layer. When a request arrives, the Orchestrator manages the entire generation process, directing which services to call. +- **Input Handler:** Preprocesses and normalizes user inputs, including text extraction from PDFs and preparation of image data for AI analysis. +- **Prompt Construction:** Dynamically builds structured prompts by combining user input, persona rules, and retrieved data. +- **AI Persona Router:** Selects fine-tuned Large Language Models (LLMs) tailored to embody distinct customer segment personalities, generating output accordingly. +- **RAG (Retrieval-Augmented Generation):** Provides factual grounding by retrieving relevant information from the **Vector DB**, ensuring responses remain accurate. +- **Persona Registry:** Stores the static attributes and behavioral definitions of each persona, guiding prompt construction and response tone. +- **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. +- **MCP Server (Model Context Protocol Server):** Enriches LLM interactions with real-time contextual or external domain data. +- **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. + + +#### **5. Monitoring and Evaluation** + +A centralized observability layer that tracks performance, quality, and reliability across all services. + +- **Evaluation Tools:** Measure the accuracy and quality of AI responses and data processing outcomes. +- **Metrics & Alerting:** Monitor key indicators such as latency, error rates, resource utilization, and token usage, triggering alerts for anomalies or system degradation. + + +#### **6. Data Storage Layer** + +The persistence foundation of the system, designed for scalability, durability, and speed. + +- **Business Logic Database:** Stores structured data such as user profiles, authentication records, saved reports, and persona definitions. +- **Object Storage (S3):** Manages large, unstructured data files (e.g., raw PDFs, images, and uploaded datasets). +- **Vector Database:** Stores embeddings for persona-related documents, historical interactions, and reference materials — powering RAG retrieval and factual grounding. + +### Functional Diagram + +#### 1. Process Flow Overview + +![](../images/ai%20persona-Functional%20diagram%20overview.png) + +##### 1. User Query Submission +- User sends a query with optional attached files (image, PDF, etc.) to the **Orchestrator**. + +###### 1.1 Orchestrator Analysis +- The Orchestrator analyzes the query and attachments to decide which services should be used. + +##### 2. Memory Integration +- Extract useful information from **chat history**. + +##### 3. Input Preprocessing +- Inputs are preprocessed before passing to the model. + +###### 3.1 Text Input +- Normalize text to make it easier to handle in later steps. + +###### 3.2 PDF Input +- Parse, process, and extract meaningful information from PDF files. + +###### 3.3 Image Input +- Process images and extract valuable information. + +##### 4. Context Retrieval (RAG System) +- Use the query and relevant input information to retrieve context (e.g., market data) via a **RAG system**. + +##### 5. Tool Selection & MCP Server Requests +- Decide which tools should be used to enrich the context. +- Send requests to the **MCP server** to gather corresponding context. + +###### 5.1 Web Search +- Extract updated information from the internet (trends, real-time data, missing internal data, etc.). + +###### 5.2 Database Query +- Retrieve useful data from internal or external databases. + +###### 5.3 External APIs +- Call APIs to obtain additional information. + +###### 5.4 Other Tools +- Use calculators, simulators, weather data extractors, or other utilities to enrich context. + +##### 6. Explanation +- The explanation module will explain in detail the thought process of the reasoning model and the data used for the thinking process. + +##### 7. Prompt Construction +- The Orchestrator aggregates useful context and passes it to **Prompt Construction**. + +##### 8. Persona Selection +- Apply the selected Persona profile, including: + - Demographics + - Behavior Data + - Transactional Data + + +##### 9. Persona Model Routing +- Route to a fine-tuned Persona model. +- Pass the enriched prompt and context. + +##### 10. Model Response +- Generate a response with: + - Specific personality + - Tone + - Linguistic style of the Persona + +#### 2. Background Processing - PEFT AI Personas + +![](../images/ai%20persona%20-Functional%20diagram%20peft.png) + +#### 3. Background Processing - Rag Indexing + +![](../images/ai%20persona%20-%20Functional%20diagram%20rag.png) diff --git a/docs/md/design/application/auth_service.md b/docs/md/design/application/auth_service.md new file mode 100644 index 0000000000000000000000000000000000000000..7435abbe77c5ab552dabb5307f49ec62ae5700b1 --- /dev/null +++ b/docs/md/design/application/auth_service.md @@ -0,0 +1,41 @@ +# Application: `AuthService` + +**Code**: `adsp/app/auth_service.py` + +## Purpose + +`AuthService` provides a minimal authentication/authorization mechanism so UI clients can be gated before invoking persona workflows. + +## Responsibilities + +- Store user → token bindings +- Validate access with token equality + +## Public API + +### `register(user: str, token: str) -> None` + +Stores the token for a user in an in-memory dictionary. + +### `is_authorized(user: str, token: str) -> bool` + +Returns `True` iff `token == stored_token_for_user`. + +## Data model + +- `_tokens: Dict[str, str]` (in-memory) + +## Key dependencies / technologies + +- Python `dataclasses` +- In-memory storage (`dict`) + +## Notes / production hardening + +The architecture in `docs/md/design.md` expects secure auth; this stub should be replaced with: + +- Identity provider / SSO integration (OIDC/SAML) +- Token verification (JWT signature + expiration) +- Role-based access control (RBAC) for persona sets / documents +- Persistence in the business database (`adsp/storage/business_db.py` or a real DB) + diff --git a/docs/md/design/application/ingestion_service.md b/docs/md/design/application/ingestion_service.md new file mode 100644 index 0000000000000000000000000000000000000000..9bccadfa17e36312a1de713720c836861b054a5a --- /dev/null +++ b/docs/md/design/application/ingestion_service.md @@ -0,0 +1,48 @@ +# Application: `IngestionService` + +**Code**: `adsp/app/ingestion_service.py` + +## Purpose + +`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. + +## Responsibilities + +- Accept uploaded file paths +- Persist their bytes into object storage +- (Planned) emit events / enqueue jobs for downstream data pipelines + +## Public API + +### `ingest_files(files: Iterable[pathlib.Path]) -> None` + +**Inputs** +- `files`: iterable of local file paths (already available on the host) + +**Output** +- None (side-effect: writes to object store) + +## Internal logic (current) + +For each `file_path`: +- Calls `adsp.storage.object_store.put(bucket, file_path)` + +## Storage interactions + +- Object storage shim: `adsp/storage/object_store.py` + - `put(bucket: str, file_path: Path) -> None` + +## Key dependencies / technologies + +- Python `dataclasses` +- `pathlib.Path` +- In-memory object store shim (to be replaced by S3/GCS/Azure Blob) + +## Notes / production hardening + +- Add validation (file type, size limits, virus scanning). +- Replace `object_store` shim with S3-compatible client. +- Integrate with `EventBroker` / message queue to trigger: + - persona extraction pipeline + - RAG indexing pipeline + diff --git a/docs/md/design/application/persona_configuration_service.md b/docs/md/design/application/persona_configuration_service.md new file mode 100644 index 0000000000000000000000000000000000000000..7bb4cda42ed21d5073ed4e97d09017e420b75b7e --- /dev/null +++ b/docs/md/design/application/persona_configuration_service.md @@ -0,0 +1,43 @@ +# Application: `PersonaConfigurationService` + +**Code**: `adsp/app/persona_config.py` + +## Purpose + +`PersonaConfigurationService` is the application-layer interface for creating and listing personas available to the system. + +## Responsibilities + +- Register persona definitions (metadata + behavioral configuration) +- List available personas +- Retrieve persona definitions by id + +## Public API + +### `register_persona(persona_id: str, definition: dict) -> None` + +Stores a persona definition in an in-memory dictionary. + +### `list_personas() -> list[str]` + +Returns sorted persona IDs. + +### `get_persona(persona_id: str) -> dict` + +Returns the persona definition; raises `KeyError` if missing. + +## Data model + +- `_personas: Dict[str, Dict]` (in-memory) + +## Key dependencies / technologies + +- Python `dataclasses` +- In-memory storage (`dict`) + +## Notes / integration + +- The Core layer has its own `PersonaRegistry` (`adsp/core/persona_registry/__init__.py`). In production you typically unify these: + - Application layer writes persona definitions to a persistent store (business DB). + - Core layer loads and caches them for prompt construction + routing. + diff --git a/docs/md/design/application/qa_service.md b/docs/md/design/application/qa_service.md new file mode 100644 index 0000000000000000000000000000000000000000..2f4a0fbf5dd9a85da62686fffbca7094b0221642 --- /dev/null +++ b/docs/md/design/application/qa_service.md @@ -0,0 +1,42 @@ +# Application: `QAService` + +**Code**: `adsp/app/qa_service.py` + +## Purpose + +`QAService` is the UI-facing entrypoint for interactive persona Q&A. It forwards queries into the Core layer’s orchestrator. + +## Responsibilities + +- Receive `(persona_id, query)` from the frontend +- Invoke the Core orchestration pipeline and return the final text response + +## Public API + +### `ask(persona_id: str, query: str) -> str` + +**Inputs** +- `persona_id`: persona to use for voice/routing +- `query`: the user question + +**Output** +- `str` response (persona answer) + +## Internal logic (current) + +1. Creates a new `core.orchestrator.Orchestrator()` +2. Calls `Orchestrator.handle_query(persona_id=persona_id, query=query)` + +## Key dependencies / technologies + +- `adsp/core/orchestrator/__init__.py` (`Orchestrator`) +- Python `dataclasses` + +## Notes / production hardening + +- 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). +- Add request metadata: + - `session_id` (for memory) + - `attachments` (PDF/image) + - `requested_personas[]` (for “virtual focus group” multi-persona fan-out) + diff --git a/docs/md/design/application/report_service.md b/docs/md/design/application/report_service.md new file mode 100644 index 0000000000000000000000000000000000000000..8881fd2e8800578f84f8d709ad35b37f2a917aac --- /dev/null +++ b/docs/md/design/application/report_service.md @@ -0,0 +1,42 @@ +# Application: `ReportService` + +**Code**: `adsp/app/report_service.py` + +## Purpose + +`ReportService` generates stakeholder-friendly reports from computed persona insights. + +## Responsibilities + +- Accept structured “insights” payloads +- Write report artifacts (currently markdown) to an output directory + +## Public API + +### `generate(persona_id: str, insights: dict) -> pathlib.Path` + +**Inputs** +- `persona_id`: identifier used to name the report file +- `insights`: arbitrary dictionary to embed in the report body + +**Output** +- Returns the filesystem path where the report was written: + - `{output_dir}/{persona_id}_report.md` + +## Internal logic (current) + +1. Constructs `report_path` +2. Writes a markdown stub containing the `insights` dict (stringified) +3. Returns `report_path` + +## Key dependencies / technologies + +- Python `dataclasses` +- `pathlib.Path` file IO + +## Notes / production hardening + +- Define a report schema (sections, citations, charts). +- Export to PDF/HTML and store in object storage. +- Add provenance: include evidence snippets and page citations from persona indicators. + diff --git a/docs/md/design/application/rest_api_server.md b/docs/md/design/application/rest_api_server.md new file mode 100644 index 0000000000000000000000000000000000000000..ec35a84137c198a91663f811712230d01ba06c7d --- /dev/null +++ b/docs/md/design/application/rest_api_server.md @@ -0,0 +1,424 @@ +# Application: REST API Server (FastAPI) + +**Code**: `adsp/app/api_server.py` + +## Purpose + +Expose the Application layer over HTTP so external clients (frontend/UI, tools, other services) can interact with: +- authentication +- persona discovery +- persona chat (Q&A) +- ingestion (upload) +- reports + +The server is designed for local development and demos. It wires existing in-process services (`adsp/app/*`) and returns typed JSON responses. + +## Key technologies + +- **FastAPI**: REST framework + OpenAPI generation +- **Pydantic**: request/response validation (reuses `adsp/core/types.py`) +- **Uvicorn**: ASGI server + +Dependencies are declared in `requirements.txt` (`fastapi`, `uvicorn[standard]`). + +## Runtime architecture (in-process) + +On startup, the API server creates and stores service singletons: + +- `AuthService` (`adsp/app/auth_service.py`) +- `QAService` (`adsp/app/qa_service.py`) → uses Core orchestrator with local RAG + persona loading +- `IngestionService` (`adsp/app/ingestion_service.py`) → writes to `object_store` shim +- `ReportService` (`adsp/app/report_service.py`) → writes markdown to `reports/api/` by default +- `SurveyManager` (`adsp/core/survey/survey_manager.py`) → stores survey definitions +- `GroupGenerator` (`adsp/core/survey/group_generator.py`) → creates respondent groups +- `ResponseSynthesizer` (`adsp/core/survey/response_synthesizer.py`) → runs survey simulations and exports results + +These are accessible to endpoints via a FastAPI dependency (`get_services()`). + +## Authentication model (dev) + +If `ADSP_REQUIRE_AUTH=true`, protected endpoints require: +- `X-User: ` +- `X-Token: ` + +Register tokens via: +- `POST /v1/auth/register` + +When `ADSP_REQUIRE_AUTH` is unset/false, endpoints are open for local demo convenience. + +## Swagger / OpenAPI + +- Swagger UI: `GET /docs` +- OpenAPI JSON: `GET /openapi.json` +- ReDoc: `GET /redoc` + +## Endpoints + +### System + +- `GET /health` + - Response fields: + - `status`: API health indicator (`ok` when service is up) + - `version`: API version string + - `qa_status`: QA service warmup status (`idle|warming|ready|error`) + - Example: + +```bash +curl -X GET "http://localhost:8000/health" +``` + +### Auth + +- `POST /v1/auth/register` + - Request fields: + - `user`: user identifier + - `token`: API token assigned to this user + - Response fields: + - `status`: registration result (`ok`) + - Example: + +```bash +curl -X POST "http://localhost:8000/v1/auth/register" \ + -H "Content-Type: application/json" \ + -d '{"user":"demo-user","token":"demo-token-123"}' +``` + +- `POST /v1/auth/validate` + - Request fields: + - `user`: user identifier to validate + - `token`: token to validate + - Response fields: + - `authorized`: `true` when user/token pair matches registry + - Example: + +```bash +curl -X POST "http://localhost:8000/v1/auth/validate" \ + -H "Content-Type: application/json" \ + -d '{"user":"demo-user","token":"demo-token-123"}' +``` + +### Personas + +- `GET /v1/personas` + - Response fields: + - `personas`: array of persona summaries + - `persona_id`: stable persona key + - `persona_name`: human-readable name + - `summary_bio`: short profile summary + - Example: + +```bash +curl -X GET "http://localhost:8000/v1/personas" +``` + +- `GET /v1/personas/{persona_id}/profile` + - Path fields: + - `persona_id`: persona to retrieve + - Response fields: + - Full `PersonaProfileModel` payload (`adsp/data_pipeline/schema.py`) + - Example: + +```bash +curl -X GET "http://localhost:8000/v1/personas/curious-connoisseurs/profile" +``` + +- `GET /v1/personas/{persona_id}/system-prompt` + - Path fields: + - `persona_id`: persona to retrieve + - Response fields: + - `system_prompt`: generated prompt string used by the orchestrator + - Example: + +```bash +curl -X GET "http://localhost:8000/v1/personas/curious-connoisseurs/system-prompt" +``` + +### Chat + +- `POST /v1/chat` + - Request fields (`ChatRequest`): + - `persona_id`: target persona id + - `query`: user question + - `session_id`: optional session key + - `persona_display_name`: optional persona label + - `attachments`: optional list of attachment objects (`type`, `name`, `mime_type`, `payload`) + - `top_k`: retrieval depth + - `use_tools`: enable/disable tool use + - Response fields (`response: ChatResponse`): + - `persona_id`: persona used to answer + - `answer`: generated response text + - `context`: assembled retrieval context + - `citations`: evidence list + - `tool_calls`: tool execution trace + - Example: + +```bash +curl -X POST "http://localhost:8000/v1/chat" \ + -H "Content-Type: application/json" \ + -d '{ + "persona_id":"curious-connoisseurs", + "query":"What matters most when buying coffee?", + "top_k":5, + "use_tools":false + }' +``` + +### Ingestion + +- `POST /v1/ingestion/upload` + - Request fields: + - `filename`: target object key + - `content_base64`: Base64-encoded file payload + - `bucket`: optional destination bucket override + - Response fields: + - `bucket`: storage bucket used + - `key`: object key written + - `size_bytes`: decoded payload size + - Example: + +```bash +curl -X POST "http://localhost:8000/v1/ingestion/upload" \ + -H "Content-Type: application/json" \ + -d '{ + "filename":"notes.txt", + "content_base64":"SGVsbG8gTGF2YXp6YSBBSSBQZXJzb25hcyE=", + "bucket":"uploads" + }' +``` + +### Reports + +- `POST /v1/reports/{persona_id}` + - Path fields: + - `persona_id`: persona key used to name output report + - Request fields: + - `insights`: free-form insights object rendered to markdown + - Response fields: + - `path`: generated report path + - Example: + +```bash +curl -X POST "http://localhost:8000/v1/reports/curious-connoisseurs" \ + -H "Content-Type: application/json" \ + -d '{ + "insights":{ + "top_drivers":["taste","price","brand trust"], + "summary":"Segment values consistent quality and practical pricing." + } + }' +``` + +### Survey Simulation + +- `GET /api/surveys` + - Query fields: + - `page`: 1-based page number (default `1`) + - `page_size`: items per page (default `20`, max `200`) + - Response fields: + - `items`: paged survey list (`survey_id`, `title`, `description`, `created_at`, `questions`) + - `paging`: metadata (`page`, `page_size`, `total_items`, `total_pages`) + - Example: + +```bash +curl -X GET "http://localhost:8000/api/surveys?page=1&page_size=20" +``` + +- `POST /api/surveys` + - Request fields: + - `survey_id`: optional id (auto-generated if omitted) + - `title`: survey title + - `description`: survey objective + - `questions`: question array (`question_id`, `text`, `type`, optional `options`, optional `metadata`) + - Response fields: + - `survey_id`, `title`, `description`, `created_at`, `questions` + - Example: + +```bash +curl -X POST "http://localhost:8000/api/surveys" \ + -H "Content-Type: application/json" \ + -d '{ + "survey_id":"coffee-pref-2026-q1", + "title":"Coffee Preference Survey", + "description":"Capture coffee purchase preferences.", + "questions":[ + { + "question_id":"q1", + "text":"Which product claim matters most?", + "type":"multiple_choice", + "options":["Great taste","Affordable price","Sustainable sourcing"] + }, + { + "question_id":"q2", + "text":"How likely are you to try a new blend?", + "type":"rating", + "metadata":{"scale":"1-5"} + } + ] + }' +``` + +- `GET /api/surveys/{survey_id}` + - Path fields: + - `survey_id`: survey identifier + - Response fields: + - `survey_id`, `title`, `description`, `created_at`, `questions` + - `simulations`: all simulation runs for this survey + - `simulation_id`, `group_id`, `status`, `started_at`, `completed_at` + - `progress` (`completed`, `pending`) + - `responses_count`, `responses`, `statistics_ready` + - Example: + +```bash +curl -X GET "http://localhost:8000/api/surveys/coffee-pref-2026-q1" +``` + +- `POST /api/groups` + - Request fields: + - `composition`: list of group parts (`persona_id`, `count`) + - `mode`: `random` or `llm` + - `sampling_ratio`: trait sampling ratio + - `include_names`: generate synthetic names flag + - `countries`: optional list of allowed countries (for example `["italy","france"]`) + - `seed`: optional deterministic seed + - Response fields: + - `group_id`, `created_at`, `total_respondents`, `composition`, `generation_method`, `sample_profiles` + - each generated profile includes `name`, `country`, `gender`, and `ethnicity` + - Example: + +```bash +curl -X POST "http://localhost:8000/api/groups" \ + -H "Content-Type: application/json" \ + -d '{ + "composition":[ + {"persona_id":"curious-connoisseurs","count":25}, + {"persona_id":"conscious-explorers","count":15} + ], + "mode":"random", + "sampling_ratio":0.7, + "include_names":true, + "countries":["italy","france"], + "seed":42 + }' +``` + +- `GET /api/groups/countries` + - Purpose: + - Lists every country id supported by `POST /api/groups` in `countries` + - Response fields: + - `countries[]`: `country_id`, `display_name`, `description` + - Example: + +```bash +curl -X GET "http://localhost:8000/api/groups/countries" +``` + +- `GET /api/groups` + - Query fields: + - `page`: 1-based page number (default `1`) + - `page_size`: items per page (default `20`, max `200`) + - Response fields: + - `items`: paged group list (`group_id`, `created_at`, `total_respondents`, `composition`, `generation_method`, `sample_profiles`) + - `paging`: metadata (`page`, `page_size`, `total_items`, `total_pages`) + - Example: + +```bash +curl -X GET "http://localhost:8000/api/groups?page=1&page_size=20" +``` + +- `GET /api/groups/{group_id}` + - Path fields: + - `group_id`: group identifier + - Query fields: + - `include_full_profiles`: `true` to include full respondent payloads + - Response fields: + - `group_id`, `created_at`, `total_respondents`, `composition`, `generation_method`, `respondents`, `sample_profiles` + - Example: + +```bash +curl -X GET "http://localhost:8000/api/groups/group-ab12cd34?include_full_profiles=false" +``` + +- `POST /api/surveys/{survey_id}/simulate` + - Path fields: + - `survey_id`: target survey id + - Query fields: + - `background`: when `true` (default), starts async run and returns immediately + - Request fields: + - `group_id`: source respondent group + - `batch_size`: processing batch size + - `format`: output format hint + - Response fields: + - `simulation_id`, `status`, `total_respondents`, `progress`, `estimated_time_minutes` + - `status` is `processing` while running and becomes `completed` after finish + - Example: + +```bash +curl -X POST "http://localhost:8000/api/surveys/coffee-pref-2026-q1/simulate?background=true" \ + -H "Content-Type: application/json" \ + -d '{ + "group_id":"group-ab12cd34", + "batch_size":10, + "format":"json" + }' +``` + +- `GET /api/surveys/{survey_id}/responses` + - Path fields: + - `survey_id`: target survey id + - Query fields: + - `simulation_id`: optional simulation id (latest when omitted) + - `format`: `csv` or `json` + - Response: + - File download (`text/csv` for `format=csv`, `application/json` for `format=json`) + - Example: + +```bash +curl -L -X GET "http://localhost:8000/api/surveys/coffee-pref-2026-q1/responses?format=csv" -o responses.csv +``` + +- `GET /api/surveys/{survey_id}/statistics` + - Path fields: + - `survey_id`: target survey id + - Query fields: + - `simulation_id`: optional simulation id (latest when omitted) + - Notes: + - Statistics are computed only for `completed` simulations. + - The first computation is stored as cache per simulation and reused on subsequent calls. + - Response fields: + - `survey_id`, `simulation_id`, `total_respondents`, `total_responses`, `computed_at`, `questions` + - Per-question fields: + - `question_id`, `text`, `type`, `answered_count`, `response_rate` + - `choice_distribution` (`multiple_choice`) + - `rating_distribution`, `rating_average`, `rating_min`, `rating_max` (`rating`) + - `text_response_count`, `sample_text_responses` (`open_ended`) + - Example: + +```bash +curl -X GET "http://localhost:8000/api/surveys/coffee-pref-2026-q1/statistics?simulation_id=sim-1234abcd" +``` + +## How to run locally + +```bash +make install +python scripts/run_api.py +``` + +Then open: +- `http://localhost:8000/docs` + +## Configuration + +Environment variables (see `.env.example`): + +- API: + - `ADSP_API_HOST` (default `0.0.0.0`) + - `ADSP_API_PORT` (default `8000`) + - `ADSP_API_RELOAD` (default `true`) + - `ADSP_REQUIRE_AUTH` (default `false`) +- Data paths: + - `ADSP_PERSONAS_DIR` + - `ADSP_PERSONA_TRAITS_DIR` +- Runtime LLM backend (optional): + - `ADSP_LLM_BACKEND=stub|openai` + - `ADSP_LLM_BASE_URL`, `ADSP_LLM_MODEL`, `ADSP_LLM_API_KEY` diff --git a/docs/md/design/application/rest_api_swagger.md b/docs/md/design/application/rest_api_swagger.md new file mode 100644 index 0000000000000000000000000000000000000000..0ce3a23ba11943df0b934bf3395843983a52a887 --- /dev/null +++ b/docs/md/design/application/rest_api_swagger.md @@ -0,0 +1,39 @@ +# REST API Swagger (OpenAPI) + +The REST server is implemented with FastAPI, which generates the Swagger/OpenAPI specification at runtime: + +- Swagger UI: `http://localhost:8000/docs` +- OpenAPI JSON: `http://localhost:8000/openapi.json` + +## Quick export (optional) + +Once dependencies are installed, you can export the OpenAPI JSON to a file: + +```bash +python -c "from adsp.app.api_server import app; import json; print(json.dumps(app.openapi(), indent=2))" > openapi.json +``` + +## Contract summary + +For the authoritative schema, use `/openapi.json`. The key routes are: + +- `GET /health` +- `POST /v1/auth/register` +- `POST /v1/auth/validate` +- `GET /v1/personas` +- `GET /v1/personas/{persona_id}/profile` +- `GET /v1/personas/{persona_id}/system-prompt` +- `POST /v1/chat` +- `POST /v1/ingestion/upload` +- `POST /v1/reports/{persona_id}` +- `GET /api/surveys` +- `POST /api/surveys` +- `GET /api/surveys/{survey_id}` +- `GET /api/groups` +- `POST /api/groups` +- `GET /api/groups/countries` +- `GET /api/groups/{group_id}` +- `POST /api/surveys/{survey_id}/simulate` +- `GET /api/surveys/{survey_id}/responses` + +All request/response fields now expose descriptions and examples directly in Swagger UI. diff --git a/docs/md/design/communication/cache_client.md b/docs/md/design/communication/cache_client.md new file mode 100644 index 0000000000000000000000000000000000000000..a82843f48b4ade279060175162ff5e3c24d0acbf --- /dev/null +++ b/docs/md/design/communication/cache_client.md @@ -0,0 +1,47 @@ +# Communication: `CacheClient` + +**Code**: `adsp/communication/cache.py` + +## Purpose + +`CacheClient` provides a low-latency caching layer for frequently repeated computations (e.g., repeated persona answers for identical prompts). + +## Responsibilities + +- Store computed values by string key +- Retrieve cached values + +## Public API + +### `get(key: str) -> Any | None` + +Returns the cached value if present; otherwise `None`. + +### `set(key: str, value: Any) -> None` + +Stores `value` under `key`. + +## Data model + +- `_entries: Dict[str, Any]` (in-memory) + +## Current usage + +Used by the Core orchestrator: +- `adsp/core/orchestrator/__init__.py` caches responses by `f"{persona_id}:{query}"` + +## Key dependencies / technologies + +- Python `dataclasses` +- In-memory `dict` + +## Notes / production hardening + +Replace the in-memory implementation with: +- Redis / Memcached +- Cache key strategy including: + - persona version / adapter version + - prompt template version + - retrieval context hash (to prevent stale grounding) +- TTLs and cache invalidation policies + diff --git a/docs/md/design/communication/event_broker.md b/docs/md/design/communication/event_broker.md new file mode 100644 index 0000000000000000000000000000000000000000..8b1b7adb9a44f2dee1049b41cd519f4a1b9eca71 --- /dev/null +++ b/docs/md/design/communication/event_broker.md @@ -0,0 +1,45 @@ +# Communication: `EventBroker` + +**Code**: `adsp/communication/event_broker.py` + +## Purpose + +`EventBroker` models the event-driven part of the architecture (`docs/md/design.md`) where ingestion and background jobs communicate asynchronously. + +## Responsibilities + +- Allow subscribers to register callbacks for a topic +- Publish a payload to all subscribers for a topic + +## Public API + +### `subscribe(topic: str, handler: Callable) -> None` + +Registers a handler to be called when `topic` receives a message. + +### `publish(topic: str, payload: dict) -> None` + +Invokes all registered handlers for `topic` with `payload`. + +## Data model + +- `_subscribers: DefaultDict[str, List[Callable]]` (in-memory) + +## Key dependencies / technologies + +- Python `dataclasses` +- `collections.defaultdict` + +## Notes / production hardening + +The architecture suggests RabbitMQ/Kafka. A production broker should provide: +- Durable queues/topics +- Retries, dead-letter queues +- Consumer groups / backpressure +- Observability (lag, throughput, failure counts) + +Typical events in this system: +- `file_ingested` (object store key + metadata) +- `persona_extraction_requested` / `persona_extraction_completed` +- `rag_indexing_requested` / `rag_indexing_completed` + diff --git a/docs/md/design/communication/rpc_client.md b/docs/md/design/communication/rpc_client.md new file mode 100644 index 0000000000000000000000000000000000000000..ff3e13ac398f8d655b2add346059c1db37ce696d --- /dev/null +++ b/docs/md/design/communication/rpc_client.md @@ -0,0 +1,41 @@ +# Communication: `RPCClient` + +**Code**: `adsp/communication/rpc.py` + +## Purpose + +`RPCClient` is a placeholder for synchronous service-to-service calls (RPC/gRPC/HTTP) inside the platform. + +## Responsibilities + +- Route a `(service, payload)` request to a resolved handler +- Return the handler’s response + +## Public API + +### `call(service: str, payload: dict) -> Any` + +**Inputs** +- `service`: logical service name +- `payload`: request payload + +**Output** +- Any response returned by the resolved handler + +## Internal logic (current) + +1. Calls `_resolver(service)` to get a callable handler +2. Calls `handler(payload)` and returns the result + +## Key dependencies / technologies + +- Python `dataclasses` +- Callable injection for `_resolver` + +## Notes / production hardening + +Replace with: +- HTTP (FastAPI) or gRPC client stubs +- Typed request/response models (Pydantic/Protobuf) +- Timeouts, retries, tracing propagation + diff --git a/docs/md/design/core/conversation_memory.md b/docs/md/design/core/conversation_memory.md new file mode 100644 index 0000000000000000000000000000000000000000..a99c382d5788263d03246b54eefda4b32a182eaa --- /dev/null +++ b/docs/md/design/core/conversation_memory.md @@ -0,0 +1,40 @@ +# Core: `ConversationMemory` + +**Code**: `adsp/core/memory/__init__.py` + +## Purpose + +`ConversationMemory` stores recent chat history so the persona can behave consistently across turns. + +## Responsibilities + +- Append messages per persona +- Enforce a maximum history length +- Return history for context building (not yet wired into prompt construction) + +## Public API + +### `store(persona_id: str, message: dict) -> None` + +Appends the message; evicts oldest entries once `max_items` is exceeded. + +### `get_history(persona_id: str) -> list[dict]` + +Returns a copy of the history list for the persona. + +## Data model + +- `_messages: DefaultDict[str, List[dict]]` (in-memory) +- `max_items: int` (default `10`) + +## Key dependencies / technologies + +- Python `dataclasses` +- `collections.defaultdict` + +## Notes / production hardening + +- Memory should be keyed by conversation/session (not only persona_id). +- Persist in a database for auditability and multi-instance deployments. +- Add summarization to fit token budgets. + diff --git a/docs/md/design/core/explanation.md b/docs/md/design/core/explanation.md new file mode 100644 index 0000000000000000000000000000000000000000..bb63360ad814ea006861fa48b49cf10b2dababf8 --- /dev/null +++ b/docs/md/design/core/explanation.md @@ -0,0 +1,41 @@ +# Core: Explanation Module (Design) + +**Architecture reference**: `docs/md/design.md` lists an “Explanation” module for transparency and traceability. + +## Purpose + +The Explanation module provides user-visible justification for outputs: +- what evidence was retrieved (citations) +- what persona rules were applied +- what tool calls (MCP) were made +- why the system refused / said “not enough data” (non-hallucination) + +## Recommended API + +Expose an explanation payload alongside the answer: + +```json +{ + "answer": "string", + "citations": [ + { "doc_id": "string", "pages": [1, 2], "snippet": "string", "score": 0.0 } + ], + "persona": { "persona_id": "string", "version": "string?" }, + "retrieval": { "k": 5, "source": "vector_db|indicator_rag", "query": "string" }, + "tool_calls": [ { "tool": "string", "payload": {}, "result_summary": "string" } ], + "safety": { "refusal": false, "not_enough_data": false } +} +``` + +## Integration points + +- `Orchestrator.handle_query()` should return a structured response (not only a string) so explanation can be returned to the UI. +- `RAGPipeline` should return structured citations (doc/page) rather than only a context string. +- `MCPServer` should log tool calls and cache keys. + +## Key technologies (recommended) + +- Typed models: Pydantic +- Logging/tracing: OpenTelemetry +- UI rendering: expandable “Evidence” panel showing citations and tool outputs + diff --git a/docs/md/design/core/input_handler.md b/docs/md/design/core/input_handler.md new file mode 100644 index 0000000000000000000000000000000000000000..3f5d856f1f69f758149e377bb2ea52470e4494fe --- /dev/null +++ b/docs/md/design/core/input_handler.md @@ -0,0 +1,35 @@ +# Core: `InputHandler` + +**Code**: `adsp/core/input_handler/__init__.py` + +## Purpose + +`InputHandler` normalizes user inputs before retrieval and prompt building. + +## Responsibilities + +- Normalize text input (current) +- (Planned) route and preprocess multimodal inputs: + - PDF text extraction + page selection + - Image preprocessing and OCR / captioning + +## Public API + +### `normalize(text: str) -> str` + +**Input** +- raw text string + +**Output** +- stripped text string (`text.strip()`) + +## Key dependencies / technologies + +- Python `dataclasses` + +## Notes / production hardening + +To meet `docs/md/design.md` multimodal requirements, expand this component with: +- PDF extraction via `pymupdf` (`fitz`) or `pdf2image` + OCR +- Attachment routing into the pipeline used in `adsp/data_pipeline/persona_data_pipeline/extract_raw/` + diff --git a/docs/md/design/core/mcp_client.md b/docs/md/design/core/mcp_client.md new file mode 100644 index 0000000000000000000000000000000000000000..e65b27d557defd89cf8930a7a07da71d79e41a32 --- /dev/null +++ b/docs/md/design/core/mcp_client.md @@ -0,0 +1,30 @@ +# Core: `MCPClient` + +**Code**: `adsp/core/mcp_server/tools/mcp_client.py` + +## Purpose + +`MCPClient` is the client-side interface to request tool execution. Today it is a mock that echoes the request. + +## Responsibilities + +- Provide a simple `request(tool, payload)` function +- (Planned) communicate with external tool servers/processes + +## Public API + +### `request(tool: str, payload: dict) -> dict` + +Returns `{ "tool": tool, "payload": payload }`. + +## Key dependencies / technologies + +- Python `dataclasses` + +## Notes / production hardening + +Replace with: +- MCP-compatible transport (HTTP/websocket/stdin-stdio) +- Tool registry and authentication +- Structured tool schemas for safe calling + diff --git a/docs/md/design/core/mcp_server.md b/docs/md/design/core/mcp_server.md new file mode 100644 index 0000000000000000000000000000000000000000..3077da8b154b79ef231c4a10e4a834db40afccb3 --- /dev/null +++ b/docs/md/design/core/mcp_server.md @@ -0,0 +1,47 @@ +# Core: `MCPServer` + +**Code**: `adsp/core/mcp_server/__init__.py`, `adsp/core/mcp_server/tools/mcp_client.py` + +## Purpose + +`MCPServer` is the Core component responsible for calling external “tools” via a Model Context Protocol-style interface and caching their responses. + +In the architecture (`docs/md/design.md`), tool calls are used to enrich the model context with: +- web search +- database queries +- external APIs +- utilities (calculators, simulators, etc.) + +## Responsibilities + +- Provide `run(tool, payload)` interface +- Cache tool responses by a deterministic key + +## Public API + +### `run(tool: str, payload: dict) -> dict` + +**Inputs** +- `tool`: tool name (string identifier) +- `payload`: tool request payload + +**Output** +- Tool response dict (cached for identical requests) + +## Internal logic (current) + +1. Creates `cache_key = f"{tool}:{tuple(sorted(payload.items()))}"` +2. If `cache_key` not present, calls `MCPClient.request(tool, payload)` and stores the result +3. Returns cached result + +## Key dependencies / technologies + +- Python `dataclasses` +- Simple in-process caching (`dict`) + +## Notes / production hardening + +- Deterministic keying should handle nested payloads and non-hashable types (current implementation assumes flat payload). +- Add timeouts, retries, rate limiting. +- Persist tool-call traces for explainability (“why did the model say this?”). + diff --git a/docs/md/design/core/orchestrator.md b/docs/md/design/core/orchestrator.md new file mode 100644 index 0000000000000000000000000000000000000000..4ff5d3fbe8d7710931db94c315cdf2f799afabec --- /dev/null +++ b/docs/md/design/core/orchestrator.md @@ -0,0 +1,102 @@ +# Core: `Orchestrator` + +**Code**: `adsp/core/orchestrator/__init__.py` + +## Purpose + +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. + +## Responsibilities + +- Provide a single “handle query” entrypoint to the Application layer (`QAService`) +- Orchestrate: + - input normalization + - retrieval (RAG) + - prompt construction + - persona model routing + - conversation memory writeback + - response caching + +## Public API + +### `handle_query(persona_id: str, query: str) -> str` + +**Inputs** +- `persona_id`: persona identifier used for retrieval + routing +- `query`: raw user question text (current implementation assumes text-only) + +**Output** +- Persona response string + +## Internal logic (current) + +1. **Cache lookup** + - `cache_key = f"{persona_id}:{session_id}:{query}"` + - Return cached value if present (`CacheClient.get`) +2. **Normalize** + - `normalized = InputHandler.normalize(query)` +3. **Retrieve context** + - `retrieved = RAGPipeline.retrieve_with_metadata(persona_id=persona_id, query=normalized, k=top_k)` +4. **Filter for relevance** + - Filter conversation history and retrieved context down to what is relevant for the current question + - `filtered_history = ConversationContextFilter.filter_history(history, normalized)` + - `filtered_retrieved = ConversationContextFilter.filter_retrieved(retrieved, normalized)` +5. **Build prompt** + - `prompt = PromptBuilder.build(persona_id=persona_id, query=normalized, context=filtered_retrieved.context, history=filtered_history)` +6. **Dispatch to persona model** + - `response = PersonaRouter.dispatch(persona_id=persona_id, prompt=prompt)` +7. **Persist memory** + - `ConversationMemory.store(persona_id=persona_id, message={"query": query, "response": response})` +8. **Cache write** + - `CacheClient.set(cache_key, response)` + +## Inputs/outputs and extension points + +The architecture (`docs/md/design.md`) calls for multimodal inputs (PDF/image). The orchestrator is the correct place to expand the request contract to: +- `attachments: list[{type, bytes|path|object_store_key}]` +- `session_id` or `conversation_id` (for memory) +- `requested_personas: list[str]` (virtual focus group fan-out) + +## Key dependencies / technologies + +- Python `dataclasses` +- Core subcomponents: + - `adsp/core/input_handler/__init__.py` (`InputHandler`) + - `adsp/core/context_filter.py` (`ConversationContextFilter`) + - `adsp/core/rag/__init__.py` (`RAGPipeline`) + - `adsp/core/prompt_builder/__init__.py` (`PromptBuilder`) + - `adsp/core/ai_persona_router/__init__.py` (`PersonaRouter`) + - `adsp/core/memory/__init__.py` (`ConversationMemory`) +- Communication: + - `adsp/communication/cache.py` (`CacheClient`) + +## Observability / monitoring (recommended) + +Wire `MetricsCollector` to capture: +- cache hit/miss +- retrieval latency and top-k +- model latency and token usage +- error counts by stage + +## Failure modes (current) + +- Missing persona in `PersonaRegistry` → `KeyError` during prompt build +- Unconfigured model backend in the inference engine (stub today) +- Retrieval returns empty context (currently allowed; may degrade factuality) + +## Relevance filtering (config) + +Relevance filtering is enabled by default and can be configured via environment variables: + +- `ADSP_CONTEXT_FILTER_ENABLED`: `true`/`false` (default: `true`) +- `ADSP_CONTEXT_FILTER_BACKEND`: `heuristic` (default) or `openai` +- `ADSP_CONTEXT_FILTER_MAX_HISTORY`: max history turns to include (default: `4`) +- `ADSP_CONTEXT_FILTER_MAX_BLOCKS`: max retrieved context blocks to include (default: `3`) +- `ADSP_CONTEXT_FILTER_MIN_COVERAGE`: minimum token coverage threshold (default: `0.2`) +- `ADSP_CONTEXT_FILTER_TIMEOUT`: LLM selection timeout in seconds (default: `20`) + +Optional OpenAI-compatible backend settings (when `ADSP_CONTEXT_FILTER_BACKEND=openai`): + +- `ADSP_CONTEXT_FILTER_BASE_URL` (defaults to `ADSP_LLM_BASE_URL` / `VLLM_BASE_URL`) +- `ADSP_CONTEXT_FILTER_MODEL` (defaults to `ADSP_LLM_MODEL` / `VLLM_MODEL`) +- `ADSP_CONTEXT_FILTER_API_KEY` (defaults to `ADSP_LLM_API_KEY` / `VLLM_API_KEY`) diff --git a/docs/md/design/core/persona_registry.md b/docs/md/design/core/persona_registry.md new file mode 100644 index 0000000000000000000000000000000000000000..18190a8d871f992fd624e9f7bb4691e97a9dbd34 --- /dev/null +++ b/docs/md/design/core/persona_registry.md @@ -0,0 +1,38 @@ +# Core: `PersonaRegistry` + +**Code**: `adsp/core/persona_registry/__init__.py` + +## Purpose + +`PersonaRegistry` stores persona metadata used by the Core layer for prompt construction and routing decisions. + +## Responsibilities + +- Maintain a catalog of persona metadata keyed by `persona_id` +- Provide read access for prompt building + +## Public API + +### `get(persona_id: str) -> dict` + +Returns persona metadata dict, raises `KeyError` if missing. + +### `upsert(persona_id: str, metadata: dict) -> None` + +Stores/replaces metadata for the persona. + +## Default persona + +On initialization, the registry contains: +- `default`: `{ "preamble": "You are a Lavazza persona who is transparent and data-grounded." }` + +## Key dependencies / technologies + +- Python `dataclasses` +- In-memory `dict` + +## Notes / integration + +Production architecture typically sources persona definitions from the extracted persona profile JSON (`data/processed/personas/`) or a business database. A common pattern is: +- Load persona profiles at startup (or on demand) and `upsert` them into the registry. + diff --git a/docs/md/design/core/persona_router.md b/docs/md/design/core/persona_router.md new file mode 100644 index 0000000000000000000000000000000000000000..bfe41aaa2c518db50234911bc89d6a98ffa7787e --- /dev/null +++ b/docs/md/design/core/persona_router.md @@ -0,0 +1,39 @@ +# Core: `PersonaRouter` + +**Code**: `adsp/core/ai_persona_router/__init__.py` + +## Purpose + +`PersonaRouter` selects the appropriate model or adapter for a given persona and dispatches the prompt to the inference engine. + +## Responsibilities + +- Choose an inference path per `persona_id` +- Send prompt to the runtime inference engine + +## Public API + +### `dispatch(persona_id: str, prompt: str) -> str` + +**Inputs** +- `persona_id`: used to select adapter/model +- `prompt`: prompt string produced by `PromptBuilder` + +**Output** +- persona response string + +## Internal logic (current) + +- Delegates to `PersonaInferenceEngine.generate(persona_id, prompt)` + +## Key dependencies / technologies + +- `adsp/modeling/inference.py` (`PersonaInferenceEngine`) + +## Notes / production hardening + +In production, this component typically: +- maps `persona_id` → adapter checkpoint (LoRA) or fine-tuned model endpoint +- supports multiple backends (local `transformers`, vLLM, TGI, etc.) +- applies safety and decoding policies consistently + diff --git a/docs/md/design/core/prompt_builder.md b/docs/md/design/core/prompt_builder.md new file mode 100644 index 0000000000000000000000000000000000000000..b0632a3549d02b8ff89b09ccd81c456b3d376571 --- /dev/null +++ b/docs/md/design/core/prompt_builder.md @@ -0,0 +1,56 @@ +# Core: `PromptBuilder` + +**Code**: `adsp/core/prompt_builder/__init__.py`, `adsp/core/prompt_builder/system_prompt.py` + +## Purpose + +`PromptBuilder` constructs the final prompt sent to a persona model by combining: +- persona rules/traits +- retrieved grounding context +- user question + +## Responsibilities + +- Retrieve persona metadata from `PersonaRegistry` +- Convert persona profiles into a system prompt (including reasoning traits when present) +- Assemble a single string prompt for the model + +## Public API + +### `build(persona_id: str, query: str, context: str) -> str` + +**Inputs** +- `persona_id`: persona to load from the registry +- `query`: normalized user question +- `context`: retrieval grounding text (already formatted) + +**Output** +- String prompt: + - system prompt + `Context:` + `Question:` + +## Internal logic (current) + +1. `persona = PersonaRegistry.get(persona_id)` +2. `system_prompt = _system_prompt_for_persona(persona)` +3. Returns: + - `{system_prompt}\n\nContext:\n{context}\n\nQuestion:\n{query}` + +## Persona profile handling + +`_system_prompt_for_persona()` supports: +- `PersonaProfileModel` (Pydantic) → `persona_to_system_prompt(profile)` +- `dict`: + - if it looks like a profile with reasoning traits, attempt to validate as `PersonaProfileModel` + - else fallback to `persona["preamble"]` or `"You are an AI persona."` + +## Key dependencies / technologies + +- `pydantic` (`ValidationError`) +- `adsp/data_pipeline/schema.py` (`PersonaProfileModel`) +- `PersonaRegistry` (`adsp/core/persona_registry/__init__.py`) + +## Notes / production hardening + +- Return structured prompt objects (`{system, user, context}`) rather than concatenated strings to better support chat-based LLM APIs. +- Add citation formatting to ensure explainability requirements are met (page refs + doc ids). + diff --git a/docs/md/design/core/rag_pipeline.md b/docs/md/design/core/rag_pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..dfda6c8a664de9cc4cd942f252af0a26718af350 --- /dev/null +++ b/docs/md/design/core/rag_pipeline.md @@ -0,0 +1,44 @@ +# Core: `RAGPipeline` + +**Code**: `adsp/core/rag/__init__.py` + +## Purpose + +`RAGPipeline` provides factual grounding by retrieving relevant context from the vector store given `(persona_id, query)`. + +## Responsibilities + +- Query the vector store for relevant evidence +- Return a context string to inject into prompt construction + +## Public API + +### `retrieve(persona_id: str, query: str) -> str` + +**Inputs** +- `persona_id`: persona scope for retrieval +- `query`: normalized user query + +**Output** +- context string + +## Internal logic (current) + +- Delegates to `VectorDatabase.search(persona_id, query)` + +## Key dependencies / technologies + +- `adsp/storage/vector_db.py` (`VectorDatabase`) — currently an in-memory stub + +## Recommended upgrade path + +This repo also contains a more realistic RAG component (LangChain-based): +- `adsp/data_pipeline/persona_data_pipeline/rag/indicator.py` (`PersonaIndicatorRAG`) + +A practical integration pattern: +1. Load persona profiles (`PersonaProfileModel`) and index indicators into a vector store. +2. At query time, run similarity search and convert `Document[]` to a prompt-ready context string. +3. Return both context and structured citations for explainability. + +See: `docs/md/design/integration/wiring_rag_into_orchestrator.md` + diff --git a/docs/md/design/core/system_prompt.md b/docs/md/design/core/system_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..e0c3f61af5c281fd5b0209f8676bd462cfb07c1d --- /dev/null +++ b/docs/md/design/core/system_prompt.md @@ -0,0 +1,44 @@ +# Core: `persona_to_system_prompt` + +**Code**: `adsp/core/prompt_builder/system_prompt.py` + +## Purpose + +`persona_to_system_prompt()` converts a persona profile (including optional reasoning traits) into an LLM system prompt that steers voice, values, and guardrails. + +## Responsibilities + +- Generate consistent persona “system” instructions +- Encode: + - voice/style (`style_profile`) + - value priorities (`value_frame`) + - reasoning tradeoffs (`reasoning_policies`) + - content guardrails (`content_filters`) + +## Public API + +### `persona_to_system_prompt(persona: PersonaProfileModel) -> str` + +**Input** +- `PersonaProfileModel` (see `adsp/data_pipeline/schema.py`) + +**Output** +- Multi-section system prompt string + +## Sections emitted + +- Header: persona label and `summary_bio` +- `Voice:` section (if `style_profile` present) +- `Value frame:` section (if `value_frame` present) +- `Reasoning policies:` section (if `reasoning_policies` present) +- `Content filters:` section (if `content_filters` present) + +## Key dependencies / technologies + +- `pydantic` models from `adsp/data_pipeline/schema.py` + +## Notes + +- This function is intentionally strict about missing data: if a trait section is absent, it is omitted from the prompt instead of being fabricated. +- If the reasoning enrichment pipeline is disabled, prompts will contain only the baseline persona header unless other fields are present. + diff --git a/docs/md/design/data_pipeline/document_ingestion_pipeline.md b/docs/md/design/data_pipeline/document_ingestion_pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..9ba1f8ddc486b11bbb6b2ba04748fa3e2227dd08 --- /dev/null +++ b/docs/md/design/data_pipeline/document_ingestion_pipeline.md @@ -0,0 +1,39 @@ +# Data Pipeline: `DocumentIngestionPipeline` + +**Code**: `adsp/data_pipeline/ingestion.py` + +## Purpose + +`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. + +## Responsibilities + +- Accept a set of file paths +- Store each file in object storage under the configured bucket + +## Public API + +### `run(files: Iterable[pathlib.Path]) -> None` + +**Inputs** +- `files`: iterable of local filesystem paths + +**Outputs** +- None (side effect: object store write) + +## Internal logic (current) + +For each file: +- `adsp.storage.object_store.put(bucket, file_path)` + +## Key dependencies / technologies + +- Python `dataclasses` +- `pathlib.Path` +- `adsp/storage/object_store.py` + +## Notes / production hardening + +- In a real deployment, this pipeline would likely be invoked asynchronously from an event broker after `IngestionService` emits an event. +- Add metadata capture (doc_id, upload time, uploader, checksum) and store it in the business database. + diff --git a/docs/md/design/data_pipeline/extract_raw_models.md b/docs/md/design/data_pipeline/extract_raw_models.md new file mode 100644 index 0000000000000000000000000000000000000000..9b87bd07cb6a94ef1d135601f967957627372815 --- /dev/null +++ b/docs/md/design/data_pipeline/extract_raw_models.md @@ -0,0 +1,27 @@ +# Data Pipeline: Page Models (`PageImage`, `PageExtractionResult`) + +**Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/models.py` + +## Purpose + +Provides minimal typed containers for: +- rendered page images +- extraction results per page + +## Models + +### `PageImage` + +Fields: +- `page_number: int` (1-based) +- `image_path: Path` +- `width: int`, `height: int` + +### `PageExtractionResult` + +Fields: +- `page_number: int` +- `raw_text: str` (raw model output) +- `parsed: dict | None` (best-effort parsed JSON payload) +- `error: str | None` (capture parsing/extraction failures) + diff --git a/docs/md/design/data_pipeline/extract_raw_utils.md b/docs/md/design/data_pipeline/extract_raw_utils.md new file mode 100644 index 0000000000000000000000000000000000000000..7aa7a2731a1819545cf3fbcde66fed007ad66211 --- /dev/null +++ b/docs/md/design/data_pipeline/extract_raw_utils.md @@ -0,0 +1,39 @@ +# Data Pipeline: Extraction Utilities + +**Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/utils.py` + +## Purpose + +Helper functions used by the extraction pipeline to improve model interoperability and robustness. + +## `strip_json_markdown(text: str) -> str` + +**Goal** +- Models frequently return JSON wrapped in markdown fences (```json ... ```). This helper extracts the JSON body. + +**Behavior** +- If no fences: returns stripped text +- If fences present: + - splits on ``` blocks + - prefers a block starting with `{` or `[` (or the largest block) + +## `encode_image_base64(image_path: Path, max_bytes: int | None) -> (str, str)` + +**Goal** +- Encode images as base64 for OpenAI “image_url” content. +- Compress to stay under request payload limits. + +**Behavior** +- If raw PNG bytes <= `max_bytes`, return base64 PNG +- Else: + - try converting to JPEG at decreasing quality + - if still too large, downscale gradually and re-encode + - fallback to raw PNG on any errors + +**Output** +- `(base64_string, mime_type)` where mime is `"image/png"` or `"image/jpeg"` + +**Dependencies** +- Uses `Pillow` when compression is needed +- Logs decisions via `loguru` + diff --git a/docs/md/design/data_pipeline/indicator_rag.md b/docs/md/design/data_pipeline/indicator_rag.md new file mode 100644 index 0000000000000000000000000000000000000000..d9fdcb9c1af8e0b1aa54ef814c351373293468e4 --- /dev/null +++ b/docs/md/design/data_pipeline/indicator_rag.md @@ -0,0 +1,58 @@ +# Data Pipeline: `PersonaIndicatorRAG` + +**Code**: `adsp/data_pipeline/persona_data_pipeline/rag/indicator.py` + +## Purpose + +`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. + +## Responsibilities + +- Render each persona’s indicators into text “documents” +- Embed and store them in a vector store +- Provide similarity search and retriever interfaces +- Convert retrieved documents into a prompt-ready context string + +## Public API + +### `index_persona(persona: PersonaProfileModel) -> list[str]` + +Adds a persona’s indicators to the vector store and returns vector store ids. + +### `index_personas(personas: Iterable[PersonaProfileModel) -> list[str]` + +Batch indexing helper. + +### `search(query: str, k: int = 5) -> list[Document]` + +Returns top-k similar documents. + +### `as_retriever(k: int = 5) -> VectorStoreRetriever` + +Returns a retriever wrapper for LangChain chains. + +### `documents_to_context_prompt(documents: Iterable[Document]) -> str` + +Renders a list of `Document` results to a single context string with headers, separated by `---`. + +## Inputs/outputs + +**Inputs** +- `embeddings: langchain_core.embeddings.Embeddings` (caller supplies the embedding model) +- personas: `PersonaProfileModel` objects (typed schema) + +**Outputs** +- Retrieval: `langchain_core.documents.Document[]` +- Context: `str` suitable for injection into prompt builder + +## Key dependencies / technologies + +- `langchain_community.vectorstores.FAISS` +- `langchain_core.documents.Document` +- `langchain_core.embeddings.Embeddings` + +## Notes / production hardening + +- Swap the default FAISS index with a persistent vector store for production. +- Add metadata filters to enforce persona scoping at retrieval time. +- Preserve `sources` (doc_id/pages) and emit citations in addition to context text. diff --git a/docs/md/design/data_pipeline/pdf_renderer.md b/docs/md/design/data_pipeline/pdf_renderer.md new file mode 100644 index 0000000000000000000000000000000000000000..6c9c8291b5cfb57fcea9c3e62dc2650de6ed9ce0 --- /dev/null +++ b/docs/md/design/data_pipeline/pdf_renderer.md @@ -0,0 +1,46 @@ +# Data Pipeline: `PDFRenderer` + +**Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/renderer.py` + +## Purpose + +`PDFRenderer` converts a PDF into page images used as inputs to the vision extractor. + +## Responsibilities + +- Render PDF pages as PNG images to an output directory +- Reuse previously rendered images when possible (cache) +- Return typed `PageImage` metadata objects + +## Public API + +### `render(pdf_path: Path, output_dir: Path, page_range: (int,int) | None, reuse_existing_images: bool) -> list[PageImage]` + +**Inputs** +- `pdf_path`: path to PDF +- `output_dir`: directory for rendered images (`page_XXXX.png`) +- `page_range`: optional inclusive 1-based page range +- `reuse_existing_images`: if `True`, reuse existing PNGs when readable + +**Output** +- List of `PageImage` objects with: + - `page_number`, `image_path`, `width`, `height` + +## Rendering backends + +1. **Primary**: PyMuPDF (`fitz`) + - Efficient rendering via `page.get_pixmap(dpi=...)` +2. **Fallback**: `pdf2image` + - Can render per page or entire doc + +## Key dependencies / technologies + +- `pymupdf` (`fitz`) OR `pdf2image` +- `Pillow` (`PIL.Image`) for reading existing images (cache reuse) +- `loguru` logging + +## Failure modes + +- Missing PDF → `FileNotFoundError` raised by the pipeline before render +- Missing render dependencies → `ImportError` with install guidance + diff --git a/docs/md/design/data_pipeline/persona_extraction_config.md b/docs/md/design/data_pipeline/persona_extraction_config.md new file mode 100644 index 0000000000000000000000000000000000000000..dfe342fa3665c9d4a379f7252ddc1f6dd0b927f7 --- /dev/null +++ b/docs/md/design/data_pipeline/persona_extraction_config.md @@ -0,0 +1,63 @@ +# Data Pipeline: `PersonaExtractionConfig` + +**Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/config.py` + +## Purpose + +Central configuration object for the persona extraction pipeline, including: +- file paths for inputs/outputs +- model endpoints and decoding params +- caching / concurrency settings +- reasoning enrichment toggles + +## Key configuration groups + +### Input/output paths + +Defaults are derived from `adsp/config.py` directory constants: +- `pdf_path` (default raw PDF under `data/raw/...`) +- `page_images_dir`, `raw_responses_dir` (interim outputs) +- `merged_output_path`, `persona_output_dir` (processed persona profiles) +- `reasoning_output_dir` (processed reasoning traits) +- `qa_report_path`, `structured_pages_output_path` (interim artifacts) + +### Rendering + +- `dpi`: resolution for page image render (default `300`) +- `page_range`: optional inclusive `(start, end)` 1-based +- `context_window`: number of adjacent pages to send as context for each extraction call + +### Vision extraction (OpenAI-compatible) + +Environment variables: +- `VLLM_BASE_URL` (default `http://localhost:8000/v1`) +- `VLLM_MODEL` (required) +- `VLLM_API_KEY` (default `EMPTY`) + +Parameters: +- `temperature`, `top_p` +- `max_tokens`, `response_timeout` +- `max_concurrent_requests`, `max_retries`, `backoff_seconds` +- `max_image_bytes` (compress images to remain under payload limits) + +### Reasoning enrichment (optional) + +Toggle: +- `generate_reasoning_profiles` (default `True`) + +Environment variables: +- `REASONING_BASE_URL` (defaults to `VLLM_BASE_URL`) +- `REASONING_MODEL` (optional; falls back to `VLLM_MODEL`) +- `REASONING_API_KEY` (defaults to `VLLM_API_KEY`) + +Parameters: +- `reasoning_temperature`, `reasoning_top_p` +- `reasoning_max_tokens` +- `reasoning_max_input_chars` (chunking control) +- `reasoning_max_concurrent` + +## Notes + +- Use `scripts/run_persona_extraction.py` to override config values via CLI flags. +- For deterministic extraction, the defaults set `temperature=0.0` and very low `top_p`. + diff --git a/docs/md/design/data_pipeline/persona_extraction_pipeline.md b/docs/md/design/data_pipeline/persona_extraction_pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..6a021843acdc2843ce21f1b328d9255a11e43b45 --- /dev/null +++ b/docs/md/design/data_pipeline/persona_extraction_pipeline.md @@ -0,0 +1,71 @@ +# Data Pipeline: `PersonaExtractionPipeline` + +**Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/pipeline.py` + +## Purpose + +`PersonaExtractionPipeline` converts a PDF segmentation study into: +- structured page-level JSON outputs +- merged persona profiles (`personas.json` + per-persona files) +- optional reasoning enrichment artifacts (style/value/guardrails per persona) + +This is the “PDF → structured persona JSON” backbone referenced in `docs/md/design.md` and `docs/md/persona_extraction_pipeline.md`. + +## High-level stages + +The pipeline is implemented as a LangChain `RunnableSequence`: + +1. Render PDF pages to images (`PDFRenderer`) +2. Plan extraction, optionally reusing cached page responses +3. Extract structured JSON per page using a vision-capable model (`VLLMOpenAIExtractor`) +4. Merge page outputs into persona profiles (`PersonaMerger`) +5. (Optional) Reason over salient indicators to derive persona traits (`PersonaReasoner`) + +## Public API + +### `run() -> dict[str, Any]` + +Returns the final state dict containing: +- `personas`: list of persona payloads +- `personas_map`: persona_id → payload dict +- `general_content`: extracted general content blocks +- `pages`: raw page payloads +- `page_results`: list of `PageExtractionResult` + +### Helper: `run_persona_extraction_pipeline(config: PersonaExtractionConfig | None) -> dict` + +Convenience wrapper to create and run the pipeline. + +## Inputs + +Configured via `PersonaExtractionConfig` (see `docs/md/design/data_pipeline/persona_extraction_config.md`), including: +- `pdf_path` +- optional `page_range` +- vLLM/OpenAI-compatible model endpoint + model name +- output paths for interim and processed artifacts + +## Outputs (filesystem) + +Defaults (see config) write to: +- **Interim** + - rendered pages: `data/interim/persona_extraction/page_images/page_XXXX.png` + - raw page outputs: `data/interim/persona_extraction/pages/page_XXXX.json` + - QA report: `data/interim/persona_extraction/qa_report.json` + - optional structured dump: `data/interim/persona_extraction/pages_structured.json` +- **Processed** + - merged personas bundle: `data/processed/personas/personas.json` + - per-persona profiles: `data/processed/personas/individual/{persona_id}.json` + - reasoning traits: `data/processed/personas/common_traits/{persona_id}.json` + +## Caching behavior + +When `reuse_cache=True`: +- The pipeline loads existing `pages/page_XXXX.json` files and skips re-extraction for pages without errors. +- Reasoning enrichment also reuses existing `{persona_id}.json` trait outputs if present. + +## Key dependencies / technologies + +- `langchain_core.runnables` for pipeline composition (`RunnableLambda`, `RunnableSequence`) +- `loguru` logging +- Vision + reasoning model calls via the `openai` Python client configured with `base_url` to a vLLM/OpenAI-compatible server + diff --git a/docs/md/design/data_pipeline/persona_merger.md b/docs/md/design/data_pipeline/persona_merger.md new file mode 100644 index 0000000000000000000000000000000000000000..76dcd4168432d00fdddc39fe80c2617e97e56f9d --- /dev/null +++ b/docs/md/design/data_pipeline/persona_merger.md @@ -0,0 +1,64 @@ +# Data Pipeline: `PersonaMerger` + +**Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/merger.py` + +## Purpose + +`PersonaMerger` aggregates page-level extraction results into: +- a merged persona bundle (`personas.json`) +- per-persona profile files (`individual/{persona_id}.json`) +- QA report for validation and parse failures + +## Responsibilities + +- Consume `PageExtractionResult` objects and merge their `parsed` payloads +- Resolve and stabilize `persona_id` values (slugify) +- Stamp indicator sources with doc_id + page references for traceability +- Merge repeated indicators/fields across pages +- Emit QA report (missing persona_name, parse failures, etc.) + +## Key behaviors + +### Persona ID resolution + +For each `persona_data` dict on a page: +- Prefer `persona_id`, else `persona_name`, else fallback `persona-page-{page_number}-{n}` +- Normalize via `_slugify()` (lowercase + kebab-case) + +### Source stamping + +`_stamp_indicator_sources()` ensures every indicator has: +- `sources[].doc_id` set (defaults to `document_name`) +- `sources[].pages` includes the current page number + +### Deep merge strategy + +`_deep_merge(target, incoming, parent_path)` merges dicts/lists/scalars with simple rules: +- Scalars default to “fill” (only write if missing) unless `merge_strategy[path]="overwrite"` +- Lists default to append + deduplicate (unless overwritten) +- `indicators` lists receive special merge logic to merge by indicator key (`id` / `indicator_id` / `label`) + +The `merge_strategy` dict is a dotted-path override (e.g., `"summary_bio": "overwrite"`). + +## Public API + +### `apply_page_result(result: PageExtractionResult) -> None` + +Applies a single page result into the internal aggregate state: +- `personas` map +- `general_content` +- `pages` +- `parse_failures` + +### `write_outputs(output_path: Path, qa_report_path: Path, page_results: Sequence[PageExtractionResult], persona_output_dir: Path | None) -> None` + +Writes: +- merged payload to `output_path` +- individual persona JSON files to `persona_output_dir` (if provided) +- QA report to `qa_report_path` + +## Key dependencies / technologies + +- `json` for output writing +- `loguru` logging + diff --git a/docs/md/design/data_pipeline/persona_reasoner.md b/docs/md/design/data_pipeline/persona_reasoner.md new file mode 100644 index 0000000000000000000000000000000000000000..d0df74a9acf2f70566df0b72488afc34c4059ce3 --- /dev/null +++ b/docs/md/design/data_pipeline/persona_reasoner.md @@ -0,0 +1,58 @@ +# Data Pipeline: `PersonaReasoner` + +**Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/reasoner.py` + +## Purpose + +`PersonaReasoner` enriches extracted persona profiles with reasoning traits: +- how the persona speaks (`style_profile`) +- what the persona values (`value_frame`) +- decision rules (`reasoning_policies`) +- guardrails (`content_filters`) + +This supports the “authenticity + critical thinking” requirements in `docs/md/design.md`. + +## Responsibilities + +- Collect salient evidence (`salience.is_salient == true`) from persona indicators +- Build a prompt to a reasoning-capable text model (OpenAI-compatible) +- Parse JSON output into trait sections +- Chunk large evidence sets and merge partial trait outputs +- Cache results per persona on disk + +## Public API + +### `process(personas: dict[str, dict], output_dir: Path, reuse_cache: bool = True) -> dict[str, dict]` + +**Inputs** +- `personas`: persona_id → extracted persona profile dict (from the merger) +- `output_dir`: directory where `{persona_id}.json` trait files are written +- `reuse_cache`: reuse existing `{persona_id}.json` results if present + +**Output** +- Map of persona_id → reasoning payload written + +## Internal logic (current) + +For each persona (concurrently via thread pool): +1. If cached traits exist and reuse enabled, load and return them +2. Build `key_indicators[]` by filtering statements with `salience.is_salient` +3. Chunk indicators by `reasoning_max_input_chars` +4. For each chunk: + - Fill `ALIGNMENT_USER_TEMPLATE` (see prompts doc) + - Call the model via `openai` client + - Parse JSON and merge into the aggregated profile +5. Write `{persona_id}.json` to disk + +## Key dependencies / technologies + +- `openai` Python client (OpenAI-compatible endpoint) +- `concurrent.futures.ThreadPoolExecutor` +- `loguru` logging + +## Failure modes + +- If reasoning is disabled (`generate_reasoning_profiles=False`) → returns `{}` and skips. +- If there are no salient indicators → returns `{}` (no enrichment). +- If model output is not valid JSON → the chunk is skipped and the profile may be partial. + diff --git a/docs/md/design/data_pipeline/prompts.md b/docs/md/design/data_pipeline/prompts.md new file mode 100644 index 0000000000000000000000000000000000000000..add1fbf6ed552a7b50f6d92fcdae8df7cd73ab08 --- /dev/null +++ b/docs/md/design/data_pipeline/prompts.md @@ -0,0 +1,34 @@ +# Data Pipeline: Prompt Templates + +This pipeline uses two prompt families: + +1. **Vision extraction prompt** (page → structured JSON) +2. **Alignment/reasoning prompt** (salient evidence → traits) + +## Vision extraction prompt + +**Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/prompts.py` (`SYSTEM_PROMPT`) + +Key requirements enforced by the prompt: +- Detect persona vs general market pages +- Separate multiple personas on the same page without cross-contamination +- Emit hierarchical data: + - Indicator → Statements → Metrics +- Include traceability and cross-page linkage hints +- Output strict JSON (no markdown fences) + +## Reasoning/alignment prompts + +**Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/alignment_prompts.py` + +- `ALIGNMENT_SYSTEM_PROMPT`: instructs “use evidence only” and output strict JSON sections. +- `ALIGNMENT_USER_TEMPLATE`: provides: + - persona identity + - current partial profile (for chunking) + - salient `key_indicators` evidence + - explicit required JSON schema for `style_profile`, `value_frame`, `reasoning_policies`, `content_filters` + +## Notes + +- Both prompts are designed for determinism and schema compliance. When using non-deterministic decoding, schema violations increase and should be caught by QA validation. + diff --git a/docs/md/design/data_pipeline/run_persona_extraction_cli.md b/docs/md/design/data_pipeline/run_persona_extraction_cli.md new file mode 100644 index 0000000000000000000000000000000000000000..45daedededf2334d6b2e3fe2b6566dfbff45e273 --- /dev/null +++ b/docs/md/design/data_pipeline/run_persona_extraction_cli.md @@ -0,0 +1,36 @@ +# Data Pipeline: Running Persona Extraction (CLI) + +**Code**: `scripts/run_persona_extraction.py` + +## Purpose + +Provides a CLI wrapper around `PersonaExtractionPipeline` so engineers can run extraction locally and control config values without editing code. + +## Basic usage + +```bash +python scripts/run_persona_extraction.py --vllm-model +``` + +## Required environment / dependencies + +- Python deps installed (`openai`, `pymupdf` or `pdf2image`, `Pillow`, `loguru`, `langchain-core`) +- An OpenAI-compatible server for the vision model (commonly vLLM), configured via: + - `--vllm-base-url` / `VLLM_BASE_URL` + - `--vllm-model` / `VLLM_MODEL` + +Optional reasoning enrichment requires a text model: +- `--reasoning-model` / `REASONING_MODEL` (or reuse the vision model if it supports text) + +## What it writes + +See `docs/md/design/data_pipeline/persona_extraction_pipeline.md` for the default output locations (interim + processed). + +## Common flags (high value) + +- `--pdf-path`: input PDF +- `--page-range start,end`: limit run to a subset of pages +- `--no-cache`: re-run extraction even if cached page outputs exist +- `--concurrency`: parallel extraction calls +- `--disable-reasoning-profiles`: skip enrichment step + diff --git a/docs/md/design/data_pipeline/schema.md b/docs/md/design/data_pipeline/schema.md new file mode 100644 index 0000000000000000000000000000000000000000..e00d63fa9208e026cc4ab211dc2fa22ef69c5e56 --- /dev/null +++ b/docs/md/design/data_pipeline/schema.md @@ -0,0 +1,51 @@ +# Data Pipeline: Persona Schema (`PersonaProfileModel`) + +**Code**: `adsp/data_pipeline/schema.py` + +## Purpose + +Defines the canonical typed schema for persona profiles produced by extraction and consumed by prompt construction and retrieval/indexing. + +## Responsibilities + +- Provide Pydantic models for: + - page sources, metrics, salience, influences + - indicators and statements + - reasoning enrichment traits (style/value/policies/filters) +- Support parsing JSON payloads into typed objects + +## Key models + +- `PersonaProfileModel` +- `Indicator` → `Statement` → `Metric` +- `Salience`, `Influences` +- Reasoning enrichment: + - `StyleProfile` + - `ValueFrame` + - `ReasoningPolicies` (with `PurchaseAdvice`, `ProductEvaluation`, `InformationProcessing`) + - `ContentFilters` + +## Important schema behaviors + +- `extra = "allow"` on all models: + - The pipeline can accept additional fields without breaking parsing. + - Good for iterative schema evolution, but can hide unexpected upstream changes; add validation checks in QA reports if strictness is needed. + +## Public helper + +### `load_persona_profile(path: str | Path) -> PersonaProfileModel` + +**Input** +- Path to a persona profile JSON file + +**Output** +- Parsed `PersonaProfileModel` + +**Failure modes** +- Raises `FileNotFoundError` if file does not exist +- Raises `pydantic.ValidationError` if payload cannot be parsed into the model + +## Related documentation + +- Human-readable schema description: `docs/md/persona_profile_schema.md` + diff --git a/docs/md/design/data_pipeline/vllm_openai_extractor.md b/docs/md/design/data_pipeline/vllm_openai_extractor.md new file mode 100644 index 0000000000000000000000000000000000000000..03ba2c58dbaa5309c326adf02476c666a1b21626 --- /dev/null +++ b/docs/md/design/data_pipeline/vllm_openai_extractor.md @@ -0,0 +1,59 @@ +# Data Pipeline: `VLLMOpenAIExtractor` + +**Code**: `adsp/data_pipeline/persona_data_pipeline/extract_raw/extractor.py` + +## Purpose + +Extracts structured JSON from page images using a vision-capable model exposed via an OpenAI-compatible API (commonly vLLM). + +## Responsibilities + +- Build a multimodal request payload (text + image(s)) +- Call `chat.completions.create(...)` against an OpenAI-compatible server +- Parse model output into JSON (with guardrails for markdown fences and malformed output) +- Run page extraction concurrently (thread pool) +- Retry with backoff on failures + +## Public API + +### `extract_pages(pages: Sequence[PageImage], *, all_pages: Sequence[PageImage] | None, context_window: int | None, on_result: Callable | None) -> list[PageExtractionResult]` + +**Inputs** +- `pages`: list of primary pages to extract +- `all_pages`: used to look up adjacent pages for context windows +- `context_window`: number of neighboring pages to include on each side +- `on_result`: optional callback invoked after each page completes (used to persist intermediates) + +**Output** +- Sorted list of `PageExtractionResult { page_number, raw_text, parsed, error }` + +## Request construction + +Messages: +- `system`: `SYSTEM_PROMPT` (see `docs/md/design/data_pipeline/prompts.md`) +- `user`: list of content blocks: + - text preface indicating the primary page number + - one or more image blocks in OpenAI “image_url” format with `data:{mime};base64,...` + +Images are base64-encoded and optionally compressed via `encode_image_base64()` to stay under payload limits. + +## Parsing strategy + +1. Strip markdown fences (`strip_json_markdown`) +2. Try parsing: + - full cleaned content + - best-effort substring `{...}` and `[...]` +3. If output is a list, select the item matching the requested page number (fallback to first dict) + +## Key dependencies / technologies + +- `openai` Python client (configured with `base_url` for OpenAI-compatible servers) +- `concurrent.futures.ThreadPoolExecutor` +- `loguru` logging + +## Failure modes + +- `VLLM_MODEL` missing → `ValueError` on initialization +- Non-JSON output → `PageExtractionResult.error` contains message; page is skipped during caching reuse +- Server/API errors → retried up to `max_retries` with `backoff_seconds * attempt` + diff --git a/docs/md/design/frontend/chat_frontend.md b/docs/md/design/frontend/chat_frontend.md new file mode 100644 index 0000000000000000000000000000000000000000..1b9a6b67b1162a8c099720b0b870072ab3faf3ee --- /dev/null +++ b/docs/md/design/frontend/chat_frontend.md @@ -0,0 +1,45 @@ +# Frontend: `ChatFrontend` + +**Code**: `adsp/fe/chat_frontend.py` + +## Purpose + +`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. + +## Responsibilities + +- Validate that a user is authorized to chat. +- Forward an authorized message to the Q&A service. + +## Public API + +### `send_message(user: str, token: str, persona_id: str, message: str) -> str` + +**Inputs** +- `user`: user identifier (string) +- `token`: auth token (string) +- `persona_id`: persona identifier to route the request +- `message`: user question / input + +**Outputs** +- Returns `"Unauthorized"` if `AuthService.is_authorized()` fails +- Otherwise returns the string response from `QAService.ask()` + +## Internal logic (current) + +1. Calls `auth_service.is_authorized(user, token)` +2. If unauthorized, returns `"Unauthorized"` +3. If authorized, calls `qa_service.ask(persona_id=persona_id, query=message)` and returns its result + +## Key dependencies / technologies + +- Python `dataclasses` +- Application-layer services: + - `adsp/app/auth_service.py` (`AuthService`) + - `adsp/app/qa_service.py` (`QAService`) + +## Notes / production hardening + +- In production, this layer would typically be a real UI (e.g., Streamlit/React) calling an HTTP API, not in-process Python objects. +- Add attachment support (PDF/image) by extending the API to accept files and forwarding them to the orchestrator input handler. + diff --git a/docs/md/design/integration/end_to_end_flow.md b/docs/md/design/integration/end_to_end_flow.md new file mode 100644 index 0000000000000000000000000000000000000000..13af40126dc21f2dcc071fdd3c26e59e9a345eeb --- /dev/null +++ b/docs/md/design/integration/end_to_end_flow.md @@ -0,0 +1,38 @@ +# End-to-End Flow (Frontend → Core) + +This describes the current in-process execution path for a single chat message. + +## Call flow + +1. `ChatFrontend.send_message(user, token, persona_id, message)` +2. `AuthService.is_authorized(user, token)` +3. `QAService.ask(persona_id, query)` +4. `Orchestrator.handle_query(persona_id, query)` + - `InputHandler.normalize(query)` + - `RAGPipeline.retrieve(persona_id, normalized_query)` + - `PromptBuilder.build(persona_id, normalized_query, context)` + - `PersonaRouter.dispatch(persona_id, prompt)` + - `ConversationMemory.store(persona_id, {"query": ..., "response": ...})` + - `CacheClient.get/set(cache_key)` + +## Minimal usage example + +```python +from adsp.app import AuthService, QAService +from adsp.fe import ChatFrontend + +auth = AuthService() +auth.register("alice", "token123") + +frontend = ChatFrontend(qa_service=QAService(), auth_service=auth) +print(frontend.send_message("alice", "token123", "default", "What do you think about this idea?")) +``` + +## How to extend (recommended) + +- Add `session_id` to `ConversationMemory` so multiple conversations don’t collide under the same persona_id. +- Change `Orchestrator.handle_query()` to return a structured response (answer + citations + explanation) to support transparency. +- Implement “virtual focus group” fan-out: + - accept `persona_ids: list[str]` + - run orchestrator per persona and return an aggregated result + diff --git a/docs/md/design/integration/index.md b/docs/md/design/integration/index.md new file mode 100644 index 0000000000000000000000000000000000000000..0f3772b96615ca869bf75510019ff32a63d183ee --- /dev/null +++ b/docs/md/design/integration/index.md @@ -0,0 +1,11 @@ +# Integration Guides + +This folder documents how to run workflows end-to-end and how components connect across layers. + +## Guides + +- End-to-end runtime flow: `docs/md/design/integration/end_to_end_flow.md` +- Run local chat: `docs/md/design/integration/running_local_chat.md` +- Run persona extraction: `docs/md/design/integration/running_persona_extraction.md` +- Wire LangChain RAG into the orchestrator: `docs/md/design/integration/wiring_rag_into_orchestrator.md` +- Local configuration and environment variables: `docs/md/design/integration/local_dev_configuration.md` diff --git a/docs/md/design/integration/local_dev_configuration.md b/docs/md/design/integration/local_dev_configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..ef6b05825dcd6a4a14bc74abc78bf58e553d8d37 --- /dev/null +++ b/docs/md/design/integration/local_dev_configuration.md @@ -0,0 +1,40 @@ +# Local Dev Configuration + +## Project paths + +`adsp/config.py` defines canonical paths relative to the repo root: +- `DATA_DIR`, `RAW_DATA_DIR`, `INTERIM_DATA_DIR`, `PROCESSED_DATA_DIR` +- `MODELS_DIR` +- `REPORTS_DIR`, `FIGURES_DIR` + +These defaults are used by: +- persona extraction pipeline config (`PersonaExtractionConfig`) +- modeling CLIs (`train`, `predict`) + +## Environment variables + +`.env` is loaded at import time via `python-dotenv` in `adsp/config.py`. + +Create it from the provided template: +- `cp .env.example .env` + +Common variables: +- `VLLM_BASE_URL`, `VLLM_MODEL`, `VLLM_API_KEY` +- `REASONING_BASE_URL`, `REASONING_MODEL`, `REASONING_API_KEY` +- Runtime chat backend: + - `ADSP_LLM_BACKEND` (`stub` or `openai`) + - `ADSP_LLM_BASE_URL`, `ADSP_LLM_MODEL`, `ADSP_LLM_API_KEY` +- Persona data paths: + - `ADSP_PERSONAS_DIR` + - `ADSP_PERSONA_TRAITS_DIR` + +## Useful commands + +- Install deps: `make install` +- Lint: `make lint` +- Format: `make format` +- Run chat: `make chat` or `python scripts/run_chat.py chat --persona-id basic-traditional` + +## Notes on current repo state + +- Several components are stubs (in-memory storage, placeholder inference/training). The design docs call out recommended production replacements. diff --git a/docs/md/design/integration/running_local_chat.md b/docs/md/design/integration/running_local_chat.md new file mode 100644 index 0000000000000000000000000000000000000000..b294dbb6ba2329ebb6cf013ba5b741f35cc5b404 --- /dev/null +++ b/docs/md/design/integration/running_local_chat.md @@ -0,0 +1,47 @@ +# Running Local Chat + +This repo includes a runnable local chat loop that exercises the full FE → App → Core flow using: +- extracted persona profiles under `data/processed/personas/` +- local RAG over persona indicators (no external embedding model downloads) +- a stub generator by default (optional OpenAI-compatible backend) + +## Prerequisites + +- Install deps: `make install` +- (Optional) create a `.env`: `cp .env.example .env` + +## List personas + +```bash +python scripts/run_chat.py list-personas +``` + +## Interactive chat + +```bash +python scripts/run_chat.py chat --persona-id basic-traditional +``` + +## One-shot ask + +```bash +python scripts/run_chat.py ask "What do you value most?" --persona-id basic-traditional --top-k 5 +``` + +## Using an OpenAI-compatible backend (optional) + +If you have a local server (e.g., vLLM) exposing `/v1`: + +```bash +export ADSP_LLM_BACKEND=openai +export ADSP_LLM_BASE_URL=http://localhost:8000/v1 +export ADSP_LLM_MODEL= +export ADSP_LLM_API_KEY=EMPTY +python scripts/run_chat.py chat --persona-id basic-traditional +``` + +## Notes + +- Persona files are loaded from `ADSP_PERSONAS_DIR` (default: `data/processed/personas/individual`). +- Reasoning traits are loaded from `ADSP_PERSONA_TRAITS_DIR` (default: `data/processed/personas/common_traits`). + diff --git a/docs/md/design/integration/running_persona_extraction.md b/docs/md/design/integration/running_persona_extraction.md new file mode 100644 index 0000000000000000000000000000000000000000..2e0f066d37add0a6df1a18073428485b3b504194 --- /dev/null +++ b/docs/md/design/integration/running_persona_extraction.md @@ -0,0 +1,42 @@ +# Running Persona Extraction (PDF → Personas) + +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. + +## Prerequisites + +- Python environment with dependencies from `requirements.txt` +- A running OpenAI-compatible model server (commonly vLLM) that supports image inputs + +## Configure model endpoint + +You can provide config via CLI flags or environment variables: + +- `VLLM_BASE_URL` (default `http://localhost:8000/v1`) +- `VLLM_MODEL` (required) +- `VLLM_API_KEY` (default `EMPTY`) + +Optional reasoning model: +- `REASONING_BASE_URL` (defaults to `VLLM_BASE_URL`) +- `REASONING_MODEL` (optional; defaults to `VLLM_MODEL`) +- `REASONING_API_KEY` (defaults to `VLLM_API_KEY`) + +## Run + +```bash +python scripts/run_persona_extraction.py \ + --pdf-path "data/raw/lavazza/customer-segmentation/2023 03_FR_Consumers Segmentation France.pdf" \ + --vllm-model "" \ + --page-range 1,10 +``` + +## Outputs + +Default outputs are documented in: +- `docs/md/design/data_pipeline/persona_extraction_pipeline.md` + +## Debugging tips + +- Use `--no-cache` to force re-extraction of pages (ignores cached `pages/page_XXXX.json`). +- Use `--debug` to write raw model text to `data/interim/persona_extraction/debug/`. +- If model output is not parseable JSON, inspect `pages/page_XXXX.json` (`raw_text` and `error`). + diff --git a/docs/md/design/integration/wiring_rag_into_orchestrator.md b/docs/md/design/integration/wiring_rag_into_orchestrator.md new file mode 100644 index 0000000000000000000000000000000000000000..6c3c9dc93b2f2798f2499873aabffca5654ae093 --- /dev/null +++ b/docs/md/design/integration/wiring_rag_into_orchestrator.md @@ -0,0 +1,48 @@ +# Wiring LangChain RAG into the Orchestrator + +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. + +## Target behavior + +- Index persona indicators into a vector store at startup (or after extraction). +- At query time: + - retrieve top-k relevant indicator documents + - format them into a context string for the prompt + - return structured citations (doc_id/pages) for explainability + +## Building the index + +Inputs: +- persona profiles: `data/processed/personas/individual/*.json` +- schema loader: `adsp.data_pipeline.schema.load_persona_profile` + +Retriever: +- `adsp.data_pipeline.persona_data_pipeline.rag.PersonaIndicatorRAG` + +Embeddings: +- Provide any `langchain_core.embeddings.Embeddings` implementation. +- This repo includes `langchain-huggingface` + `sentence-transformers` in `requirements.txt`. + +## Query-time retrieval + +1. `docs = indicator_rag.search(query, k=5)` +2. `context = documents_to_context_prompt(docs)` +3. Build prompt: `PromptBuilder.build(..., context=context)` + +## Integrating with `Orchestrator` + +Recommended approach: +- Replace `RAGPipeline.retrieve()` to return both: + - `context: str` + - `citations: list[dict]` (derived from `Document.metadata` + `sources`) +- Update `Orchestrator.handle_query()` to return a structured response including citations. + +If you keep the current string-only API: +- You can still return `context` built from `documents_to_context_prompt()`, but citations will be lost unless added elsewhere. + +## Related docs + +- `docs/md/design/data_pipeline/indicator_rag.md` +- `docs/md/design/core/rag_pipeline.md` +- `docs/md/design/core/explanation.md` + diff --git a/docs/md/design/modeling/cli_predict.md b/docs/md/design/modeling/cli_predict.md new file mode 100644 index 0000000000000000000000000000000000000000..5532abf7245e228d97b50144bf76c7ba5502e824 --- /dev/null +++ b/docs/md/design/modeling/cli_predict.md @@ -0,0 +1,26 @@ +# Modeling: CLI `predict` + +**Code**: `adsp/modeling/predict.py` + +## Purpose + +CLI utility to run persona inference from a prompt file using `PersonaInferenceEngine`. + +## Usage + +```bash +python -m adsp.modeling.predict --persona-id default --prompt-path prompt.txt +``` + +## Interface + +Arguments: +- `persona_id` (default `"default"`) +- `prompt_path` (default `prompt.txt`) +- `model_dir` (default `models/` via `adsp.config.MODELS_DIR`; currently unused placeholder) + +## Key dependencies / technologies + +- `typer` CLI +- `pathlib.Path` + diff --git a/docs/md/design/modeling/cli_train.md b/docs/md/design/modeling/cli_train.md new file mode 100644 index 0000000000000000000000000000000000000000..3a7382c975e82ea3d244dc7fcc77a6bd65b78e5d --- /dev/null +++ b/docs/md/design/modeling/cli_train.md @@ -0,0 +1,25 @@ +# Modeling: CLI `train` + +**Code**: `adsp/modeling/train.py` + +## Purpose + +CLI wrapper around `PersonaTrainer`. + +## Usage + +```bash +python -m adsp.modeling.train --dataset-path data/processed/persona_dataset.parquet --output-dir models/ +``` + +## Interface + +Arguments: +- `dataset_path` (defaults to `data/processed/persona_dataset.parquet`) +- `output_dir` (defaults to `models/`) + +## Key dependencies / technologies + +- `typer` CLI +- `pathlib.Path` + diff --git a/docs/md/design/modeling/persona_inference_engine.md b/docs/md/design/modeling/persona_inference_engine.md new file mode 100644 index 0000000000000000000000000000000000000000..011abf30e60ac11bb8ab13c05c98d31728b7ba47 --- /dev/null +++ b/docs/md/design/modeling/persona_inference_engine.md @@ -0,0 +1,44 @@ +# Modeling: `PersonaInferenceEngine` + +**Code**: `adsp/modeling/inference.py` + +## Purpose + +`PersonaInferenceEngine` is the runtime “model serving” abstraction used by the Core `PersonaRouter`. + +Today it is a placeholder that echoes the prompt; in production it should be backed by a real LLM serving stack (vLLM/TGI/transformers). + +## Responsibilities + +- Generate a persona response given `(persona_id, prompt)` +- (Planned) load persona-specific adapters (LoRA) and apply decoding policies + +## Public API + +### `generate(persona_id: str, prompt: str) -> str` + +**Input** +- `persona_id`: used to select adapter/model +- `prompt`: full prompt from `PromptBuilder` + +**Output** +- response string + +## Current behavior + +- Returns `f"[{persona_id}] {prompt[:200]}"` + +## Key dependencies / technologies + +- Python `dataclasses` + +## Notes / production hardening + +Recommended features: +- Support OpenAI-compatible chat API calls and/or local `transformers` generation +- Adapter management: + - persona_id → adapter path + - hot reload / versioning +- Safety policies and refusal logic (“not enough data”) +- Structured outputs (answer + citations + explanation) + diff --git a/docs/md/design/modeling/persona_trainer.md b/docs/md/design/modeling/persona_trainer.md new file mode 100644 index 0000000000000000000000000000000000000000..7e2b0e312bba39fa3298d90b3fb7bf6c38344c80 --- /dev/null +++ b/docs/md/design/modeling/persona_trainer.md @@ -0,0 +1,45 @@ +# Modeling: `PersonaTrainer` + +**Code**: `adsp/modeling/training.py` + +## Purpose + +`PersonaTrainer` is the entrypoint for training persona adapters (PEFT/LoRA) so each persona can have a distinct voice and reasoning style. + +Today it is a stub that writes a placeholder file. + +## Responsibilities + +- Load a persona training dataset +- Train and export an adapter artifact to an output directory + +## Public API + +### `train() -> pathlib.Path` + +**Inputs** +- `dataset_path`: path to the training dataset +- `output_dir`: directory where the adapter is written + +**Output** +- Path to the saved adapter artifact + +## Current behavior + +- Writes `persona_adapter.bin` with placeholder content and returns its path. + +## Key dependencies / technologies + +- Python `dataclasses` +- `pathlib.Path` file IO + +## Notes / production hardening + +To implement actual PEFT training, typical stack: +- `transformers` + `peft` + `datasets` +- Base model checkpoint (e.g., Llama/Mistral family) +- Training data derived from: + - persona profile `summary_bio`, salient indicators, style_profile/value_frame + - curated dialogue examples +- Evaluation suite gating before promotion (see `docs/md/design/monitoring/evaluation_suite.md`) + diff --git a/docs/md/design/monitoring/evaluation_suite.md b/docs/md/design/monitoring/evaluation_suite.md new file mode 100644 index 0000000000000000000000000000000000000000..4426e132c5e715472a83a6a9116ee030b7d704e7 --- /dev/null +++ b/docs/md/design/monitoring/evaluation_suite.md @@ -0,0 +1,41 @@ +# Monitoring: `EvaluationSuite` + +**Code**: `adsp/monitoring/evaluation.py` + +## Purpose + +`EvaluationSuite` runs a list of checks against persona responses (rule-based, unit tests, or “LLM-as-judge” functions). + +## Responsibilities + +- Execute a configured set of `checks` on a response string +- Aggregate results into a dict keyed by check name + +## Public API + +### `run(response: str) -> dict` + +**Input** +- `response`: model output text + +**Output** +- `dict` mapping `check.__name__` → `check(response)` result + +## Data model + +- `checks: Iterable` of callables + +## Key dependencies / technologies + +- Python `dataclasses` +- Callable checks (can be pure Python, LLM calls, etc.) + +## Recommended checks for this project + +Aligned to `docs/md/design.md` requirements: +- Non-hallucination / “no evidence” fallback behavior +- Persona voice consistency (style_profile adherence) +- Citation/traceability presence (when using RAG) +- Toxicity/safety constraints +- Latency/token budget checks + diff --git a/docs/md/design/monitoring/metrics_collector.md b/docs/md/design/monitoring/metrics_collector.md new file mode 100644 index 0000000000000000000000000000000000000000..e7e390ee322e122e5ca728dac5c07ee1ca4e8ddf --- /dev/null +++ b/docs/md/design/monitoring/metrics_collector.md @@ -0,0 +1,48 @@ +# Monitoring: `MetricsCollector` + +**Code**: `adsp/monitoring/metrics.py` + +## Purpose + +`MetricsCollector` is a minimal metrics sink for counters/gauges in-process. It corresponds to the observability layer in `docs/md/design.md`. + +## Responsibilities + +- Increment counters (`incr`) +- Set gauges (`write`) +- Read current values (`read`) + +## Public API + +### `incr(name: str, value: float = 1.0) -> None` + +Adds `value` to the metric `name`. + +### `write(name: str, value: float = 1.0) -> float` + +Sets the metric `name` to `value` and returns the stored value. + +### `read(name: str) -> float` + +Returns current value for `name`, defaulting to `0.0`. + +## Data model + +- `_metrics: Dict[str, float]` (in-memory) + +## Key dependencies / technologies + +- Python `dataclasses` +- In-memory storage (`dict`) + +## Notes / production hardening + +Replace with: +- Prometheus metrics (client library + scrape endpoint) +- OpenTelemetry traces and logs correlation +- Structured metrics for: + - request latency (p50/p95/p99) + - retrieval hits/misses + - cache hit ratio + - model token usage + diff --git a/docs/md/design/overview/component_map.md b/docs/md/design/overview/component_map.md new file mode 100644 index 0000000000000000000000000000000000000000..375975551382363b46ef5785a034099ac7cb367c --- /dev/null +++ b/docs/md/design/overview/component_map.md @@ -0,0 +1,32 @@ +# Component Map (Architecture → Code) + +This document maps the system architecture in `docs/md/design.md` to the current code layout under `adsp/`. + +> Note: Several “services” are currently implemented as in-process Python classes (stubs/placeholders). The docs describe the current interfaces and also call out production-grade upgrades where the architecture expects distributed services. + +## Layer map + +| Architecture layer | Primary code location | Primary components (code) | Design docs | +|---|---|---|---| +| UI / Frontend | `adsp/fe/` | `ChatFrontend` | `docs/md/design/frontend/chat_frontend.md` | +| Application layer | `adsp/app/` | `AuthService`, `QAService`, `IngestionService`, `ReportService`, `PersonaConfigurationService`, REST API (`api_server.py`) | `docs/md/design/application/` | +| Communication layer | `adsp/communication/` | `RPCClient`, `CacheClient`, `EventBroker` | `docs/md/design/communication/` | +| Core layer | `adsp/core/` | `Orchestrator`, `InputHandler`, `PromptBuilder`, `PersonaRegistry`, `PersonaRouter`, `RAGPipeline`, `ConversationMemory`, `MCPServer` | `docs/md/design/core/` | +| Data pipeline (background) | `adsp/data_pipeline/` | persona extraction + schema + RAG indexing | `docs/md/design/data_pipeline/` | +| Modeling (background + runtime) | `adsp/modeling/` | `PersonaTrainer`, `PersonaInferenceEngine` | `docs/md/design/modeling/` | +| Monitoring & evaluation | `adsp/monitoring/` | `EvaluationSuite`, `MetricsCollector` | `docs/md/design/monitoring/` | +| Storage | `adsp/storage/` | `BusinessDatabase`, `object_store.put/get`, `VectorDatabase` | `docs/md/design/storage/` | + +## Key end-to-end runtime flow (current implementation) + +1. `ChatFrontend.send_message()` checks `AuthService.is_authorized()` +2. `QAService.ask()` instantiates `core.orchestrator.Orchestrator` and calls `Orchestrator.handle_query()` +3. `Orchestrator.handle_query()`: + - normalizes input (`InputHandler.normalize`) + - retrieves context (`RAGPipeline.retrieve`) + - builds prompt (`PromptBuilder.build`) + - dispatches to persona inference (`PersonaRouter.dispatch`) + - stores conversation history (`ConversationMemory.store`) + - caches response (`CacheClient.set`) + +See: `docs/md/design/integration/end_to_end_flow.md` diff --git a/docs/md/design/overview/data_contracts.md b/docs/md/design/overview/data_contracts.md new file mode 100644 index 0000000000000000000000000000000000000000..86ce8c656751e72bd429b872ae4429db0e9a0ced --- /dev/null +++ b/docs/md/design/overview/data_contracts.md @@ -0,0 +1,60 @@ +# Data Contracts & Schemas + +This system’s behavior depends on a few core payloads that move between layers (persona profile JSON, prompts, extraction outputs, retrieval context). + +## Persona profile (canonical) + +**Source of truth** +- Extraction pipeline outputs: `data/processed/personas/personas.json` and `data/processed/personas/individual/*.json` +- Pydantic model: `adsp/data_pipeline/schema.py` (`PersonaProfileModel`) +- Human-readable doc: `docs/md/persona_profile_schema.md` + +**Key fields (high level)** +- Identity: `persona_id`, `persona_name` +- Description: `visual_description`, `summary_bio` +- Evidence: `indicators[]` (each indicator contains `statements[]`, `metrics[]`, and `sources[]`) +- Traceability: `source_pages[]`, `document` +- Optional reasoning enrichment: + - `key_indicators[]` (salient statements, derived) + - `style_profile`, `value_frame`, `reasoning_policies`, `content_filters` + +## Orchestrator request/response + +**Current in-process call** +- Input: `persona_id: str`, `query: str` +- Output: `response: str` + +In production the same contract typically becomes an HTTP/gRPC endpoint: +- Request: `{ persona_id, query, attachments?, session_id? }` +- Response: `{ answer, citations?, explanation?, tool_calls?, latency_ms? }` + +See: `docs/md/design/core/orchestrator.md` + +## Page-level extraction output (intermediate) + +Produced by `PersonaExtractionPipeline` and stored under `data/interim/persona_extraction/`: + +- **Rendered pages**: `page_images/page_XXXX.png` +- **Raw page responses**: `pages/page_XXXX.json` + - `{ page, parsed, error, raw_text }` +- **Structured pages dump** (optional): `pages_structured.json` + +Core typed representation: +- `adsp/data_pipeline/persona_data_pipeline/extract_raw/models.py` + - `PageImage { page_number, image_path, width, height }` + - `PageExtractionResult { page_number, raw_text, parsed, error }` + +## Retrieval context (RAG) + +Two retriever paths exist today: + +1. **Core stub retriever** (used by `Orchestrator`): + - `adsp/storage/vector_db.py` returns a string context via `VectorDatabase.search()` + +2. **LangChain-based indicator retriever** (data-pipeline utility): + - `adsp/data_pipeline/persona_data_pipeline/rag/indicator.py` + - `PersonaIndicatorRAG.search()` returns `langchain_core.documents.Document[]` + - `documents_to_context_prompt()` converts documents into a prompt-ready context string + +See: `docs/md/design/data_pipeline/indicator_rag.md` and `docs/md/design/core/rag_pipeline.md` + diff --git a/docs/md/design/overview/glossary.md b/docs/md/design/overview/glossary.md new file mode 100644 index 0000000000000000000000000000000000000000..a678ff1076d452c5b9e249ce8f87e40d644b5527 --- /dev/null +++ b/docs/md/design/overview/glossary.md @@ -0,0 +1,20 @@ +# Glossary + +## Core persona terms + +- **Persona**: A synthetic agent representing a consumer segment, grounded in proprietary segmentation evidence. +- **Persona profile**: JSON object describing the persona (identity + indicators + optional reasoning traits). +- **Indicator**: A bucketed theme (e.g., “Demographics”, “Coffee behavior”) containing multiple statements. +- **Statement**: A single insight line item within an indicator; can include metrics and salience. +- **Metric**: A normalized value for a statement (e.g., `58 %`, `120 index`). +- **Salience**: Whether a statement is visually/semantically emphasized and should strongly influence reasoning. +- **Influences**: Flags indicating whether the statement shapes the persona’s *tone* and/or *stance*. + +## LLM system terms + +- **RAG (Retrieval-Augmented Generation)**: Retrieve relevant evidence at query time and inject it into the prompt to reduce hallucination and increase traceability. +- **Vector DB**: Stores embeddings and supports similarity search for RAG. +- **PEFT / LoRA**: Parameter-Efficient Fine-Tuning methods to instill persona voice and reasoning style without retraining an entire LLM. +- **vLLM (OpenAI-compatible)**: A local/private model server that can expose OpenAI-style `/v1` APIs (used for extraction/reasoning in this repo via the `openai` Python client). +- **MCP (Model Context Protocol)**: A standard interface for “tools” (web search, DB queries, calculators) that can provide extra context to an LLM. + diff --git a/docs/md/design/overview/index.md b/docs/md/design/overview/index.md new file mode 100644 index 0000000000000000000000000000000000000000..61d2e4dc00d1f40f27d05599d25486fe38f9219e --- /dev/null +++ b/docs/md/design/overview/index.md @@ -0,0 +1,21 @@ +# Design Deep Dives + +This folder breaks down the high-level architecture in `docs/md/design.md` into per-component design documents. + +## How to read these docs + +1. Start with `docs/md/design/overview/component_map.md` to understand how architecture layers map to code. +2. Use the layer folders (`frontend/`, `core/`, `data_pipeline/`, etc.) to deep-dive into each component’s logic and interface. +3. Use `docs/md/design/integration/` docs to run workflows end-to-end and understand how components connect. + +## Layers + +- Frontend: `docs/md/design/frontend/chat_frontend.md` +- Application services: `docs/md/design/application/auth_service.md`, `docs/md/design/application/qa_service.md`, ... +- REST API server: `docs/md/design/application/rest_api_server.md` +- Communication: `docs/md/design/communication/cache_client.md`, `docs/md/design/communication/event_broker.md`, `docs/md/design/communication/rpc_client.md` +- Core: `docs/md/design/core/orchestrator.md` (plus prompt/RAG/router/memory) +- Data pipeline: `docs/md/design/data_pipeline/persona_extraction_pipeline.md` (plus renderer/extractor/merger/reasoner) +- Storage: `docs/md/design/storage/object_store.md`, `docs/md/design/storage/vector_database.md`, `docs/md/design/storage/business_database.md` +- Modeling: `docs/md/design/modeling/persona_inference_engine.md`, `docs/md/design/modeling/persona_trainer.md` +- Monitoring: `docs/md/design/monitoring/evaluation_suite.md`, `docs/md/design/monitoring/metrics_collector.md` diff --git a/docs/md/design/storage/business_database.md b/docs/md/design/storage/business_database.md new file mode 100644 index 0000000000000000000000000000000000000000..40ff421180cd87a7cdcb16d976c164625f77bc78 --- /dev/null +++ b/docs/md/design/storage/business_database.md @@ -0,0 +1,41 @@ +# Storage: `BusinessDatabase` + +**Code**: `adsp/storage/business_db.py` + +## Purpose + +`BusinessDatabase` represents the system-of-record store for non-vector, structured data (users, auth records, persona definitions, reports metadata). + +## Responsibilities + +- Upsert structured records into named “tables” +- Fetch records by key + +## Public API + +### `upsert(table: str, key: str, value: dict) -> None` + +Stores `value` under the given `(table, key)`. + +### `fetch(table: str, key: str) -> dict` + +Returns the stored record, or `{}` if missing. + +## Data model + +- `_tables: Dict[str, Dict]` (in-memory) + +## Key dependencies / technologies + +- Python `dataclasses` +- In-memory storage (`dict`) + +## Notes / production hardening + +Replace with a real DB (e.g., Postgres) and define explicit tables: +- `users` +- `sessions` / `tokens` +- `persona_definitions` +- `reports` +- `audit_logs` (especially important for explainability and compliance) + diff --git a/docs/md/design/storage/object_store.md b/docs/md/design/storage/object_store.md new file mode 100644 index 0000000000000000000000000000000000000000..cb7b3f1324479098dbafbdc7e6675ab3dcabf034 --- /dev/null +++ b/docs/md/design/storage/object_store.md @@ -0,0 +1,40 @@ +# Storage: `object_store` + +**Code**: `adsp/storage/object_store.py` + +## Purpose + +`object_store` is a minimal object storage shim used by ingestion and pipelines. In the architecture it corresponds to S3 (or equivalent). + +## Responsibilities + +- Store bytes for a file under a bucket/key +- Retrieve stored bytes by bucket/key + +## Public API + +### `put(bucket: str, file_path: pathlib.Path) -> None` + +Reads bytes from `file_path` and stores them under `(bucket, file_path.name)`. + +### `get(bucket: str, key: str) -> bytes` + +Returns stored bytes for `(bucket, key)`. + +## Data model + +- `_STORE: Dict[str, Dict[str, bytes]]` (process-global in-memory) + +## Key dependencies / technologies + +- `pathlib.Path` for file IO +- In-memory dictionary storage + +## Notes / production hardening + +Replace with: +- AWS S3 / MinIO / GCS / Azure Blob client +- Content-addressable keys (hash-based) to avoid accidental overwrites +- Metadata (content type, original filename, uploaded_by, timestamps) +- Pre-signed URLs for frontend upload/download + diff --git a/docs/md/design/storage/vector_database.md b/docs/md/design/storage/vector_database.md new file mode 100644 index 0000000000000000000000000000000000000000..945f91b7ec66a3635962eee35190abb67597db0a --- /dev/null +++ b/docs/md/design/storage/vector_database.md @@ -0,0 +1,47 @@ +# Storage: `VectorDatabase` + +**Code**: `adsp/storage/vector_db.py` + +## Purpose + +`VectorDatabase` is a placeholder vector store used by the Core RAG pipeline to retrieve grounding context. + +## Responsibilities + +- Store persona-associated “documents” (currently strings) +- Return a relevant document for a query (currently naive) + +## Public API + +### `upsert(persona_id: str, document: str) -> None` + +Appends `document` to the persona’s document list. + +### `search(persona_id: str, query: str) -> str` + +Returns the last stored document for the persona, or `""` if none exists. + +## Data model + +- `_documents: DefaultDict[str, List[str]]` (in-memory) + +## Current usage + +Used by: +- `adsp/core/rag/__init__.py` (`RAGPipeline.retrieve()` → `VectorDatabase.search()`) + +## Key dependencies / technologies + +- Python `dataclasses` +- `collections.defaultdict` + +## Notes / production hardening + +Replace with a real vector DB (FAISS/Chroma/Weaviate/Pinecone/etc.) plus: +- Embeddings model (e.g., `sentence-transformers` or `langchain-huggingface`) +- Metadata filters (persona_id, indicator domain/category, document/page ids) +- Source citations returned as structured data (not just a string) + +If you plan to use LangChain’s in-memory vector store today, see: +- `docs/md/design/data_pipeline/indicator_rag.md` + diff --git a/docs/md/evaluation.md b/docs/md/evaluation.md new file mode 100644 index 0000000000000000000000000000000000000000..72ce5f92b84470dfbeb4c1a1904edde019e35201 --- /dev/null +++ b/docs/md/evaluation.md @@ -0,0 +1,413 @@ +# Lavazza AI Personas - Evaluation Guide + +**Version:** 1.0 +**Date:** December 2025 +**Purpose:** Focused evaluation framework for critical system components + +--- + +## 1. Introduction + +### 1.1 Purpose + +This document provides detailed evaluation methodologies for four critical components of the Lavazza AI Personas system: + +1. **Persona Extraction Pipeline** - Validates extraction of persona indicators/metrics from PDF documents +2. **Fact Extraction Accuracy** - Ensures fact data is correctly extracted +3. **Retrieval Relevance** - Measures RAG system's ability to retrieve relevant context +4. **Authenticity Evaluation** - Confirms AI personas authentically represent consumer segments + +### 1.2 Evaluation Philosophy + +Each evaluation follows a structured approach: + +- **Clear objectives** - What we are measuring +- **Step-by-step methodology** - How to conduct the evaluation +- **Example data structures** - Concrete formats for test data + +--- + +## 2. Evaluation Overview + +### 2.1 Critical Components Priority + +| Component | Criticality | Impact | Evaluation Focus | +|----------------------|-------------|---------------------------------|-------------------------------------| +| Persona Extraction | CRITICAL | Foundation for all persona data | Accuracy, completeness, consistency | +| Fact Extraction | CRITICAL | Factual grounding for responses | Numeric accuracy, attribution | +| RAG Retrieval | CRITICAL | Prevents hallucinations | Relevance, precision, recall | +| Persona Authenticity | HIGH | User trust and value | Segment alignment, consistency | + + +## 3. Persona Extraction Pipeline Evaluation + +### 3.1 Objective + +Verify that persona indicators (categories,statements, metrics) are correctly extracted from source PDF documents. + +### 3.2 Methodology + +#### Step 1: Create Ground Truth Dataset + +**Action:** Manually annotate 20-30 representative PDF pages (focusing on Curious Connoisseur Segmentation). + +**Annotation Process:** + +1. Select pages covering: + - Curious Connoisseur persona segment + - Various indicator types (demographics, behaviors, preferences, values) + - Different visual styles (infographics, tables, text blocks) + +2. For each page, document: + - Expected personas mentioned + - Expected indicators with complete taxonomy (domain/category) + - Expected statements with associated metrics + +3. Store annotations in structured JSON format + +**Example Ground Truth Structure:** + +```json +{ + "page_id": "page_11", + "data_source": "data/raw/lavazza_segmentation_report.pdf", + "page_number": 11, + "ground_truth": { + "personas": [ + "curious-connoisseurs" + ], + "indicators": [ + { + "indicator_id": "gt_ind_001", + "persona_id": "curious-connoisseurs", + "domain": "demographics", + "category": "age", + "label": "age_distribution", + "statements": [ + { + "label": "45-54 age group", + "metrics": [ + { + "value": 24.0, + "unit": "%", + "description": "45-65 age group representation" + } + ] + } + ] + } + ] + } +} +``` + +#### Step 2: Run Extraction Pipeline + +**Action:** Execute persona extraction on the same annotated pages. + +#### Step 3: Compare and Compute Metrics + +**Action:** Compare system output against ground truth. + +**Metrics to Compute:** + +1. **Persona Detection Rate** + ``` + Persona Detection Rate = (Correctly Detected Personas) / (Total Ground Truth Personas) + ``` + +2. **Metric Recall** + ``` + Metrics Recall = (Correctly Metrics) / (Total Ground Truth Metrics) + ``` + +3. **Metric Precision** + ``` + Metrics Precision = (Correct Metrics) / (All Extracted Metrics) + ``` + + +**Metric Matching Rules** + +Only retain **indicators** and **statements** that contain **at least one metric**. + +A metric is considered a match with a ground truth metric **if all of the following conditions are satisfied**: + + 1. Indicator Match + + An indicator matches the ground truth if the number of shared words between the indicator label (or description) and the ground truth label, divided by the smaller word count, is at least 70%. + 2. Statement Label Match + + A statement label matches the ground truth if the number of shared words between the statement label and the ground truth label, divided by the smaller word count, is at least 70%. + + 3. Value Match + + The metric value must match the ground truth value. + + 4. Unit Match + + Units are considered equivalent if they belong to the same synonym group defined below. + + **Unit Synonym Mapping** + + | Equivalent Units | + | ---------------- | + | %, percentage | + | index, idx | + | €, euro, eur | + | $, dollar, usd | + | £, pound, gbp | + | ¥, yen, jpy | + | ₹, rupee, inr | + | ₩, won, krw | + | ₽, ruble, rub | + | ₺, lira, try | + | ₫, dong, vnd | + | ₱, peso, php | + | ₦, naira, ngn | + | ₴, hryvnia, uah | + | ₡, colon, crc | + | ₲, guarani, pyg | + | ₵, cedi, ghc | + | ₸, tenge, kzt | + | ₼, manat, azn | + +**Implementation Notes** + +* Normalize text (lowercase, remove punctuation, collapse whitespace) before computing word intersections. +* Apply the 70% threshold consistently across all matching steps. + + + +## 4. Fact Extraction Accuracy Evaluation + +### 4.1 Objective + +Ensure data (numbers, percentages, ratios) are correctly extracted from PDF charts, tables, and infographics. + +### 4.2 Methodology + +#### Step 1: Create Ground Truth from Source Data + +**Action:** Obtain or create ground truth with known values. + +Manually extract and verify statistics from 20-30 test pages (focus on Curious Connoisseurs). + +**Example Ground Truth Data Structure:** + +```json +{ + "fact_id": "fact_demographics_001", + "data_source": "data/raw/lavazza_segmentation_report.pdf", + "page_number": 11, + "facts": [ + { + "value": "52%", + "context": "female percentage in segment" + }, + { + "value": "Ground Coffee: 79, Caps (NCC): 104, Coffee Beans: 206, Caps (NC): 79, Instant Coffee: 49, Paper Pods: 91", + "context": "Consumption index of curious connoisseurs" + } + ] +} +``` + +#### Step 2: Run Fact Extraction Pipeline + +**Action:** Extract facts data using the pipeline to get markdown files for each page. + +#### Step 3: Compare and Compute Metrics + +**Metrics:** + +1. **Exact Match Accuracy** + ``` + Exact Match Accuracy = (Exactly Matching Values) / (Total Ground Truth Values) + ``` + +**Note:** A value is considered a match if more than 80% of the words from the ground truth appear in the markdown file. + +## 5. Retrieval Relevance Evaluation + +### 5.1 Objective + +Measure how well the RAG system retrieves relevant persona and fact context for user queries. + +### 5.2 Methodology + +#### Step 1: Create Query-Relevance Dataset + +**Action:** Generate test queries( focus on Curious Connoisseurs). + +**Example Test Queries:** + +```json +{ + "test_queries": [ + { + "query_id": "q_001", + "persona_id": "curious-connoisseurs", + "query": "What is your age?" + }, + { + "query_id": "q_002", + "persona_id": "curious-connoisseurs", + "query": "What is your gender?" + } + ] +} +``` + +#### Step 2: Run Retrieval System + +**Action:** Execute RAG retrieval for all test queries. + +#### Step 3: Manually Label Relevance + +For each query, manually label the relevance of retrieved documents. + +**Relevance Labels:** + +- **1 :** Related +- **0 :** Unrelated + +**Example Relevance Annotation:** + +```json +{ + "query_id": "q_001", + "persona_id": "curious-connoisseurs", + "query": "What is your age?", + "relevant_docs": [ + { + "page_content": "Average age is 47 years old", + "relevance": 1 + }, + { + "page_content": "I like to try out new food or drink products", + "relevance": 0 + } + ] +} +``` + +#### Step 4: Compute Retrieval Metrics + +**Metrics:** + +1. **Precision@K** + ``` + Precision@K = (Relevant docs in top-K) / K + ``` + +2. **Recall@K** + ``` + Recall@K = (Relevant docs in top-K) / (Total relevant docs) + ``` +**Implementation notes:** + +* Set retrieval **top-k = 20** (configable) to ensure high recall. +* Manually review the retrieved chunks and mark those that are relevant. +* Treat **all marked relevant chunks** as the ground-truth recall set. +* Compute **Precision@k** and **Recall@k** for **k = 3, 5, 10, and 20**. + +## 6. Authenticity Evaluation + +### 6.1 Objective + +Ensure AI personas authentically represent their consumer segments through expert validation and consistency testing. + +### 6.2 Methodology + +#### Step 1: Generate Persona Responses + +**Action:** Create a set of test questions and generate persona responses (focus on Curious Connoisseurs). + +**Test Question Categories:** + +```json +{ + "test_questions": [ + { + "persona_id": "curious-connoisseurs", + "query": "What coffee format do you prefer and why?", + "category": "product_preferences" + }, + { + "persona_id": "curious-connoisseurs", + "query": "What factors influence your coffee purchasing decision?", + "category": "product_preferences" + } + ] +} +``` + +#### Step 2: Response Generation + +Use the system to generate responses for the persona to all test questions. + +#### Step 3: Expert Evaluation + +**Action:** Have domain experts rate persona authenticity. + +*Rating Criteria:* + +1. **Authenticity (1-5 scale)** + - How well does the response reflect the expected persona characteristics? + - 1 = Not authentic, 5 = Very authentic +2. **Style Alignment** + - Tone, vocabulary, reasoning depth + - 1 = Poorly aligned, 5 = Perfectly aligned +3. **Factual Grounding** + - Are statements factually accurate and well-cited? + - 1 = No citations/hallucinations, 5 = Well-cited and accurate + +**Expert Evaluation Form:** + +```json +{ + "test_questions": [ + { + "persona_id": "curious-connoisseurs", + "query": "What coffee format do you prefer and why?", + "category": "product_preferences", + "response": "I prefer espresso because...", + "ratings": { + "authenticity": 3, + "style_alignment": 4, + "factual_grounding": 5 + } + }, + { + "persona_id": "curious-connoisseurs", + "query": "What factors influence your coffee purchasing decision?", + "category": "product_preferences", + "response": "Quality is my primary consideration because...", + "ratings": { + "authenticity": 4, + "style_alignment": 4, + "factual_grounding": 1 + } + } + ] +} +``` + +#### Step 4: Compute Authenticity Metrics + +**Metrics:** + +1. **Expert Authenticity Score** + ``` + Average authenticity rating across all expert evaluations (1-5 scale) + ``` + +2. **Style Alignment Score** + ``` + Average style alignment rating across all expert evaluations (1-5 scale) + ``` +3. **Factual Grounding Score** + ``` + Average factual grounding rating across all expert evaluations (1-5 scale) + ``` \ No newline at end of file diff --git a/docs/md/folder_structure.md b/docs/md/folder_structure.md new file mode 100644 index 0000000000000000000000000000000000000000..f78f126b46d8db8f0fdc601bee5e0b57e8147592 --- /dev/null +++ b/docs/md/folder_structure.md @@ -0,0 +1,79 @@ +# Repository Folder Structure + +This document mirrors the layout described in `README.md` and expands on how each directory supports the Lavazza AI Personas system design. + +## High-Level Layout + +```text +root/ +├── LICENSE +├── Makefile +├── pyproject.toml +├── requirements.txt +├── setup.cfg +├── README.md +├── data/ +│ ├── raw/ +│ ├── interim/ +│ ├── processed/ +│ └── external/ +├── docs/ +│ ├── design.md +│ ├── folder_structure.md +│ ├── images/ +│ └── docs/ (MkDocs sources) +├── models/ +├── notebooks/ +├── references/ +├── reports/ +│ └── figures/ +├── tests/ +└── adsp/ + ├── config.py + ├── fe/ + ├── app/ + ├── communication/ + ├── core/ + │ ├── input_handler/ + │ ├── memory/ + │ ├── orchestrator/ + │ ├── persona_registry/ + │ ├── ai_persona_router/ + │ ├── prompt_builder/ + │ ├── rag/ + │ └── mcp_server/ + │ └── tools/ + ├── data_pipeline/ + ├── modeling/ + ├── monitoring/ + ├── storage/ + └── utils/ +``` + +## Directory Details + +### Root-Level Assets +- `README.md` – quickstart for contributors; tree above stays in sync with that section. +- `pyproject.toml`, `requirements.txt`, `setup.cfg` – dependency and tooling configuration. +- `Makefile` – automation hooks for ingestion, training, and evaluation workflows. +- `LICENSE` – legal terms for redistribution. + +### Data & Knowledge Repositories +- `data/` – canonical datasets following the Cookiecutter Data Science immutability rules (`raw/` is read-only, `processed/` feeds modeling/RAG, etc.). +- `references/` – persona briefs, dictionaries, and qualitative research artifacts. +- `docs/` – architecture materials, including `design.md` and this structure guide. The nested `docs/` directory contains MkDocs pages for publishing to a documentation site. +- `reports/` – generated deliverables; `reports/figures/` stores reusable charts. + +### Source Code (`adsp/`) +- `fe/` – Frontend prototypes (e.g., chat client) that orchestrate authentication plus Q&A calls, reflecting the UI entry point from the system design. +- `app/` – Application layer services invoked by UI clients. Each module mirrors the services called out in the design: persona configuration, ingestion orchestration, report generation, Q&A routing, and authentication. +- `communication/` – RPC, cache, and message broker connectors that model the Communication layer of the architecture. +- `core/` – Home of the Orchestrator, prompt construction, memory, persona registry/router, and the MCP Server package that manages tool access via Model Context Protocol. +- `data_pipeline/` – ETL/RAG ingestion helpers that load PDFs/images, normalize them, and populate the vector store via a consistent schema. +- `modeling/` – Training/inference code for PEFT adapters (`training.py`, `train.py` CLI) and runtime persona inference (`inference.py`, `predict.py`). +- `monitoring/` – Evaluation suites plus lightweight metrics collection matching the Monitoring & Evaluation layer. +- `storage/` – Connectors for business databases, object storage, and the vector database abstraction. +- `utils/` – Cross-cutting helpers like logging configuration and custom exceptions. + +### Testing +- `tests/` – Central place for automated regression and contract tests. As new modules go live, add suites here to cover their behavior. diff --git a/docs/md/index.md b/docs/md/index.md new file mode 100644 index 0000000000000000000000000000000000000000..8a30ad7f14f8849aa737df8b9084e2428c168e2f --- /dev/null +++ b/docs/md/index.md @@ -0,0 +1,10 @@ +# 2025-P3-AI-Personas documentation! + +## Description + +Applied Data Science Project + +## Commands + +The Makefile contains the central entry points for common tasks related to this project. + diff --git a/docs/md/persona_extraction_pipeline.md b/docs/md/persona_extraction_pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..1a22bc091464383a9b285511dcf54e8d4f5656e2 --- /dev/null +++ b/docs/md/persona_extraction_pipeline.md @@ -0,0 +1,136 @@ +# Persona Extraction Pipeline + +High-level overview of how a PDF becomes persona data and derived reasoning artifacts. + +## Processing Stages +1) **Ingest & Render** + - Load the PDF and render pages to images (reuse cached renders when enabled). + +2) **VLLM Page Extraction** + - Send each target page (plus optional context) to the vision model with the indicator-centric persona prompt. The prompt is generalized to pull persona indicators from any document type (not tied to fixed templates). + - Persist raw responses and parsed JSON per page; optionally write debug text. When caching is on, skip extraction for the pages where the raw responses are already extracted + +3) **Aggregate & Persist** + - Merge page-level personas, general content, and metadata into: + - Merged personas bundle (`personas.json`) + - Per-persona files (`individual/{persona_id}.json`) + - QA report and structured per-page dump + +4) **Reasoning** + - Collect salient statements and run a text model to derive persona traits (style/value/guardrails). + - Chunk inputs if large; reuse cached results when present. + - Write per-persona reasoning artifacts to `common_traits/{persona_id}.json`. + +### Indicators (VLLM extraction output) +- `indicators`: top-level buckets (domain/category/label) grouping related statements. +- `statements`: individual insights within an indicator; each carries metrics, salience, and influences. +- `metrics`: normalized numeric/text measures with units (`index`, `%`, `count`, `rank`, `€`, `other`) plus optional description/context. +- `salience`: marks whether a statement is visually emphasized (`is_salient`) with direction (`high|low|neutral`) and magnitude (`strong|medium|weak`), and a short rationale. +- `influences`: flags whether a statement shapes tone or stance of the persona. +- `sources`: document/page references for traceability. + +Example indicator shape (with field meanings): +```json +Indicator { + id: "string", + domain: "string", // broad area, e.g., "demographics", "coffee_behaviour", "media" + category: "string", // finer grouping, e.g., "age_band", "format", "machine_ownership" + label: "string", // human-readable title of the indicator + description: "string", // optional extra context/definition + + sources: [ + { + "doc_id": "2023_03_FR_Consumers_Segmentation_France", // document identifier/name + "pages": [10, 12] // page references for traceability + } + ], + + statements: [ + { + "label": "Skewing Female", // short handle for the insight + "description": "Majority female within this persona", // fuller text/quote + "metrics": [ + { + "value": 58, // numeric value (or string if needed) + "unit": "%", // normalized unit: %, index, rank, count, €, other + "description": "of persona" // optional context for the metric + }, + { + "value": 120, + "unit": "index", + "description": "vs population" + } + ], + "salience": { + "is_salient": true, // highlighted/important? + "direction": "high", // high | low | neutral + "magnitude": "strong", // strong | medium | weak + "rationale": "Highlighted and index 120" // why it's salient + }, + "influences": { + "tone": false, // Should this statement shape how the LLM talks? + "stance": true // Should this statement shape what the LLM prioritises? + } + } + ] +} +``` + +### Traits (reasoning output) +- `style_profile`: how the persona would speak (tone adjectives, formality, directness, emotional flavour, criticality, verbosity, preferred structures, example phrases). +- `value_frame`: what they prioritize as core values (priority_rank plus sustainability, price sensitivity, novelty seeking, brand loyalty, health concern, and a summary description). +- `reasoning_policies`: + - `purchase_advice`: default biases and tradeoff rules to apply when recommending. + - `product_evaluation`: what earns praise, what triggers criticism, and must-always-check items. + - `information_processing`: trust preferences, skepticism targets, and requested rigor level. +- `content_filters`: styles to avoid and topics needing emphasized disclaimers (e.g., health claims). + +Canonical shapes for reasoning traits: +```json +// How the model should "speak" +style_profile: { + tone_adjectives: string[], // ["curious", "confident", "quality-focused", "pragmatic", ...] + formality_level: "low" | "medium" | "high", + directness: "very_direct" | "balanced" | "hedged", + emotional_flavour: "neutral" | "enthusiastic" | "cool_detached" | "warm_reflective", + criticality_level: "high" | "medium" | "low", + verbosity_preference: "concise" | "detailed" | "varies_by_question", + preferred_structures: string[], // ["bullet_points", "clear_tradeoffs", "pros_cons", "step_by_step"] + typical_register_examples: string[] // short example phrases in-target style +}, + +// What they care about – used to bias recommendations / reasoning +value_frame: { + priority_rank: string[], // e.g. ["quality", "convenience", "sustainability", "price"] + sustainability_orientation: "high" | "medium" | "low", + price_sensitivity: "high" | "medium" | "low", + novelty_seeking: "high" | "medium" | "low", + brand_loyalty: "high" | "medium" | "low", + health_concern: "high" | "medium" | "low", + description: string // natural language summary +}, + +// Concrete behavioural rules for the model: "given a question, lean this way" +reasoning_policies: { + purchase_advice: { + default_biases: string[], // e.g. ["prefer quality even at higher price", "avoid cheap but low-quality options"] + tradeoff_rules: string[], // e.g. ["if forced to choose, sacrifice price before quality", "flag environmental impact of packaging when relevant"] + }, + product_evaluation: { + praise_triggers: string[], // conditions that justify positive language + criticism_triggers: string[], // conditions to be sceptical / critical + must_always_check: string[] // things the model must always comment on (e.g. origin, sustainability) + }, + information_processing: { + trust_preference: string[], // ["data + evidence", "real-world usage", "expert sources"] + scepticism_towards: string[], // ["vague marketing claims", "unverified health promises"] + requested_rigor_level: "high" | "medium" | "low" + } +}, + +// Guardrails aligned with persona (in addition to global safety policies) +content_filters: { + avoid_styles: string[], // e.g. ["overly emotional hype", "blind brand loyalty"] + emphasise_disclaimers_on: string[] // ["health claims", "environmental certifications"] +} +``` diff --git a/docs/md/persona_profile_schema.md b/docs/md/persona_profile_schema.md new file mode 100644 index 0000000000000000000000000000000000000000..3a2052bfcae9ee663385b2039b31580954d11c0e --- /dev/null +++ b/docs/md/persona_profile_schema.md @@ -0,0 +1,62 @@ +# Persona Profile Schema + +This schema reflects the JSON produced by the extraction pipeline and used by downstream persona consumers. + +## Shape + +```json +PersonaProfile { + persona_id: string, + persona_name: string, + visual_description: string, + summary_bio: string, + indicators: Indicator[], + source_pages: int[], + document: string, + key_indicators: object[], // salient statements, present when reasoning runs + style_profile: StyleProfile | null, + value_frame: ValueFrame | null, + reasoning_policies: ReasoningPolicies | null, + content_filters: ContentFilters | null +} +``` + +### Indicator +```json +{ + "id": "string", + "domain": "string", + "category": "string", + "label": "string", + "description": "string", + "sources": [{ "doc_id": "string", "pages": [int] }], + "statements": Statement[] +} +``` + +### Statement +```json +{ + "label": "string", + "description": "string", + "metrics": [{ "value": number|string, "unit": "index|%|count|rank|€|other", "description": "string" }], + "salience": { "is_salient": bool, "direction": "high|low|neutral", "magnitude": "strong|medium|weak", "rationale": "string" }, + "influences": { "tone": bool, "stance": bool } +} +``` + +### Reasoning +When the reasoning step runs, personas may include: + +- `key_indicators`: salient statements harvested for reasoning (retains sources/metrics/salience). +- `style_profile`: tone and delivery hints (adjectives, formality, directness, emotional flavour, verbosity, preferred structures, register examples). +- `value_frame`: what they prioritize (priority_rank plus sustainability, price, novelty, loyalty, health flags, description). +- `reasoning_policies`: purchase_advice, product_evaluation, information_processing. +- `content_filters`: avoid_styles, emphasise_disclaimers_on. + +## Usage Notes +- `persona_id` is kebab-case; `document` holds the originating PDF name; `source_pages` shows where the persona was observed. +- Metrics should be numeric when possible; units normalize to the allowed set. +- Salience drives reasoning inputs; only `salience.is_salient == true` statements populate `key_indicators`. +- Sources are preserved and propagated into reasoning payloads so traceability is retained. + diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml new file mode 100644 index 0000000000000000000000000000000000000000..22db3fafd3484469143a9dca07f345f6df73a9e3 --- /dev/null +++ b/docs/mkdocs.yml @@ -0,0 +1,4 @@ +site_name: 2025-P3-AI-Personas +# +site_author: team 1 +# \ No newline at end of file