thanhnv2323 commited on
Commit
09da05c
·
1 Parent(s): 98083b1

init: add app fastapi

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +15 -0
  2. .env.example +162 -0
  3. .gitignore +197 -0
  4. .streamlit/config.toml +6 -0
  5. Dockerfile +20 -0
  6. LICENSE +10 -0
  7. Makefile +167 -0
  8. README.md +385 -10
  9. adsp/__init__.py +16 -0
  10. adsp/app/__init__.py +15 -0
  11. adsp/app/api/__init__.py +1 -0
  12. adsp/app/api/routes/__init__.py +21 -0
  13. adsp/app/api/routes/auth.py +65 -0
  14. adsp/app/api/routes/chat.py +48 -0
  15. adsp/app/api/routes/groups.py +391 -0
  16. adsp/app/api/routes/ingestion.py +67 -0
  17. adsp/app/api/routes/personas.py +139 -0
  18. adsp/app/api/routes/reports.py +58 -0
  19. adsp/app/api/routes/surveys.py +479 -0
  20. adsp/app/api/routes/system.py +34 -0
  21. adsp/app/api_server.py +213 -0
  22. adsp/app/auth_service.py +25 -0
  23. adsp/app/ingestion_service.py +32 -0
  24. adsp/app/persona_config.py +31 -0
  25. adsp/app/qa_service.py +36 -0
  26. adsp/app/report_service.py +20 -0
  27. adsp/communication/__init__.py +7 -0
  28. adsp/communication/cache.py +19 -0
  29. adsp/communication/event_broker.py +21 -0
  30. adsp/communication/rpc.py +17 -0
  31. adsp/config.py +45 -0
  32. adsp/core/__init__.py +21 -0
  33. adsp/core/ai_persona_router/__init__.py +18 -0
  34. adsp/core/context_filter.py +436 -0
  35. adsp/core/input_handler/__init__.py +13 -0
  36. adsp/core/mcp_server/__init__.py +27 -0
  37. adsp/core/mcp_server/tools/__init__.py +5 -0
  38. adsp/core/mcp_server/tools/mcp_client.py +13 -0
  39. adsp/core/memory/__init__.py +28 -0
  40. adsp/core/orchestrator/__init__.py +253 -0
  41. adsp/core/persona_registry/__init__.py +33 -0
  42. adsp/core/prompt_builder/__init__.py +91 -0
  43. adsp/core/prompt_builder/survey_simulation_prompt.py +24 -0
  44. adsp/core/prompt_builder/system_prompt.py +229 -0
  45. adsp/core/rag/__init__.py +39 -0
  46. adsp/core/rag/fact_data_index.py +158 -0
  47. adsp/core/rag/persona_index.py +158 -0
  48. adsp/core/runtime.py +429 -0
  49. adsp/core/survey/__init__.py +29 -0
  50. adsp/core/survey/group_generator.py +507 -0
.dockerignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ .git
3
+ .idea
4
+ .pytest_cache
5
+ __pycache__/
6
+ *.pyc
7
+ docs/
8
+ models/
9
+ notebooks/
10
+ references/
11
+ reports/
12
+ tests/
13
+ data/huggingface/
14
+ data/interim/
15
+ data/raw/
.env.example ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copy this file to `.env` for local development.
2
+
3
+ # REST API server (scripts/run_api.py, FastAPI)
4
+ # Note: if you also run vLLM on port 8000, set ADSP_API_PORT=8080.
5
+ ADSP_API_HOST=0.0.0.0
6
+ ADSP_API_PORT=8000
7
+ ADSP_API_RELOAD=true
8
+ ADSP_API_RUN_MODE=uvicorn
9
+ ADSP_API_WORKERS=1
10
+ ADSP_API_DEBUG=false
11
+ # Case-insensitive: INFO, DEBUG, ERROR, WARNING, TRACE, CRITICAL
12
+ ADSP_API_LOG_LEVEL=INFO
13
+ ADSP_API_TITLE=Lavazza AI Personas API
14
+ ADSP_API_VERSION=0.1.0
15
+ # GPU settings for the `api` service in `docker compose up`
16
+ ADSP_API_GPU_REQUEST=all
17
+ ADSP_API_GPU_VISIBLE_DEVICES=all
18
+ ADSP_API_GPU_DRIVER_CAPABILITIES=compute,utility
19
+
20
+ # If true, protected endpoints require X-User and X-Token headers.
21
+ ADSP_REQUIRE_AUTH=false
22
+
23
+ # Application services
24
+ ADSP_INGESTION_BUCKET=uploads
25
+ ADSP_REPORTS_DIR=reports/api
26
+ ADSP_SURVEYS_DIR=data/processed/surveys
27
+
28
+ # Runtime LLM backend:
29
+ # - `stub`: no external server required (default)
30
+ # - `openai`: call an OpenAI-compatible endpoint (e.g., vLLM)
31
+ ADSP_LLM_BACKEND=openai
32
+
33
+ # OpenAI-compatible runtime model settings (only used when ADSP_LLM_BACKEND=openai)
34
+ ADSP_LLM_BASE_URL=http://localhost:8000/v1
35
+ ADSP_LLM_MODEL=
36
+ ADSP_LLM_API_KEY=EMPTY
37
+
38
+ # Optional generation knobs
39
+ ADSP_LLM_TEMPERATURE=0.2
40
+ ADSP_LLM_MAX_TOKENS=512
41
+ ADSP_LLM_TIMEOUT=60
42
+
43
+ # Survey/group OpenAI generation knobs (group profile + response synthesis)
44
+ ADSP_SURVEY_LLM_TEMPERATURE=0.2
45
+ ADSP_SURVEY_LLM_MAX_TOKENS=10000
46
+ ADSP_SURVEY_LLM_TIMEOUT=120
47
+
48
+ # Survey response simulation worker threads
49
+ ADSP_SURVEY_SIMULATION_MAX_WORKERS=4
50
+
51
+ # Orchestrator relevance filtering (history + retrieved context)
52
+ ADSP_CONTEXT_FILTER_ENABLED=true
53
+ ADSP_CONTEXT_FILTER_BACKEND=heuristic
54
+ ADSP_CONTEXT_FILTER_MAX_HISTORY=10
55
+ ADSP_CONTEXT_FILTER_MAX_BLOCKS=10
56
+ ADSP_CONTEXT_FILTER_MIN_COVERAGE=0.2
57
+ ADSP_CONTEXT_FILTER_TIMEOUT=30
58
+
59
+ # OpenAI-compatible context filter model settings (only used when ADSP_CONTEXT_FILTER_BACKEND=openai)
60
+ # Defaults to ADSP_LLM_* / VLLM_* if left blank.
61
+ ADSP_CONTEXT_FILTER_BASE_URL=
62
+ ADSP_CONTEXT_FILTER_MODEL=
63
+ ADSP_CONTEXT_FILTER_API_KEY=
64
+
65
+ # Persona data locations (override if you store outputs elsewhere)
66
+ ADSP_PERSONAS_DIR=data/processed/personas/individual
67
+ ADSP_PERSONA_TRAITS_DIR=data/processed/personas/common_traits
68
+ ADSP_SURVEY_TRAITS_DIR=data/processed/personas/common_traits
69
+
70
+ # Fact-data RAG runtime (used by orchestrator startup)
71
+ ADSP_FACTDATA_RAG_ENABLED=true
72
+ ADSP_FACTDATA_MARKDOWN_DIR=data/processed/fact_data
73
+ ADSP_FACTDATA_MARKDOWN_PATTERN=*.md
74
+ ADSP_FACTDATA_RUN_EXTRACTION=false
75
+
76
+ # Embedding model configuration
77
+ ADSP_EMBEDDING_BACKEND=huggingface
78
+ ADSP_EMBEDDING_MODEL_NAME=sentence-transformers/all-mpnet-base-v2
79
+ # `auto` picks the best available device: `cuda`, then `mps`, else `cpu`
80
+ ADSP_EMBEDDING_DEVICE=auto
81
+ ADSP_EMBEDDING_BATCH_SIZE=
82
+ # OpenAI-compatible embeddings backend settings (for example, NVIDIA NIM)
83
+ ADSP_EMBEDDING_API_BASE_URL=
84
+ ADSP_EMBEDDING_API_KEY=
85
+ ADSP_EMBEDDING_ENCODING_FORMAT=float
86
+ ADSP_EMBEDDING_EXTRA_BODY=
87
+ ADSP_EMBEDDING_QUERY_EXTRA_BODY=
88
+ ADSP_EMBEDDING_DOCUMENT_EXTRA_BODY=
89
+ # Example for NVIDIA NIM retrieval models:
90
+ #ADSP_EMBEDDING_BACKEND=openai
91
+ #ADSP_EMBEDDING_MODEL_NAME=nvidia/llama-nemotron-embed-vl-1b-v2
92
+ #ADSP_EMBEDDING_API_BASE_URL=https://integrate.api.nvidia.com/v1
93
+ #ADSP_EMBEDDING_ENCODING_FORMAT=float
94
+ #ADSP_EMBEDDING_API_KEY={YOUR_API_KEY}
95
+ #ADSP_EMBEDDING_QUERY_EXTRA_BODY={"input_type":"query","truncate":"NONE"}
96
+ #ADSP_EMBEDDING_DOCUMENT_EXTRA_BODY={"input_type":"passage","truncate":"NONE"}
97
+
98
+ # PyTorch runtime bootstrap (docker-compose)
99
+ # Default installs CUDA wheels so `ADSP_EMBEDDING_DEVICE=cuda` can work at runtime.
100
+ ADSP_TORCH_INSTALL_ENABLED=true
101
+ ADSP_TORCH_EXPECT_CUDA=true
102
+ ADSP_TORCH_INDEX_URL=https://download.pytorch.org/whl/cu124
103
+ ADSP_TORCH_PACKAGES=torch torchvision torchaudio
104
+ ADSP_TORCH_FORCE_REINSTALL=false
105
+
106
+ # LangChain vector store backend
107
+ # Supported backends: `faiss` (default), `chroma`, `milvus`
108
+ ADSP_VECTORSTORE_BACKEND=faiss
109
+ ADSP_VECTORSTORE_PERSIST_DIR=data/processed/vectorstores
110
+ ADSP_VECTORSTORE_COLLECTION_PREFIX=adsp
111
+ ADSP_VECTORSTORE_RESET_ON_STARTUP=false
112
+ ADSP_VECTORSTORE_MILVUS_URI=http://localhost:19530
113
+ ADSP_VECTORSTORE_MILVUS_TOKEN=
114
+ ADSP_VECTORSTORE_MILVUS_DB_NAME=
115
+
116
+ # Persona extraction pipeline (scripts/run_persona_extraction.py)
117
+ VLLM_BASE_URL=http://localhost:8000/v1
118
+ VLLM_MODEL=
119
+ VLLM_API_KEY=EMPTY
120
+
121
+ # Optional extraction request tuning
122
+ TEMPERATURE=0.0
123
+ TOP_P=0.01
124
+ MAX_TOKENS=100000
125
+ RESPONSE_TIMEOUT=300.0
126
+ VLLM_MAX_CONCURRENT_REQUESTS=4
127
+ VLM_MAX_RETRIES=3
128
+ VLLM_BACKOFF_SECONDS=1
129
+
130
+ # Optional reasoning enrichment model (can reuse the same endpoint)
131
+ REASONING_BASE_URL=http://localhost:8000/v1
132
+ REASONING_MODEL=
133
+ REASONING_API_KEY=EMPTY
134
+
135
+ # Optional reasoning model tuning
136
+ REASONING_TEMPERATURE=0.0
137
+ REASONING_TOP_P=0.01
138
+ REASONING_MAX_TOKENS=100000
139
+ REASONING_MAX_INPUT_CHARS=100000
140
+ REASONING_MAX_CONCURRENT=4
141
+
142
+ # Docker Compose pipeline controls (docker-compose.yml)
143
+ # Required: source PDF path used by both extraction jobs.
144
+ PERSONA_PDF_PATH=data/raw/
145
+ FACT_DATA_PDF_PATH=data/raw/
146
+
147
+ # Optional page ranges: "start,end" (1-based, inclusive). Leave blank to process full PDF.
148
+ PERSONA_PAGE_RANGE=
149
+ FACT_PAGE_RANGE=
150
+
151
+ # Optional extraction toggles/extra args.
152
+ PERSONA_DEBUG=false
153
+ PERSONA_NO_CACHE=false
154
+ PERSONA_DISABLE_REASONING_PROFILES=false
155
+ PERSONA_EXTRA_ARGS=
156
+ FACT_DEBUG=false
157
+ FACT_NO_CACHE=false
158
+ FACT_EXTRA_ARGS=
159
+
160
+ # Frontend container defaults.
161
+ ADSP_FE_PORT=8501
162
+ ADSP_FE_API_URL=http://api:8000
.gitignore ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ignore any Facebook Dino dependency that may appear at root level
2
+ /utils.py
3
+ /vision_transformer.py
4
+
5
+ # Ignore any 'data' folder
6
+ #data/
7
+
8
+ # Ignore any 'checkpoints' folder (for local training)
9
+ checkpoints/
10
+
11
+ # Mac OS-specific storage files
12
+ .DS_Store
13
+
14
+ # vim
15
+ *.swp
16
+ *.swo
17
+
18
+ ## https://github.com/github/gitignore/blob/e8554d85bf62e38d6db966a50d2064ac025fd82a/Python.gitignore
19
+
20
+ # Byte-compiled / optimized / DLL files
21
+ __pycache__/
22
+ *.py[cod]
23
+ *$py.class
24
+
25
+ # C extensions
26
+ *.so
27
+
28
+ # Distribution / packaging
29
+ .Python
30
+ build/
31
+ develop-eggs/
32
+ dist/
33
+ downloads/
34
+ eggs/
35
+ .eggs/
36
+ lib/
37
+ lib64/
38
+ parts/
39
+ sdist/
40
+ var/
41
+ wheels/
42
+ share/python-wheels/
43
+ *.egg-info/
44
+ .installed.cfg
45
+ *.egg
46
+ MANIFEST
47
+
48
+ # PyInstaller
49
+ # Usually these files are written by a python script from a template
50
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
51
+ *.manifest
52
+ *.spec
53
+
54
+ # Installer logs
55
+ pip-log.txt
56
+ pip-delete-this-directory.txt
57
+
58
+ # Unit test / coverage reports
59
+ htmlcov/
60
+ .tox/
61
+ .nox/
62
+ .coverage
63
+ .coverage.*
64
+ .cache
65
+ nosetests.xml
66
+ coverage.xml
67
+ *.cover
68
+ *.py,cover
69
+ .hypothesis/
70
+ .pytest_cache/
71
+ cover/
72
+
73
+ # Translations
74
+ *.mo
75
+ *.pot
76
+
77
+ # Django stuff:
78
+ *.log
79
+ local_settings.py
80
+ db.sqlite3
81
+ db.sqlite3-journal
82
+
83
+ # Flask stuff:
84
+ instance/
85
+ .webassets-cache
86
+
87
+ # Scrapy stuff:
88
+ .scrapy
89
+
90
+ # MkDocs documentation
91
+ docs/site/
92
+
93
+ # PyBuilder
94
+ .pybuilder/
95
+ target/
96
+
97
+ # Jupyter Notebook
98
+ .ipynb_checkpoints
99
+
100
+ # IPython
101
+ profile_default/
102
+ ipython_config.py
103
+
104
+ # pyenv
105
+ # For a library or package, you might want to ignore these files since the code is
106
+ # intended to run in multiple environments; otherwise, check them in:
107
+ # .python-version
108
+
109
+ # pipenv
110
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
111
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
112
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
113
+ # install all needed dependencies.
114
+ #Pipfile.lock
115
+
116
+ # UV
117
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
118
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
119
+ # commonly ignored for libraries.
120
+ #uv.lock
121
+
122
+ # poetry
123
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
124
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
125
+ # commonly ignored for libraries.
126
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
127
+ #poetry.lock
128
+
129
+ # pdm
130
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
131
+ #pdm.lock
132
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
133
+ # in version control.
134
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
135
+ .pdm.toml
136
+ .pdm-python
137
+ .pdm-build/
138
+
139
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
140
+ __pypackages__/
141
+
142
+ # Celery stuff
143
+ celerybeat-schedule
144
+ celerybeat.pid
145
+
146
+ # SageMath parsed files
147
+ *.sage.py
148
+
149
+ # Environments
150
+ .env
151
+ .venv
152
+ env/
153
+ venv/
154
+ ENV/
155
+ env.bak/
156
+ venv.bak/
157
+
158
+ # Spyder project settings
159
+ .spyderproject
160
+ .spyproject
161
+
162
+ # Rope project settings
163
+ .ropeproject
164
+
165
+ # mkdocs documentation
166
+ /site
167
+
168
+ # mypy
169
+ .mypy_cache/
170
+ .dmypy.json
171
+ dmypy.json
172
+
173
+ # Pyre type checker
174
+ .pyre/
175
+
176
+ # pytype static type analyzer
177
+ .pytype/
178
+
179
+ # Cython debug symbols
180
+ cython_debug/
181
+
182
+ # PyCharm
183
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
184
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
185
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
186
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
187
+ .idea/
188
+
189
+ # Ruff stuff:
190
+ .ruff_cache/
191
+
192
+ # PyPI configuration file
193
+ .pypirc
194
+ wandb-keys.txt
195
+ Lavazza-AIPersonas.pdf
196
+
197
+ temp
.streamlit/config.toml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [theme]
2
+ base = "dark"
3
+ primaryColor = "#7CC6FF"
4
+ backgroundColor = "#0F1419"
5
+ secondaryBackgroundColor = "#182028"
6
+ textColor = "#F3F7FB"
Dockerfile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ ENV PYTHONDONTWRITEBYTECODE=1 \
4
+ PYTHONUNBUFFERED=1 \
5
+ PIP_NO_CACHE_DIR=1 \
6
+ PORT=7860
7
+
8
+ WORKDIR /app
9
+
10
+ COPY requirements.txt pyproject.toml README.md LICENSE ./
11
+ COPY adsp ./adsp
12
+ COPY scripts ./scripts
13
+ COPY data ./data
14
+
15
+ RUN python -m pip install --upgrade pip && \
16
+ pip install -r requirements.txt
17
+
18
+ EXPOSE 7860
19
+
20
+ CMD ["python", "scripts/run_hf_space.py"]
LICENSE ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ The MIT License (MIT)
3
+ Copyright (c) 2025, team 1
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10
+
Makefile ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #################################################################################
2
+ # GLOBALS #
3
+ #################################################################################
4
+
5
+ PROJECT_NAME = 2025-P3-AI-Personas
6
+ PYTHON_VERSION := 3.10
7
+ PYTHON_INTERPRETER := python3
8
+ VENV_DIR := .venv
9
+
10
+ # detect operating system, assign variables
11
+ ifeq ($(OS),Windows_NT)
12
+ ACTIVATE := $(VENV_DIR)\Scripts\activate.bat
13
+ PYTHON := $(VENV_DIR)\Scripts\python.exe
14
+ else
15
+ ACTIVATE := source $(VENV_DIR)/bin/activate
16
+ PYTHON := $(VENV_DIR)/bin/python
17
+ endif
18
+
19
+ # Check if venv exists (if it exists it will output echo) and use it, otherwise fallback to system Python
20
+ ifeq ($(shell test -d $(VENV_DIR) && echo 1),1)
21
+ # If the venv exists, use its Python interpreter
22
+ PYTHON := $(VENV_DIR)/bin/python
23
+ else
24
+ # If no venv, fall back to system Python
25
+ PYTHON := python3
26
+ endif
27
+
28
+ #################################################################################
29
+ # COMMANDS #
30
+ #################################################################################
31
+
32
+ ## Lint using ruff (use `make format` to do formatting)
33
+ .PHONY: lint
34
+ lint:
35
+ @echo ""
36
+ @echo "🔍 ----------------------------------------------------------"
37
+ @echo "🔍 Running Ruff Linter (checking code formatting and issues)..."
38
+ @echo "🔍 ----------------------------------------------------------"
39
+ @echo ""
40
+ ruff format --check
41
+ ruff check
42
+
43
+ @echo ""
44
+ @echo "✅ Linting complete. No issues detected (if any)."
45
+ @echo ""
46
+
47
+ ## Format source code with ruff
48
+ .PHONY: format
49
+ format:
50
+ @echo ""
51
+ @echo "⚙️ ----------------------------------------------------------"
52
+ @echo "⚙️ Running Ruff Formatter (auto-fixing issues)..."
53
+ @echo "⚙️ ----------------------------------------------------------"
54
+ @echo ""
55
+ ruff check --fix
56
+ ruff format
57
+
58
+ @echo ""
59
+ @echo "✅ Formatting complete. Code is now formatted."
60
+ @echo ""
61
+
62
+ ## Set up new venv and install requirements
63
+ .PHONY: install
64
+ install:
65
+ @echo ""
66
+ @echo "🔧 ----------------------------------------------------------"
67
+ @echo "🔧 Creating virtual environment (if it doesn't exist)..."
68
+ @echo "🔧 ----------------------------------------------------------"
69
+ @echo ""
70
+ @test -d $(VENV_DIR) || $(PYTHON_INTERPRETER) -m venv $(VENV_DIR)
71
+
72
+ @echo ""
73
+ @echo "📦 Installing Python dependencies..."
74
+ @echo "📦 ----------------------------------------------------------"
75
+ @echo ""
76
+ $(PYTHON) -m pip install --upgrade pip
77
+ $(PYTHON) -m pip install -r requirements.txt
78
+
79
+ @echo ""
80
+ @echo "✅ Environment setup complete in '$(VENV_DIR)'"
81
+ @echo ""
82
+
83
+ ## Install only requirements (assumes venv or conda already exists)
84
+ .PHONY: requirements
85
+ requirements:
86
+ @echo ""
87
+ @echo "📦 Installing dependencies from requirements.txt..."
88
+ @echo ""
89
+ $(PYTHON) -m pip install -r requirements.txt
90
+ @echo ""
91
+ @echo "✅ Dependencies installed."
92
+ @echo ""
93
+
94
+ ## Delete all compiled Python files and venv
95
+ .PHONY: clean
96
+ clean:
97
+ @echo ""
98
+ @echo "🧹 Cleaning up __pycache__ and .pyc files..."
99
+ @echo ""
100
+ find . -type f -name "*.py[co]" -delete
101
+ find . -type d -name "__pycache__" -delete
102
+
103
+ @echo ""
104
+ @echo "🧨 Removing virtual environment directory..."
105
+ @echo ""
106
+ rm -rf $(VENV_DIR)
107
+
108
+ @echo ""
109
+ @echo "✅ Cleanup complete."
110
+ @echo ""
111
+
112
+ ## Download the dataset
113
+ .PHONY: data
114
+ data: requirements
115
+ @echo ""
116
+ @echo "⬇️ Downloading dataset with fl_g13.dataset..."
117
+ @echo ""
118
+ $(PYTHON) -m fl_g13.dataset
119
+ @echo ""
120
+ @echo "✅ Dataset downloaded successfully."
121
+ @echo ""
122
+
123
+ ## Export all notebooks in the notebooks/ directory
124
+ .PHONY: export
125
+ export: requirements
126
+ @echo ""
127
+ @echo "📤 Exporting all notebooks in 'notebooks/' using nbautoexport..."
128
+ @echo ""
129
+ $(PYTHON) -m nbautoexport export notebooks/
130
+ @echo ""
131
+ @echo "✅ Notebooks exported successfully."
132
+ @echo ""
133
+
134
+ ## Run the local chat CLI (end-to-end demo)
135
+ .PHONY: chat
136
+ chat: requirements
137
+ @echo ""
138
+ @echo "💬 Starting local chat CLI..."
139
+ @echo ""
140
+ $(PYTHON) scripts/run_chat.py chat
141
+
142
+ ## Run the REST API server (FastAPI + Swagger)
143
+ .PHONY: api
144
+ api: requirements
145
+ @echo ""
146
+ @echo "🛰️ Starting REST API server..."
147
+ @echo "🧭 Swagger UI: http://localhost:8000/docs"
148
+ @echo ""
149
+ $(PYTHON) scripts/run_api.py
150
+
151
+ #################################################################################
152
+ # Self Documenting Commands #
153
+ #################################################################################
154
+
155
+ .DEFAULT_GOAL := help
156
+
157
+ define PRINT_HELP_PYSCRIPT
158
+ import re, sys; \
159
+ lines = '\n'.join([line for line in sys.stdin]); \
160
+ matches = re.findall(r'\n## (.*)\n[\s\S]+?\n([a-zA-Z_-]+):', lines); \
161
+ print('Available rules:\n'); \
162
+ print('\n'.join(['{:25}{}'.format(*reversed(match)) for match in matches]))
163
+ endef
164
+ export PRINT_HELP_PYSCRIPT
165
+
166
+ help:
167
+ @$(PYTHON) -c "${PRINT_HELP_PYSCRIPT}" < $(MAKEFILE_LIST)
README.md CHANGED
@@ -1,10 +1,385 @@
1
- ---
2
- title: Ai Persona
3
- emoji: 👀
4
- colorFrom: green
5
- colorTo: gray
6
- sdk: docker
7
- pinned: false
8
- ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2025-P3-AI-Personas - Team 1
2
+
3
+ <a target="_blank" href="https://cookiecutter-data-science.drivendata.org/">
4
+ <img src="https://img.shields.io/badge/CCDS-Project%20template-328F97?logo=cookiecutter" />
5
+ </a>
6
+
7
+ Applied Data Science Project
8
+
9
+ ## Description
10
+
11
+ ### Objectives
12
+ The **Lavazza AI Personas** project builds an AI platform that enables internal business teams to interact with AI personas representing different market segments, allowing them to explore and test strategies through dynamic, conversational agents. By transforming static customer segmentation studies into authentic AI representations of Lavazza's customer segments, this system serves as a next-generation consumer insights platform for market research, idea validation, and strategic decision-making.
13
+
14
+ **Key Benefits:**
15
+ - **Accelerated Insights**: Reduce time and resources spent on manual data preprocessing and analysis
16
+ - **Trustworthy Intelligence**: Provide credible, fact-grounded responses backed by Lavazza's proprietary research data
17
+ - **Strategic Focus**: Help teams make more informed, data-driven market strategies with immediate access to customer perspectives
18
+
19
+ ### Key Features
20
+
21
+ - **Authentic Personality**: AI personas that embody specific customer segments with consistent tone, style, and values
22
+ - **Factual Grounding**: RAG-based system that prevents hallucinations by grounding responses in Lavazza's proprietary data
23
+ - **Critical Thinking**: Personas provide honest, critical feedback rather than generic positive responses
24
+ - **Transparency**: Clear source attribution showing whether information comes from internal documentation or external sources
25
+ - **Multimodal Support**: Process text, images, and PDF documents (e.g., packaging designs, concept notes)
26
+ - **Virtual Focus Groups**: Interact with multiple personas simultaneously for comprehensive feedback
27
+
28
+ ## Methodology
29
+
30
+ ![Functional diagram](docs/images/functional_diagram.png)
31
+
32
+ The system runs in two phases. During data ingestion, we extract persona indicators and traits, and extract facts from the source dataset, build a persona registry, and index facts into the RAG store. During the online process, the orchestrator receives a query, retrieves relevant context, conversation history and persona descriptions, assembles the prompt, and calls the LLM to generate a grounded response.
33
+
34
+ ## Getting Started
35
+
36
+ ### Installation
37
+
38
+ ```bash
39
+ make install
40
+ ```
41
+
42
+ ### Data Extraction Pipelines
43
+
44
+ #### 1. Persona Extraction Pipeline
45
+
46
+ Extract persona indicators (demographics, behaviors, values) from PDF segmentation studies:
47
+
48
+ ```bash
49
+ python scripts/run_persona_extraction.py \
50
+ --pdf-path data/raw/segmentation_study.pdf \
51
+ --page-range 1,50 \
52
+ --vllm-base-url http://localhost:8000/v1 \
53
+ --vllm-model mistralai/mistral-medium-3-instruct \
54
+ --generate-reasoning-profiles
55
+ ```
56
+
57
+ Key options:
58
+ - `--pdf-path`: Path to segmentation study PDF
59
+ - `--page-range`: Pages to process (1-based, inclusive)
60
+ - `--vllm-base-url`: OpenAI-compatible API endpoint
61
+ - `--vllm-model`: Vision model for extraction
62
+ - `--generate-reasoning-profiles`: Generate style/value/guardrail profiles
63
+ - `--no-cache`: Force re-extraction (ignore cached responses)
64
+
65
+ Outputs:
66
+ - `data/interim/personas/personas.json`: Merged persona data
67
+ - `data/interim/personas/individual/{persona_id}.json`: Individual persona files
68
+ - `data/interim/personas/common_traits/{persona_id}.json`: Reasoning profiles
69
+
70
+ #### 2. Fact Extraction Pipeline
71
+
72
+ Convert PDF pages to structured markdown for RAG indexing:
73
+
74
+ ```bash
75
+ python scripts/run_fact_data_extraction.py \
76
+ --pdf-path data/raw/segmentation_study.pdf \
77
+ --page-range 1,100 \
78
+ --vllm-base-url http://localhost:8000/v1 \
79
+ --vllm-model mistralai/mistral-large-3-675b-instruct-2512
80
+ ```
81
+
82
+ Key options:
83
+ - `--pdf-path`: Path to source PDF
84
+ - `--page-range`: Pages to extract (1-based, inclusive)
85
+ - `--context-window`: Adjacent pages for context (default: 0)
86
+
87
+ Outputs:
88
+ - `data/interim/fact_data/{doc_id}/pages/`: Per-page markdown files
89
+ - `data/interim/fact_data/{doc_id}/qa_report.txt`: Quality assurance report
90
+
91
+ #### 3. Index Fact Data for RAG
92
+
93
+ Index extracted facts into the vector database:
94
+
95
+ ```bash
96
+ python scripts/index_fact_data.py \
97
+ --fact-data-dir data/interim/fact_data/segmentation_study \
98
+ --vector-db-path data/processed/vector_store
99
+ ```
100
+
101
+ ### Running the Application
102
+
103
+ #### Docker Compose
104
+
105
+ Run the full stack:
106
+
107
+ ```bash
108
+ docker compose up
109
+ ```
110
+
111
+ The `api` service requests `gpus: all`. Your Docker host must have NVIDIA GPU container support configured, or Compose will fail during container creation.
112
+
113
+ The vector store cache is persisted on the host at `./data/processed/vectorstores` and is mounted into the API container at `/app/data/processed/vectorstores`.
114
+
115
+ #### Backend API
116
+
117
+ Start the FastAPI backend server:
118
+
119
+ ```bash
120
+ python scripts/run_api.py
121
+ ```
122
+
123
+ - Swagger UI: `http://localhost:8000/docs`
124
+ - OpenAPI JSON: `http://localhost:8000/openapi.json`
125
+
126
+ Advanced options:
127
+
128
+ ```bash
129
+ # Uvicorn with auto-reload
130
+ python scripts/run_api.py --mode uvicorn --reload
131
+
132
+ # Direct mode for debugging
133
+ python scripts/run_api.py --mode direct --debug
134
+ ```
135
+
136
+ Environment variables:
137
+ - `ADSP_API_RUN_MODE`: `uvicorn` (default) or `direct`
138
+ - `ADSP_API_HOST`, `ADSP_API_PORT`: Host and port configuration
139
+ - `ADSP_API_RELOAD`: `true`/`false` (uvicorn mode only)
140
+ - `ADSP_API_WORKERS`: worker process count for uvicorn mode. Use `ADSP_API_RELOAD=false` when setting this above `1`.
141
+ - `ADSP_API_DEBUG`: `true`/`false`
142
+ - `ADSP_API_LOG_LEVEL`: `INFO`, `DEBUG`, `ERROR`, etc. Case-insensitive.
143
+
144
+ #### Frontend UI
145
+
146
+ Launch the Streamlit frontend:
147
+
148
+ ```bash
149
+ python scripts/run_frontend.py
150
+ ```
151
+
152
+ The frontend will be available at `http://localhost:8501`
153
+
154
+ #### LLM Backend Configuration
155
+
156
+ To use an OpenAI-compatible LLM backend (e.g., vLLM):
157
+
158
+ ```bash
159
+ export ADSP_LLM_BACKEND=openai
160
+ export ADSP_LLM_BASE_URL=http://localhost:8000/v1
161
+ export ADSP_LLM_MODEL=mistralai/mistral-small-24b-instruct
162
+ export ADSP_LLM_API_KEY=EMPTY
163
+ ```
164
+
165
+ #### Embedding Backend Configuration
166
+
167
+ By default, embeddings use a local HuggingFace model:
168
+
169
+ ```bash
170
+ export ADSP_EMBEDDING_BACKEND=huggingface
171
+ export ADSP_EMBEDDING_MODEL_NAME=sentence-transformers/all-mpnet-base-v2
172
+ ```
173
+
174
+ To use an OpenAI-compatible embeddings endpoint such as NVIDIA NIM:
175
+
176
+ ```bash
177
+ export ADSP_EMBEDDING_BACKEND=openai
178
+ export ADSP_EMBEDDING_MODEL_NAME=nvidia/llama-3.2-nemoretriever-1b-vlm-embed-v1
179
+ export ADSP_EMBEDDING_API_BASE_URL=https://integrate.api.nvidia.com/v1
180
+ export ADSP_EMBEDDING_API_KEY="$NVIDIA_API_KEY"
181
+ export ADSP_EMBEDDING_QUERY_EXTRA_BODY='{"modality":["text"],"input_type":"query","truncate":"NONE"}'
182
+ export ADSP_EMBEDDING_DOCUMENT_EXTRA_BODY='{"modality":["text"],"input_type":"passage","truncate":"NONE"}'
183
+ ```
184
+
185
+ The embedding-model cache container skips local model downloads automatically when `ADSP_EMBEDDING_BACKEND=openai`.
186
+
187
+ ### Quickstart Demo (CLI)
188
+
189
+ Test personas via command line:
190
+
191
+ ```bash
192
+ python scripts/run_chat.py list-personas
193
+ python scripts/run_chat.py chat --persona-id basic-traditional
194
+ ```
195
+
196
+ ## Evaluation Results
197
+
198
+ The system has been evaluated across four key dimensions using Mistral models:
199
+
200
+ ### 1. Persona Extraction
201
+
202
+ **Model**: `mistralai/mistral-medium-3-instruct`
203
+ **Dataset**: 23 pages (Curious Connoisseurs segment), 1,051 manually validated metrics
204
+
205
+ | Metric | Score | Interpretation |
206
+ | ---------------------- | ------ | ------------------------------------------------------ |
207
+ | Persona Detection Rate | 100% | All personas correctly identified (23/23) |
208
+ | Metrics Recall | 95.30% | Very high coverage of ground-truth metrics (1002/1051) |
209
+ | Metrics Precision | 96.80% | Minimal noise in extracted metrics (1002/1035) |
210
+
211
+ ### 2. Fact Extraction
212
+
213
+ **Model**: `mistralai/mistral-large-3-675b-instruct-2512`
214
+ **Dataset**: 23 pages, 467 validated metric snippets
215
+
216
+ | Metric | Score | Interpretation |
217
+ | -------------------- | ----- | ----------------------------------------------- |
218
+ | Exact Match Accuracy | 97% | High extraction accuracy with minimal deviation |
219
+
220
+
221
+ ### 3. Retrieval Relevance
222
+
223
+ **Embedding Model**: `sentence-transformers/all-mpnet-base-v2`
224
+ **RAG Setup**: 222-page document, 712 chunks (1,200 chars, 50 overlap)
225
+
226
+ | Metric | Score | Interpretation |
227
+ | ------------- | ----------- | --------------------------------------------- |
228
+ | Precision@3 | 89.25% | Top-3 results are mostly relevant |
229
+ | Precision@5 | 88.39% | High relevance persists in top 5 |
230
+ | Precision@10 | 86.13% | Strong top-10 relevance with minor noise |
231
+ | Precision@20 | 82.58% | Relevance remains high but dilutes with depth |
232
+ | Precision@25 | 80.90% | Moderate noise beyond top 20 |
233
+ | Recall@3 | 14.87% | Small share of relevant docs in top 3 |
234
+ | Recall@5 | 23.35% | Less than a quarter in top 5 |
235
+ | Recall@10 | 45.98% | Roughly half captured by top 10 |
236
+ | Recall@20 | 82.08% | Most relevant docs retrieved by top 20 |
237
+ | **Recall@25** | **100.00%** | **All relevant docs retrieved by top 25** |
238
+
239
+ ### 4. Persona Authenticity
240
+
241
+ **Models**: `mistralai/mistral-medium-3-instruct` (filter), `mistralai/mistral-small-24b-instruct` (generation)
242
+ **RAG Setup**: 222-page document, 712 chunks (1,200 chars, 50 overlap)
243
+ **Dataset**: 31 evaluation questions (Curious Connoisseurs segment)
244
+
245
+ | Metric | Score | Interpretation |
246
+ | ------------------------- | -------- | ---------------------------------------------- |
247
+ | Expert Authenticity Score | 4.66 / 5 | Persona behavior is highly authentic |
248
+ | Style Alignment Score | 4.74 / 5 | Style is highly consistent, with minimal drift |
249
+ | Factual Grounding Score | 4.44 / 5 | Responses are well grounded |
250
+
251
+ **Key Finding**: Authenticity, style alignment, and grounding all score above 4.4/5, indicating strong persona fidelity with consistent style and reliable grounding.
252
+
253
+ For detailed evaluation methodology and results, see `reports/evaluation/`.
254
+
255
+ ## Project Organization
256
+
257
+ ```
258
+ ├── LICENSE <- Open-source license if one is chosen
259
+ ├── Makefile <- Makefile with convenience commands like `make data` or `make train`
260
+ ├── README.md <- The top-level README for developers using this project.
261
+ ├── data
262
+ │ ├── external <- Data from third party sources.
263
+ │ ├── interim <- Intermediate data that has been transformed.
264
+ │ ├── processed <- The final, canonical data sets for modeling.
265
+ │ └── raw <- The original, immutable data dump.
266
+ │
267
+ ├── docs <- Design notes, ADRs, and folder structure reference
268
+ │
269
+ ├── models <- Trained and serialized models, model predictions, or model summaries
270
+ │
271
+ ├── notebooks <- Jupyter notebooks. Naming convention is a number (for ordering),
272
+ │ the creator's initials, and a short `-` delimited description, e.g.
273
+ │ `1.0-jqp-initial-data-exploration`.
274
+ │
275
+ ├── pyproject.toml <- Project configuration file with package metadata for
276
+ │ adsp and configuration for tools like black
277
+ │
278
+ ├── references <- Data dictionaries, manuals, and all other explanatory materials.
279
+ │
280
+ ├── reports <- Generated analysis as HTML, PDF, LaTeX, etc.
281
+ │ └── figures <- Generated graphics and figures to be used in reporting
282
+ │
283
+ ├── requirements.txt <- The requirements file for reproducing the analysis environment, e.g.
284
+ │ generated with `pip freeze > requirements.txt`
285
+ │
286
+ ├── setup.cfg <- Configuration file for lint/format tools
287
+ │
288
+ └── adsp <- Source code for use in this project.
289
+ ├── __init__.py <- Python package bootstrapper
290
+ ├── config.py <- Shared paths and environment config
291
+ ├── app/ <- UI-facing services (auth, ingestion, reporting, Q&A)
292
+ ├── fe/ <- Frontend stubs (chat client, upload UI)
293
+ ├── communication/ <- RPC, cache, and event broker adapters
294
+ ├── core/ <- Orchestrator, prompt/RAG, persona routing, memory, tool use
295
+ ├── data_pipeline/ <- Data ingestion, transformation, vectorization
296
+ ├── modeling/ <- Training and inference utilities
297
+ ├── monitoring/ <- Evaluation + metrics collection
298
+ ├── storage/ <- Business DB, object store, vector DB shims
299
+ └── utils/ <- Logging, exceptions, helpers
300
+ ```
301
+
302
+ --------
303
+
304
+
305
+ ## How to contribute
306
+
307
+ ### **Commit Message and Branch Naming Rules**
308
+
309
+ 1. **Commit Message Format**
310
+ - Use the following format for commit messages:
311
+ ```
312
+ <type>: <short description>
313
+ ```
314
+ - **Types**:
315
+ - `feature` or`feat`: A new feature
316
+ - `fix`: A bug fix
317
+ - `docs`: Documentation changes
318
+ - `chore`: maintenance tasks, repo setup, config, etc.
319
+ - `style`: Code style changes (formatting, missing semicolons, etc.)
320
+ - `refactor`: Code refactoring without adding features or fixing bugs
321
+ - `test`: adding or updating tests.
322
+ - Example:
323
+ ```
324
+ feat: add data preprocessing pipeline
325
+ fix: resolve issue with model training script
326
+ ```
327
+ - Details: [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/)
328
+
329
+ 2. **Branch Naming Convention**
330
+ - Use the following format for branch names:
331
+ ```
332
+ <type>/<short-description>
333
+ ```
334
+ - **Types**:
335
+ - `main` or `master`: Stable, production-ready code
336
+ - `develop`: Integration branch for features before release (optional)
337
+ - `feature` or `feat`: For new features or enhancements
338
+ - `fix`: For bug fixes
339
+ - `hotfix`: For urgent production fixes
340
+ - `chore`: For maintenance, build, or config tasks
341
+ - `docs`: For documentation-only changes
342
+ - `refactor`: For code refactoring without behavior change
343
+ - `test`: For adding or updating tests
344
+ - `release`: For preparing production releases
345
+ - Example:
346
+ ```
347
+ feat/add-preprocessing-pipeline
348
+ fix/model-training-bug
349
+ ```
350
+ - Details: [Git Branch Naming Convention](https://conventional-branch.github.io/#specification)
351
+
352
+ - Branch Flow:
353
+ ```
354
+ main <--- release <--- develop <--- feature
355
+ ^ |
356
+ | |
357
+ └-------- hotfix ---------┘
358
+ ```
359
+ ### **Jupyter Notebook Usage**
360
+
361
+ 1. **Notebook Organization**
362
+ - Notebooks must be stored in the `notebooks/` directory.
363
+ - Naming convention: `PHASE.NOTEBOOK-INITIALS-DESCRIPTION.ipynb`
364
+
365
+ Example: `0.01-pjb-data-source-1.ipynb`
366
+
367
+ - `PHASE` codes:
368
+ - `0` – Data exploration
369
+ - `1` – Data cleaning & feature engineering
370
+ - `2` – Visualization
371
+ - `3` – Modeling
372
+ - `4` – Publication
373
+ - `INITIALS` – Your initials; helps identify the author and avoid conflicts.
374
+ - `DESCRIPTION` – Short, clear description of the notebook's purpose.
375
+
376
+ ### **Code Reusability & Refactoring Regulation**
377
+
378
+ 1. **Refactor Shared Code into Modules**
379
+ - Store reusable code in the `src/` package.
380
+ - Add the following cell at the top of each notebook:
381
+
382
+ ```python
383
+ %load_ext autoreload
384
+ %autoreload 2
385
+ ```
adsp/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Top-level package for the Lavazza AI Personas project."""
2
+
3
+ from adsp import config # noqa: F401
4
+ from adsp import app, communication, core, data_pipeline, modeling, monitoring, storage, utils
5
+
6
+ __all__ = [
7
+ "app",
8
+ "communication",
9
+ "core",
10
+ "data_pipeline",
11
+ "modeling",
12
+ "monitoring",
13
+ "storage",
14
+ "utils",
15
+ "config",
16
+ ]
adsp/app/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Application-layer services exposed to user-facing clients."""
2
+
3
+ from .persona_config import PersonaConfigurationService
4
+ from .ingestion_service import IngestionService
5
+ from .report_service import ReportService
6
+ from .qa_service import QAService
7
+ from .auth_service import AuthService
8
+
9
+ __all__ = [
10
+ "PersonaConfigurationService",
11
+ "IngestionService",
12
+ "ReportService",
13
+ "QAService",
14
+ "AuthService",
15
+ ]
adsp/app/api/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """REST API route modules and helpers."""
adsp/app/api/routes/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Route registration helpers for the REST API server."""
2
+
3
+ from .auth import register_auth_routes
4
+ from .chat import register_chat_routes
5
+ from .groups import register_group_routes
6
+ from .ingestion import register_ingestion_routes
7
+ from .personas import register_persona_routes
8
+ from .reports import register_report_routes
9
+ from .surveys import register_survey_routes
10
+ from .system import register_system_routes
11
+
12
+ __all__ = [
13
+ "register_auth_routes",
14
+ "register_chat_routes",
15
+ "register_group_routes",
16
+ "register_ingestion_routes",
17
+ "register_persona_routes",
18
+ "register_report_routes",
19
+ "register_survey_routes",
20
+ "register_system_routes",
21
+ ]
adsp/app/api/routes/auth.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Authentication API routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field
8
+
9
+
10
+ class AuthRegisterRequest(BaseModel):
11
+ model_config = ConfigDict(json_schema_extra={"example": {"user": "demo-user", "token": "demo-token-123"}})
12
+
13
+ user: str = Field(description="Unique user identifier used for API calls.", examples=["demo-user"])
14
+ token: str = Field(description="Token to register for the user.", examples=["demo-token-123"])
15
+
16
+
17
+ class AuthValidateRequest(BaseModel):
18
+ model_config = ConfigDict(json_schema_extra={"example": {"user": "demo-user", "token": "demo-token-123"}})
19
+
20
+ user: str = Field(description="User identifier to validate.", examples=["demo-user"])
21
+ token: str = Field(description="Token to validate for the user.", examples=["demo-token-123"])
22
+
23
+
24
+ class AuthRegisterResponse(BaseModel):
25
+ model_config = ConfigDict(json_schema_extra={"example": {"status": "ok"}})
26
+
27
+ status: str = Field(description="Registration status.", examples=["ok"])
28
+
29
+
30
+ class AuthValidateResponse(BaseModel):
31
+ model_config = ConfigDict(json_schema_extra={"example": {"authorized": True}})
32
+
33
+ authorized: bool = Field(description="Whether the supplied user/token pair is authorized.")
34
+
35
+
36
+ def register_auth_routes(
37
+ app: Any,
38
+ *,
39
+ get_services: Callable[..., Any],
40
+ ) -> None:
41
+ from fastapi import Depends
42
+
43
+ @app.post(
44
+ "/v1/auth/register",
45
+ response_model=AuthRegisterResponse,
46
+ tags=["auth"],
47
+ summary="Register API Token",
48
+ description="Registers or updates the token associated with a user.",
49
+ )
50
+ def register_auth(payload: AuthRegisterRequest, services: Any = Depends(get_services)) -> AuthRegisterResponse:
51
+ services.auth.register(payload.user, payload.token)
52
+ return AuthRegisterResponse(status="ok")
53
+
54
+ @app.post(
55
+ "/v1/auth/validate",
56
+ response_model=AuthValidateResponse,
57
+ tags=["auth"],
58
+ summary="Validate API Token",
59
+ description="Checks whether a user/token pair is currently authorized.",
60
+ )
61
+ def validate_auth(
62
+ payload: AuthValidateRequest,
63
+ services: Any = Depends(get_services),
64
+ ) -> AuthValidateResponse:
65
+ return AuthValidateResponse(authorized=services.auth.is_authorized(payload.user, payload.token))
adsp/app/api/routes/chat.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chat API routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field
8
+
9
+ from adsp.core.types import ChatRequest, ChatResponse
10
+
11
+
12
+ class ChatResponseEnvelope(BaseModel):
13
+ model_config = ConfigDict(
14
+ json_schema_extra={
15
+ "example": {
16
+ "response": {
17
+ "persona_id": "curious-connoisseurs",
18
+ "answer": "I look for consistent taste, trusted quality, and fair price.",
19
+ "context": "",
20
+ "citations": [],
21
+ "tool_calls": [],
22
+ }
23
+ }
24
+ }
25
+ )
26
+
27
+ response: ChatResponse = Field(description="Persona chat response payload.")
28
+
29
+
30
+ def register_chat_routes(
31
+ app: Any,
32
+ *,
33
+ get_qa_service: Callable[..., Any],
34
+ authorize: Callable[..., Any],
35
+ ) -> None:
36
+ from fastapi import Depends
37
+
38
+ @app.post(
39
+ "/v1/chat",
40
+ response_model=ChatResponseEnvelope,
41
+ tags=["chat"],
42
+ dependencies=[Depends(authorize)],
43
+ summary="Persona Chat",
44
+ description="Runs one persona-grounded chat turn and returns the generated answer.",
45
+ )
46
+ def chat(payload: ChatRequest, qa: Any = Depends(get_qa_service)) -> ChatResponseEnvelope:
47
+ response = qa.orchestrator.handle(payload)
48
+ return ChatResponseEnvelope(response=response)
adsp/app/api/routes/groups.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Respondent group API routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import Any, Callable, Dict, List, Optional
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+
11
+ def _available_country_ids_from_profiles() -> List[str]:
12
+ from adsp.core.survey.group_generator import _COUNTRY_PROFILES
13
+
14
+ return sorted(_COUNTRY_PROFILES.keys())
15
+
16
+
17
+ def _group_create_description() -> str:
18
+ countries = ", ".join(f"`{country}`" for country in _available_country_ids_from_profiles())
19
+ return (
20
+ "Generates a synthetic respondent group from persona composition input.\n\n"
21
+ f"Available countries for the `countries` field: {countries}.\n"
22
+ "For the latest supported list, use `GET /api/groups/countries`."
23
+ )
24
+
25
+
26
+ class PagingMeta(BaseModel):
27
+ model_config = ConfigDict(
28
+ json_schema_extra={
29
+ "example": {
30
+ "page": 1,
31
+ "page_size": 20,
32
+ "total_items": 12,
33
+ "total_pages": 1,
34
+ }
35
+ }
36
+ )
37
+
38
+ page: int = Field(description="Current page number (1-based).")
39
+ page_size: int = Field(description="Maximum number of items per page.")
40
+ total_items: int = Field(description="Total number of available items.")
41
+ total_pages: int = Field(description="Total number of pages at the selected page size.")
42
+
43
+
44
+ class GroupCreateRequest(BaseModel):
45
+ model_config = ConfigDict(
46
+ json_schema_extra={
47
+ "example": {
48
+ "composition": [
49
+ {"persona_id": "curious-connoisseurs", "count": 25},
50
+ {"persona_id": "conscious-explorers", "count": 15},
51
+ ],
52
+ "mode": "random",
53
+ "sampling_ratio": 0.7,
54
+ "include_names": True,
55
+ "countries": ["italy", "france"],
56
+ "seed": 42,
57
+ }
58
+ }
59
+ )
60
+
61
+ composition: List[Dict[str, Any]] = Field(
62
+ default_factory=list,
63
+ description="Group composition list with `persona_id` and `count` per segment.",
64
+ )
65
+ mode: str = Field(default="random", description="Profile generation mode: `random` or `llm`.")
66
+ sampling_ratio: float = Field(
67
+ default=0.7,
68
+ description="Sampling ratio used for trait sub-selection when generating respondents.",
69
+ )
70
+ include_names: bool = Field(default=True, description="Whether to synthesize person-like names for respondents.")
71
+ countries: Optional[List[str]] = Field(
72
+ default=None,
73
+ description=(
74
+ "Optional allowed countries for generated respondents. "
75
+ "Use `GET /api/groups/countries` to list supported values."
76
+ ),
77
+ )
78
+ seed: Optional[int] = Field(default=None, description="Optional random seed for deterministic generation.")
79
+
80
+
81
+ class GroupCreateResponse(BaseModel):
82
+ model_config = ConfigDict(
83
+ json_schema_extra={
84
+ "example": {
85
+ "group_id": "group-ab12cd34",
86
+ "created_at": "2026-03-08T15:40:03.123000+00:00",
87
+ "total_respondents": 40,
88
+ "composition": [
89
+ {"persona_id": "curious-connoisseurs", "count": 7},
90
+ {"persona_id": "conscious-explorers", "count": 5},
91
+ ],
92
+ "generation_method": "random",
93
+ "sample_profiles": [
94
+ {
95
+ "respondent_id": "group-ab12cd34-resp-00001",
96
+ "persona_id": "curious-connoisseurs",
97
+ "name": "Luca Rossi",
98
+ "style_profile": {"tone_adjectives": ["clear", "pragmatic"]},
99
+ "value_frame": {"priority_rank": ["quality", "price"]},
100
+ "generation_method": "random",
101
+ }
102
+ ],
103
+ }
104
+ }
105
+ )
106
+
107
+ group_id: str = Field(description="Generated respondent group identifier.")
108
+ created_at: str = Field(description="Group creation timestamp in ISO-8601 format.")
109
+ total_respondents: int = Field(description="Total number of generated respondents.")
110
+ composition: List[Dict[str, Any]] = Field(default_factory=list, description="Normalized requested composition.")
111
+ generation_method: str = Field(description="Generation method used to build the group.")
112
+ sample_profiles: List[Dict[str, Any]] = Field(
113
+ default_factory=list,
114
+ description="Short preview of generated respondent profiles.",
115
+ )
116
+
117
+
118
+ class GroupFetchResponse(BaseModel):
119
+ model_config = ConfigDict(
120
+ json_schema_extra={
121
+ "example": {
122
+ "group_id": "group-ab12cd34",
123
+ "created_at": "2026-03-08T15:40:03.123000+00:00",
124
+ "total_respondents": 40,
125
+ "composition": [{"persona_id": "curious-connoisseurs", "count": 25}],
126
+ "generation_method": "random",
127
+ "respondents": [],
128
+ "sample_profiles": [
129
+ {
130
+ "respondent_id": "group-ab12cd34-resp-00001",
131
+ "persona_id": "curious-connoisseurs",
132
+ "name": "Luca Rossi",
133
+ "style_profile": {"tone_adjectives": ["clear", "pragmatic"]},
134
+ "value_frame": {"priority_rank": ["quality", "price"]},
135
+ "generation_method": "random",
136
+ }
137
+ ],
138
+ }
139
+ }
140
+ )
141
+
142
+ group_id: str = Field(description="Respondent group identifier.")
143
+ created_at: str = Field(description="Group creation timestamp.")
144
+ total_respondents: int = Field(description="Total respondents in this group.")
145
+ composition: List[Dict[str, Any]] = Field(default_factory=list, description="Group composition by persona segment.")
146
+ generation_method: str = Field(description="Generation method used for the group.")
147
+ respondents: List[Dict[str, Any]] = Field(
148
+ default_factory=list,
149
+ description="Full respondent payloads (returned only if `include_full_profiles=true`).",
150
+ )
151
+ sample_profiles: List[Dict[str, Any]] = Field(default_factory=list, description="Always-returned sample profiles.")
152
+
153
+
154
+ class GroupsListItemResponse(BaseModel):
155
+ model_config = ConfigDict(
156
+ json_schema_extra={
157
+ "example": {
158
+ "group_id": "group-ab12cd34",
159
+ "created_at": "2026-03-08T15:40:03.123000+00:00",
160
+ "total_respondents": 40,
161
+ "composition": [{"persona_id": "curious-connoisseurs", "count": 25}],
162
+ "generation_method": "random",
163
+ "sample_profiles": [
164
+ {
165
+ "respondent_id": "group-ab12cd34-resp-00001",
166
+ "persona_id": "curious-connoisseurs",
167
+ "name": "Luca Rossi",
168
+ "style_profile": {"tone_adjectives": ["clear", "pragmatic"]},
169
+ "value_frame": {"priority_rank": ["quality", "price"]},
170
+ "generation_method": "random",
171
+ }
172
+ ],
173
+ }
174
+ }
175
+ )
176
+
177
+ group_id: str = Field(description="Respondent group identifier.")
178
+ created_at: str = Field(description="Group creation timestamp.")
179
+ total_respondents: int = Field(description="Total respondents in this group.")
180
+ composition: List[Dict[str, Any]] = Field(default_factory=list, description="Group composition by persona segment.")
181
+ generation_method: str = Field(description="Generation method used for the group.")
182
+ sample_profiles: List[Dict[str, Any]] = Field(default_factory=list, description="Preview respondent profiles.")
183
+
184
+
185
+ class GroupsListResponse(BaseModel):
186
+ model_config = ConfigDict(
187
+ json_schema_extra={
188
+ "example": {
189
+ "items": [
190
+ {
191
+ "group_id": "group-ab12cd34",
192
+ "created_at": "2026-03-08T15:40:03.123000+00:00",
193
+ "total_respondents": 40,
194
+ "composition": [{"persona_id": "curious-connoisseurs", "count": 25}],
195
+ "generation_method": "random",
196
+ "sample_profiles": [],
197
+ }
198
+ ],
199
+ "paging": {"page": 1, "page_size": 20, "total_items": 12, "total_pages": 1},
200
+ }
201
+ }
202
+ )
203
+
204
+ items: List[GroupsListItemResponse] = Field(default_factory=list, description="Paged group list.")
205
+ paging: PagingMeta = Field(description="Paging metadata for the group list.")
206
+
207
+
208
+ def _to_iso(value: Any) -> str:
209
+ if hasattr(value, "isoformat"):
210
+ return value.isoformat()
211
+ return str(value)
212
+
213
+
214
+ def _sample_profile(profile: Dict[str, Any]) -> Dict[str, Any]:
215
+ return {
216
+ "respondent_id": profile.get("respondent_id"),
217
+ "persona_id": profile.get("persona_id"),
218
+ "name": profile.get("name"),
219
+ "country": profile.get("country"),
220
+ "gender": profile.get("gender"),
221
+ "ethnicity": profile.get("ethnicity"),
222
+ "style_profile": {
223
+ "tone_adjectives": (profile.get("style_profile") or {}).get("tone_adjectives", [])
224
+ },
225
+ "value_frame": {
226
+ "priority_rank": (profile.get("value_frame") or {}).get("priority_rank", [])
227
+ },
228
+ "generation_method": profile.get("generation_method"),
229
+ }
230
+
231
+
232
+ class GroupCountryItemResponse(BaseModel):
233
+ country_id: str = Field(description="Canonical country id to use in `POST /api/groups`.")
234
+ display_name: str = Field(description="Human-readable country name.")
235
+ description: str = Field(description="Short description of this country profile option.")
236
+
237
+
238
+ class GroupCountriesResponse(BaseModel):
239
+ countries: List[GroupCountryItemResponse] = Field(
240
+ default_factory=list,
241
+ description="List of supported countries for respondent generation.",
242
+ )
243
+
244
+
245
+ def register_group_routes(
246
+ app: Any,
247
+ *,
248
+ get_services: Callable[..., Any],
249
+ ) -> None:
250
+ from fastapi import Depends, HTTPException, Path, Query
251
+
252
+ @app.post(
253
+ "/api/groups",
254
+ response_model=GroupCreateResponse,
255
+ tags=["survey"],
256
+ summary="Create Respondent Group",
257
+ description=_group_create_description(),
258
+ )
259
+ def create_group(
260
+ payload: GroupCreateRequest,
261
+ services: Any = Depends(get_services),
262
+ ) -> GroupCreateResponse:
263
+ try:
264
+ group = services.groups.create_group(
265
+ payload.composition,
266
+ mode=payload.mode,
267
+ sampling_ratio=payload.sampling_ratio,
268
+ include_names=payload.include_names,
269
+ countries=payload.countries,
270
+ seed=payload.seed,
271
+ )
272
+ except FileNotFoundError as exc:
273
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
274
+ except Exception as exc:
275
+ raise HTTPException(status_code=400, detail=f"Invalid group payload: {exc}") from exc
276
+
277
+ respondents = [
278
+ profile.model_dump(mode="json") if hasattr(profile, "model_dump") else profile.dict()
279
+ for profile in group.respondents
280
+ ]
281
+ return GroupCreateResponse(
282
+ group_id=group.group_id,
283
+ created_at=_to_iso(group.created_at),
284
+ total_respondents=len(group.respondents),
285
+ composition=[
286
+ item.model_dump(mode="json") if hasattr(item, "model_dump") else item.dict()
287
+ for item in group.composition
288
+ ],
289
+ generation_method=group.generation_method,
290
+ sample_profiles=[_sample_profile(profile) for profile in respondents[:3]],
291
+ )
292
+
293
+ @app.get(
294
+ "/api/groups/countries",
295
+ response_model=GroupCountriesResponse,
296
+ tags=["survey"],
297
+ summary="List Available Countries",
298
+ description=(
299
+ "Returns all country values accepted by `POST /api/groups` via the `countries` field. "
300
+ "Provide one or more ids from this list to constrain generated respondent demographics."
301
+ ),
302
+ )
303
+ def list_available_countries(
304
+ services: Any = Depends(get_services),
305
+ ) -> GroupCountriesResponse:
306
+ return GroupCountriesResponse(countries=[GroupCountryItemResponse(**item) for item in services.groups.list_available_countries()])
307
+
308
+ @app.get(
309
+ "/api/groups",
310
+ response_model=GroupsListResponse,
311
+ tags=["survey"],
312
+ summary="List Respondent Groups",
313
+ description="Returns respondent groups with pagination.",
314
+ )
315
+ def list_groups(
316
+ page: int = Query(default=1, ge=1, description="1-based page number."),
317
+ page_size: int = Query(default=20, ge=1, le=200, description="Number of groups per page."),
318
+ services: Any = Depends(get_services),
319
+ ) -> GroupsListResponse:
320
+ groups = services.groups.list_groups()
321
+ total_items = len(groups)
322
+ total_pages = max(1, math.ceil(total_items / page_size)) if total_items else 1
323
+ start = (page - 1) * page_size
324
+ end = start + page_size
325
+
326
+ items: List[GroupsListItemResponse] = []
327
+ for group in groups[start:end]:
328
+ respondents = [
329
+ profile.model_dump(mode="json") if hasattr(profile, "model_dump") else profile.dict()
330
+ for profile in group.respondents
331
+ ]
332
+ items.append(
333
+ GroupsListItemResponse(
334
+ group_id=group.group_id,
335
+ created_at=_to_iso(group.created_at),
336
+ total_respondents=len(group.respondents),
337
+ composition=[
338
+ item.model_dump(mode="json") if hasattr(item, "model_dump") else item.dict()
339
+ for item in group.composition
340
+ ],
341
+ generation_method=group.generation_method,
342
+ sample_profiles=[_sample_profile(profile) for profile in respondents[:3]],
343
+ )
344
+ )
345
+
346
+ return GroupsListResponse(
347
+ items=items,
348
+ paging=PagingMeta(
349
+ page=page,
350
+ page_size=page_size,
351
+ total_items=total_items,
352
+ total_pages=total_pages,
353
+ ),
354
+ )
355
+
356
+ @app.get(
357
+ "/api/groups/{group_id}",
358
+ response_model=GroupFetchResponse,
359
+ tags=["survey"],
360
+ summary="Get Respondent Group",
361
+ description="Returns group metadata and optionally all full respondent profiles.",
362
+ )
363
+ def get_group(
364
+ group_id: str = Path(description="Group identifier to fetch.", examples=["group-ab12cd34"]),
365
+ include_full_profiles: bool = Query(
366
+ default=False,
367
+ description="Set true to include all generated respondent profiles in the response.",
368
+ ),
369
+ services: Any = Depends(get_services),
370
+ ) -> GroupFetchResponse:
371
+ try:
372
+ group = services.groups.get_group(group_id)
373
+ except KeyError as exc:
374
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
375
+
376
+ respondents = [
377
+ profile.model_dump(mode="json") if hasattr(profile, "model_dump") else profile.dict()
378
+ for profile in group.respondents
379
+ ]
380
+ return GroupFetchResponse(
381
+ group_id=group.group_id,
382
+ created_at=_to_iso(group.created_at),
383
+ total_respondents=len(group.respondents),
384
+ composition=[
385
+ item.model_dump(mode="json") if hasattr(item, "model_dump") else item.dict()
386
+ for item in group.composition
387
+ ],
388
+ generation_method=group.generation_method,
389
+ respondents=respondents if include_full_profiles else [],
390
+ sample_profiles=[_sample_profile(profile) for profile in respondents[:3]],
391
+ )
adsp/app/api/routes/ingestion.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ingestion API routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ from typing import Any, Callable, Optional
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+
11
+ class UploadRequest(BaseModel):
12
+ model_config = ConfigDict(
13
+ json_schema_extra={
14
+ "example": {
15
+ "filename": "notes.txt",
16
+ "content_base64": "SGVsbG8gTGF2YXp6YSBBSSBQZXJzb25hcyE=",
17
+ "bucket": "uploads",
18
+ }
19
+ }
20
+ )
21
+
22
+ filename: str = Field(description="Target object key/filename in object storage.")
23
+ content_base64: str = Field(
24
+ description="File content encoded as Base64 string.",
25
+ examples=["SGVsbG8gTGF2YXp6YSBBSSBQZXJzb25hcyE="],
26
+ )
27
+ bucket: Optional[str] = Field(
28
+ default=None,
29
+ description="Optional destination bucket. Defaults to configured ingestion bucket.",
30
+ examples=["uploads"],
31
+ )
32
+
33
+
34
+ class UploadResponse(BaseModel):
35
+ model_config = ConfigDict(json_schema_extra={"example": {"bucket": "uploads", "key": "notes.txt", "size_bytes": 25}})
36
+
37
+ bucket: str = Field(description="Destination bucket where payload was stored.")
38
+ key: str = Field(description="Stored object key.")
39
+ size_bytes: int = Field(description="Decoded payload size in bytes.")
40
+
41
+
42
+ def register_ingestion_routes(
43
+ app: Any,
44
+ *,
45
+ get_services: Callable[..., Any],
46
+ authorize: Callable[..., Any],
47
+ ) -> None:
48
+ from fastapi import Depends, HTTPException
49
+
50
+ @app.post(
51
+ "/v1/ingestion/upload",
52
+ response_model=UploadResponse,
53
+ tags=["ingestion"],
54
+ dependencies=[Depends(authorize)],
55
+ summary="Upload File Payload",
56
+ description="Uploads a Base64 payload into object storage through the ingestion service.",
57
+ )
58
+ def upload(payload: UploadRequest, services: Any = Depends(get_services)) -> UploadResponse:
59
+ try:
60
+ raw = base64.b64decode(payload.content_base64)
61
+ except Exception as exc:
62
+ raise HTTPException(status_code=400, detail=f"Invalid base64 payload: {exc}") from exc
63
+
64
+ bucket = payload.bucket or services.ingestion.bucket
65
+ key = payload.filename
66
+ services.ingestion.ingest_bytes(key, raw, bucket=bucket)
67
+ return UploadResponse(bucket=bucket, key=key, size_bytes=len(raw))
adsp/app/api/routes/personas.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persona catalog and prompt API routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, List, Optional
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field
8
+
9
+ from adsp.core.prompt_builder.system_prompt import (
10
+ persona_to_system_prompt,
11
+ preamble_to_system_prompt,
12
+ )
13
+ from adsp.data_pipeline.schema import PersonaProfileModel
14
+
15
+
16
+ class PersonaSummary(BaseModel):
17
+ model_config = ConfigDict(
18
+ json_schema_extra={
19
+ "example": {
20
+ "persona_id": "curious-connoisseurs",
21
+ "persona_name": "Curious Connoisseurs",
22
+ "summary_bio": "Enjoys discovering nuanced flavor profiles with informed choices.",
23
+ }
24
+ }
25
+ )
26
+
27
+ persona_id: str = Field(description="Stable persona identifier.", examples=["curious-connoisseurs"])
28
+ persona_name: Optional[str] = Field(
29
+ default=None,
30
+ description="Human-readable persona name when available.",
31
+ examples=["Curious Connoisseurs"],
32
+ )
33
+ summary_bio: Optional[str] = Field(
34
+ default=None,
35
+ description="Short persona biography snippet when available.",
36
+ )
37
+
38
+
39
+ class PersonasListResponse(BaseModel):
40
+ model_config = ConfigDict(
41
+ json_schema_extra={
42
+ "example": {
43
+ "personas": [
44
+ {
45
+ "persona_id": "curious-connoisseurs",
46
+ "persona_name": "Curious Connoisseurs",
47
+ "summary_bio": "Enjoys discovering nuanced flavor profiles with informed choices.",
48
+ }
49
+ ]
50
+ }
51
+ }
52
+ )
53
+
54
+ personas: List[PersonaSummary] = Field(
55
+ default_factory=list,
56
+ description="All persona summaries available in the current registry.",
57
+ )
58
+
59
+
60
+ class SystemPromptResponse(BaseModel):
61
+ model_config = ConfigDict(
62
+ json_schema_extra={
63
+ "example": {
64
+ "system_prompt": "You are Curious Connoisseurs. Prioritize flavor depth, craft quality, and exploration."
65
+ }
66
+ }
67
+ )
68
+
69
+ system_prompt: str = Field(description="Resolved system prompt used for this persona.")
70
+
71
+
72
+ def register_persona_routes(
73
+ app: Any,
74
+ *,
75
+ get_qa_service: Callable[..., Any],
76
+ ) -> None:
77
+ from fastapi import Depends, HTTPException, Path
78
+
79
+ @app.get(
80
+ "/v1/personas",
81
+ response_model=PersonasListResponse,
82
+ tags=["personas"],
83
+ summary="List Personas",
84
+ description="Returns all personas currently available to the QA orchestrator.",
85
+ )
86
+ def list_personas(qa: Any = Depends(get_qa_service)) -> PersonasListResponse:
87
+ registry = qa.orchestrator.prompt_builder.registry
88
+ items: List[PersonaSummary] = []
89
+ for persona_id in registry.list_personas():
90
+ persona = registry.get(persona_id)
91
+ if isinstance(persona, PersonaProfileModel):
92
+ items.append(
93
+ PersonaSummary(
94
+ persona_id=persona_id,
95
+ persona_name=persona.persona_name,
96
+ summary_bio=persona.summary_bio,
97
+ )
98
+ )
99
+ elif isinstance(persona, dict):
100
+ items.append(PersonaSummary(persona_id=persona_id, persona_name=persona.get("persona_name")))
101
+ else:
102
+ items.append(PersonaSummary(persona_id=persona_id))
103
+ return PersonasListResponse(personas=items)
104
+
105
+ @app.get(
106
+ "/v1/personas/{persona_id}/profile",
107
+ response_model=PersonaProfileModel,
108
+ tags=["personas"],
109
+ summary="Get Persona Profile",
110
+ description="Returns the full structured profile for a specific persona.",
111
+ )
112
+ def get_persona_profile(
113
+ persona_id: str = Path(description="Persona identifier to fetch.", examples=["curious-connoisseurs"]),
114
+ qa: Any = Depends(get_qa_service),
115
+ ) -> PersonaProfileModel:
116
+ registry = qa.orchestrator.prompt_builder.registry
117
+ persona = registry.get(persona_id)
118
+ if not isinstance(persona, PersonaProfileModel):
119
+ raise HTTPException(status_code=404, detail="Persona profile not available")
120
+ return persona
121
+
122
+ @app.get(
123
+ "/v1/personas/{persona_id}/system-prompt",
124
+ response_model=SystemPromptResponse,
125
+ tags=["personas"],
126
+ summary="Get Persona System Prompt",
127
+ description="Builds and returns the active system prompt for a persona.",
128
+ )
129
+ def get_system_prompt(
130
+ persona_id: str = Path(description="Persona identifier to fetch.", examples=["curious-connoisseurs"]),
131
+ qa: Any = Depends(get_qa_service),
132
+ ) -> SystemPromptResponse:
133
+ registry = qa.orchestrator.prompt_builder.registry
134
+ persona = registry.get(persona_id)
135
+ if isinstance(persona, PersonaProfileModel):
136
+ return SystemPromptResponse(system_prompt=persona_to_system_prompt(persona))
137
+ if isinstance(persona, dict):
138
+ return SystemPromptResponse(system_prompt=preamble_to_system_prompt(persona.get("preamble")))
139
+ raise HTTPException(status_code=404, detail="Persona not found")
adsp/app/api/routes/reports.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reporting API routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Dict
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field
8
+
9
+
10
+ class ReportGenerateRequest(BaseModel):
11
+ model_config = ConfigDict(
12
+ json_schema_extra={
13
+ "example": {
14
+ "insights": {
15
+ "top_drivers": ["taste", "price", "brand trust"],
16
+ "summary": "Customer segment values consistency and practical value.",
17
+ }
18
+ }
19
+ }
20
+ )
21
+
22
+ insights: Dict[str, Any] = Field(
23
+ default_factory=dict,
24
+ description="Arbitrary insights payload to render into a report markdown file.",
25
+ )
26
+
27
+
28
+ class ReportGenerateResponse(BaseModel):
29
+ model_config = ConfigDict(
30
+ json_schema_extra={"example": {"path": "reports/api/curious-connoisseurs_report.md"}}
31
+ )
32
+
33
+ path: str = Field(description="Absolute or relative path of generated report file.")
34
+
35
+
36
+ def register_report_routes(
37
+ app: Any,
38
+ *,
39
+ get_services: Callable[..., Any],
40
+ authorize: Callable[..., Any],
41
+ ) -> None:
42
+ from fastapi import Depends, Path
43
+
44
+ @app.post(
45
+ "/v1/reports/{persona_id}",
46
+ response_model=ReportGenerateResponse,
47
+ tags=["reports"],
48
+ dependencies=[Depends(authorize)],
49
+ summary="Generate Persona Report",
50
+ description="Writes a markdown report for the selected persona using provided insights.",
51
+ )
52
+ def generate_report(
53
+ payload: ReportGenerateRequest,
54
+ persona_id: str = Path(description="Persona identifier used to name the report file."),
55
+ services: Any = Depends(get_services),
56
+ ) -> ReportGenerateResponse:
57
+ report_path = services.reports.generate(persona_id=persona_id, insights=payload.insights)
58
+ return ReportGenerateResponse(path=str(report_path))
adsp/app/api/routes/surveys.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Survey simulation API routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import Any, Callable, Dict, List, Optional
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+
11
+ class SurveyCreateRequest(BaseModel):
12
+ model_config = ConfigDict(
13
+ json_schema_extra={
14
+ "example": {
15
+ "survey_id": "coffee-pref-2026-q1",
16
+ "title": "Coffee Preference Survey",
17
+ "description": "Capture product and value preferences for coffee buyers.",
18
+ "questions": [
19
+ {
20
+ "question_id": "q1",
21
+ "text": "Which product claim matters most?",
22
+ "type": "multiple_choice",
23
+ "options": ["Great taste", "Affordable price", "Sustainable sourcing"],
24
+ },
25
+ {
26
+ "question_id": "q2",
27
+ "text": "How likely are you to try a new blend?",
28
+ "type": "rating",
29
+ "metadata": {"scale": "1-5"},
30
+ },
31
+ ],
32
+ }
33
+ }
34
+ )
35
+
36
+ survey_id: Optional[str] = Field(
37
+ default=None,
38
+ description="Optional survey identifier. If omitted, one is generated automatically.",
39
+ )
40
+ title: str = Field(description="Survey display title.")
41
+ description: str = Field(default="", description="Survey description or objective.")
42
+ questions: List[Dict[str, Any]] = Field(
43
+ default_factory=list,
44
+ description=(
45
+ "Question list. Each item should include at least `question_id`, `text`, and `type` "
46
+ "(multiple_choice, rating, open_ended)."
47
+ ),
48
+ )
49
+
50
+
51
+ class SurveyDetailResponse(BaseModel):
52
+ model_config = ConfigDict(
53
+ json_schema_extra={
54
+ "example": {
55
+ "survey_id": "coffee-pref-2026-q1",
56
+ "title": "Coffee Preference Survey",
57
+ "description": "Capture product and value preferences for coffee buyers.",
58
+ "created_at": "2026-03-08T15:30:12.002812+00:00",
59
+ "questions": [
60
+ {
61
+ "question_id": "q1",
62
+ "text": "Which product claim matters most?",
63
+ "type": "multiple_choice",
64
+ "options": ["Great taste", "Affordable price", "Sustainable sourcing"],
65
+ }
66
+ ],
67
+ "simulations": [],
68
+ }
69
+ }
70
+ )
71
+
72
+ survey_id: str = Field(description="Survey identifier.")
73
+ title: str = Field(description="Survey title.")
74
+ description: str = Field(default="", description="Survey description.")
75
+ created_at: str = Field(description="Creation timestamp in ISO-8601 format.")
76
+ questions: List[Dict[str, Any]] = Field(default_factory=list, description="Persisted survey question list.")
77
+ simulations: List[Dict[str, Any]] = Field(
78
+ default_factory=list,
79
+ description="Simulation runs with metadata and progress for this survey.",
80
+ )
81
+
82
+
83
+ class PagingMeta(BaseModel):
84
+ model_config = ConfigDict(
85
+ json_schema_extra={
86
+ "example": {
87
+ "page": 1,
88
+ "page_size": 20,
89
+ "total_items": 45,
90
+ "total_pages": 3,
91
+ }
92
+ }
93
+ )
94
+
95
+ page: int = Field(description="Current page number (1-based).")
96
+ page_size: int = Field(description="Maximum number of items per page.")
97
+ total_items: int = Field(description="Total number of available items.")
98
+ total_pages: int = Field(description="Total number of pages at the selected page size.")
99
+
100
+
101
+ class SurveysListResponse(BaseModel):
102
+ model_config = ConfigDict(
103
+ json_schema_extra={
104
+ "example": {
105
+ "items": [
106
+ {
107
+ "survey_id": "coffee-pref-2026-q1",
108
+ "title": "Coffee Preference Survey",
109
+ "description": "Capture product and value preferences for coffee buyers.",
110
+ "created_at": "2026-03-08T15:30:12.002812+00:00",
111
+ "questions": [],
112
+ }
113
+ ],
114
+ "paging": {"page": 1, "page_size": 20, "total_items": 45, "total_pages": 3},
115
+ }
116
+ }
117
+ )
118
+
119
+ items: List[SurveyDetailResponse] = Field(default_factory=list, description="Paged survey list.")
120
+ paging: PagingMeta = Field(description="Paging metadata for the survey list.")
121
+
122
+
123
+ class SimulateSurveyRequest(BaseModel):
124
+ model_config = ConfigDict(
125
+ json_schema_extra={"example": {"group_id": "group-ab12cd34"}}
126
+ )
127
+
128
+ group_id: str = Field(description="Respondent group identifier used for simulation.")
129
+ # batch_size: int = Field(default=10, description="Requested batch size for response generation.")
130
+ # format: str = Field(
131
+ # default="json",
132
+ # description="Desired output format hint (current export route supports csv/json).",
133
+ # )
134
+
135
+
136
+ class SimulateSurveyResponse(BaseModel):
137
+ model_config = ConfigDict(
138
+ json_schema_extra={
139
+ "example": {
140
+ "simulation_id": "sim-1234abcd",
141
+ "status": "processing",
142
+ "total_respondents": 40,
143
+ "progress": {"completed": 0, "pending": 40},
144
+ "estimated_time_minutes": 1,
145
+ }
146
+ }
147
+ )
148
+
149
+ simulation_id: str = Field(description="Simulation identifier.")
150
+ status: str = Field(description="Simulation status.")
151
+ total_respondents: int = Field(description="Total respondents processed for this simulation.")
152
+ progress: Dict[str, int] = Field(default_factory=dict, description="Completion counters for simulation progress.")
153
+ estimated_time_minutes: int = Field(description="Estimated completion time in minutes.")
154
+
155
+
156
+ class DistributionEntry(BaseModel):
157
+ model_config = ConfigDict(
158
+ json_schema_extra={"example": {"value": "Great taste", "count": 18, "percentage": 0.45}}
159
+ )
160
+
161
+ value: str = Field(description="Answer value bucket.")
162
+ count: int = Field(description="Number of answers in this bucket.")
163
+ percentage: float = Field(description="Bucket ratio over non-empty answers for the question.")
164
+
165
+
166
+ class SurveyQuestionStatistics(BaseModel):
167
+ model_config = ConfigDict(
168
+ json_schema_extra={
169
+ "example": {
170
+ "question_id": "q1",
171
+ "text": "Which product claim matters most?",
172
+ "type": "multiple_choice",
173
+ "answered_count": 40,
174
+ "response_rate": 1.0,
175
+ "choice_distribution": [
176
+ {"value": "Great taste", "count": 18, "percentage": 0.45},
177
+ {"value": "Affordable price", "count": 12, "percentage": 0.3},
178
+ {"value": "Sustainable sourcing", "count": 10, "percentage": 0.25},
179
+ ],
180
+ "rating_distribution": [],
181
+ "rating_average": None,
182
+ "rating_min": None,
183
+ "rating_max": None,
184
+ "text_response_count": 0,
185
+ "sample_text_responses": [],
186
+ }
187
+ }
188
+ )
189
+
190
+ question_id: str = Field(description="Question identifier.")
191
+ text: str = Field(description="Question text.")
192
+ type: str = Field(description="Question type.")
193
+ answered_count: int = Field(description="Count of non-empty answers for this question.")
194
+ response_rate: float = Field(description="Answer rate over `total_respondents`.")
195
+ choice_distribution: List[DistributionEntry] = Field(
196
+ default_factory=list,
197
+ description="Choice distribution for `multiple_choice` questions.",
198
+ )
199
+ rating_distribution: List[DistributionEntry] = Field(
200
+ default_factory=list,
201
+ description="Rating distribution for `rating` questions.",
202
+ )
203
+ rating_average: Optional[float] = Field(default=None, description="Average rating value when applicable.")
204
+ rating_min: Optional[float] = Field(default=None, description="Minimum rating value when applicable.")
205
+ rating_max: Optional[float] = Field(default=None, description="Maximum rating value when applicable.")
206
+ text_response_count: int = Field(description="Count of non-empty text answers for `open_ended` questions.")
207
+ sample_text_responses: List[str] = Field(
208
+ default_factory=list,
209
+ description="Up to three sample text responses for `open_ended` questions.",
210
+ )
211
+
212
+
213
+ class SurveyStatisticsResponse(BaseModel):
214
+ model_config = ConfigDict(
215
+ json_schema_extra={
216
+ "example": {
217
+ "survey_id": "coffee-pref-2026-q1",
218
+ "simulation_id": "sim-1234abcd",
219
+ "total_respondents": 40,
220
+ "total_responses": 40,
221
+ "computed_at": "2026-03-08T18:00:00+00:00",
222
+ "questions": [],
223
+ }
224
+ }
225
+ )
226
+
227
+ survey_id: str = Field(description="Survey identifier.")
228
+ simulation_id: str = Field(description="Simulation identifier used to compute stats.")
229
+ total_respondents: int = Field(description="Total respondents in the selected simulation.")
230
+ total_responses: int = Field(description="Total response documents processed.")
231
+ computed_at: str = Field(description="Statistic computation timestamp in ISO-8601 format.")
232
+ questions: List[SurveyQuestionStatistics] = Field(
233
+ default_factory=list,
234
+ description="Question-level response statistics for the selected simulation.",
235
+ )
236
+
237
+
238
+ def _model_payload(payload: BaseModel) -> Dict[str, Any]:
239
+ if hasattr(payload, "model_dump"):
240
+ return payload.model_dump(exclude_none=True)
241
+ return payload.dict(exclude_none=True)
242
+
243
+
244
+ def _to_iso(value: Any) -> str:
245
+ if hasattr(value, "isoformat"):
246
+ return value.isoformat()
247
+ return str(value)
248
+
249
+
250
+ def _survey_response_payload(
251
+ survey: Any,
252
+ *,
253
+ simulations: Optional[List[Dict[str, Any]]] = None,
254
+ ) -> SurveyDetailResponse:
255
+ payload = survey.model_dump(mode="json") if hasattr(survey, "model_dump") else survey.dict()
256
+ return SurveyDetailResponse(
257
+ survey_id=str(payload.get("survey_id", "")),
258
+ title=str(payload.get("title", "")),
259
+ description=str(payload.get("description", "")),
260
+ created_at=_to_iso(payload.get("created_at")),
261
+ questions=payload.get("questions", []) if isinstance(payload.get("questions"), list) else [],
262
+ simulations=simulations or [],
263
+ )
264
+
265
+
266
+ def _simulation_payload(simulation: Any, *, statistics_ready: bool) -> Dict[str, Any]:
267
+ return {
268
+ "simulation_id": simulation.simulation_id,
269
+ "group_id": simulation.group_id,
270
+ "status": simulation.status,
271
+ "started_at": _to_iso(simulation.started_at),
272
+ "completed_at": _to_iso(simulation.completed_at) if simulation.completed_at is not None else None,
273
+ "total_respondents": simulation.total_respondents,
274
+ "progress": {"completed": simulation.completed, "pending": simulation.pending},
275
+ "responses_count": simulation.completed,
276
+ "statistics_ready": statistics_ready,
277
+ }
278
+
279
+
280
+ def register_survey_routes(
281
+ app: Any,
282
+ *,
283
+ get_services: Callable[..., Any],
284
+ ) -> None:
285
+ from fastapi import Depends, HTTPException, Path, Query
286
+ from fastapi.responses import FileResponse
287
+
288
+ @app.get(
289
+ "/api/surveys",
290
+ response_model=SurveysListResponse,
291
+ tags=["survey"],
292
+ summary="List Surveys",
293
+ description="Returns surveys with pagination.",
294
+ )
295
+ def list_surveys(
296
+ page: int = Query(default=1, ge=1, description="1-based page number."),
297
+ page_size: int = Query(default=20, ge=1, le=200, description="Number of surveys per page."),
298
+ services: Any = Depends(get_services),
299
+ ) -> SurveysListResponse:
300
+ surveys = services.surveys.list_surveys()
301
+ total_items = len(surveys)
302
+ total_pages = max(1, math.ceil(total_items / page_size)) if total_items else 1
303
+ start = (page - 1) * page_size
304
+ end = start + page_size
305
+
306
+ items = [_survey_response_payload(survey) for survey in surveys[start:end]]
307
+ return SurveysListResponse(
308
+ items=items,
309
+ paging=PagingMeta(
310
+ page=page,
311
+ page_size=page_size,
312
+ total_items=total_items,
313
+ total_pages=total_pages,
314
+ ),
315
+ )
316
+
317
+ @app.post(
318
+ "/api/surveys",
319
+ response_model=SurveyDetailResponse,
320
+ tags=["survey"],
321
+ summary="Create Survey",
322
+ description="Creates and persists a survey definition.",
323
+ )
324
+ def create_survey(
325
+ payload: SurveyCreateRequest,
326
+ services: Any = Depends(get_services),
327
+ ) -> SurveyDetailResponse:
328
+ try:
329
+ survey = services.surveys.create_survey(_model_payload(payload))
330
+ return _survey_response_payload(survey)
331
+ except Exception as exc:
332
+ raise HTTPException(status_code=400, detail=f"Invalid survey payload: {exc}") from exc
333
+
334
+ @app.get(
335
+ "/api/surveys/{survey_id}",
336
+ response_model=SurveyDetailResponse,
337
+ tags=["survey"],
338
+ summary="Get Survey",
339
+ description="Fetches a previously created survey definition.",
340
+ )
341
+ def get_survey(
342
+ survey_id: str = Path(description="Survey identifier to fetch.", examples=["coffee-pref-2026-q1"]),
343
+ services: Any = Depends(get_services),
344
+ ) -> SurveyDetailResponse:
345
+ try:
346
+ survey = services.surveys.get_survey(survey_id)
347
+ simulation_items: List[Dict[str, Any]] = []
348
+ for simulation in services.responses.list_simulations(survey_id):
349
+ simulation_items.append(
350
+ _simulation_payload(
351
+ simulation,
352
+ statistics_ready=services.responses.has_statistics_cache(
353
+ survey_id,
354
+ simulation.simulation_id,
355
+ ),
356
+ )
357
+ )
358
+ return _survey_response_payload(survey, simulations=simulation_items)
359
+ except KeyError as exc:
360
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
361
+
362
+ @app.post(
363
+ "/api/surveys/{survey_id}/simulate",
364
+ response_model=SimulateSurveyResponse,
365
+ tags=["survey"],
366
+ summary="Run Survey Simulation",
367
+ description="Runs survey response synthesis for a chosen survey and respondent group.",
368
+ )
369
+ def simulate_survey(
370
+ payload: SimulateSurveyRequest,
371
+ survey_id: str = Path(description="Survey identifier to simulate.", examples=["coffee-pref-2026-q1"]),
372
+ background: bool = Query(
373
+ default=True,
374
+ description="Run simulation in background when true; return immediate processing status.",
375
+ ),
376
+ services: Any = Depends(get_services),
377
+ ) -> SimulateSurveyResponse:
378
+ try:
379
+ if background:
380
+ result = services.responses.run_simulation_background(
381
+ survey_id=survey_id,
382
+ group_id=payload.group_id
383
+ )
384
+ else:
385
+ result = services.responses.run_simulation(
386
+ survey_id=survey_id,
387
+ group_id=payload.group_id
388
+ )
389
+ except KeyError as exc:
390
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
391
+ except Exception as exc:
392
+ raise HTTPException(status_code=400, detail=f"Simulation failed: {exc}") from exc
393
+
394
+ estimated_minutes = max(1, round(result.total_respondents / 60))
395
+ return SimulateSurveyResponse(
396
+ simulation_id=result.simulation_id,
397
+ status=result.status,
398
+ total_respondents=result.total_respondents,
399
+ progress={"completed": result.completed, "pending": result.pending},
400
+ estimated_time_minutes=estimated_minutes,
401
+ )
402
+
403
+ @app.get(
404
+ "/api/surveys/{survey_id}/responses",
405
+ tags=["survey"],
406
+ summary="Download Simulation Responses",
407
+ description="Downloads simulation responses as a CSV or JSON file for a survey.",
408
+ responses={
409
+ 200: {
410
+ "description": "Simulation response export file.",
411
+ "content": {
412
+ "text/csv": {"schema": {"type": "string", "format": "binary"}},
413
+ "application/json": {"schema": {"type": "string", "format": "binary"}},
414
+ },
415
+ }
416
+ },
417
+ )
418
+ def get_simulation_results(
419
+ survey_id: str = Path(description="Survey identifier for exported responses.", examples=["coffee-pref-2026-q1"]),
420
+ simulation_id: Optional[str] = Query(
421
+ default=None,
422
+ description="Specific simulation identifier. Defaults to the latest simulation if omitted.",
423
+ ),
424
+ format: str = Query(default="csv", description="Export format: `csv` or `json`."),
425
+ services: Any = Depends(get_services),
426
+ ) -> Any:
427
+ simulations = services.responses.list_simulations(survey_id)
428
+ if not simulations:
429
+ raise HTTPException(status_code=404, detail=f"No simulations found for survey '{survey_id}'")
430
+
431
+ chosen = simulation_id or simulations[-1].simulation_id
432
+ normalized_format = (format or "csv").strip().lower()
433
+ if normalized_format not in {"csv", "json"}:
434
+ raise HTTPException(status_code=400, detail="format must be either 'csv' or 'json'")
435
+
436
+ try:
437
+ path = services.responses.export_responses(
438
+ survey_id=survey_id,
439
+ format=normalized_format,
440
+ simulation_id=chosen,
441
+ )
442
+ except Exception as exc:
443
+ raise HTTPException(status_code=400, detail=f"Unable to export responses: {exc}") from exc
444
+
445
+ media_type = "text/csv" if normalized_format == "csv" else "application/json"
446
+ filename = f"{survey_id}-{chosen}-responses.{normalized_format}"
447
+ return FileResponse(
448
+ path=path,
449
+ media_type=media_type,
450
+ filename=filename,
451
+ )
452
+
453
+ @app.get(
454
+ "/api/surveys/{survey_id}/statistics",
455
+ response_model=SurveyStatisticsResponse,
456
+ tags=["survey"],
457
+ summary="Compute Simulation Statistics",
458
+ description="Computes question-level response statistics for a survey simulation.",
459
+ )
460
+ def get_simulation_statistics(
461
+ survey_id: str = Path(description="Survey identifier for statistics.", examples=["coffee-pref-2026-q1"]),
462
+ simulation_id: Optional[str] = Query(
463
+ default=None,
464
+ description="Specific simulation identifier. Defaults to latest simulation when omitted.",
465
+ ),
466
+ services: Any = Depends(get_services),
467
+ ) -> SurveyStatisticsResponse:
468
+ try:
469
+ payload = services.responses.compute_response_statistics(
470
+ survey_id=survey_id,
471
+ simulation_id=simulation_id,
472
+ )
473
+ return SurveyStatisticsResponse(**payload)
474
+ except KeyError as exc:
475
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
476
+ except RuntimeError as exc:
477
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
478
+ except Exception as exc:
479
+ raise HTTPException(status_code=400, detail=f"Unable to compute statistics: {exc}") from exc
adsp/app/api/routes/system.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """System/health API routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field
8
+
9
+
10
+ class HealthResponse(BaseModel):
11
+ model_config = ConfigDict(
12
+ json_schema_extra={"example": {"status": "ok", "version": "0.1.0", "qa_status": "ready"}}
13
+ )
14
+
15
+ status: str = Field(default="ok", description="Overall API health status.")
16
+ version: str = Field(description="Application API version.")
17
+ qa_status: str = Field(
18
+ default="unknown",
19
+ description="QA service warmup status. Expected values: idle, warming, ready, error.",
20
+ )
21
+
22
+
23
+ def register_system_routes(app: Any, *, version: str) -> None:
24
+ @app.get(
25
+ "/health",
26
+ response_model=HealthResponse,
27
+ tags=["system"],
28
+ summary="Health Check",
29
+ description="Returns API liveness and QA warmup status.",
30
+ )
31
+ def health() -> HealthResponse:
32
+ services = getattr(app.state, "services", None)
33
+ qa_status = getattr(getattr(services, "qa", None), "status", "unknown")
34
+ return HealthResponse(version=version, qa_status=qa_status)
adsp/app/api_server.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """REST API server for the Application layer.
2
+
3
+ This module is intentionally not imported from `adsp.app.__init__` so that the
4
+ core package remains usable even when FastAPI/uvicorn are not installed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ import os
11
+ from pathlib import Path
12
+ import threading
13
+ import time
14
+ from typing import Any, Callable, Optional
15
+
16
+ from loguru import logger
17
+
18
+ from adsp.app.api.routes import (
19
+ register_auth_routes,
20
+ register_chat_routes,
21
+ register_group_routes,
22
+ register_ingestion_routes,
23
+ register_persona_routes,
24
+ register_report_routes,
25
+ register_survey_routes,
26
+ register_system_routes,
27
+ )
28
+ from adsp.app.auth_service import AuthService
29
+ from adsp.app.ingestion_service import IngestionService
30
+ from adsp.app.qa_service import QAService
31
+ from adsp.app.report_service import ReportService
32
+ from adsp.config import PROCESSED_DATA_DIR
33
+
34
+
35
+ def _require_fastapi():
36
+ try:
37
+ from fastapi import FastAPI # noqa: F401
38
+ except ImportError as exc: # pragma: no cover - import guard
39
+ raise ImportError(
40
+ "FastAPI is required to run the REST API server. "
41
+ "Install with `pip install fastapi uvicorn` (or `make install`)."
42
+ ) from exc
43
+
44
+
45
+ class LazyQAService:
46
+ """Lazily build the QA stack so API startup can return quickly."""
47
+
48
+ def __init__(self, factory: Optional[Callable[[], QAService]] = None) -> None:
49
+ self._factory = factory or QAService
50
+ self._instance: Optional[QAService] = None
51
+ self._error: Optional[Exception] = None
52
+ self._lock = threading.Lock()
53
+ self._status = "idle"
54
+
55
+ @property
56
+ def status(self) -> str:
57
+ return self._status
58
+
59
+ def warmup_async(self) -> None:
60
+ if self._instance is not None or self._error is not None or self._status == "warming":
61
+ return
62
+ self._status = "warming"
63
+ logger.info("API startup step 4/5: starting QA warmup thread")
64
+ thread = threading.Thread(target=self._warmup, name="qa-service-warmup", daemon=True)
65
+ thread.start()
66
+
67
+ def _warmup(self) -> None:
68
+ logger.info("QA warmup step 1/2: building QA service")
69
+ try:
70
+ self._get_instance()
71
+ except Exception:
72
+ logger.exception("QA service warmup failed")
73
+
74
+ def _get_instance(self) -> QAService:
75
+ instance = self._instance
76
+ if instance is not None:
77
+ return instance
78
+
79
+ with self._lock:
80
+ if self._instance is not None:
81
+ return self._instance
82
+ if self._error is not None:
83
+ raise RuntimeError("QA service initialization failed") from self._error
84
+
85
+ start = time.perf_counter()
86
+ try:
87
+ instance = self._factory()
88
+ except Exception as exc:
89
+ self._error = exc
90
+ self._status = "error"
91
+ raise RuntimeError("QA service initialization failed") from exc
92
+
93
+ self._instance = instance
94
+ self._status = "ready"
95
+ logger.info(
96
+ "QA warmup step 2/2: QA service ready in {:.2f}s",
97
+ time.perf_counter() - start,
98
+ )
99
+ return instance
100
+
101
+ def get_instance(self) -> QAService:
102
+ return self._get_instance()
103
+
104
+ def __getattr__(self, name: str) -> Any:
105
+ return getattr(self._get_instance(), name)
106
+
107
+
108
+ @dataclass
109
+ class AppServices:
110
+ auth: AuthService
111
+ qa: Any
112
+ ingestion: IngestionService
113
+ reports: ReportService
114
+ surveys: Any
115
+ groups: Any
116
+ responses: Any
117
+
118
+
119
+ def create_app() -> Any:
120
+ """Create and configure the FastAPI application."""
121
+
122
+ _require_fastapi()
123
+ from fastapi import Depends, FastAPI, Header, HTTPException
124
+
125
+ title = os.environ.get("ADSP_API_TITLE", "Lavazza AI Personas API")
126
+ version = os.environ.get("ADSP_API_VERSION", "0.1.0")
127
+ debug = os.environ.get("ADSP_API_DEBUG", "false").strip().lower() in {"1", "true", "yes", "on"}
128
+ description = (
129
+ "REST API for the Lavazza AI Personas application layer.\n\n"
130
+ "Swagger UI: `/docs`\n"
131
+ "OpenAPI JSON: `/openapi.json`"
132
+ )
133
+
134
+ app = FastAPI(
135
+ title=title,
136
+ version=version,
137
+ description=description,
138
+ debug=debug,
139
+ docs_url="/docs",
140
+ redoc_url="/redoc",
141
+ openapi_url="/openapi.json",
142
+ )
143
+
144
+ @app.on_event("startup")
145
+ def _startup() -> None:
146
+ from adsp.core.survey.group_generator import GroupGenerator
147
+ from adsp.core.survey.response_synthesizer import ResponseSynthesizer
148
+ from adsp.core.survey.survey_manager import SurveyManager
149
+
150
+ logger.info("API startup step 1/5: preparing application services")
151
+ bucket = os.environ.get("ADSP_INGESTION_BUCKET", "uploads")
152
+ reports_dir = Path(os.environ.get("ADSP_REPORTS_DIR", "reports/api"))
153
+ reports_dir.mkdir(parents=True, exist_ok=True)
154
+ surveys_dir = Path(os.environ.get("ADSP_SURVEYS_DIR", str(PROCESSED_DATA_DIR / "surveys")))
155
+ logger.info("API startup step 2/5: reports directory ready at {}", reports_dir)
156
+ qa = LazyQAService()
157
+ logger.info("API startup step 3/5: creating auth, ingestion, and report services")
158
+ app.state.services = AppServices(
159
+ auth=AuthService(),
160
+ qa=qa,
161
+ ingestion=IngestionService(bucket=bucket),
162
+ reports=ReportService(output_dir=reports_dir),
163
+ surveys=SurveyManager(base_dir=surveys_dir),
164
+ groups=GroupGenerator(base_dir=surveys_dir),
165
+ responses=ResponseSynthesizer(base_dir=surveys_dir),
166
+ )
167
+ qa.warmup_async()
168
+ logger.info("API startup step 5/5: server ready; health endpoint available; qa_status={}", qa.status)
169
+
170
+ def get_services() -> AppServices:
171
+ services = getattr(app.state, "services", None)
172
+ if services is None:
173
+ raise HTTPException(status_code=503, detail="Application services are not initialized")
174
+ return services
175
+
176
+ def get_qa_service(services: AppServices = Depends(get_services)) -> Any:
177
+ try:
178
+ qa = services.qa
179
+ if isinstance(qa, LazyQAService):
180
+ return qa.get_instance()
181
+ return qa
182
+ except Exception as exc:
183
+ raise HTTPException(status_code=503, detail=f"QA service unavailable: {exc}") from exc
184
+
185
+ def auth_required() -> bool:
186
+ raw = os.environ.get("ADSP_REQUIRE_AUTH", "false").strip().lower()
187
+ return raw in {"1", "true", "yes", "on"}
188
+
189
+ def authorize(
190
+ services: AppServices = Depends(get_services),
191
+ x_user: Optional[str] = Header(None, alias="X-User"),
192
+ x_token: Optional[str] = Header(None, alias="X-Token"),
193
+ ) -> None:
194
+ if not auth_required():
195
+ return
196
+ if not x_user or not x_token:
197
+ raise HTTPException(status_code=401, detail="Missing X-User/X-Token")
198
+ if not services.auth.is_authorized(x_user, x_token):
199
+ raise HTTPException(status_code=401, detail="Unauthorized")
200
+
201
+ register_system_routes(app, version=version)
202
+ register_auth_routes(app, get_services=get_services)
203
+ register_persona_routes(app, get_qa_service=get_qa_service)
204
+ register_chat_routes(app, get_qa_service=get_qa_service, authorize=authorize)
205
+ register_ingestion_routes(app, get_services=get_services, authorize=authorize)
206
+ register_report_routes(app, get_services=get_services, authorize=authorize)
207
+ register_group_routes(app, get_services=get_services)
208
+ register_survey_routes(app, get_services=get_services)
209
+
210
+ return app
211
+
212
+
213
+ app = create_app()
adsp/app/auth_service.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Authentication and authorization helpers for UI clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Dict
7
+
8
+
9
+ @dataclass
10
+ class AuthService:
11
+ """Very small in-memory auth registry for illustration purposes.
12
+ It has to manage authentication and authorization, user access, permissions, and ensure only authorized users can interact
13
+ with certain parts of the system"""
14
+
15
+ _tokens: Dict[str, str] = field(default_factory=dict)
16
+
17
+ def register(self, user: str, token: str) -> None:
18
+ """Register a token for a given user."""
19
+
20
+ self._tokens[user] = token
21
+
22
+ def is_authorized(self, user: str, token: str) -> bool:
23
+ """Validate whether the provided token matches the stored one."""
24
+
25
+ return self._tokens.get(user) == token
adsp/app/ingestion_service.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Handles user-driven ingestion requests for PDFs, images, and structured data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Iterable, Optional
8
+
9
+ from adsp.storage import object_store
10
+
11
+
12
+ @dataclass
13
+ class IngestionService:
14
+ """Uploads artifacts to object storage and queues preprocessing jobs."""
15
+
16
+ bucket: str
17
+
18
+ def ingest_files(self, files: Iterable[Path]) -> None:
19
+ """Persist files to object storage and emit events for downstream pipelines."""
20
+
21
+ for file_path in files:
22
+ object_store.put(self.bucket, file_path)
23
+
24
+ def ingest_bytes(self, filename: str, payload: bytes, *, bucket: Optional[str] = None) -> str:
25
+ """Persist an in-memory payload to object storage.
26
+
27
+ Returns the stored object key.
28
+ """
29
+
30
+ target_bucket = bucket or self.bucket
31
+ object_store.put_bytes(target_bucket, filename, payload)
32
+ return filename
adsp/app/persona_config.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persona configuration workflows surfaced to the frontend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Dict, List
7
+
8
+
9
+ @dataclass
10
+ class PersonaConfigurationService:
11
+ """Stores and retrieves persona definitions used by the orchestration core."""
12
+
13
+ _personas: Dict[str, Dict] = field(default_factory=dict)
14
+
15
+ def register_persona(self, persona_id: str, definition: Dict) -> None:
16
+ """Persist a persona definition so that the Core layer can retrieve it."""
17
+
18
+ self._personas[persona_id] = definition
19
+
20
+ def list_personas(self) -> List[str]:
21
+ """Return identifiers for the personas currently available in the system."""
22
+
23
+ return sorted(self._personas.keys())
24
+
25
+ def get_persona(self, persona_id: str) -> Dict:
26
+ """Return a single persona definition, raising if it does not exist."""
27
+
28
+ try:
29
+ return self._personas[persona_id]
30
+ except KeyError as exc: # pragma: no cover - defensive message
31
+ raise KeyError(f"Persona '{persona_id}' is not registered") from exc
adsp/app/qa_service.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interactive Q&A experience surface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Optional
7
+
8
+ from adsp.core.runtime import build_default_orchestrator
9
+ from adsp.core.types import ChatRequest, ChatResponse
10
+ from adsp.core.orchestrator import Orchestrator
11
+
12
+
13
+ @dataclass
14
+ class QAService:
15
+ """Thin wrapper that forwards prompts to the orchestrator."""
16
+
17
+ orchestrator: Orchestrator = field(default_factory=build_default_orchestrator)
18
+
19
+ def ask(self, persona_id: str, query: str) -> str:
20
+ """Send a query to the orchestrator and return the persona response."""
21
+
22
+ return self.orchestrator.handle_query(persona_id=persona_id, query=query)
23
+
24
+ def ask_with_metadata(
25
+ self,
26
+ *,
27
+ persona_id: str,
28
+ query: str,
29
+ session_id: Optional[str] = None,
30
+ top_k: int = 5,
31
+ ) -> ChatResponse:
32
+ """Return a structured response including retrieved context and citations."""
33
+
34
+ return self.orchestrator.handle(
35
+ ChatRequest(persona_id=persona_id, query=query, session_id=session_id, top_k=top_k)
36
+ )
adsp/app/report_service.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generates structured reports from processed persona insights."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+
9
+ @dataclass
10
+ class ReportService:
11
+ """Coordinates pulling insights and writing them to human-friendly formats."""
12
+
13
+ output_dir: Path
14
+
15
+ def generate(self, persona_id: str, insights: dict) -> Path:
16
+ """Persist the supplied insights in a markdown stub for stakeholders."""
17
+
18
+ report_path = self.output_dir / f"{persona_id}_report.md"
19
+ report_path.write_text(f"# Insights for {persona_id}\n\n{insights}\n", encoding="utf-8")
20
+ return report_path
adsp/communication/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Communication infrastructure clients for RPC, caching, and messaging."""
2
+
3
+ from .rpc import RPCClient
4
+ from .cache import CacheClient
5
+ from .event_broker import EventBroker
6
+
7
+ __all__ = ["RPCClient", "CacheClient", "EventBroker"]
adsp/communication/cache.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Caching abstraction for low-latency persona responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, Optional
7
+
8
+
9
+ @dataclass
10
+ class CacheClient:
11
+ """A naive in-memory cache placeholder. Replace with Redis/Memcached."""
12
+
13
+ _entries: Dict[str, Any] = field(default_factory=dict)
14
+
15
+ def get(self, key: str) -> Optional[Any]:
16
+ return self._entries.get(key)
17
+
18
+ def set(self, key: str, value: Any) -> None:
19
+ self._entries[key] = value
adsp/communication/event_broker.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Message-queue interface for asynchronous workflows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Callable, DefaultDict, List
7
+ from collections import defaultdict
8
+
9
+
10
+ @dataclass
11
+ class EventBroker:
12
+ """Publishes events to in-memory subscribers for now."""
13
+
14
+ _subscribers: DefaultDict[str, List[Callable]] = field(default_factory=lambda: defaultdict(list))
15
+
16
+ def subscribe(self, topic: str, handler: Callable) -> None:
17
+ self._subscribers[topic].append(handler)
18
+
19
+ def publish(self, topic: str, payload: dict) -> None:
20
+ for handler in self._subscribers[topic]:
21
+ handler(payload)
adsp/communication/rpc.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RPC client placeholder used for synchronous service-to-service calls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Callable
7
+
8
+
9
+ @dataclass
10
+ class RPCClient:
11
+ """Simple callable registry that mimics RPC semantics for local dev."""
12
+
13
+ _resolver: Callable[[str], Callable]
14
+
15
+ def call(self, service: str, payload: dict) -> Any:
16
+ handler = self._resolver(service)
17
+ return handler(payload)
adsp/config.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ import sys
4
+
5
+ from dotenv import load_dotenv
6
+ from loguru import logger
7
+
8
+ # Load environment variables from .env file if it exists
9
+ load_dotenv()
10
+
11
+ # Paths
12
+ PROJ_ROOT = Path(__file__).resolve().parents[1]
13
+ # logger.info(f"PROJ_ROOT path is: {PROJ_ROOT}")
14
+
15
+ DATA_DIR = PROJ_ROOT / "data"
16
+ RAW_DATA_DIR = DATA_DIR / "raw"
17
+ INTERIM_DATA_DIR = DATA_DIR / "interim"
18
+ PROCESSED_DATA_DIR = DATA_DIR / "processed"
19
+ EXTERNAL_DATA_DIR = DATA_DIR / "external"
20
+
21
+ MODELS_DIR = PROJ_ROOT / "models"
22
+
23
+ REPORTS_DIR = PROJ_ROOT / "reports"
24
+ FIGURES_DIR = REPORTS_DIR / "figures"
25
+
26
+
27
+ def get_configured_log_level(default: str = "INFO") -> str:
28
+ """Return the configured log level normalized for Loguru/Uvicorn."""
29
+
30
+ for env_var in ("ADSP_LOG_LEVEL", "ADSP_API_LOG_LEVEL"):
31
+ raw = os.environ.get(env_var, "").strip()
32
+ if raw:
33
+ return raw.upper()
34
+ return default.upper()
35
+
36
+ # If tqdm is installed, configure loguru with tqdm.write
37
+ # https://github.com/Delgan/loguru/issues/135
38
+ logger.remove()
39
+
40
+ try:
41
+ from tqdm import tqdm
42
+
43
+ logger.add(lambda msg: tqdm.write(msg, end=""), colorize=True, level=get_configured_log_level())
44
+ except ModuleNotFoundError:
45
+ logger.add(sys.stderr, level=get_configured_log_level())
adsp/core/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core intelligence components (orchestrator, RAG, personas)."""
2
+
3
+ from .ai_persona_router import PersonaRouter
4
+ from .input_handler import InputHandler
5
+ from .mcp_server import MCPServer
6
+ from .memory import ConversationMemory
7
+ from .orchestrator import Orchestrator
8
+ from .persona_registry import PersonaRegistry
9
+ from .prompt_builder import PromptBuilder
10
+ from .rag import RAGPipeline
11
+
12
+ __all__ = [
13
+ "Orchestrator",
14
+ "InputHandler",
15
+ "PromptBuilder",
16
+ "PersonaRegistry",
17
+ "PersonaRouter",
18
+ "RAGPipeline",
19
+ "ConversationMemory",
20
+ "MCPServer",
21
+ ]
adsp/core/ai_persona_router/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Routes prompts to persona-specific model endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from adsp.modeling.inference import PersonaInferenceEngine
8
+
9
+
10
+ @dataclass
11
+ class PersonaRouter:
12
+ """Leverages persona metadata to pick the right PEFT adapter/model."""
13
+
14
+ # inference_engine: PersonaInferenceEngine = PersonaInferenceEngine()
15
+ inference_engine: PersonaInferenceEngine = field(default_factory=PersonaInferenceEngine)
16
+
17
+ def dispatch(self, persona_id: str, prompt: str) -> str:
18
+ return self.inference_engine.generate(persona_id=persona_id, prompt=prompt)
adsp/core/context_filter.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Filter conversation history and retrieved context for relevance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ import json
7
+ import os
8
+ import re
9
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
10
+
11
+ from adsp.core.types import RetrievedContext
12
+
13
+ _CONTEXT_SEPARATOR = "\n\n---\n\n"
14
+
15
+ _WORD_RE = re.compile(r"[a-zA-Z0-9]+(?:[-_][a-zA-Z0-9]+)?")
16
+ _STOPWORDS = {
17
+ "a",
18
+ "an",
19
+ "and",
20
+ "are",
21
+ "as",
22
+ "at",
23
+ "be",
24
+ "by",
25
+ "can",
26
+ "could",
27
+ "do",
28
+ "does",
29
+ "for",
30
+ "from",
31
+ "have",
32
+ "how",
33
+ "i",
34
+ "in",
35
+ "is",
36
+ "it",
37
+ "its",
38
+ "me",
39
+ "my",
40
+ "of",
41
+ "on",
42
+ "or",
43
+ "our",
44
+ "please",
45
+ "so",
46
+ "that",
47
+ "the",
48
+ "their",
49
+ "them",
50
+ "then",
51
+ "there",
52
+ "these",
53
+ "they",
54
+ "this",
55
+ "to",
56
+ "us",
57
+ "was",
58
+ "we",
59
+ "what",
60
+ "when",
61
+ "where",
62
+ "which",
63
+ "who",
64
+ "why",
65
+ "with",
66
+ "you",
67
+ "your",
68
+ }
69
+
70
+
71
+ def _env_flag(name: str, default: bool) -> bool:
72
+ raw = os.environ.get(name)
73
+ if raw is None:
74
+ return default
75
+ return raw.strip().lower() in {"1", "true", "yes", "on"}
76
+
77
+
78
+ def _env_int(name: str, default: int) -> int:
79
+ raw = os.environ.get(name)
80
+ if raw is None:
81
+ return default
82
+ try:
83
+ value = int(raw)
84
+ return value if value > 0 else default
85
+ except Exception:
86
+ return default
87
+
88
+
89
+ def _env_float(name: str, default: float) -> float:
90
+ raw = os.environ.get(name)
91
+ if raw is None:
92
+ return default
93
+ try:
94
+ return float(raw)
95
+ except Exception:
96
+ return default
97
+
98
+
99
+ def _tokenize(text: str) -> List[str]:
100
+ return [token.lower() for token in _WORD_RE.findall(text or "")]
101
+
102
+
103
+ def _meaningful_tokens(text: str) -> List[str]:
104
+ return [t for t in _tokenize(text) if t not in _STOPWORDS]
105
+
106
+
107
+ def _token_coverage(query_tokens: Sequence[str], candidate_text: str) -> float:
108
+ if not query_tokens:
109
+ return 0.0
110
+ query_set = set(query_tokens)
111
+ cand_set = set(_meaningful_tokens(candidate_text))
112
+ if not cand_set:
113
+ return 0.0
114
+ return len(query_set.intersection(cand_set)) / max(1, len(query_set))
115
+
116
+
117
+ def _looks_like_follow_up(query: str) -> bool:
118
+ q = (query or "").strip().lower()
119
+ if not q:
120
+ return False
121
+ if q.startswith(("and ", "also ", "so ", "then ", "what about", "how about")):
122
+ return True
123
+ raw_tokens = _tokenize(q)
124
+ if any(token in {"it", "that", "this", "these", "those", "they", "them"} for token in raw_tokens):
125
+ return True
126
+ tokens = _meaningful_tokens(q)
127
+ if not tokens:
128
+ return True
129
+ if len(tokens) == 1 and len(raw_tokens) <= 3:
130
+ return True
131
+ return False
132
+
133
+
134
+ def _split_context_blocks(context: str) -> List[str]:
135
+ blocks = [b.strip() for b in (context or "").split(_CONTEXT_SEPARATOR)]
136
+ return [b for b in blocks if b]
137
+
138
+
139
+ def _join_context_blocks(blocks: Sequence[str]) -> str:
140
+ return _CONTEXT_SEPARATOR.join(b for b in blocks if b)
141
+
142
+
143
+ def _extract_json(text: str) -> Optional[str]:
144
+ cleaned = (text or "").strip()
145
+ if not cleaned:
146
+ return None
147
+ if "```" in cleaned:
148
+ parts = [part.strip() for part in cleaned.split("```") if part.strip()]
149
+ for part in parts:
150
+ candidate = part
151
+ if candidate.startswith("json"):
152
+ candidate = candidate[len("json") :].strip()
153
+ if candidate.startswith("{") and candidate.endswith("}"):
154
+ return candidate
155
+ if cleaned.startswith("{") and cleaned.endswith("}"):
156
+ return cleaned
157
+ match = re.search(r"(\{.*\})", cleaned, flags=re.DOTALL)
158
+ if match:
159
+ return match.group(1).strip()
160
+ return None
161
+
162
+
163
+ @dataclass
164
+ class ConversationContextFilter:
165
+ """Filters memory + RAG context down to question-relevant snippets.
166
+
167
+ Configuration (environment variables):
168
+ - `ADSP_CONTEXT_FILTER_BACKEND`: `heuristic` (default) or `openai`
169
+ - `ADSP_CONTEXT_FILTER_MAX_HISTORY`: max history turns passed to the prompt (default: 4)
170
+ - `ADSP_CONTEXT_FILTER_MAX_BLOCKS`: max context blocks passed to the prompt (default: 3)
171
+ - `ADSP_CONTEXT_FILTER_MIN_COVERAGE`: minimum token coverage score (default: 0.2)
172
+
173
+ OpenAI backend (optional):
174
+ - `ADSP_CONTEXT_FILTER_BASE_URL` (defaults to `ADSP_LLM_BASE_URL` / `VLLM_BASE_URL`)
175
+ - `ADSP_CONTEXT_FILTER_MODEL` (defaults to `ADSP_LLM_MODEL` / `VLLM_MODEL`)
176
+ - `ADSP_CONTEXT_FILTER_API_KEY` (defaults to `ADSP_LLM_API_KEY` / `VLLM_API_KEY`)
177
+ """
178
+
179
+ backend: str = field(
180
+ default_factory=lambda: os.environ.get("ADSP_CONTEXT_FILTER_BACKEND", "heuristic")
181
+ )
182
+ max_history_items: int = field(default_factory=lambda: _env_int("ADSP_CONTEXT_FILTER_MAX_HISTORY", 4))
183
+ max_context_blocks: int = field(default_factory=lambda: _env_int("ADSP_CONTEXT_FILTER_MAX_BLOCKS", 3))
184
+ min_coverage: float = field(default_factory=lambda: _env_float("ADSP_CONTEXT_FILTER_MIN_COVERAGE", 0.2))
185
+
186
+ base_url: str = field(
187
+ default_factory=lambda: os.environ.get(
188
+ "ADSP_CONTEXT_FILTER_BASE_URL",
189
+ os.environ.get("ADSP_LLM_BASE_URL", os.environ.get("VLLM_BASE_URL", "")),
190
+ )
191
+ )
192
+ model: str = field(
193
+ default_factory=lambda: os.environ.get(
194
+ "ADSP_CONTEXT_FILTER_MODEL",
195
+ os.environ.get("ADSP_LLM_MODEL", os.environ.get("VLLM_MODEL", "")),
196
+ )
197
+ )
198
+ api_key: str = field(
199
+ default_factory=lambda: os.environ.get(
200
+ "ADSP_CONTEXT_FILTER_API_KEY",
201
+ os.environ.get("ADSP_LLM_API_KEY", os.environ.get("VLLM_API_KEY", "EMPTY")),
202
+ )
203
+ )
204
+ timeout_s: float = field(default_factory=lambda: _env_float("ADSP_CONTEXT_FILTER_TIMEOUT", 20.0))
205
+ enabled: bool = field(default_factory=lambda: _env_flag("ADSP_CONTEXT_FILTER_ENABLED", True))
206
+
207
+ def filter_history(self, history: List[dict] | None, query: str) -> List[dict]:
208
+ if not self.enabled or not history:
209
+ return history or []
210
+
211
+ if (self.backend or "").strip().lower() == "openai":
212
+ selected = self._select_history_with_openai(query=query, history=history)
213
+ if selected is not None:
214
+ return [history[idx] for idx in selected if isinstance(history[idx], dict)]
215
+
216
+ query_tokens = _meaningful_tokens(query)
217
+ if _looks_like_follow_up(query) or not query_tokens:
218
+ return [item for item in history[-2:] if isinstance(item, dict)]
219
+
220
+ candidates = []
221
+ for idx, item in enumerate(history):
222
+ if not isinstance(item, dict):
223
+ continue
224
+ text = " ".join(str(item.get(key, "")) for key in ("query", "response") if item.get(key))
225
+ score = _token_coverage(query_tokens, text)
226
+ candidates.append((idx, score))
227
+
228
+ candidates.sort(key=lambda pair: pair[1], reverse=True)
229
+ keep = [idx for idx, score in candidates if score >= self.min_coverage][: self.max_history_items]
230
+ keep.sort()
231
+ return [history[idx] for idx in keep if isinstance(history[idx], dict)]
232
+
233
+ def filter_retrieved(self, retrieved: RetrievedContext, query: str) -> RetrievedContext:
234
+ if not self.enabled:
235
+ return retrieved
236
+
237
+ context = (retrieved.context or "").strip()
238
+ if not context:
239
+ return retrieved
240
+
241
+ blocks = _split_context_blocks(context)
242
+ if not blocks:
243
+ return RetrievedContext(context="", citations=[], raw=retrieved.raw or {})
244
+
245
+ context_keep: Optional[List[int]] = None
246
+ if (self.backend or "").strip().lower() == "openai":
247
+ context_keep = self._select_context_with_openai(query=query, context_blocks=blocks)
248
+
249
+ if context_keep is None:
250
+ context_keep = self._select_context_blocks_heuristic(query=query, context_blocks=blocks)
251
+
252
+ kept_blocks = [blocks[i] for i in context_keep if 0 <= i < len(blocks)]
253
+ filtered_context = _join_context_blocks(kept_blocks)
254
+
255
+ citations = list(retrieved.citations or [])
256
+ filtered_citations = [citations[i] for i in context_keep if 0 <= i < len(citations)]
257
+
258
+ raw: Dict[str, Any] = dict(retrieved.raw or {})
259
+ raw_docs = raw.get("documents")
260
+ if isinstance(raw_docs, list):
261
+ raw["documents"] = [raw_docs[i] for i in context_keep if 0 <= i < len(raw_docs)]
262
+
263
+ raw["context_keep"] = context_keep
264
+
265
+ return RetrievedContext(context=filtered_context, citations=filtered_citations, raw=raw)
266
+
267
+ def _select_context_blocks_heuristic(self, query: str, context_blocks: Sequence[str]) -> List[int]:
268
+ if _looks_like_follow_up(query):
269
+ return list(range(min(self.max_context_blocks, len(context_blocks))))
270
+
271
+ query_tokens = _meaningful_tokens(query)
272
+ if not query_tokens:
273
+ return []
274
+
275
+ scored: List[Tuple[int, float]] = []
276
+ for idx, block in enumerate(context_blocks):
277
+ scored.append((idx, _token_coverage(query_tokens, block)))
278
+ scored.sort(key=lambda pair: pair[1], reverse=True)
279
+
280
+ keep = [idx for idx, score in scored if score >= self.min_coverage][: self.max_context_blocks]
281
+ keep.sort()
282
+ return keep
283
+
284
+ def _select_history_with_openai(
285
+ self,
286
+ *,
287
+ query: str,
288
+ history: Sequence[dict],
289
+ ) -> Optional[List[int]]:
290
+ if not (self.base_url and self.model):
291
+ return None
292
+ try:
293
+ from openai import OpenAI # type: ignore
294
+ except ImportError:
295
+ return None
296
+
297
+ client = OpenAI(base_url=self.base_url, api_key=self.api_key)
298
+ items = []
299
+ for idx, item in enumerate(history):
300
+ if not isinstance(item, dict):
301
+ continue
302
+ q = str(item.get("query", "")).strip()
303
+ a = str(item.get("response", "")).strip()
304
+ combined = f"User: {q}\nPersona: {a}".strip()
305
+ if len(combined) > 400:
306
+ combined = combined[:397] + "..."
307
+ items.append(f"[{idx}]\n{combined}")
308
+
309
+ system = (
310
+ "You select ONLY the conversation history turns needed to answer the user's question.\n"
311
+ "Return JSON only with key keep_history: array of integer indices.\n"
312
+ f"Choose at most {self.max_history_items} indices.\n"
313
+ "If none are needed, return an empty array.\n"
314
+ )
315
+ user = "\n".join(
316
+ [
317
+ f"Question: {query.strip()}",
318
+ "",
319
+ "Conversation history (oldest to newest):",
320
+ *items,
321
+ ]
322
+ ).strip()
323
+
324
+ try:
325
+ completion = client.chat.completions.create(
326
+ model=self.model,
327
+ messages=[
328
+ {"role": "system", "content": system},
329
+ {"role": "user", "content": user},
330
+ ],
331
+ temperature=0.0,
332
+ max_tokens=200,
333
+ timeout=self.timeout_s,
334
+ )
335
+ content = completion.choices[0].message.content or ""
336
+ except Exception:
337
+ return None
338
+
339
+ payload = _extract_json(content)
340
+ if not payload:
341
+ return None
342
+ try:
343
+ data = json.loads(payload)
344
+ except Exception:
345
+ return None
346
+
347
+ keep_history = data.get("keep_history")
348
+ if not isinstance(keep_history, list):
349
+ return None
350
+ indices: List[int] = []
351
+ for value in keep_history:
352
+ try:
353
+ idx = int(value)
354
+ except Exception:
355
+ continue
356
+ if 0 <= idx < len(history):
357
+ indices.append(idx)
358
+ return sorted(set(indices))[: self.max_history_items]
359
+
360
+ def _select_context_with_openai(
361
+ self,
362
+ *,
363
+ query: str,
364
+ context_blocks: Sequence[str],
365
+ ) -> Optional[List[int]]:
366
+ if not (self.base_url and self.model):
367
+ return None
368
+ try:
369
+ from openai import OpenAI # type: ignore
370
+ except ImportError:
371
+ return None
372
+
373
+ client = OpenAI(base_url=self.base_url, api_key=self.api_key)
374
+ block_summaries = []
375
+ for idx, block in enumerate(context_blocks):
376
+ snippet = " ".join(line.strip() for line in block.splitlines() if line.strip())
377
+ if len(snippet) > 500:
378
+ snippet = snippet[:497] + "..."
379
+ block_summaries.append(f"[{idx}] {snippet}")
380
+
381
+ system = (
382
+ "You select ONLY the context blocks needed to answer the user's question.\n"
383
+ "Return JSON only, with keys:\n"
384
+ "- keep_context: array of integer indices\n"
385
+ "Rules:\n"
386
+ f"- Choose at most {self.max_context_blocks} indices.\n"
387
+ "- If none are helpful, return an empty array.\n"
388
+ )
389
+ user = "\n".join(
390
+ [
391
+ f"Question: {query.strip()}",
392
+ "",
393
+ "Context blocks:",
394
+ *block_summaries,
395
+ ]
396
+ ).strip()
397
+
398
+ try:
399
+ completion = client.chat.completions.create(
400
+ model=self.model,
401
+ messages=[
402
+ {"role": "system", "content": system},
403
+ {"role": "user", "content": user},
404
+ ],
405
+ temperature=0.0,
406
+ max_tokens=200,
407
+ timeout=self.timeout_s,
408
+ )
409
+ content = completion.choices[0].message.content or ""
410
+ except Exception:
411
+ return None
412
+
413
+ payload = _extract_json(content)
414
+ if not payload:
415
+ return None
416
+ try:
417
+ data = json.loads(payload)
418
+ except Exception:
419
+ return None
420
+
421
+ keep_context = data.get("keep_context")
422
+ if not isinstance(keep_context, list):
423
+ return None
424
+ indices: List[int] = []
425
+ for value in keep_context:
426
+ try:
427
+ idx = int(value)
428
+ except Exception:
429
+ continue
430
+ if 0 <= idx < len(context_blocks):
431
+ indices.append(idx)
432
+ indices = sorted(set(indices))[: self.max_context_blocks]
433
+ return indices
434
+
435
+
436
+ __all__ = ["ConversationContextFilter"]
adsp/core/input_handler/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Input normalization utilities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass
9
+ class InputHandler:
10
+ """Normalizes text or routes other modalities to preprocessors."""
11
+
12
+ def normalize(self, text: str) -> str:
13
+ return text.strip()
adsp/core/mcp_server/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Selects external tools to enrich persona prompts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Dict
7
+
8
+ from adsp.core.mcp_server.tools import MCPClient
9
+
10
+
11
+ @dataclass
12
+ class MCPServer:
13
+ """Coordinates MCP tool calls and caches their responses for reuse."""
14
+
15
+ # mcp: MCPClient = MCPClient()
16
+ mcp: MCPClient = field(default_factory=MCPClient)
17
+ _cache: Dict[str, dict] = None
18
+
19
+ def __post_init__(self) -> None:
20
+ if self._cache is None:
21
+ self._cache = {}
22
+
23
+ def run(self, tool: str, payload: dict) -> dict:
24
+ cache_key = f"{tool}:{tuple(sorted(payload.items()))}"
25
+ if cache_key not in self._cache:
26
+ self._cache[cache_key] = self.mcp.request(tool, payload)
27
+ return self._cache[cache_key]
adsp/core/mcp_server/tools/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Auxiliary tools accessible via the MCP server."""
2
+
3
+ from .mcp_client import MCPClient
4
+
5
+ __all__ = ["MCPClient"]
adsp/core/mcp_server/tools/mcp_client.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mock MCP client that would normally communicate with external tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass
9
+ class MCPClient:
10
+ """Provides a very small interface to request external context."""
11
+
12
+ def request(self, tool: str, payload: dict) -> dict:
13
+ return {"tool": tool, "payload": payload}
adsp/core/memory/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Short-term memory store for conversations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from dataclasses import dataclass, field
7
+ from typing import DefaultDict, List, Optional, Tuple
8
+
9
+
10
+ @dataclass
11
+ class ConversationMemory:
12
+ """Stores the last few interactions per persona."""
13
+
14
+ max_items: int = 10
15
+ _messages: DefaultDict[Tuple[str, str], List[dict]] = field(default_factory=lambda: defaultdict(list))
16
+
17
+ @staticmethod
18
+ def _key(persona_id: str, session_id: Optional[str]) -> Tuple[str, str]:
19
+ return persona_id, session_id or "default"
20
+
21
+ def store(self, persona_id: str, message: dict, *, session_id: Optional[str] = None) -> None:
22
+ history = self._messages[self._key(persona_id, session_id)]
23
+ history.append(message)
24
+ if len(history) > self.max_items:
25
+ history.pop(0)
26
+
27
+ def get_history(self, persona_id: str, *, session_id: Optional[str] = None) -> List[dict]:
28
+ return list(self._messages[self._key(persona_id, session_id)])
adsp/core/orchestrator/__init__.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Main coordination engine for persona responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ import time
7
+ from typing import Optional, TYPE_CHECKING
8
+
9
+ from loguru import logger
10
+
11
+ from adsp.communication.cache import CacheClient
12
+ from adsp.core.ai_persona_router import PersonaRouter
13
+ from adsp.core.context_filter import ConversationContextFilter
14
+ from adsp.core.input_handler import InputHandler
15
+ from adsp.core.memory import ConversationMemory
16
+ from adsp.core.prompt_builder import PromptBuilder
17
+ from adsp.core.rag import RAGPipeline
18
+ from adsp.core.types import ChatRequest, ChatResponse, RetrievedContext
19
+ from adsp.data_pipeline.schema import PersonaProfileModel
20
+
21
+ if TYPE_CHECKING: # pragma: no cover
22
+ from adsp.core.rag.fact_data_index import FactDataRAGIndex
23
+
24
+ _CONTEXT_SEPARATOR = "\n\n---\n\n"
25
+
26
+
27
+ def _split_context_blocks(context: str) -> list[str]:
28
+ return [b.strip() for b in (context or "").split(_CONTEXT_SEPARATOR) if b.strip()]
29
+
30
+
31
+ def _join_context_blocks(blocks: list[str]) -> str:
32
+ return _CONTEXT_SEPARATOR.join(block for block in blocks if block)
33
+
34
+
35
+ def _merge_retrieved_contexts(
36
+ primary: RetrievedContext,
37
+ secondary: RetrievedContext,
38
+ ) -> RetrievedContext:
39
+ primary_blocks = _split_context_blocks(primary.context)
40
+ secondary_blocks = _split_context_blocks(secondary.context)
41
+
42
+ merged_blocks = [*primary_blocks, *secondary_blocks]
43
+ merged_citations = [*(primary.citations or []), *(secondary.citations or [])]
44
+
45
+ primary_docs = (primary.raw or {}).get("documents")
46
+ secondary_docs = (secondary.raw or {}).get("documents")
47
+ merged_docs = []
48
+ if isinstance(primary_docs, list):
49
+ merged_docs.extend(primary_docs)
50
+ if isinstance(secondary_docs, list):
51
+ merged_docs.extend(secondary_docs)
52
+
53
+ return RetrievedContext(
54
+ context=_join_context_blocks(merged_blocks),
55
+ citations=merged_citations,
56
+ raw={"documents": merged_docs},
57
+ )
58
+
59
+
60
+ @dataclass
61
+ class Orchestrator:
62
+ """Wires together preprocessing, retrieval, routing, and memory."""
63
+
64
+ input_handler: InputHandler = field(default_factory=InputHandler)
65
+ context_filter: ConversationContextFilter = field(default_factory=ConversationContextFilter)
66
+ prompt_builder: PromptBuilder = field(default_factory=PromptBuilder)
67
+ retriever: RAGPipeline = field(default_factory=RAGPipeline)
68
+ fact_data_index: Optional["FactDataRAGIndex"] = None
69
+ router: PersonaRouter = field(default_factory=PersonaRouter)
70
+ memory: ConversationMemory = field(default_factory=ConversationMemory)
71
+ cache: CacheClient = field(default_factory=CacheClient)
72
+
73
+ def _build_fact_data_query(self, *, persona_id: str, query: str) -> str:
74
+ persona_name = None
75
+ persona_summary = None
76
+ try:
77
+ persona = self.prompt_builder.registry.get(persona_id)
78
+ except Exception:
79
+ persona = None
80
+
81
+ if isinstance(persona, PersonaProfileModel):
82
+ persona_name = persona.persona_name
83
+ persona_summary = persona.summary_bio
84
+ elif isinstance(persona, dict):
85
+ persona_name = persona.get("persona_name") if isinstance(persona.get("persona_name"), str) else None
86
+
87
+ segment = (persona_name or persona_id or "").strip()
88
+ if segment and segment != "default":
89
+ summary = (persona_summary or "").strip()
90
+ if len(summary) > 160:
91
+ summary = summary[:157] + "..."
92
+ parts = [f"Segment: {segment}", query]
93
+ if summary:
94
+ parts.insert(1, f"Persona summary: {summary}")
95
+ return "\n".join(parts).strip()
96
+
97
+ return query.strip()
98
+
99
+ def handle(self, request: ChatRequest) -> ChatResponse:
100
+ """Process a chat request end-to-end using the configured components."""
101
+
102
+ start_total = time.perf_counter()
103
+
104
+ # cache_key = f"{request.persona_id}:{request.session_id or 'default'}:{request.query}"
105
+ # cached = self.cache.get(cache_key)
106
+ # if isinstance(cached, ChatResponse):
107
+ # return cached
108
+ # if isinstance(cached, str) and cached:
109
+ # return ChatResponse(persona_id=request.persona_id, answer=cached)
110
+
111
+ start_step = time.perf_counter()
112
+ normalized = self.input_handler.normalize(request.query)
113
+ logger.debug(
114
+ "orchestrator.normalize persona_id={} ms={:.2f}",
115
+ request.persona_id,
116
+ (time.perf_counter() - start_step) * 1000.0,
117
+ )
118
+
119
+ start_step = time.perf_counter()
120
+ history = self.memory.get_history(persona_id=request.persona_id, session_id=request.session_id)
121
+ logger.debug(
122
+ "orchestrator.get_history persona_id={} session_id={} items={} ms={:.2f}",
123
+ request.persona_id,
124
+ request.session_id,
125
+ len(history or []),
126
+ (time.perf_counter() - start_step) * 1000.0,
127
+ )
128
+
129
+ start_step = time.perf_counter()
130
+ persona_retrieved = self.retriever.retrieve_with_metadata(
131
+ persona_id=request.persona_id, query=normalized, k=request.top_k
132
+ )
133
+ logger.debug(
134
+ "orchestrator.retrieve_persona persona_id={} k={} context_chars={} citations={} ms={:.2f}",
135
+ request.persona_id,
136
+ request.top_k,
137
+ len(persona_retrieved.context or ""),
138
+ len(persona_retrieved.citations or []),
139
+ (time.perf_counter() - start_step) * 1000.0,
140
+ )
141
+ merged_retrieved = persona_retrieved
142
+
143
+ fact_retrieved: RetrievedContext | None = None
144
+
145
+ if self.fact_data_index is not None:
146
+ start_step = time.perf_counter()
147
+ fact_query = self._build_fact_data_query(persona_id=request.persona_id, query=normalized)
148
+ logger.debug(
149
+ "orchestrator.build_fact_query persona_id={} k={} query_chars={} ms={:.2f}",
150
+ request.persona_id,
151
+ request.top_k,
152
+ len(fact_query),
153
+ (time.perf_counter() - start_step) * 1000.0,
154
+ )
155
+ try:
156
+ start_step = time.perf_counter()
157
+ fact_retrieved = self.fact_data_index.retrieve(fact_query, k=request.top_k)
158
+ logger.debug(
159
+ "orchestrator.retrieve_fact_data persona_id={} k={} context_chars={} citations={} ms={:.2f}",
160
+ request.persona_id,
161
+ request.top_k,
162
+ len((fact_retrieved.context or "").strip()),
163
+ len(fact_retrieved.citations or []),
164
+ (time.perf_counter() - start_step) * 1000.0,
165
+ )
166
+ except Exception as exc: # pragma: no cover - defensive retrieval
167
+ logger.warning("Fact data retrieval failed: {}", exc)
168
+ fact_retrieved = None
169
+
170
+ if fact_retrieved and (fact_retrieved.context or "").strip():
171
+ start_step = time.perf_counter()
172
+ merged_retrieved = _merge_retrieved_contexts(persona_retrieved, fact_retrieved)
173
+ logger.debug(
174
+ "orchestrator.merge_context persona_id={} merged_chars={} merged_citations={} ms={:.2f}",
175
+ request.persona_id,
176
+ len(merged_retrieved.context or ""),
177
+ len(merged_retrieved.citations or []),
178
+ (time.perf_counter() - start_step) * 1000.0,
179
+ )
180
+
181
+ start_step = time.perf_counter()
182
+ filtered_history = self.context_filter.filter_history(history, normalized)
183
+ logger.debug(
184
+ "orchestrator.filter_history persona_id={} kept_items={} ms={:.2f}",
185
+ request.persona_id,
186
+ len(filtered_history or []),
187
+ (time.perf_counter() - start_step) * 1000.0,
188
+ )
189
+
190
+ start_step = time.perf_counter()
191
+ filtered_retrieved = self.context_filter.filter_retrieved(merged_retrieved, normalized)
192
+ logger.debug(
193
+ "orchestrator.filter_retrieved persona_id={} context_chars={} citations={} ms={:.2f}",
194
+ request.persona_id,
195
+ len(filtered_retrieved.context or ""),
196
+ len(filtered_retrieved.citations or []),
197
+ (time.perf_counter() - start_step) * 1000.0,
198
+ )
199
+
200
+ start_step = time.perf_counter()
201
+ prompt = self.prompt_builder.build(
202
+ persona_id=request.persona_id,
203
+ query=normalized,
204
+ context=filtered_retrieved.context,
205
+ history=filtered_history,
206
+ display_name=request.persona_display_name,
207
+ )
208
+ logger.debug(
209
+ "orchestrator.build_prompt persona_id={} prompt_chars={} ms={:.2f}",
210
+ request.persona_id,
211
+ len(prompt),
212
+ (time.perf_counter() - start_step) * 1000.0,
213
+ )
214
+
215
+ start_step = time.perf_counter()
216
+ answer = self.router.dispatch(persona_id=request.persona_id, prompt=prompt)
217
+ logger.debug(
218
+ "orchestrator.dispatch persona_id={} answer_chars={} ms={:.2f}",
219
+ request.persona_id,
220
+ len(answer or ""),
221
+ (time.perf_counter() - start_step) * 1000.0,
222
+ )
223
+
224
+ start_step = time.perf_counter()
225
+ self.memory.store(
226
+ persona_id=request.persona_id,
227
+ session_id=request.session_id,
228
+ message={"query": request.query, "response": answer},
229
+ )
230
+ logger.debug(
231
+ "orchestrator.memory_store persona_id={} session_id={} ms={:.2f}",
232
+ request.persona_id,
233
+ request.session_id,
234
+ (time.perf_counter() - start_step) * 1000.0,
235
+ )
236
+ response = ChatResponse(
237
+ persona_id=request.persona_id,
238
+ answer=answer,
239
+ context=filtered_retrieved.context,
240
+ citations=filtered_retrieved.citations,
241
+ )
242
+ logger.debug(
243
+ "orchestrator.total persona_id={} ms={:.2f}",
244
+ request.persona_id,
245
+ (time.perf_counter() - start_total) * 1000.0,
246
+ )
247
+ # self.cache.set(cache_key, response)
248
+ return response
249
+
250
+ def handle_query(self, persona_id: str, query: str) -> str:
251
+ """Backwards-compatible string-only entrypoint."""
252
+
253
+ return self.handle(ChatRequest(persona_id=persona_id, query=query)).answer
adsp/core/persona_registry/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-memory persona catalog."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, Iterable, List
7
+
8
+ DEFAULT_PERSONA = {
9
+ "preamble": "You are a Lavazza persona who is transparent and data-grounded.",
10
+ }
11
+
12
+
13
+ @dataclass
14
+ class PersonaRegistry:
15
+ """Keeps persona metadata available for prompt construction and routing."""
16
+
17
+ _personas: Dict[str, Any] = field(default_factory=lambda: {"default": DEFAULT_PERSONA})
18
+
19
+ def get(self, persona_id: str) -> Any:
20
+ try:
21
+ return self._personas[persona_id]
22
+ except KeyError as exc: # pragma: no cover - defensive message
23
+ raise KeyError(f"Persona '{persona_id}' is not registered") from exc
24
+
25
+ def upsert(self, persona_id: str, metadata: Any) -> None:
26
+ self._personas[persona_id] = metadata
27
+
28
+ def upsert_many(self, personas: Iterable[tuple[str, Any]]) -> None:
29
+ for persona_id, metadata in personas:
30
+ self.upsert(persona_id, metadata)
31
+
32
+ def list_personas(self) -> List[str]:
33
+ return sorted(self._personas.keys())
adsp/core/prompt_builder/__init__.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Constructs prompts by mixing persona rules, query, and retrieved context."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from pydantic import ValidationError
9
+
10
+ from adsp.core.persona_registry import PersonaRegistry
11
+ from adsp.core.prompt_builder.system_prompt import (
12
+ persona_to_system_prompt,
13
+ preamble_to_system_prompt,
14
+ )
15
+ from adsp.data_pipeline.schema import PersonaProfileModel
16
+
17
+
18
+ @dataclass
19
+ class PromptBuilder:
20
+ # registry: PersonaRegistry = PersonaRegistry()
21
+ registry: PersonaRegistry = field(default_factory=PersonaRegistry)
22
+
23
+ def build(self, persona_id: str, query: str, context: str, history: list[dict] | None = None, display_name: str | None = None) -> str:
24
+ persona = self.registry.get(persona_id)
25
+ # get system prompt from persona
26
+ system_prompt = self._system_prompt_for_persona(persona, display_name)
27
+ history_block = self._history_block(history)
28
+ if history_block:
29
+ return f"""
30
+ SYSTEM PROMPT:\n{system_prompt}
31
+ ------------
32
+ HISTORY:\n\n{history_block}
33
+ ------------
34
+ CONTEXT:\n\n{context}
35
+ -------------
36
+ \n\nQUESTION:\n{query}
37
+ """
38
+
39
+ return f"""
40
+ SYSTEM PROMPT:\n{system_prompt}
41
+ ------------
42
+ CONTEXT:\n\n{context}
43
+ -------------
44
+ \n\nQUESTION:\n{query}
45
+ """
46
+
47
+ @staticmethod
48
+ def _history_block(history: list[dict] | None) -> str:
49
+ if not history:
50
+ return ""
51
+ lines = ["Conversation history (reference only; most recent last):"]
52
+ for item in history[-10:]:
53
+ if not isinstance(item, dict):
54
+ continue
55
+ q = item.get("query")
56
+ r = item.get("response")
57
+ if q:
58
+ lines.append(f"- User: {q}")
59
+ if r:
60
+ lines.append(f"- Persona: {r}")
61
+ if len(lines) == 1:
62
+ return ""
63
+ return "\n".join(lines)
64
+
65
+ def _system_prompt_for_persona(self, persona: Any, display_name: str | None = None) -> str:
66
+ if isinstance(persona, PersonaProfileModel):
67
+ return persona_to_system_prompt(persona, display_name)
68
+
69
+ if isinstance(persona, dict):
70
+ has_reasoning_traits = any(
71
+ key in persona
72
+ for key in (
73
+ "style_profile",
74
+ "value_frame",
75
+ "reasoning_policies",
76
+ "content_filters",
77
+ )
78
+ )
79
+ if has_reasoning_traits:
80
+ try:
81
+ profile = PersonaProfileModel(**persona)
82
+ return persona_to_system_prompt(profile, display_name)
83
+ except ValidationError:
84
+ pass
85
+ # get value of preamble, otherwise use the default value
86
+ return preamble_to_system_prompt(persona.get("preamble"), display_name)
87
+
88
+ return preamble_to_system_prompt(None, display_name)
89
+
90
+
91
+ __all__ = ["PromptBuilder", "persona_to_system_prompt"]
adsp/core/prompt_builder/survey_simulation_prompt.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SURVEY_SIMULATION_PRIMING_PROMPT = """
2
+ You are given a survey and a respondent profile. Answer the survey as if you are this respondent.
3
+
4
+ Instructions:
5
+ - Use the respondent profile as persona guidance for all answers.
6
+ - Answer every question. Do not omit any question.
7
+ - Keep responses consistent with the respondent’s preferences, priorities, communication style, and reasoning guidance.
8
+ - For each answer, include:
9
+ - "question_id": the exact question ID
10
+ - "value": the selected answer or rating
11
+ - "reasoning": a brief but specific explanation grounded in the profile
12
+
13
+ Output format:
14
+ Return valid JSON only, with this exact structure:
15
+ {"answers":[{"question_id":"...","value":"...","reasoning":"..."}]}
16
+
17
+ Rules:
18
+ - Do not include any text outside the JSON.
19
+ - For multiple-choice questions, the "value" must exactly match one of the provided options.
20
+ - For rating questions, the "value" must be a valid value within the specified scale.
21
+ - Base all reasoning on the profile and persona, not on generic assumptions.
22
+ - Ensure the reasoning reflects likely tradeoffs, such as sustainability over convenience, innovation over brand loyalty, and quality over price when relevant.
23
+
24
+ """
adsp/core/prompt_builder/system_prompt.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turn persona profiles into LLM-ready system prompts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Iterable, Optional
6
+
7
+ from adsp.data_pipeline.schema import (
8
+ ContentFilters,
9
+ PersonaProfileModel,
10
+ ReasoningPolicies,
11
+ StyleProfile,
12
+ ValueFrame,
13
+ )
14
+
15
+
16
+ def persona_to_system_prompt(persona: PersonaProfileModel, display_name: Optional[str] = None) -> str:
17
+ """Convert a persona profile (with reasoning traits) into a system prompt."""
18
+ persona_label = persona.persona_name or persona.persona_id or "the persona"
19
+ if persona.persona_id and persona.persona_name:
20
+ persona_label = f'{persona.persona_name} (id: {persona.persona_id})'
21
+
22
+ header_lines = [f'You are persona "{persona_label}".']
23
+
24
+ if display_name and display_name != persona.persona_name:
25
+ header_lines.append(f"For this conversation, your name is '{display_name}'.")
26
+
27
+ if persona.summary_bio:
28
+ header_lines.append(f"Summary: {persona.summary_bio}")
29
+
30
+ sections = [
31
+ "\n".join(header_lines),
32
+ _style_section(persona.style_profile),
33
+ _value_frame_section(persona.value_frame),
34
+ _reasoning_policies_section(persona.reasoning_policies),
35
+ _content_filters_section(persona.content_filters),
36
+ _answering_guidelines_section(),
37
+ (
38
+ "Stay in this voice, respect the value priorities and tradeoff rules, and "
39
+ "surface disclaimers when filters apply."
40
+ ),
41
+ ]
42
+ return "\n\n".join([section for section in sections if section])
43
+
44
+
45
+ def _style_section(style: Optional[StyleProfile]) -> Optional[str]:
46
+ if not style:
47
+ return None
48
+
49
+ lines = ["Voice:"]
50
+ if style.tone_adjectives:
51
+ lines.append(f"- Tone adjectives: {_join(style.tone_adjectives)}")
52
+
53
+ delivery = []
54
+ if style.formality_level:
55
+ delivery.append(f"formality={style.formality_level}")
56
+ if style.directness:
57
+ delivery.append(f"directness={style.directness}")
58
+ if style.emotional_flavour:
59
+ delivery.append(f"emotional_flavour={style.emotional_flavour}")
60
+ if style.criticality_level:
61
+ delivery.append(f"criticality={style.criticality_level}")
62
+ if delivery:
63
+ lines.append(f"- Delivery: {'; '.join(delivery)}")
64
+
65
+ if style.verbosity_preference:
66
+ lines.append(f"- Verbosity: {style.verbosity_preference}")
67
+ if style.preferred_structures:
68
+ lines.append(f"- Preferred structures: {_join(style.preferred_structures)}")
69
+ if style.typical_register_examples:
70
+ lines.append(f"- Register examples: {_join(style.typical_register_examples)}")
71
+ return "\n".join(lines)
72
+
73
+
74
+ def _value_frame_section(value_frame: Optional[ValueFrame]) -> Optional[str]:
75
+ if not value_frame:
76
+ return None
77
+
78
+ lines = ["Value frame:"]
79
+ if value_frame.priority_rank:
80
+ lines.append(f"- Priority order: {' > '.join(value_frame.priority_rank)}")
81
+
82
+ sensitivities = []
83
+ if value_frame.sustainability_orientation:
84
+ sensitivities.append(f"sustainability={value_frame.sustainability_orientation}")
85
+ if value_frame.price_sensitivity:
86
+ sensitivities.append(f"price_sensitivity={value_frame.price_sensitivity}")
87
+ if value_frame.novelty_seeking:
88
+ sensitivities.append(f"novelty_seeking={value_frame.novelty_seeking}")
89
+ if value_frame.brand_loyalty:
90
+ sensitivities.append(f"brand_loyalty={value_frame.brand_loyalty}")
91
+ if value_frame.health_concern:
92
+ sensitivities.append(f"health_concern={value_frame.health_concern}")
93
+ if sensitivities:
94
+ lines.append(f"- Sensitivities: {'; '.join(sensitivities)}")
95
+
96
+ if value_frame.description:
97
+ lines.append(f"- Summary: {value_frame.description}")
98
+ return "\n".join(lines)
99
+
100
+
101
+ def _reasoning_policies_section(policies: Optional[ReasoningPolicies]) -> Optional[str]:
102
+ if not policies:
103
+ return None
104
+
105
+ lines = ["Reasoning policies:"]
106
+ if policies.purchase_advice:
107
+ purchase = []
108
+ if policies.purchase_advice.default_biases:
109
+ purchase.append(f"biases: {_join(policies.purchase_advice.default_biases)}")
110
+ if policies.purchase_advice.tradeoff_rules:
111
+ purchase.append(f"tradeoff rules: {_join(policies.purchase_advice.tradeoff_rules)}")
112
+ if purchase:
113
+ lines.append(f"- Purchase advice: {'; '.join(purchase)}")
114
+
115
+ if policies.product_evaluation:
116
+ evaluation = []
117
+ if policies.product_evaluation.praise_triggers:
118
+ evaluation.append(
119
+ f"praise triggers: {_join(policies.product_evaluation.praise_triggers)}"
120
+ )
121
+ if policies.product_evaluation.criticism_triggers:
122
+ evaluation.append(
123
+ f"criticism triggers: {_join(policies.product_evaluation.criticism_triggers)}"
124
+ )
125
+ if policies.product_evaluation.must_always_check:
126
+ evaluation.append(
127
+ f"must always check: {_join(policies.product_evaluation.must_always_check)}"
128
+ )
129
+ if evaluation:
130
+ lines.append(f"- Product evaluation: {'; '.join(evaluation)}")
131
+
132
+ if policies.information_processing:
133
+ info = []
134
+ if policies.information_processing.trust_preference:
135
+ info.append(f"trust: {_join(policies.information_processing.trust_preference)}")
136
+ if policies.information_processing.scepticism_towards:
137
+ info.append(
138
+ f"sceptical of: {_join(policies.information_processing.scepticism_towards)}"
139
+ )
140
+ if policies.information_processing.requested_rigor_level:
141
+ info.append(f"rigor={policies.information_processing.requested_rigor_level}")
142
+ if info:
143
+ lines.append(f"- Information processing: {'; '.join(info)}")
144
+
145
+ if len(lines) == 1:
146
+ return None
147
+ return "\n".join(lines)
148
+
149
+
150
+ def _content_filters_section(filters: Optional[ContentFilters]) -> Optional[str]:
151
+ if not filters:
152
+ return None
153
+
154
+ lines = ["Content filters:"]
155
+ if filters.avoid_styles:
156
+ lines.append(f"- Avoid styles: {_join(filters.avoid_styles)}")
157
+ if filters.emphasise_disclaimers_on:
158
+ lines.append(f"- Emphasise disclaimers on: {_join(filters.emphasise_disclaimers_on)}")
159
+
160
+ if len(lines) == 1:
161
+ return None
162
+ return "\n".join(lines)
163
+
164
+
165
+ def _join(values: Iterable[str], sep: str = ", ") -> str:
166
+ return sep.join(str(v) for v in values if v)
167
+
168
+
169
+ def preamble_to_system_prompt(preamble: str | None, display_name: str | None = None) -> str:
170
+ """Wrap a plain persona preamble with consistent response rules."""
171
+
172
+ base = (preamble or "").strip() or "You are an AI persona."
173
+
174
+ if display_name:
175
+ base = f"{base}\n\nFor this conversation, your name is '{display_name}'."
176
+
177
+ sections = [
178
+ base,
179
+ _answering_guidelines_section(),
180
+ ]
181
+ return "\n\n".join(section for section in sections if section)
182
+
183
+
184
+ def _answering_guidelines_section() -> str:
185
+ return "\n".join(
186
+ [
187
+ """
188
+
189
+ **Answering Rules (Strict):**
190
+
191
+ * Answer **only** the user's question. Nothing extra.
192
+ * Do not volunteer information about coffee, products, or related topics unless the user asks about them.
193
+ * Use context **only if it directly changes the answer**; otherwise ignore it.
194
+ * If essential info is missing, ask **one clear clarifying question**.
195
+ * Write like a real person in casual conversation, not a system or narrator.
196
+ * Keep responses **as short as possible** while still correct (1-2 sentences for simple questions).
197
+ * No background explanations, side facts, or prompt restatement unless explicitly requested.
198
+
199
+ **Human-like Response Guidelines:**
200
+
201
+ * Use natural, conversational language - avoid formal or robotic phrasing.
202
+ * Express numbers naturally:
203
+ - Instead of "2.5 cups," say "around two and a half cups" or "about two or three cups"
204
+ - Instead of "73.4%," say "most of the time" or "pretty often"
205
+ - Instead of "3.2 times per week," say "a few times a week" or "three or four times a week"
206
+ * Use approximations and qualifiers: "around," "about," "roughly," "usually," "sometimes"
207
+ * Express preferences with feeling: "I really like," "I'm not a fan of," "I prefer," "I love"
208
+ * Include mild fillers when natural: "well," "you know," "I mean," "honestly"
209
+ * Vary sentence structure - avoid repetitive patterns.
210
+ * Use contractions naturally: "I'm," "don't," "can't," "it's"
211
+ * Show slight uncertainty when appropriate: "I think," "probably," "usually," "tends to"
212
+ * React authentically to questions - express enthusiasm, hesitation, or indifference when fitting.
213
+
214
+ **Persona Requirements (only when relevant):**
215
+
216
+ * Maintain a consistent professional background with clear career progression.
217
+ * Reflect a realistic daily routine aligned with that profession.
218
+ * Let personality traits influence tone and decision-making.
219
+ * Demonstrate specific, measurable skills through answers - not descriptions.
220
+ * Share personal experiences naturally without over-explaining.
221
+
222
+ **Priority:**
223
+ Accuracy > Clarity > Authenticity > Brevity.
224
+ When these conflict, always prioritize factual correctness and safety over style or persona.
225
+ Sound like a real person. No overthinking. No embellishment. Answer naturally.
226
+ """
227
+
228
+ ]
229
+ )
adsp/core/rag/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Retrieval-Augmented Generation utilities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Optional
7
+
8
+ from adsp.core.rag.fact_data_index import FactDataRAGIndex, build_fact_data_index_from_markdown
9
+ from adsp.core.rag.persona_index import PersonaRAGIndex
10
+ from adsp.core.types import RetrievedContext
11
+ from adsp.storage.vector_db import VectorDatabase
12
+
13
+
14
+ @dataclass
15
+ class RAGPipeline:
16
+ """Retriever used by the runtime orchestrator.
17
+
18
+ The pipeline supports two modes:
19
+ - Persona indicator RAG (preferred for local demo): `persona_index`
20
+ - Fallback string store: `vector_db`
21
+ """
22
+
23
+ vector_db: VectorDatabase = field(default_factory=VectorDatabase)
24
+ persona_index: Optional[PersonaRAGIndex] = None
25
+
26
+ def retrieve(self, persona_id: str, query: str, *, k: int = 5) -> str:
27
+ return self.retrieve_with_metadata(persona_id=persona_id, query=query, k=k).context
28
+
29
+ def retrieve_with_metadata(self, persona_id: str, query: str, *, k: int = 5) -> RetrievedContext:
30
+ if self.persona_index and self.persona_index.has_persona(persona_id):
31
+ return self.persona_index.retrieve(persona_id, query, k=k)
32
+ return RetrievedContext(context=self.vector_db.search(persona_id=persona_id, query=query))
33
+
34
+
35
+ __all__ = [
36
+ "RAGPipeline",
37
+ "FactDataRAGIndex",
38
+ "build_fact_data_index_from_markdown",
39
+ ]
adsp/core/rag/fact_data_index.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fact data RAG index for runtime retrieval."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import List, Optional
8
+
9
+ from langchain_core.documents import Document
10
+ from langchain_core.embeddings import Embeddings
11
+ from langchain_core.vectorstores import VectorStore
12
+
13
+ from adsp.core.types import Citation, RetrievedContext
14
+ from adsp.data_pipeline.embedding_utils import (
15
+ build_configured_embeddings,
16
+ get_configured_embedding_model_name,
17
+ )
18
+ from adsp.data_pipeline.fact_data_pipeline.rag.indicator import (
19
+ FactDataRAG,
20
+ documents_to_context_prompt,
21
+ )
22
+ from adsp.storage.langchain_vectorstore import VectorStoreProvider
23
+
24
+ DEFAULT_EMBEDDING_MODEL_NAME = get_configured_embedding_model_name()
25
+
26
+
27
+ def _default_embeddings() -> Embeddings:
28
+ return build_configured_embeddings(model_name=get_configured_embedding_model_name())
29
+
30
+
31
+ @dataclass
32
+ class FactDataRAGIndex:
33
+ """In-memory similarity search over fact-data markdown chunks."""
34
+
35
+ embeddings: Embeddings = field(default_factory=_default_embeddings)
36
+ namespace: str = "fact-data"
37
+ loaded_from_persisted: bool = False
38
+ vectorstore: Optional[VectorStore] = None
39
+ vectorstore_provider: Optional[VectorStoreProvider] = None
40
+ rag: FactDataRAG = field(init=False)
41
+ indexed_chunk_ids: List[str] = field(default_factory=list)
42
+
43
+ def __post_init__(self) -> None:
44
+ vectorstore = self.vectorstore
45
+ if vectorstore is None and self.vectorstore_provider is not None:
46
+ vectorstore = self.vectorstore_provider.get(self.namespace)
47
+ self.rag = FactDataRAG(
48
+ self.embeddings,
49
+ vectorstore=vectorstore,
50
+ namespace=self.namespace,
51
+ )
52
+
53
+ def index_markdown_directory(self, directory: Path, *, pattern: str = "*.md") -> int:
54
+ chunk_ids = self.rag.index_markdown_directory(Path(directory), pattern=pattern)
55
+ self.indexed_chunk_ids.extend(chunk_ids)
56
+ return len(chunk_ids)
57
+
58
+ def search(self, query: str, *, k: int = 10) -> List[Document]:
59
+ return self.rag.search(query, k=k)
60
+
61
+ def retrieve(self, query: str, *, k: int = 10) -> RetrievedContext:
62
+ docs = self.search(query, k=k)
63
+ if not docs:
64
+ return RetrievedContext(context="", citations=[], raw={"documents": []})
65
+
66
+ citations = [self._citation_from_doc(doc) for doc in docs]
67
+ raw_docs = [{"page_content": d.page_content, "metadata": d.metadata} for d in docs]
68
+ return RetrievedContext(
69
+ context=documents_to_context_prompt(docs),
70
+ citations=citations,
71
+ raw={"documents": raw_docs},
72
+ )
73
+
74
+ @staticmethod
75
+ def _citation_from_doc(doc: Document) -> Citation:
76
+ meta = doc.metadata or {}
77
+ doc_id = meta.get("source_file") if isinstance(meta.get("source_file"), str) else None
78
+
79
+ pages: List[int] = []
80
+ page = meta.get("page_number") or meta.get("page")
81
+ try:
82
+ page_int = int(page)
83
+ if page_int > 0:
84
+ pages.append(page_int)
85
+ except Exception:
86
+ pass
87
+
88
+ snippet = doc.page_content.strip()
89
+ if len(snippet) > 240:
90
+ snippet = snippet[:237] + "..."
91
+
92
+ segment = meta.get("segment") if isinstance(meta.get("segment"), str) else None
93
+ section = meta.get("section") if isinstance(meta.get("section"), str) else None
94
+ template = meta.get("template") if isinstance(meta.get("template"), str) else None
95
+ label_parts = [value for value in (segment, section, template) if value]
96
+
97
+ return Citation(
98
+ doc_id=doc_id or "fact_data",
99
+ pages=pages,
100
+ domain="fact_data",
101
+ category=segment or section,
102
+ indicator_label=" | ".join(label_parts) if label_parts else "fact_data",
103
+ snippet=snippet,
104
+ )
105
+
106
+
107
+ def _safe_dir_has_files(directory: Path, *, pattern: str) -> bool:
108
+ directory = Path(directory)
109
+ if not directory.exists() or not directory.is_dir():
110
+ return False
111
+ return any(directory.rglob(pattern))
112
+
113
+
114
+ def build_fact_data_index_from_markdown(
115
+ markdown_dir: Path,
116
+ *,
117
+ embeddings: Optional[Embeddings] = None,
118
+ vectorstore_provider: Optional[VectorStoreProvider] = None,
119
+ fingerprint: Optional[str] = None,
120
+ pattern: str = "*.md",
121
+ ) -> Optional[FactDataRAGIndex]:
122
+ """Create and populate a fact-data index from a markdown directory."""
123
+
124
+ if not _safe_dir_has_files(markdown_dir, pattern=pattern):
125
+ return None
126
+
127
+ if vectorstore_provider is not None and fingerprint:
128
+ loaded_store = vectorstore_provider.load("fact-data", fingerprint=fingerprint)
129
+ if loaded_store is not None:
130
+ return FactDataRAGIndex(
131
+ embeddings=embeddings or _default_embeddings(),
132
+ namespace="fact-data",
133
+ loaded_from_persisted=True,
134
+ vectorstore=loaded_store,
135
+ vectorstore_provider=vectorstore_provider,
136
+ )
137
+
138
+ vectorstore = (
139
+ vectorstore_provider.create("fact-data", reset=True)
140
+ if vectorstore_provider is not None
141
+ else None
142
+ )
143
+ index = FactDataRAGIndex(
144
+ embeddings=embeddings or _default_embeddings(),
145
+ vectorstore=vectorstore,
146
+ vectorstore_provider=vectorstore_provider,
147
+ )
148
+ index.index_markdown_directory(markdown_dir, pattern=pattern)
149
+ if vectorstore_provider is not None and fingerprint:
150
+ vectorstore_provider.persist(
151
+ "fact-data",
152
+ fingerprint=fingerprint,
153
+ vectorstore=index.rag.vectorstore,
154
+ )
155
+ return index
156
+
157
+
158
+ __all__ = ["FactDataRAGIndex", "build_fact_data_index_from_markdown"]
adsp/core/rag/persona_index.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local RAG index over persona indicators."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import hashlib
7
+ from dataclasses import dataclass, field
8
+ from typing import Dict, Iterable, List, Optional
9
+
10
+ from langchain_core.documents import Document
11
+ from langchain_core.embeddings import Embeddings
12
+
13
+ from adsp.core.types import Citation, RetrievedContext
14
+ from adsp.data_pipeline.embedding_utils import (
15
+ build_configured_embeddings,
16
+ get_configured_embedding_model_name,
17
+ )
18
+ from adsp.data_pipeline.persona_data_pipeline.rag.indicator import (
19
+ PersonaIndicatorRAG,
20
+ documents_to_context_prompt,
21
+ )
22
+ from adsp.data_pipeline.schema import PersonaProfileModel
23
+ from adsp.storage.langchain_vectorstore import VectorStoreProvider
24
+
25
+ DEFAULT_EMBEDDING_MODEL_NAME = get_configured_embedding_model_name()
26
+
27
+
28
+ def get_default_embeddings() -> Embeddings:
29
+ return build_configured_embeddings(model_name=get_configured_embedding_model_name())
30
+
31
+
32
+ class HashEmbeddings(Embeddings):
33
+ """Deterministic local embeddings with no external model downloads.
34
+
35
+ This is intentionally simple: it uses token hashing into a fixed-size vector.
36
+ """
37
+
38
+ def __init__(self, dim: int = 384) -> None:
39
+ if dim <= 0:
40
+ raise ValueError("dim must be > 0")
41
+ self.dim = dim
42
+
43
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
44
+ return [self._embed(text) for text in texts]
45
+
46
+ def embed_query(self, text: str) -> List[float]:
47
+ return self._embed(text)
48
+
49
+ def _embed(self, text: str) -> List[float]:
50
+ vector = [0.0] * self.dim
51
+ if not text:
52
+ return vector
53
+
54
+ for raw_token in text.lower().split():
55
+ token = "".join(ch for ch in raw_token if ch.isalnum() or ch in ("-", "_"))
56
+ if not token:
57
+ continue
58
+ digest = hashlib.blake2b(token.encode("utf-8"), digest_size=8).digest()
59
+ h = int.from_bytes(digest, "big", signed=False)
60
+ idx = h % self.dim
61
+ vector[idx] += 1.0 if (h & 1) else -1.0
62
+
63
+ norm = math.sqrt(sum(v * v for v in vector))
64
+ if norm > 0:
65
+ vector = [v / norm for v in vector]
66
+ return vector
67
+
68
+
69
+ @dataclass
70
+ class PersonaRAGIndex:
71
+ """Builds and queries per-persona indicator vector stores."""
72
+
73
+ embeddings: Embeddings = field(default_factory=get_default_embeddings)
74
+ vectorstore_provider: Optional[VectorStoreProvider] = None
75
+ _indexes: Dict[str, PersonaIndicatorRAG] = field(default_factory=dict)
76
+
77
+ def attach_persona_vectorstore(self, persona_id: str, *, vectorstore, namespace: str) -> None:
78
+ self._indexes[persona_id] = PersonaIndicatorRAG(
79
+ self.embeddings,
80
+ vectorstore=vectorstore,
81
+ namespace=namespace,
82
+ )
83
+
84
+ def index_personas(self, personas: Iterable[PersonaProfileModel]) -> None:
85
+ for persona in personas:
86
+ if not persona.persona_id:
87
+ continue
88
+ namespace = f"persona-{persona.persona_id}"
89
+ vectorstore = (
90
+ self.vectorstore_provider.get(namespace)
91
+ if self.vectorstore_provider is not None
92
+ else None
93
+ )
94
+ rag = PersonaIndicatorRAG(
95
+ self.embeddings,
96
+ vectorstore=vectorstore,
97
+ namespace=namespace,
98
+ )
99
+ rag.index_persona(persona)
100
+ self._indexes[persona.persona_id] = rag
101
+
102
+ def has_persona(self, persona_id: str) -> bool:
103
+ return persona_id in self._indexes
104
+
105
+ def search(self, persona_id: str, query: str, *, k: int = 5) -> List[Document]:
106
+ rag = self._indexes.get(persona_id)
107
+ if rag is None:
108
+ return []
109
+ return rag.search(query, k=k)
110
+
111
+ def retrieve(self, persona_id: str, query: str, *, k: int = 5) -> RetrievedContext:
112
+ docs = self.search(persona_id, query, k=k)
113
+ context = documents_to_context_prompt(docs) if docs else ""
114
+ citations = [self._citation_from_doc(doc) for doc in docs]
115
+ citations = [c for c in citations if c is not None]
116
+ raw_docs = [{"page_content": d.page_content, "metadata": d.metadata} for d in docs]
117
+ return RetrievedContext(
118
+ context=context,
119
+ citations=citations, # type: ignore[arg-type]
120
+ raw={"documents": raw_docs},
121
+ )
122
+
123
+ @staticmethod
124
+ def _citation_from_doc(doc: Document) -> Optional[Citation]:
125
+ meta = doc.metadata or {}
126
+ sources = meta.get("sources")
127
+
128
+ doc_id = None
129
+ pages: List[int] = []
130
+ if isinstance(sources, list) and sources:
131
+ first = sources[0]
132
+ if isinstance(first, dict):
133
+ doc_id = first.get("doc_id") if isinstance(first.get("doc_id"), str) else None
134
+ raw_pages = first.get("pages")
135
+ if isinstance(raw_pages, list):
136
+ for value in raw_pages:
137
+ try:
138
+ pages.append(int(value))
139
+ except Exception:
140
+ continue
141
+
142
+ snippet = doc.page_content.strip()
143
+ if len(snippet) > 240:
144
+ snippet = snippet[:237] + "..."
145
+
146
+ return Citation(
147
+ doc_id=doc_id,
148
+ pages=pages,
149
+ persona_id=meta.get("persona_id"),
150
+ indicator_id=meta.get("indicator_id"),
151
+ indicator_label=meta.get("indicator_label"),
152
+ domain=meta.get("domain"),
153
+ category=meta.get("category"),
154
+ snippet=snippet,
155
+ )
156
+
157
+
158
+ __all__ = ["HashEmbeddings", "PersonaRAGIndex"]
adsp/core/runtime.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers to build a runnable local system configuration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import time
10
+ from typing import List, Optional, Tuple
11
+
12
+ from loguru import logger
13
+
14
+ from adsp.config import PROCESSED_DATA_DIR
15
+ from adsp.core.orchestrator import Orchestrator
16
+ from adsp.core.persona_registry import PersonaRegistry
17
+ from adsp.core.prompt_builder import PromptBuilder
18
+ from adsp.core.rag import RAGPipeline
19
+ from adsp.core.rag.fact_data_index import FactDataRAGIndex, build_fact_data_index_from_markdown
20
+ from adsp.core.rag.persona_index import PersonaRAGIndex
21
+ from adsp.data_pipeline.embedding_utils import (
22
+ build_configured_embeddings,
23
+ get_configured_embedding_config,
24
+ get_configured_embedding_model_name,
25
+ get_configured_embedding_signature,
26
+ )
27
+ from adsp.data_pipeline.persona_data_pipeline.rag.indicator import PersonaIndicatorRAG
28
+ from adsp.data_pipeline.schema import PersonaProfileModel
29
+ from adsp.storage.langchain_vectorstore import VectorStoreProvider, get_vectorstore_config
30
+ from adsp.utils.progress import progress_bar
31
+
32
+
33
+ def resolve_persona_paths(
34
+ processed_dir: Path = PROCESSED_DATA_DIR,
35
+ ) -> Tuple[Path, Path]:
36
+ """Return (individual_dir, traits_dir) based on defaults + env overrides."""
37
+
38
+ individual_dir = Path(
39
+ os.environ.get(
40
+ "ADSP_PERSONAS_DIR",
41
+ str(processed_dir / "personas" / "individual"),
42
+ )
43
+ )
44
+ traits_dir = Path(
45
+ os.environ.get(
46
+ "ADSP_PERSONA_TRAITS_DIR",
47
+ str(processed_dir / "personas" / "common_traits"),
48
+ )
49
+ )
50
+ return individual_dir, traits_dir
51
+
52
+
53
+ def load_personas_from_disk(
54
+ individual_dir: Path,
55
+ *,
56
+ traits_dir: Optional[Path] = None,
57
+ ) -> List[PersonaProfileModel]:
58
+ """Load persona profiles and optional reasoning traits from disk."""
59
+
60
+ personas: List[PersonaProfileModel] = []
61
+ traits_dir = traits_dir if traits_dir and traits_dir.exists() else None
62
+
63
+ if not individual_dir.exists():
64
+ logger.warning(f"Persona directory does not exist: {individual_dir}")
65
+ return personas
66
+
67
+ for path in sorted(individual_dir.glob("*.json")):
68
+ try:
69
+ base_payload = json.loads(path.read_text(encoding="utf-8"))
70
+ if not isinstance(base_payload, dict):
71
+ continue
72
+
73
+ persona_id = base_payload.get("persona_id") or path.stem
74
+ base_payload["persona_id"] = persona_id
75
+
76
+ if traits_dir:
77
+ traits_path = traits_dir / f"{persona_id}.json"
78
+ if traits_path.exists():
79
+ traits_payload = json.loads(traits_path.read_text(encoding="utf-8"))
80
+ if isinstance(traits_payload, dict):
81
+ for key in (
82
+ "key_indicators",
83
+ "style_profile",
84
+ "value_frame",
85
+ "reasoning_policies",
86
+ "content_filters",
87
+ ):
88
+ if key in traits_payload:
89
+ base_payload[key] = traits_payload[key]
90
+
91
+ personas.append(PersonaProfileModel(**base_payload))
92
+ except Exception as exc:
93
+ logger.warning(f"Failed to load persona profile {path}: {exc}")
94
+
95
+ return personas
96
+
97
+
98
+ def build_registry(personas: List[PersonaProfileModel]) -> PersonaRegistry:
99
+ registry = PersonaRegistry()
100
+ for persona in personas:
101
+ if persona.persona_id:
102
+ registry.upsert(persona.persona_id, persona)
103
+ return registry
104
+
105
+
106
+ def _env_flag(name: str, default: bool) -> bool:
107
+ raw = os.environ.get(name)
108
+ if raw is None:
109
+ return default
110
+ return raw.strip().lower() in {"1", "true", "yes", "on"}
111
+
112
+
113
+ def _fingerprint_paths(paths: List[Path], *, label: str) -> str:
114
+ digest = hashlib.sha256()
115
+ digest.update(label.encode("utf-8"))
116
+ digest.update(get_configured_embedding_signature().encode("utf-8"))
117
+
118
+ for path in sorted({Path(p) for p in paths}, key=lambda item: str(item)):
119
+ digest.update(str(path).encode("utf-8"))
120
+ if not path.exists():
121
+ digest.update(b"missing")
122
+ continue
123
+ stat = path.stat()
124
+ digest.update(str(stat.st_size).encode("utf-8"))
125
+ digest.update(str(stat.st_mtime_ns).encode("utf-8"))
126
+
127
+ return digest.hexdigest()
128
+
129
+
130
+ def _collect_persona_source_paths(individual_dir: Path, traits_dir: Optional[Path]) -> List[Path]:
131
+ paths = list(individual_dir.glob("*.json")) if individual_dir.exists() else []
132
+ if traits_dir and traits_dir.exists():
133
+ paths.extend(traits_dir.glob("*.json"))
134
+ return sorted(paths, key=lambda path: str(path))
135
+
136
+
137
+ def _collect_factdata_source_paths(markdown_dir: Path, *, pattern: str) -> List[Path]:
138
+ if not markdown_dir.exists():
139
+ return []
140
+ return sorted((path for path in markdown_dir.rglob(pattern) if path.is_file()), key=lambda path: str(path))
141
+
142
+
143
+ def _factdata_fingerprint(markdown_dir: Path, *, pattern: str) -> str | None:
144
+ fact_paths = _collect_factdata_source_paths(markdown_dir, pattern=pattern)
145
+ if not fact_paths:
146
+ return None
147
+ return _fingerprint_paths(fact_paths, label=f"fact-data:{pattern}")
148
+
149
+
150
+ def _log_runtime_rag_config() -> None:
151
+ embedding_config = get_configured_embedding_config()
152
+ vectorstore_config = get_vectorstore_config()
153
+ logger.info(
154
+ "QA runtime config: embedding_backend={} embedding_model={} device={} batch_size={} api_base_url={}",
155
+ embedding_config.backend,
156
+ embedding_config.model_name,
157
+ embedding_config.device or "n/a",
158
+ embedding_config.batch_size or "default",
159
+ embedding_config.api_base_url or "n/a",
160
+ )
161
+ logger.info(
162
+ "QA runtime config: vectorstore_backend={} persist_dir={} reset_on_startup={}",
163
+ vectorstore_config.backend,
164
+ vectorstore_config.persist_dir,
165
+ vectorstore_config.reset_on_startup,
166
+ )
167
+
168
+
169
+ def build_fact_data_index(
170
+ *,
171
+ processed_dir: Path = PROCESSED_DATA_DIR,
172
+ embeddings=None,
173
+ vectorstore_provider: Optional[VectorStoreProvider] = None,
174
+ ) -> Optional[FactDataRAGIndex]:
175
+ """Build the FactData RAG index at startup (optional)."""
176
+
177
+ if not _env_flag("ADSP_FACTDATA_RAG_ENABLED", True):
178
+ logger.info("QA bootstrap step 5/6: fact-data RAG disabled by env")
179
+ return None
180
+
181
+ try:
182
+ from adsp.data_pipeline.fact_data_pipeline.extract_raw.config import (
183
+ FactDataExtractionConfig,
184
+ )
185
+ except Exception as exc: # pragma: no cover - optional dependency guard
186
+ logger.debug(f"Fact data pipeline unavailable: {exc}")
187
+ return None
188
+
189
+ start_total = time.perf_counter()
190
+ cfg = FactDataExtractionConfig()
191
+ cfg.fact_data_output_dir = processed_dir / "fact_data"
192
+
193
+ markdown_dir = Path(
194
+ os.environ.get(
195
+ "ADSP_FACTDATA_MARKDOWN_DIR",
196
+ str(cfg.fact_data_output_dir),
197
+ )
198
+ )
199
+ markdown_pattern = os.environ.get("ADSP_FACTDATA_MARKDOWN_PATTERN", "*.md")
200
+ logger.info(
201
+ "QA bootstrap step 5/6: preparing fact-data RAG from {} (pattern={})",
202
+ markdown_dir,
203
+ markdown_pattern,
204
+ )
205
+
206
+ resolved_embeddings = embeddings or build_configured_embeddings()
207
+ fact_fingerprint = _factdata_fingerprint(markdown_dir, pattern=markdown_pattern)
208
+
209
+ index = build_fact_data_index_from_markdown(
210
+ markdown_dir,
211
+ embeddings=resolved_embeddings,
212
+ vectorstore_provider=vectorstore_provider,
213
+ fingerprint=fact_fingerprint,
214
+ pattern=markdown_pattern,
215
+ )
216
+ if index is not None:
217
+ if index.loaded_from_persisted:
218
+ logger.info(
219
+ "QA bootstrap step 5/6: loaded persisted fact-data vector store in {:.2f}s",
220
+ time.perf_counter() - start_total,
221
+ )
222
+ else:
223
+ logger.info(
224
+ "QA bootstrap step 5/6: fact-data RAG ready ({} chunks) in {:.2f}s",
225
+ len(index.indexed_chunk_ids),
226
+ time.perf_counter() - start_total,
227
+ )
228
+ return index
229
+
230
+ if markdown_dir.exists() and any(markdown_dir.rglob(markdown_pattern)):
231
+ index = build_fact_data_index_from_markdown(
232
+ markdown_dir,
233
+ embeddings=resolved_embeddings,
234
+ vectorstore_provider=vectorstore_provider,
235
+ fingerprint=fact_fingerprint,
236
+ pattern=markdown_pattern,
237
+ )
238
+ if index is not None:
239
+ if index.loaded_from_persisted:
240
+ logger.info(
241
+ "QA bootstrap step 5/6: loaded persisted fact-data vector store in {:.2f}s",
242
+ time.perf_counter() - start_total,
243
+ )
244
+ else:
245
+ logger.info(
246
+ "QA bootstrap step 5/6: fact-data RAG ready ({} chunks) in {:.2f}s",
247
+ len(index.indexed_chunk_ids),
248
+ time.perf_counter() - start_total,
249
+ )
250
+ return index
251
+
252
+ if not _env_flag("ADSP_FACTDATA_RUN_EXTRACTION", False):
253
+ logger.info("QA bootstrap step 5/6: no fact-data markdown found; extraction disabled")
254
+ return None
255
+
256
+ if not cfg.vllm_model:
257
+ logger.warning("Fact data extraction requested but no model configured; set `VLLM_MODEL`.")
258
+ return None
259
+
260
+ try:
261
+ from adsp.data_pipeline.fact_data_pipeline.extract_raw import (
262
+ run_fact_data_extraction_pipeline,
263
+ )
264
+
265
+ logger.info("QA bootstrap step 5/6: running fact-data extraction during startup")
266
+ run_fact_data_extraction_pipeline(cfg)
267
+ logger.info("Fact data extraction completed - markdown files generated")
268
+ fact_fingerprint = _factdata_fingerprint(markdown_dir, pattern=markdown_pattern)
269
+ except Exception as exc: # pragma: no cover - external pipeline
270
+ logger.warning(f"Fact data extraction pipeline failed: {exc}")
271
+ return None
272
+
273
+ index = build_fact_data_index_from_markdown(
274
+ markdown_dir,
275
+ embeddings=resolved_embeddings,
276
+ vectorstore_provider=vectorstore_provider,
277
+ fingerprint=fact_fingerprint,
278
+ pattern=markdown_pattern,
279
+ )
280
+ if index is not None:
281
+ if index.loaded_from_persisted:
282
+ logger.info(
283
+ "QA bootstrap step 5/6: loaded persisted fact-data vector store in {:.2f}s",
284
+ time.perf_counter() - start_total,
285
+ )
286
+ else:
287
+ logger.info(
288
+ "QA bootstrap step 5/6: fact-data RAG ready ({} chunks) in {:.2f}s",
289
+ len(index.indexed_chunk_ids),
290
+ time.perf_counter() - start_total,
291
+ )
292
+ return index
293
+
294
+
295
+ def build_default_orchestrator(
296
+ *,
297
+ processed_dir: Path = PROCESSED_DATA_DIR,
298
+ ) -> Orchestrator:
299
+ """Create an orchestrator wired for local execution.
300
+
301
+ - Loads persona profiles from `data/processed/personas/individual`
302
+ - Loads reasoning traits from `data/processed/personas/common_traits` when present
303
+ - Builds an in-memory RAG index over persona indicators
304
+ """
305
+
306
+ start_total = time.perf_counter()
307
+
308
+ logger.info("QA bootstrap step 1/6: resolving persona directories")
309
+ individual_dir, traits_dir = resolve_persona_paths(processed_dir)
310
+ logger.info(
311
+ "QA bootstrap step 1/6: individual_dir={} traits_dir={}",
312
+ individual_dir,
313
+ traits_dir,
314
+ )
315
+
316
+ start_step = time.perf_counter()
317
+ logger.info("QA bootstrap step 2/6: loading persona profiles from disk")
318
+ personas = load_personas_from_disk(individual_dir, traits_dir=traits_dir)
319
+ logger.info(
320
+ "QA bootstrap step 2/6: loaded {} personas in {:.2f}s",
321
+ len(personas),
322
+ time.perf_counter() - start_step,
323
+ )
324
+
325
+ start_step = time.perf_counter()
326
+ logger.info("QA bootstrap step 3/6: building persona registry")
327
+ registry = build_registry(personas)
328
+ logger.info(
329
+ "QA bootstrap step 3/6: registry ready with {} personas in {:.2f}s",
330
+ len(registry.list_personas()),
331
+ time.perf_counter() - start_step,
332
+ )
333
+
334
+ logger.info("QA bootstrap step 4/6: building prompt builder and persona RAG")
335
+ prompt_builder = PromptBuilder(registry=registry)
336
+ _log_runtime_rag_config()
337
+ embeddings = build_configured_embeddings()
338
+ logger.info("QA bootstrap step 4/6: embedding model initialized once and shared")
339
+ vectorstore_provider = VectorStoreProvider(embeddings=embeddings)
340
+ logger.info("QA bootstrap step 4/6: vector store provider initialized once and shared")
341
+ start_step = time.perf_counter()
342
+ persona_index = PersonaRAGIndex(
343
+ embeddings=embeddings,
344
+ vectorstore_provider=vectorstore_provider,
345
+ )
346
+ persona_sources = _collect_persona_source_paths(individual_dir, traits_dir)
347
+ persona_fingerprint = _fingerprint_paths(persona_sources, label="persona")
348
+ loaded_persona_stores = 0
349
+ rebuilt_persona_stores = 0
350
+ total_personas = len(personas)
351
+ with progress_bar(
352
+ total=total_personas,
353
+ desc="Indexing personas",
354
+ unit="persona",
355
+ leave=False,
356
+ ) as progress:
357
+ for persona in personas:
358
+ if not persona.persona_id:
359
+ progress.update(1)
360
+ progress.set_postfix(status="skipped", persona_id="missing")
361
+ continue
362
+ namespace = f"persona-{persona.persona_id}"
363
+ store = vectorstore_provider.load(namespace, fingerprint=persona_fingerprint)
364
+ if store is not None:
365
+ persona_index.attach_persona_vectorstore(
366
+ persona.persona_id,
367
+ vectorstore=store,
368
+ namespace=namespace,
369
+ )
370
+ loaded_persona_stores += 1
371
+ progress.update(1)
372
+ progress.set_postfix(status="loaded", persona_id=persona.persona_id)
373
+ continue
374
+
375
+ store = vectorstore_provider.create(namespace, reset=True)
376
+ rag = PersonaIndicatorRAG(
377
+ embeddings,
378
+ vectorstore=store,
379
+ namespace=namespace,
380
+ )
381
+ rag.index_persona(persona)
382
+ vectorstore_provider.persist(
383
+ namespace,
384
+ fingerprint=persona_fingerprint,
385
+ vectorstore=store,
386
+ )
387
+ persona_index.attach_persona_vectorstore(
388
+ persona.persona_id,
389
+ vectorstore=store,
390
+ namespace=namespace,
391
+ )
392
+ rebuilt_persona_stores += 1
393
+ progress.update(1)
394
+ progress.set_postfix(status="rebuilt", persona_id=persona.persona_id)
395
+ retriever = RAGPipeline(persona_index=persona_index)
396
+ logger.info(
397
+ "QA bootstrap step 4/6: persona RAG ready for {} personas in {:.2f}s (loaded={}, rebuilt={})",
398
+ len(personas),
399
+ time.perf_counter() - start_step,
400
+ loaded_persona_stores,
401
+ rebuilt_persona_stores,
402
+ )
403
+
404
+ fact_data_index = build_fact_data_index(
405
+ processed_dir=processed_dir,
406
+ embeddings=embeddings,
407
+ vectorstore_provider=vectorstore_provider,
408
+ )
409
+
410
+ logger.info("QA bootstrap step 6/6: assembling orchestrator")
411
+ orchestrator = Orchestrator(
412
+ prompt_builder=prompt_builder,
413
+ retriever=retriever,
414
+ fact_data_index=fact_data_index,
415
+ )
416
+ logger.info(
417
+ "QA bootstrap complete in {:.2f}s",
418
+ time.perf_counter() - start_total,
419
+ )
420
+ return orchestrator
421
+
422
+
423
+ __all__ = [
424
+ "resolve_persona_paths",
425
+ "load_personas_from_disk",
426
+ "build_registry",
427
+ "build_fact_data_index",
428
+ "build_default_orchestrator",
429
+ ]
adsp/core/survey/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Survey simulation module."""
2
+
3
+ from .group_generator import GroupGenerator
4
+ from .models import (
5
+ Answer,
6
+ PersonaConfig,
7
+ Question,
8
+ RespondentGroup,
9
+ RespondentProfile,
10
+ SimulationResult,
11
+ Survey,
12
+ SurveyResponse,
13
+ )
14
+ from .response_synthesizer import ResponseSynthesizer
15
+ from .survey_manager import SurveyManager
16
+
17
+ __all__ = [
18
+ "Answer",
19
+ "GroupGenerator",
20
+ "PersonaConfig",
21
+ "Question",
22
+ "RespondentGroup",
23
+ "RespondentProfile",
24
+ "ResponseSynthesizer",
25
+ "SimulationResult",
26
+ "Survey",
27
+ "SurveyManager",
28
+ "SurveyResponse",
29
+ ]
adsp/core/survey/group_generator.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Respondent group generation for survey simulation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import os
7
+ from pathlib import Path
8
+ import random
9
+ import shutil
10
+ from typing import Any, Dict, Iterable, List, Mapping, Sequence
11
+
12
+ from loguru import logger
13
+
14
+ from adsp.config import PROCESSED_DATA_DIR
15
+
16
+ from .models import PersonaConfig, RespondentGroup, RespondentProfile
17
+ from .utils import (
18
+ ensure_dir,
19
+ load_json,
20
+ make_identifier,
21
+ model_dump,
22
+ save_json,
23
+ utc_now,
24
+ )
25
+ from .validators import validate_group, validate_group_composition, validate_respondent_profile
26
+
27
+ try:
28
+ from faker import Faker
29
+ except Exception: # pragma: no cover
30
+ Faker = None # type: ignore[assignment]
31
+
32
+ _FORMALITY_LEVELS = ["formal", "medium", "casual"]
33
+ _DIRECTNESS_LEVELS = ["direct", "balanced", "indirect"]
34
+ _EMOTIONAL_LEVELS = ["enthusiastic", "neutral", "reserved"]
35
+ _CRITICALITY_LEVELS = ["high", "medium", "low"]
36
+ _VERBOSITY_LEVELS = ["detailed", "balanced", "concise"]
37
+ _LOW_MED_HIGH = ["low", "medium", "high"]
38
+
39
+ _COUNTRY_PROFILES: Dict[str, Dict[str, Any]] = {
40
+ "italy": {
41
+ "display_name": "Italy",
42
+ "description": "Italian respondents and naming locale.",
43
+ "faker_locale": "it_IT",
44
+ "ethnicities": ["Italian", "Mediterranean", "North African", "Eastern European", "Mixed"],
45
+ },
46
+ "france": {
47
+ "display_name": "France",
48
+ "description": "French respondents and naming locale.",
49
+ "faker_locale": "fr_FR",
50
+ "ethnicities": ["French", "North African", "Sub-Saharan African", "European", "Mixed"],
51
+ },
52
+ "united_states": {
53
+ "display_name": "United States",
54
+ "description": "US respondents and naming locale.",
55
+ "faker_locale": "en_US",
56
+ "ethnicities": ["White American", "Black American", "Hispanic/Latino", "Asian American", "Mixed"],
57
+ },
58
+ "united_kingdom": {
59
+ "display_name": "United Kingdom",
60
+ "description": "UK respondents and naming locale.",
61
+ "faker_locale": "en_GB",
62
+ "ethnicities": ["White British", "Black British", "British Asian", "Middle Eastern British", "Mixed"],
63
+ },
64
+ "spain": {
65
+ "display_name": "Spain",
66
+ "description": "Spanish respondents and naming locale.",
67
+ "faker_locale": "es_ES",
68
+ "ethnicities": ["Spanish", "Latin American", "North African", "Roma", "Mixed"],
69
+ },
70
+ "germany": {
71
+ "display_name": "Germany",
72
+ "description": "German respondents and naming locale.",
73
+ "faker_locale": "de_DE",
74
+ "ethnicities": ["German", "Turkish German", "Eastern European", "Middle Eastern", "Mixed"],
75
+ },
76
+ "vietnam": {
77
+ "display_name": "Vietnam",
78
+ "description": "Vietnamese respondents and naming locale.",
79
+ "faker_locale": "vi_VN",
80
+ "ethnicities": ["Kinh", "Tay", "Thai", "Hoa", "Mixed"],
81
+ },
82
+ }
83
+
84
+
85
+ class GroupGenerator:
86
+ """Creates respondent groups from persona trait files."""
87
+
88
+ def __init__(
89
+ self,
90
+ base_dir: Path | None = None,
91
+ traits_dirs: Sequence[Path] | None = None,
92
+ ) -> None:
93
+ self.base_dir = Path(base_dir or (PROCESSED_DATA_DIR / "surveys"))
94
+ self.groups_dir = ensure_dir(self.base_dir / "groups")
95
+ self._traits_dirs = self._resolve_traits_dirs(traits_dirs)
96
+
97
+ def create_group(
98
+ self,
99
+ composition: Iterable[Mapping[str, Any]],
100
+ mode: str = "random",
101
+ **options: Any,
102
+ ) -> RespondentGroup:
103
+ mode_normalized = (mode or "random").strip().lower()
104
+ if mode_normalized not in {"random", "llm"}:
105
+ raise ValueError("mode must be one of: random, llm")
106
+
107
+ configs: List[PersonaConfig] = validate_group_composition(composition)
108
+ sampling_ratio = float(options.get("sampling_ratio", 0.7))
109
+ include_names = bool(options.get("include_names", True))
110
+ countries = self._normalize_country_list(options.get("countries"))
111
+ requested_seed = options.get("seed")
112
+ base_seed = int(requested_seed) if requested_seed is not None else random.randint(1, 2_147_483_647)
113
+ rng = random.Random(base_seed)
114
+
115
+ group_id = str(options.get("group_id") or make_identifier("group", rng=rng))
116
+ respondents: List[RespondentProfile] = []
117
+
118
+ for config in configs:
119
+ traits = self._load_traits(config.persona_id)
120
+ for _ in range(config.count):
121
+ respondent_seed = rng.randint(1, 2_147_483_647)
122
+ respondent_id = f"{group_id}-resp-{len(respondents) + 1:05d}"
123
+ generation_method = "llm" if mode_normalized == "llm" else "random"
124
+ profile = self.generate_profile_random(
125
+ persona_id=config.persona_id,
126
+ seed=respondent_seed,
127
+ respondent_id=respondent_id,
128
+ traits=traits,
129
+ sampling_ratio=sampling_ratio,
130
+ include_names=include_names,
131
+ countries=countries,
132
+ generation_method=generation_method,
133
+ )
134
+ respondents.append(profile)
135
+
136
+ group = RespondentGroup(
137
+ group_id=group_id,
138
+ created_at=utc_now(),
139
+ composition=configs,
140
+ respondents=respondents,
141
+ generation_method=mode_normalized,
142
+ )
143
+ self._write_group(group)
144
+ return group
145
+
146
+ def generate_profile_random(
147
+ self,
148
+ persona_id: str,
149
+ seed: int,
150
+ *,
151
+ respondent_id: str | None = None,
152
+ traits: Mapping[str, Any] | None = None,
153
+ sampling_ratio: float = 0.7,
154
+ include_names: bool = True,
155
+ countries: Sequence[str] | None = None,
156
+ generation_method: str = "random",
157
+ ) -> RespondentProfile:
158
+ rng = random.Random(int(seed))
159
+ source = dict(traits) if traits is not None else self._load_traits(persona_id)
160
+
161
+ key_indicators = self._sample_key_indicators(source.get("key_indicators") or [], sampling_ratio, rng)
162
+ style_profile = self._sample_style_profile(source.get("style_profile") or {}, rng)
163
+ value_frame = self._sample_value_frame(source.get("value_frame") or {}, rng)
164
+ reasoning_policies = self._sample_reasoning_policies(source.get("reasoning_policies") or {}, rng)
165
+ content_filters = copy.deepcopy(source.get("content_filters") or {})
166
+
167
+ profile_id = respondent_id or make_identifier("resp", rng=rng)
168
+ available_countries = list(countries) if countries else list(_COUNTRY_PROFILES.keys())
169
+ country = rng.choice(available_countries)
170
+ gender = self._sample_gender(rng)
171
+ ethnicity = self._sample_ethnicity(country, rng)
172
+ if include_names:
173
+ name = self.generate_name(country=country, gender=gender, rng=rng)
174
+ else:
175
+ name = profile_id
176
+
177
+ payload = {
178
+ "respondent_id": profile_id,
179
+ "persona_id": persona_id,
180
+ "name": name,
181
+ "country": country,
182
+ "gender": gender,
183
+ "ethnicity": ethnicity,
184
+ "key_indicators": key_indicators,
185
+ "style_profile": style_profile,
186
+ "value_frame": value_frame,
187
+ "reasoning_policies": reasoning_policies,
188
+ "content_filters": content_filters,
189
+ "generation_method": generation_method,
190
+ "seed": int(seed),
191
+ "created_at": utc_now(),
192
+ }
193
+ return validate_respondent_profile(payload)
194
+
195
+ def generate_name(
196
+ self,
197
+ *,
198
+ country: str,
199
+ gender: str,
200
+ rng: random.Random | None = None,
201
+ ) -> str:
202
+ local_rng = rng or random.Random()
203
+ profile = _COUNTRY_PROFILES.get(country, _COUNTRY_PROFILES["united_states"])
204
+ faker_locale = str(profile.get("faker_locale", "en_US"))
205
+
206
+ if Faker is None:
207
+ return make_identifier("name", rng=local_rng)
208
+
209
+ try:
210
+ fake = Faker(faker_locale)
211
+ fake.seed_instance(local_rng.randint(1, 2_147_483_647))
212
+ if gender == "female" and hasattr(fake, "first_name_female"):
213
+ first = str(fake.first_name_female())
214
+ elif gender == "male" and hasattr(fake, "first_name_male"):
215
+ first = str(fake.first_name_male())
216
+ else:
217
+ first = str(fake.first_name())
218
+ return f"{first} {fake.last_name()}"
219
+ except Exception:
220
+ logger.debug("Faker name generation failed for country={} locale={}", country, faker_locale)
221
+ return make_identifier("name", rng=local_rng)
222
+
223
+ @staticmethod
224
+ def list_available_countries() -> List[Dict[str, str]]:
225
+ items: List[Dict[str, str]] = []
226
+ for country_id in sorted(_COUNTRY_PROFILES.keys()):
227
+ profile = _COUNTRY_PROFILES[country_id]
228
+ items.append(
229
+ {
230
+ "country_id": country_id,
231
+ "display_name": str(profile.get("display_name", country_id)),
232
+ "description": str(profile.get("description", "")),
233
+ }
234
+ )
235
+ return items
236
+
237
+ def get_group(self, group_id: str) -> RespondentGroup:
238
+ info_path = self._group_info_path(group_id)
239
+ if info_path.exists():
240
+ info_payload = load_json(info_path)
241
+ profiles_payload: List[Dict[str, Any]] = []
242
+ for profile_path in sorted(self._profiles_dir(group_id).glob("*.json")):
243
+ profile_payload = load_json(profile_path)
244
+ if isinstance(profile_payload, dict):
245
+ profiles_payload.append(profile_payload)
246
+
247
+ if isinstance(info_payload, dict):
248
+ payload = dict(info_payload)
249
+ payload["respondents"] = profiles_payload
250
+ return validate_group(payload)
251
+
252
+ legacy_path = self._legacy_group_path(group_id)
253
+ if legacy_path.exists():
254
+ return validate_group(load_json(legacy_path))
255
+
256
+ raise KeyError(f"Group '{group_id}' not found")
257
+
258
+ def list_groups(self) -> List[RespondentGroup]:
259
+ groups: List[RespondentGroup] = []
260
+ seen: set[str] = set()
261
+
262
+ for path in sorted(self.groups_dir.iterdir()):
263
+ if not path.is_dir():
264
+ continue
265
+ group_id = path.name
266
+ try:
267
+ groups.append(self.get_group(group_id))
268
+ seen.add(group_id)
269
+ except Exception as exc:
270
+ logger.warning("Skipping invalid group directory {}: {}", path, exc)
271
+
272
+ for path in sorted(self.groups_dir.glob("*.json")):
273
+ group_id = path.stem
274
+ if group_id in seen:
275
+ continue
276
+ try:
277
+ groups.append(validate_group(load_json(path)))
278
+ except Exception as exc:
279
+ logger.warning("Skipping invalid group file {}: {}", path, exc)
280
+ return groups
281
+
282
+ def _write_group(self, group: RespondentGroup) -> None:
283
+ group_dir = self._group_dir(group.group_id)
284
+ if group_dir.exists():
285
+ shutil.rmtree(group_dir)
286
+ profiles_dir = ensure_dir(group_dir / "profiles")
287
+
288
+ payload = model_dump(group)
289
+ respondents = payload.pop("respondents", [])
290
+ save_json(group_dir / "group_info.json", payload)
291
+
292
+ for profile in respondents:
293
+ respondent_id = str(profile.get("respondent_id", "")).strip()
294
+ if not respondent_id:
295
+ continue
296
+ save_json(profiles_dir / f"{respondent_id}.json", profile)
297
+
298
+ def _group_dir(self, group_id: str) -> Path:
299
+ return self.groups_dir / group_id
300
+
301
+ def _group_info_path(self, group_id: str) -> Path:
302
+ return self._group_dir(group_id) / "group_info.json"
303
+
304
+ def _profiles_dir(self, group_id: str) -> Path:
305
+ return self._group_dir(group_id) / "profiles"
306
+
307
+ def _legacy_group_path(self, group_id: str) -> Path:
308
+ return self.groups_dir / f"{group_id}.json"
309
+
310
+ def _load_traits(self, persona_id: str) -> Dict[str, Any]:
311
+ for directory in self._traits_dirs:
312
+ path = directory / f"{persona_id}.json"
313
+ if not path.exists():
314
+ continue
315
+ payload = load_json(path)
316
+ if isinstance(payload, dict):
317
+ return payload
318
+
319
+ searched = ", ".join(str(path) for path in self._traits_dirs)
320
+ raise FileNotFoundError(f"Traits file not found for persona '{persona_id}'. Searched: {searched}")
321
+
322
+ @staticmethod
323
+ def _resolve_traits_dirs(traits_dirs: Sequence[Path] | None) -> List[Path]:
324
+ if traits_dirs:
325
+ return [Path(path) for path in traits_dirs]
326
+
327
+ resolved: List[Path] = []
328
+
329
+ env_survey = os.environ.get("ADSP_SURVEY_TRAITS_DIR", "")
330
+ env_persona = os.environ.get("ADSP_PERSONA_TRAITS_DIR", "")
331
+
332
+ for raw in (env_survey, env_persona):
333
+ if not raw:
334
+ continue
335
+ for segment in raw.split(os.pathsep):
336
+ segment = segment.strip()
337
+ if segment:
338
+ resolved.append(Path(segment))
339
+
340
+ resolved.extend(
341
+ [
342
+ PROCESSED_DATA_DIR / "personas_" / "common_traits",
343
+ PROCESSED_DATA_DIR / "personas" / "common_traits",
344
+ ]
345
+ )
346
+
347
+ deduped: List[Path] = []
348
+ seen: set[str] = set()
349
+ for path in resolved:
350
+ marker = str(path)
351
+ if marker in seen:
352
+ continue
353
+ seen.add(marker)
354
+ deduped.append(path)
355
+ return deduped
356
+
357
+ def _sample_key_indicators(
358
+ self,
359
+ indicators: Sequence[Mapping[str, Any]],
360
+ sampling_ratio: float,
361
+ rng: random.Random,
362
+ ) -> List[Dict[str, Any]]:
363
+ items = [copy.deepcopy(item) for item in indicators if isinstance(item, Mapping)]
364
+ if not items:
365
+ return []
366
+
367
+ ratio = max(0.05, min(1.0, float(sampling_ratio)))
368
+ sample_size = max(1, min(len(items), int(round(len(items) * ratio))))
369
+ selected = rng.sample(items, k=sample_size)
370
+
371
+ for indicator in selected:
372
+ metrics = indicator.get("metrics")
373
+ if not isinstance(metrics, list):
374
+ continue
375
+ for metric in metrics:
376
+ if not isinstance(metric, dict):
377
+ continue
378
+ value = metric.get("value")
379
+ if isinstance(value, (int, float)):
380
+ jitter = 1.0 + rng.uniform(-0.05, 0.05)
381
+ candidate = float(value) * jitter
382
+ metric["value"] = round(candidate, 2)
383
+
384
+ return selected
385
+
386
+ def _sample_style_profile(self, style_profile: Mapping[str, Any], rng: random.Random) -> Dict[str, Any]:
387
+ style = copy.deepcopy(dict(style_profile))
388
+
389
+ tones = [tone for tone in style.get("tone_adjectives", []) if isinstance(tone, str)]
390
+ if tones:
391
+ target = min(len(tones), rng.randint(3, min(5, len(tones))))
392
+ style["tone_adjectives"] = rng.sample(tones, k=target)
393
+
394
+ style["formality_level"] = self._maybe_shift(style.get("formality_level"), _FORMALITY_LEVELS, rng)
395
+ style["directness"] = self._maybe_shift(style.get("directness"), _DIRECTNESS_LEVELS, rng)
396
+ style["emotional_flavour"] = self._maybe_shift(style.get("emotional_flavour"), _EMOTIONAL_LEVELS, rng)
397
+ style["criticality_level"] = self._maybe_shift(style.get("criticality_level"), _CRITICALITY_LEVELS, rng)
398
+ style["verbosity_preference"] = self._maybe_shift(style.get("verbosity_preference"), _VERBOSITY_LEVELS, rng)
399
+
400
+ return style
401
+
402
+ def _sample_value_frame(self, value_frame: Mapping[str, Any], rng: random.Random) -> Dict[str, Any]:
403
+ frame = copy.deepcopy(dict(value_frame))
404
+ priorities = [item for item in frame.get("priority_rank", []) if isinstance(item, str)]
405
+ if priorities:
406
+ if len(priorities) <= 3:
407
+ frame["priority_rank"] = priorities
408
+ else:
409
+ keep = rng.randint(3, min(5, len(priorities)))
410
+ primary = priorities[0]
411
+ tail = priorities[1:]
412
+ rng.shuffle(tail)
413
+
414
+ if rng.random() < 0.8:
415
+ chosen = [primary, *tail[: max(0, keep - 1)]]
416
+ else:
417
+ shuffled = priorities[:]
418
+ rng.shuffle(shuffled)
419
+ chosen = shuffled[:keep]
420
+ frame["priority_rank"] = chosen
421
+
422
+ for field in (
423
+ "sustainability_orientation",
424
+ "price_sensitivity",
425
+ "novelty_seeking",
426
+ "brand_loyalty",
427
+ "health_concern",
428
+ ):
429
+ frame[field] = self._maybe_shift(frame.get(field), _LOW_MED_HIGH, rng)
430
+ return frame
431
+
432
+ def _sample_reasoning_policies(
433
+ self,
434
+ reasoning_policies: Mapping[str, Any],
435
+ rng: random.Random,
436
+ ) -> Dict[str, Any]:
437
+ policies = copy.deepcopy(dict(reasoning_policies))
438
+ return self._prune_nested_lists(policies, rng)
439
+
440
+ def _prune_nested_lists(self, payload: Any, rng: random.Random) -> Any:
441
+ if isinstance(payload, list):
442
+ if len(payload) <= 1:
443
+ return payload
444
+ drop_ratio = rng.uniform(0.1, 0.2)
445
+ drop_count = int(round(len(payload) * drop_ratio))
446
+ keep_count = max(1, len(payload) - drop_count)
447
+ if keep_count >= len(payload):
448
+ return payload
449
+ return rng.sample(payload, keep_count)
450
+
451
+ if isinstance(payload, dict):
452
+ return {key: self._prune_nested_lists(value, rng) for key, value in payload.items()}
453
+
454
+ return payload
455
+
456
+ @staticmethod
457
+ def _maybe_shift(value: Any, levels: List[str], rng: random.Random) -> Any:
458
+ if not isinstance(value, str):
459
+ return value
460
+ normalized = value.strip().lower()
461
+ if normalized not in levels:
462
+ return value
463
+ if rng.random() >= 0.2:
464
+ return normalized
465
+
466
+ current = levels.index(normalized)
467
+ direction = rng.choice([-1, 1])
468
+ candidate = max(0, min(len(levels) - 1, current + direction))
469
+ return levels[candidate]
470
+
471
+ @staticmethod
472
+ def _sample_gender(rng: random.Random) -> str:
473
+ return rng.choices(["female", "male"], k=1)[0]
474
+
475
+ @staticmethod
476
+ def _sample_ethnicity(country: str, rng: random.Random) -> str:
477
+ profile = _COUNTRY_PROFILES.get(country, _COUNTRY_PROFILES["united_states"])
478
+ choices = [str(item) for item in profile.get("ethnicities", []) if str(item).strip()]
479
+ if not choices:
480
+ return "Mixed"
481
+ return rng.choice(choices)
482
+
483
+ def _normalize_country_list(self, value: Any) -> List[str] | None:
484
+ if value is None:
485
+ return None
486
+ if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):
487
+ raise ValueError("countries must be a list of country ids or names")
488
+
489
+ resolved: List[str] = []
490
+ unknown: List[str] = []
491
+ seen: set[str] = set()
492
+ for item in value:
493
+ candidate = str(item or "").strip().lower().replace("-", "_").replace(" ", "_")
494
+ if candidate not in _COUNTRY_PROFILES:
495
+ unknown.append(str(item))
496
+ continue
497
+ if candidate in seen:
498
+ continue
499
+ seen.add(candidate)
500
+ resolved.append(candidate)
501
+
502
+ if unknown:
503
+ supported = ", ".join(sorted(_COUNTRY_PROFILES.keys()))
504
+ raise ValueError(f"Unknown countries: {', '.join(unknown)}. Supported values: {supported}")
505
+ if not resolved:
506
+ raise ValueError("countries must contain at least one supported country")
507
+ return resolved