Israelbliz commited on
Commit
e33977d
Β·
verified Β·
1 Parent(s): 217cdb9

Upload 12 files

Browse files
core/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """User Modeling Agent β€” shared intelligence core.
2
+
3
+ Modules:
4
+ config : env-loaded settings
5
+ llm : provider-agnostic LLM client (OpenAI / Gemini)
6
+ persona : behavioral persona extraction from review history
7
+ nigerian : optional style-transfer layer for Nigerian English register
8
+ reflection : self-critique and refinement loop
9
+ """
10
+ from core.config import settings
11
+ from core.llm import LLMClient
12
+ from core.persona import PersonaEngine, UserPersona
13
+
14
+ __all__ = [
15
+ "settings",
16
+ "LLMClient",
17
+ "PersonaEngine",
18
+ "UserPersona",
19
+ ]
core/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (731 Bytes). View file
 
core/__pycache__/config.cpython-313.pyc ADDED
Binary file (3.94 kB). View file
 
core/__pycache__/llm.cpython-313.pyc ADDED
Binary file (7.94 kB). View file
 
core/__pycache__/nigerian.cpython-313.pyc ADDED
Binary file (6.05 kB). View file
 
core/__pycache__/persona.cpython-313.pyc ADDED
Binary file (16.1 kB). View file
 
core/__pycache__/reflection.cpython-313.pyc ADDED
Binary file (14.7 kB). View file
 
core/config.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Central configuration loaded from environment variables.
2
+
3
+ All other modules import `settings` from here. Never call os.environ directly
4
+ in agent code β€” keeps the surface small and testable.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from dotenv import load_dotenv
13
+
14
+ load_dotenv()
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Settings:
19
+ # LLM provider switch
20
+ llm_provider: str # 'openai' or 'gemini'
21
+
22
+ # OpenAI
23
+ openai_api_key: str
24
+ openai_reasoning_model: str
25
+ openai_bulk_model: str
26
+
27
+ # Gemini
28
+ gemini_api_key: str
29
+ gemini_reasoning_model: str
30
+ gemini_bulk_model: str
31
+
32
+ # Convenience aliases (backward compat with older code that uses these)
33
+ reasoning_model: str
34
+ bulk_model: str
35
+
36
+ # Embeddings
37
+ sbert_model: str
38
+
39
+ # Paths
40
+ data_dir: Path
41
+ processed_dir: Path
42
+ chroma_persist_dir: Path
43
+
44
+ # Service ports
45
+ task_a_api_port: int
46
+ task_a_ui_port: int
47
+ task_b_api_port: int
48
+ task_b_ui_port: int
49
+
50
+
51
+ def _build() -> Settings:
52
+ data_dir = Path(os.environ.get("DATA_DIR", "./data")).resolve()
53
+ provider = os.environ.get("LLM_PROVIDER", "openai").lower()
54
+
55
+ openai_reasoning = os.environ.get("OPENAI_REASONING_MODEL", "gpt-4o")
56
+ openai_bulk = os.environ.get("OPENAI_BULK_MODEL", "gpt-4o-mini")
57
+ gemini_reasoning = os.environ.get("GEMINI_REASONING_MODEL", "gemini-2.5-flash")
58
+ gemini_bulk = os.environ.get("GEMINI_BULK_MODEL", "gemini-2.5-flash-lite")
59
+
60
+ # Convenience aliases point to the active provider's models
61
+ if provider == "gemini":
62
+ active_reasoning, active_bulk = gemini_reasoning, gemini_bulk
63
+ else:
64
+ active_reasoning, active_bulk = openai_reasoning, openai_bulk
65
+
66
+ return Settings(
67
+ llm_provider=provider,
68
+ openai_api_key=os.environ.get("OPENAI_API_KEY", ""),
69
+ openai_reasoning_model=openai_reasoning,
70
+ openai_bulk_model=openai_bulk,
71
+ gemini_api_key=os.environ.get("GEMINI_API_KEY", ""),
72
+ gemini_reasoning_model=gemini_reasoning,
73
+ gemini_bulk_model=gemini_bulk,
74
+ reasoning_model=active_reasoning,
75
+ bulk_model=active_bulk,
76
+ sbert_model=os.environ.get("SBERT_MODEL", "sentence-transformers/all-MiniLM-L6-v2"),
77
+ data_dir=data_dir,
78
+ processed_dir=data_dir / "processed",
79
+ chroma_persist_dir=Path(os.environ.get("CHROMA_PERSIST_DIR", data_dir / "chroma")),
80
+ task_a_api_port=int(os.environ.get("TASK_A_API_PORT", 8001)),
81
+ task_a_ui_port=int(os.environ.get("TASK_A_UI_PORT", 8501)),
82
+ task_b_api_port=int(os.environ.get("TASK_B_API_PORT", 8002)),
83
+ task_b_ui_port=int(os.environ.get("TASK_B_UI_PORT", 8502)),
84
+ )
85
+
86
+
87
+ settings = _build()
core/llm.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LLM client β€” provider-agnostic wrapper for OpenAI and Gemini.
2
+
3
+ Why a wrapper:
4
+ - Two-tier model selection (reasoning vs bulk) without scattering model names
5
+ - Two-provider support (OpenAI / Gemini), switchable via LLM_PROVIDER env var
6
+ - Built-in retry on transient errors
7
+ - Pydantic-validated structured outputs
8
+ - Single chokepoint for logging / token accounting
9
+
10
+ The provider is chosen at construction time from settings.llm_provider:
11
+ - 'openai' (default) β†’ gpt-4o + gpt-4o-mini via langchain-openai
12
+ - 'gemini' β†’ gemini-2.5-flash + gemini-2.5-flash-lite via langchain-google-genai
13
+
14
+ Both providers share the same interface, so calling code never needs to
15
+ care which one is active.
16
+
17
+ Usage:
18
+ llm = LLMClient()
19
+ answer = llm.complete("Why is the sky blue?", model="bulk")
20
+ parsed = llm.structured(prompt, ReviewOutput, model="reasoning")
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import logging
25
+ from typing import Any, Type, TypeVar
26
+
27
+ from langchain_core.language_models import BaseChatModel
28
+ from langchain_core.output_parsers import PydanticOutputParser
29
+ from langchain_core.prompts import ChatPromptTemplate
30
+ from pydantic import BaseModel
31
+ from tenacity import retry, stop_after_attempt, wait_exponential
32
+
33
+ from core.config import settings
34
+
35
+ log = logging.getLogger(__name__)
36
+
37
+ T = TypeVar("T", bound=BaseModel)
38
+
39
+
40
+ def _build_openai_models(temp_reasoning: float, temp_bulk: float) -> tuple[BaseChatModel, BaseChatModel]:
41
+ """Construct OpenAI reasoning + bulk models."""
42
+ from langchain_openai import ChatOpenAI
43
+ if not settings.openai_api_key:
44
+ raise RuntimeError(
45
+ "LLM_PROVIDER=openai but OPENAI_API_KEY not set. "
46
+ "Add it to .env or switch LLM_PROVIDER to 'gemini'."
47
+ )
48
+ reasoning = ChatOpenAI(
49
+ model=settings.openai_reasoning_model,
50
+ temperature=temp_reasoning,
51
+ api_key=settings.openai_api_key,
52
+ )
53
+ bulk = ChatOpenAI(
54
+ model=settings.openai_bulk_model,
55
+ temperature=temp_bulk,
56
+ api_key=settings.openai_api_key,
57
+ )
58
+ return reasoning, bulk
59
+
60
+
61
+ def _build_gemini_models(temp_reasoning: float, temp_bulk: float) -> tuple[BaseChatModel, BaseChatModel]:
62
+ """Construct Gemini reasoning + bulk models."""
63
+ try:
64
+ from langchain_google_genai import ChatGoogleGenerativeAI
65
+ except ImportError as e:
66
+ raise ImportError(
67
+ "LLM_PROVIDER=gemini but langchain-google-genai is not installed. "
68
+ "Run: pip install langchain-google-genai"
69
+ ) from e
70
+
71
+ if not settings.gemini_api_key:
72
+ raise RuntimeError(
73
+ "LLM_PROVIDER=gemini but GEMINI_API_KEY not set. "
74
+ "Get a key at https://aistudio.google.com/apikey and add it to .env."
75
+ )
76
+ reasoning = ChatGoogleGenerativeAI(
77
+ model=settings.gemini_reasoning_model,
78
+ temperature=temp_reasoning,
79
+ google_api_key=settings.gemini_api_key,
80
+ )
81
+ bulk = ChatGoogleGenerativeAI(
82
+ model=settings.gemini_bulk_model,
83
+ temperature=temp_bulk,
84
+ google_api_key=settings.gemini_api_key,
85
+ )
86
+ return reasoning, bulk
87
+
88
+
89
+ class LLMClient:
90
+ """Two-tier, two-provider LLM client.
91
+
92
+ Tier 'reasoning' β†’ flagship model (gpt-4o / gemini-2.5-flash).
93
+ Used for: review generation, recommendation reasoning, persona summarization.
94
+ Tier 'bulk' β†’ cheap/fast model (gpt-4o-mini / gemini-2.5-flash-lite).
95
+ Used for: tone classification, vocabulary fingerprinting, lightweight ops.
96
+ """
97
+
98
+ def __init__(self, temperature_reasoning: float = 0.7,
99
+ temperature_bulk: float = 0.3,
100
+ provider: str | None = None):
101
+ self.provider = (provider or settings.llm_provider).lower()
102
+ log.info(f"LLMClient initializing with provider={self.provider!r}")
103
+
104
+ if self.provider == "openai":
105
+ self._reasoning, self._bulk = _build_openai_models(
106
+ temperature_reasoning, temperature_bulk,
107
+ )
108
+ elif self.provider == "gemini":
109
+ self._reasoning, self._bulk = _build_gemini_models(
110
+ temperature_reasoning, temperature_bulk,
111
+ )
112
+ else:
113
+ raise ValueError(
114
+ f"Unknown LLM_PROVIDER={self.provider!r}; expected 'openai' or 'gemini'"
115
+ )
116
+
117
+ def _model(self, tier: str) -> BaseChatModel:
118
+ if tier == "reasoning":
119
+ return self._reasoning
120
+ if tier == "bulk":
121
+ return self._bulk
122
+ raise ValueError(f"Unknown tier {tier!r}; expected 'reasoning' or 'bulk'")
123
+
124
+ # ──────────────────────────────────────────────────────────────────
125
+ # Free-form completion
126
+ # ──────────────────────────────────────────────────────────────────
127
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(min=1, max=10))
128
+ def complete(self, prompt: str, model: str = "bulk",
129
+ system: str | None = None) -> str:
130
+ messages: list[Any] = []
131
+ if system:
132
+ messages.append(("system", system))
133
+ messages.append(("human", "{input}"))
134
+ chain = ChatPromptTemplate.from_messages(messages) | self._model(model)
135
+ result = chain.invoke({"input": prompt})
136
+ # Both providers return BaseMessage with .content as str
137
+ content = result.content
138
+ if isinstance(content, list):
139
+ # Gemini occasionally returns list of content parts; flatten
140
+ content = "".join(p.get("text", "") if isinstance(p, dict) else str(p) for p in content)
141
+ return content
142
+
143
+ # ──────────────────────────────────────────────────────────────────
144
+ # Structured output β€” pydantic-validated
145
+ # ──────────────────────────────────────────────────────────────────
146
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(min=1, max=10))
147
+ def structured(self, prompt: str, schema: Type[T], model: str = "reasoning",
148
+ system: str | None = None) -> T:
149
+ """Run prompt, parse output into the given Pydantic schema.
150
+
151
+ Uses LangChain's PydanticOutputParser. The schema's format instructions
152
+ are appended to the prompt automatically.
153
+ """
154
+ parser = PydanticOutputParser(pydantic_object=schema)
155
+ format_instructions = parser.get_format_instructions()
156
+
157
+ messages: list[Any] = []
158
+ if system:
159
+ messages.append(("system", system))
160
+ messages.append((
161
+ "human",
162
+ "{input}\n\n{format_instructions}"
163
+ ))
164
+ chain = (
165
+ ChatPromptTemplate.from_messages(messages)
166
+ | self._model(model)
167
+ | parser
168
+ )
169
+ return chain.invoke({
170
+ "input": prompt,
171
+ "format_instructions": format_instructions,
172
+ })
core/nigerian.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Nigerian style layer β€” bonus marks via cultural contextualization.
2
+
3
+ The challenge brief awards extra credit for systems that *behave and sound
4
+ like Nigerians*. We treat this as a toggleable rendering layer, not as a
5
+ core dependency, for two reasons:
6
+
7
+ 1. Eval datasets are English Amazon reviews. Rendering everything in
8
+ Nigerian register would hurt our ROUGE / BERTScore against the
9
+ ground truth.
10
+ 2. Keeping it as a flag means we can showcase the capability without
11
+ sacrificing benchmark scores. Best of both rubric worlds.
12
+
13
+ Two functions:
14
+
15
+ naija_style_review(text) β†’ rewrites a generated review in Nigerian
16
+ English register, preserving sentiment,
17
+ rating intent, and key entities.
18
+
19
+ naija_persona_examples() β†’ returns hand-crafted Nigerian personas the
20
+ judges can demo Task B against. These show
21
+ the system handling local taste profiles
22
+ (afrobeats, jollof, Nollywood, etc.) even
23
+ when the underlying catalog is Amazon-global.
24
+
25
+ Design note: the style layer renders output in rich, expressive Nigerian
26
+ Pidgin β€” confident and fluent across the whole text, the way a Nigerian
27
+ genuinely talks when giving a strong opinion. Sentiment, rating intent and
28
+ factual content are always preserved; only the register changes.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ from core.llm import LLMClient
33
+
34
+ NAIJA_STYLE_SYSTEM = """You are a stylist who rewrites text in rich, expressive Nigerian Pidgin English β€” the way a Nigerian would genuinely talk when sharing strong opinions. Rules:
35
+
36
+ - Keep the sentiment, rating intent, and all factual content unchanged. A positive review stays positive; a 2-star pan stays a pan; named items, authors, and plot facts stay accurate.
37
+ - Write FULLY in Nigerian Pidgin register β€” not standard English with a sprinkle. Lean into it confidently across the whole text.
38
+ - Use natural Pidgin grammar and vocabulary throughout. Examples of the texture wanted:
39
+ Β· "This book sweet me die, I no fit drop am at all."
40
+ Β· "Abeg, the storyline just dey drag, e tire me well well."
41
+ Β· "Na correct work be this β€” the writer sabi wetin e dey do."
42
+ Β· "I no go lie, the ending shock me, I no see am coming."
43
+ Β· "The characters dey alive, you go feel like say you sabi them."
44
+ Β· "E no make sense, I vex small as I read am finish."
45
+ Β· "This one na better book, e make sense gan-gan."
46
+ - Common markers to use freely: "abeg", "sha", "na", "dey", "wetin", "e be like say", "no be small thing", "gan-gan", "well well", "I no go lie", "comot", "sabi", "vex", "sweet me", "make sense".
47
+ - Keep it authentic, not caricature β€” write like a real Nigerian sharing a genuine opinion, not a parody. It should read as natural Pidgin, fluent and confident.
48
+ - Do NOT add cultural references that weren't in the original (no jollof, Lagos traffic, etc. unless the source mentioned them).
49
+ - Length should stay roughly the same.
50
+ - Return ONLY the rewritten text. No preamble, no explanation."""
51
+
52
+
53
+ def naija_style_review(text: str, llm: LLMClient | None = None) -> str:
54
+ """Rewrite an English review in Nigerian English register.
55
+
56
+ Idempotent on already-Naija text in practice (the model leaves natural
57
+ phrasings alone).
58
+ """
59
+ llm = llm or LLMClient()
60
+ return llm.complete(
61
+ prompt=f"Rewrite this review in Nigerian English register:\n\n{text}",
62
+ system=NAIJA_STYLE_SYSTEM,
63
+ model="bulk",
64
+ ).strip()
65
+
66
+
67
+ # ──────────────────────────────────────────────────────────────────────────────
68
+ # Demo personas β€” used in the Streamlit UI to showcase cold-start handling
69
+ # ──────────────────────────────────────────────────────────────────────────────
70
+
71
+ NAIJA_DEMO_PERSONAS: list[dict] = [
72
+ {
73
+ "name": "Tunde β€” Lagos software engineer",
74
+ "description": (
75
+ "A 28-year-old software engineer in Lagos who reads mostly non-fiction "
76
+ "(business biographies, productivity, AI/tech), watches African and "
77
+ "international thrillers, and complains when books are padded or movies "
78
+ "are too slow. Prefers concise, practical writing. Gives 5 stars only "
79
+ "when something genuinely changed his thinking; defaults to 4. "
80
+ "Frequently mentions 'value for time' and 'execution'."
81
+ ),
82
+ "stated_preferences": ["business biographies", "AI and tech books",
83
+ "fast-paced thrillers", "Nollywood crime dramas",
84
+ "concise practical writing"],
85
+ "deal_breakers": ["padded chapters", "slow pacing", "academic jargon"],
86
+ },
87
+ {
88
+ "name": "Ngozi β€” Abuja public health doctor",
89
+ "description": (
90
+ "A 35-year-old doctor in Abuja who reads literary fiction and African "
91
+ "memoirs, watches character-driven dramas (West African and global), "
92
+ "and dislikes anything that handles women's lives shallowly. Writes "
93
+ "thoughtful, longer-than-average reviews. Rates with a tough 3.5 average. "
94
+ "Often references 'emotional truth' and 'craft'."
95
+ ),
96
+ "stated_preferences": ["literary fiction", "African memoirs",
97
+ "character-driven dramas", "Adichie-adjacent voice"],
98
+ "deal_breakers": ["shallow female characters", "trauma porn",
99
+ "lazy plotting"],
100
+ },
101
+ {
102
+ "name": "Bayo β€” Ibadan undergraduate",
103
+ "description": (
104
+ "A 21-year-old student in Ibadan who reads YA fantasy, plays a lot of "
105
+ "Afrobeats during study sessions, watches anime and Nollywood comedies, "
106
+ "and writes short bursty reviews. Quick to give 5 stars when entertained. "
107
+ "Mentions vibes, pacing, and whether something 'hits'."
108
+ ),
109
+ "stated_preferences": ["YA fantasy", "anime", "Nollywood comedies",
110
+ "fast-paced action"],
111
+ "deal_breakers": ["long descriptive passages", "overly serious tone"],
112
+ },
113
+ ]
114
+
115
+
116
+ def naija_persona_examples() -> list[dict]:
117
+ """Return demo personas for the Task B UI's cold-start showcase."""
118
+ return [dict(p) for p in NAIJA_DEMO_PERSONAS]
core/persona.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persona engine β€” turn a user's review history into a behavioral fingerprint.
2
+
3
+ The persona is the spine of the whole system. Both tasks ask it different
4
+ questions:
5
+
6
+ Task A: "Given this persona and this item, how would the user rate and review it?"
7
+ Task B: "Given this persona, what items would the user want next?"
8
+
9
+ A persona has two layers:
10
+
11
+ 1. Quantitative signals (computed deterministically from history)
12
+ - rating cadence: mean, std, distribution shape
13
+ - review length: mean, std
14
+ - vocabulary fingerprint: top distinctive terms
15
+ - domain mix: which categories the user engages with
16
+ - verified-purchase rate, helpful-vote signal
17
+
18
+ 2. Qualitative summary (LLM-generated, cached)
19
+ - tone descriptor (snarky / earnest / analytical / casual / ...)
20
+ - common preferences (themes, styles)
21
+ - common complaints (deal-breakers)
22
+ - recommended audience for THIS user (one-liner persona pitch)
23
+
24
+ The qualitative layer is what makes generated reviews feel like the actual
25
+ user wrote them. Without it, you get generic LLM prose. With it, you get
26
+ behavioral fidelity β€” which is one of Task A's three scored axes.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import logging
31
+ from collections import Counter
32
+ from dataclasses import dataclass, field, asdict
33
+ from typing import Any
34
+
35
+ import pandas as pd
36
+ from pydantic import BaseModel, Field
37
+
38
+ from core.llm import LLMClient
39
+
40
+ log = logging.getLogger(__name__)
41
+
42
+
43
+ # ──────────────────────────────────────────────────────────────────────────────
44
+ # Schemas
45
+ # ──────────────────────────────────────────────────────────────────────────────
46
+
47
+ class QualitativeSummary(BaseModel):
48
+ """LLM-generated qualitative layer of a persona."""
49
+ tone: str = Field(description="One-word tone descriptor: snarky, earnest, analytical, casual, enthusiastic, terse, verbose, etc.")
50
+ preferred_themes: list[str] = Field(description="3-5 themes/styles/qualities this user gravitates toward")
51
+ common_complaints: list[str] = Field(description="2-4 recurring deal-breakers or critique patterns")
52
+ voice_one_liner: str = Field(description="A single sentence describing this user's reviewing voice as if pitching them to a casting director")
53
+
54
+
55
+ @dataclass
56
+ class UserPersona:
57
+ """Complete persona β€” quantitative signals + qualitative summary + history."""
58
+ user_id: str
59
+
60
+ # Quantitative
61
+ n_reviews: int
62
+ avg_rating: float
63
+ std_rating: float
64
+ avg_review_length: float
65
+ std_review_length: float
66
+ verified_rate: float
67
+ domains: list[str]
68
+ n_domains: int
69
+ rating_distribution: dict[int, float] # {1: 0.05, 2: 0.1, ..., 5: 0.4}
70
+ top_terms: list[str] # vocabulary fingerprint
71
+
72
+ # Qualitative (lazily filled by PersonaEngine.enrich)
73
+ tone: str = ""
74
+ preferred_themes: list[str] = field(default_factory=list)
75
+ common_complaints: list[str] = field(default_factory=list)
76
+ voice_one_liner: str = ""
77
+
78
+ # Sample history for retrieval/grounding (subset of training reviews)
79
+ history_samples: list[dict[str, Any]] = field(default_factory=list)
80
+
81
+ def to_prompt_block(self) -> str:
82
+ """Render the persona as a structured prompt section.
83
+
84
+ This text is what the LLM sees when generating reviews / recommendations.
85
+ Keeping it formatted consistently is what makes generation behaviorally
86
+ faithful.
87
+ """
88
+ dist = " ".join(f"{r}β˜…:{p:.0%}" for r, p in sorted(self.rating_distribution.items()))
89
+ return (
90
+ f"USER PERSONA\n"
91
+ f" Reviews written: {self.n_reviews}\n"
92
+ f" Avg rating: {self.avg_rating:.2f} (Β±{self.std_rating:.2f})\n"
93
+ f" Rating distribution: {dist}\n"
94
+ f" Avg review length: {self.avg_review_length:.0f} words (Β±{self.std_review_length:.0f})\n"
95
+ f" Verified-purchase rate: {self.verified_rate:.0%}\n"
96
+ f" Active domains: {', '.join(self.domains)}\n"
97
+ f" Vocabulary fingerprint: {', '.join(self.top_terms[:15])}\n"
98
+ f" Tone: {self.tone or 'unspecified'}\n"
99
+ f" Preferred themes: {', '.join(self.preferred_themes) or 'unspecified'}\n"
100
+ f" Common complaints: {', '.join(self.common_complaints) or 'unspecified'}\n"
101
+ f" Voice: {self.voice_one_liner or 'unspecified'}\n"
102
+ )
103
+
104
+ def as_dict(self) -> dict:
105
+ return asdict(self)
106
+
107
+
108
+ # ──────────────────────────────────────────────────────────────────────────────
109
+ # Engine
110
+ # ──────────────────────────────────────────────────────────────────────────────
111
+
112
+ # A small set of generic English stopwords + Amazon-review noise. Keeping
113
+ # this in-module avoids pulling in nltk's download flow.
114
+ _STOPWORDS = set("""
115
+ a an the and or but if then else when while of in on at by to for with from
116
+ into onto over under is are was were be been being have has had do does did
117
+ i you he she it we they me him her us them my your his its our their this
118
+ that these those there here what which who whom whose how why so as too very
119
+ just also more most some any all each every other another such no not nor only
120
+ own same can will would could should might may must one two three really get
121
+ got gets just like dont didnt isnt arent wasnt werent havent hadnt hasnt cant
122
+ couldnt wouldnt shouldnt wont thats whats theres heres ive ill ive youve im
123
+ """.split())
124
+
125
+
126
+ class PersonaEngine:
127
+ """Build personas from review history.
128
+
129
+ Two entry points:
130
+ from_dataframe(user_id, training_reviews_df) -> UserPersona
131
+ enrich(persona) -> UserPersona # adds qualitative summary via LLM
132
+ """
133
+
134
+ def __init__(self, llm: LLMClient | None = None,
135
+ top_terms_k: int = 20,
136
+ history_samples_k: int = 8):
137
+ self.llm = llm or LLMClient()
138
+ self.top_terms_k = top_terms_k
139
+ self.history_samples_k = history_samples_k
140
+
141
+ # ─────────────────────────── Quantitative ────────────────────────────
142
+ def from_dataframe(self, user_id: str,
143
+ reviews: pd.DataFrame) -> UserPersona:
144
+ """Build a UserPersona from a DataFrame of one user's training reviews.
145
+
146
+ Expected columns: user_id, parent_asin, rating, text, verified_purchase,
147
+ domain, timestamp.
148
+ """
149
+ user_reviews = reviews[reviews["user_id"] == user_id]
150
+ if user_reviews.empty:
151
+ raise ValueError(f"No reviews found for user_id={user_id!r}")
152
+
153
+ ratings = user_reviews["rating"].astype(float)
154
+ lengths = user_reviews["text"].fillna("").str.split().str.len()
155
+
156
+ # Rating distribution as proportions
157
+ dist = ratings.round().astype(int).value_counts(normalize=True).to_dict()
158
+ rating_dist = {int(k): float(v) for k, v in dist.items()}
159
+
160
+ # Vocabulary fingerprint: most common non-stopword tokens
161
+ top_terms = self._top_terms(user_reviews["text"].tolist())
162
+
163
+ # Sample history items for retrieval grounding β€” keep the most recent
164
+ history = user_reviews.sort_values("timestamp", ascending=False) \
165
+ .head(self.history_samples_k)
166
+ history_samples = [
167
+ {
168
+ "parent_asin": row["parent_asin"],
169
+ "rating": float(row["rating"]),
170
+ "text": row["text"][:500],
171
+ "domain": row["domain"],
172
+ }
173
+ for _, row in history.iterrows()
174
+ ]
175
+
176
+ return UserPersona(
177
+ user_id=user_id,
178
+ n_reviews=len(user_reviews),
179
+ avg_rating=float(ratings.mean()),
180
+ std_rating=float(ratings.std()) if len(ratings) > 1 else 0.0,
181
+ avg_review_length=float(lengths.mean()),
182
+ std_review_length=float(lengths.std()) if len(lengths) > 1 else 0.0,
183
+ verified_rate=float(user_reviews["verified_purchase"].mean()),
184
+ domains=sorted(user_reviews["domain"].unique().tolist()),
185
+ n_domains=int(user_reviews["domain"].nunique()),
186
+ rating_distribution=rating_dist,
187
+ top_terms=top_terms,
188
+ history_samples=history_samples,
189
+ )
190
+
191
+ def _top_terms(self, texts: list[str]) -> list[str]:
192
+ """Most frequent content tokens, stopwords removed."""
193
+ counter: Counter = Counter()
194
+ for txt in texts:
195
+ if not isinstance(txt, str):
196
+ continue
197
+ tokens = [t.lower().strip(".,!?\"'()[]{}:;") for t in txt.split()]
198
+ tokens = [t for t in tokens
199
+ if t and len(t) > 2 and t not in _STOPWORDS and t.isalpha()]
200
+ counter.update(tokens)
201
+ return [w for w, _ in counter.most_common(self.top_terms_k)]
202
+
203
+ # ─────────────────────────── Qualitative ─────────────────────────────
204
+ def enrich(self, persona: UserPersona) -> UserPersona:
205
+ """Add LLM-generated qualitative summary to an existing persona.
206
+
207
+ Uses the reasoning model (gpt-4o) β€” more reliable structured output
208
+ than the bulk model. If the LLM call still fails, falls back to a
209
+ deterministic summary derived from the writing samples so we never
210
+ end up with an empty Voice/Tone.
211
+ """
212
+ if not persona.history_samples:
213
+ log.warning(f"User {persona.user_id} has no history samples; skipping enrichment")
214
+ return self._apply_deterministic_fallback(persona)
215
+
216
+ sample_block = "\n\n".join(
217
+ f"[{i+1}] Rating: {s['rating']}β˜… Domain: {s['domain']}\n{s['text'][:400]}"
218
+ for i, s in enumerate(persona.history_samples)
219
+ )
220
+
221
+ prompt = (
222
+ f"Below are review samples from a single user. Read them carefully "
223
+ f"and infer their reviewing voice.\n\n"
224
+ f"{sample_block}\n\n"
225
+ f"Quantitative signals about this user:\n"
226
+ f"- Average rating: {persona.avg_rating:.2f} of 5\n"
227
+ f"- Average review length: {persona.avg_review_length:.0f} words\n"
228
+ f"- Vocabulary they use often: {', '.join(persona.top_terms[:15])}\n\n"
229
+ f"Produce a qualitative summary of their reviewer voice. "
230
+ f"Be concise and concrete. If the samples are too sparse or generic, "
231
+ f"infer the most plausible voice rather than refusing."
232
+ )
233
+
234
+ try:
235
+ summary = self.llm.structured(
236
+ prompt, QualitativeSummary, model="reasoning",
237
+ system="You are a behavioral analyst specializing in online review patterns. Always produce valid output.",
238
+ )
239
+ persona.tone = summary.tone or persona.tone
240
+ persona.preferred_themes = summary.preferred_themes or persona.preferred_themes
241
+ persona.common_complaints = summary.common_complaints or persona.common_complaints
242
+ persona.voice_one_liner = summary.voice_one_liner or persona.voice_one_liner
243
+ except Exception as e:
244
+ log.warning(f"LLM enrichment failed for {persona.user_id} ({type(e).__name__}); using deterministic fallback")
245
+ persona = self._apply_deterministic_fallback(persona)
246
+
247
+ return persona
248
+
249
+ @staticmethod
250
+ def _apply_deterministic_fallback(persona: UserPersona) -> UserPersona:
251
+ """Fill in tone/themes/voice from quantitative signals when LLM fails.
252
+
253
+ This isn't as rich as an LLM summary, but it guarantees downstream
254
+ query construction has SOMETHING to work with β€” much better than
255
+ an empty string.
256
+ """
257
+ # Tone bucket from avg rating
258
+ if persona.avg_rating >= 4.5:
259
+ tone = "enthusiastic"
260
+ elif persona.avg_rating >= 3.8:
261
+ tone = "earnest"
262
+ elif persona.avg_rating >= 3.0:
263
+ tone = "measured"
264
+ else:
265
+ tone = "critical"
266
+
267
+ # Use top distinctive terms as proxy themes (filter out true generics)
268
+ generic_terms = {"book", "read", "story", "movie", "film", "great", "good",
269
+ "really", "much", "first", "next", "through", "about"}
270
+ candidate_themes = [t for t in persona.top_terms if t not in generic_terms][:5]
271
+ themes = candidate_themes or persona.top_terms[:3]
272
+
273
+ # Domain-grounded voice
274
+ domain_str = "/".join(persona.domains) if persona.domains else "general"
275
+ length_descriptor = (
276
+ "writes brief reviews" if persona.avg_review_length < 30
277
+ else "writes detailed reviews" if persona.avg_review_length > 150
278
+ else "writes moderate-length reviews"
279
+ )
280
+ voice = (
281
+ f"A {tone} {domain_str} reviewer who {length_descriptor} "
282
+ f"(avg {persona.avg_rating:.1f}β˜… over {persona.n_reviews} reviews)."
283
+ )
284
+
285
+ if not persona.tone:
286
+ persona.tone = tone
287
+ if not persona.preferred_themes:
288
+ persona.preferred_themes = themes
289
+ if not persona.voice_one_liner:
290
+ persona.voice_one_liner = voice
291
+ return persona
core/reflection.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-reflection β€” the act β†’ critique β†’ revise loop.
2
+
3
+ This is what makes NaijaTaste AI an agent rather than a one-shot pipeline.
4
+ After a first-pass output, the agent critiques its own work against the
5
+ persona and, if the critique finds problems, revises.
6
+
7
+ Two public entry points:
8
+
9
+ reflect_on_review(...) β€” Task A: critique + refine a generated review
10
+ reflect_on_recommendations(...) β€” Task B: critique + refine a top-N list
11
+
12
+ Each runs at most `max_iterations` revise cycles (default 2). The loop
13
+ stops early once the critique passes (no blocking issues). Every cycle is
14
+ logged so the paper can report how often refinement triggered and what it
15
+ changed.
16
+
17
+ Reference: Madaan et al. 2023, "Self-Refine: Iterative Refinement with
18
+ Self-Feedback"; Shinn et al. 2023, "Reflexion".
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import logging
23
+ from dataclasses import dataclass, field
24
+ from typing import Optional
25
+
26
+ from pydantic import BaseModel, Field
27
+
28
+ from core.llm import LLMClient
29
+ from core.persona import UserPersona
30
+
31
+ log = logging.getLogger(__name__)
32
+
33
+
34
+ # ──────────────────────────────────────────────────────────────────────────────
35
+ # Critique schemas
36
+ # ──────────────────────────────────────────────────────────────────────────────
37
+
38
+ class ReviewCritique(BaseModel):
39
+ """The critique LLM's assessment of a generated review (Task A)."""
40
+ rating_text_consistent: bool = Field(
41
+ description="True if the review text matches the star rating "
42
+ "(e.g. a 4-star review doesn't read like a 2-star pan)"
43
+ )
44
+ voice_match: bool = Field(
45
+ description="True if the review sounds like THIS user β€” their length, "
46
+ "register, vocabulary, and quirks"
47
+ )
48
+ on_topic: bool = Field(
49
+ description="True if the review is about the actual item, not generic filler"
50
+ )
51
+ issues: str = Field(
52
+ description="If any check failed, a specific 1-2 sentence description of what "
53
+ "to fix. If all passed, the string 'none'."
54
+ )
55
+
56
+ @property
57
+ def passed(self) -> bool:
58
+ return self.rating_text_consistent and self.voice_match and self.on_topic
59
+
60
+
61
+ class RecommendationCritique(BaseModel):
62
+ """The critique LLM's assessment of a top-N recommendation list (Task B)."""
63
+ titles_are_real: bool = Field(
64
+ description="True if the recommended items look like real products, "
65
+ "not review-headline fragments"
66
+ )
67
+ well_matched: bool = Field(
68
+ description="True if the picks genuinely fit the persona's tastes"
69
+ )
70
+ reasoning_grounded: bool = Field(
71
+ description="True if each pick's reasoning cites specific persona signals, "
72
+ "not generic filler"
73
+ )
74
+ diverse_enough: bool = Field(
75
+ description="True if the list isn't 10 near-identical items"
76
+ )
77
+ issues: str = Field(
78
+ description="If any check failed, a specific 1-2 sentence description of what "
79
+ "to fix. If all passed, the string 'none'."
80
+ )
81
+
82
+ @property
83
+ def passed(self) -> bool:
84
+ return (self.titles_are_real and self.well_matched
85
+ and self.reasoning_grounded and self.diverse_enough)
86
+
87
+
88
+ # ──────────────────────────────────────────────────────────────────────────────
89
+ # Reflection trace (for logging / paper reporting)
90
+ # ──────────────────────────────────────────────────────────────────────────────
91
+
92
+ @dataclass
93
+ class ReflectionTrace:
94
+ """Record of what the reflection loop did β€” useful for the paper."""
95
+ iterations_run: int = 0
96
+ critiques: list[str] = field(default_factory=list) # issues found each cycle
97
+ passed_final: bool = False
98
+ refined: bool = False # True if at least one revision happened
99
+
100
+
101
+ # ──────────────────────────────────────────────────────────────────────────────
102
+ # Task A β€” review reflection
103
+ # ──────────────────────────────────────────────────────────────────────────────
104
+
105
+ def _critique_review(llm: LLMClient, persona: UserPersona,
106
+ item_title: str, item_domain: str,
107
+ rating: float, review: str) -> ReviewCritique:
108
+ """One critique pass over a generated review."""
109
+ prompt = (
110
+ f"You are a strict editor checking whether an AI-generated review "
111
+ f"faithfully imitates a specific user. Be critical β€” your job is to "
112
+ f"catch problems, not to be nice.\n\n"
113
+ f"{'=' * 55}\n"
114
+ f"THE USER\n"
115
+ f"{'=' * 55}\n"
116
+ f"{persona.to_prompt_block()}\n\n"
117
+ f"{'=' * 55}\n"
118
+ f"ITEM REVIEWED\n"
119
+ f"{'=' * 55}\n"
120
+ f"Domain: {item_domain}\n"
121
+ f"Title: {item_title}\n\n"
122
+ f"{'=' * 55}\n"
123
+ f"THE GENERATED REVIEW (check this)\n"
124
+ f"{'=' * 55}\n"
125
+ f"Rating: {rating}\u2605\n"
126
+ f"Review: {review}\n\n"
127
+ f"{'=' * 55}\n"
128
+ f"YOUR CHECKS\n"
129
+ f"{'=' * 55}\n"
130
+ f"1. rating_text_consistent: Does the review TEXT match the {rating}-star "
131
+ f"rating? A 4-5 star review should read positive; a 1-2 star review should "
132
+ f"read negative; a 3 should read mixed.\n"
133
+ f"2. voice_match: Does it sound like THIS user? Check their typical review "
134
+ f"length ({persona.avg_review_length:.0f} words avg), tone ({persona.tone}), "
135
+ f"and quirks. A terse user given a long essay = fail. A user who writes in "
136
+ f"all-caps given lowercase = fail.\n"
137
+ f"3. on_topic: Is the review about the actual item, or is it generic filler "
138
+ f"that could apply to anything?\n\n"
139
+ f"If any check fails, describe specifically what to fix in 'issues'. "
140
+ f"If all pass, set 'issues' to 'none'."
141
+ )
142
+ return llm.structured(
143
+ prompt, ReviewCritique, model="reasoning",
144
+ system="You are a meticulous editor. Catch every inconsistency.",
145
+ )
146
+
147
+
148
+ def _refine_review(llm: LLMClient, persona: UserPersona,
149
+ item_title: str, item_domain: str,
150
+ prev_rating: float, prev_review: str,
151
+ critique_issues: str) -> tuple[float, str]:
152
+ """Regenerate a review given critique feedback. Returns (rating, review)."""
153
+
154
+ class RefinedReview(BaseModel):
155
+ rating: float = Field(description="Star rating 1.0-5.0")
156
+ review: str = Field(description="The improved review in the user's voice")
157
+
158
+ prompt = (
159
+ f"You previously wrote a review imitating a specific user, but an editor "
160
+ f"found problems. Rewrite the review to fix them.\n\n"
161
+ f"{'=' * 55}\n"
162
+ f"THE USER\n"
163
+ f"{'=' * 55}\n"
164
+ f"{persona.to_prompt_block()}\n\n"
165
+ f"ITEM: [{item_domain}] {item_title}\n\n"
166
+ f"YOUR PREVIOUS ATTEMPT:\n"
167
+ f" Rating: {prev_rating}\u2605\n"
168
+ f" Review: {prev_review}\n\n"
169
+ f"EDITOR'S FEEDBACK β€” fix these specific issues:\n"
170
+ f" {critique_issues}\n\n"
171
+ f"Rewrite the review addressing the feedback. Keep what worked; fix what "
172
+ f"the editor flagged. Stay in the user's authentic voice."
173
+ )
174
+ result = llm.structured(
175
+ prompt, RefinedReview, model="reasoning",
176
+ system="You are an expert behavioral simulator revising your work based on feedback.",
177
+ )
178
+ return result.rating, result.review
179
+
180
+
181
+ def reflect_on_review(llm: LLMClient, persona: UserPersona,
182
+ item_title: str, item_domain: str,
183
+ rating: float, review: str,
184
+ max_iterations: int = 2) -> tuple[float, str, ReflectionTrace]:
185
+ """Critique a generated review and refine it if needed.
186
+
187
+ Returns: (final_rating, final_review, trace)
188
+
189
+ The loop:
190
+ 1. Critique the current review.
191
+ 2. If it passes β†’ stop, return as-is.
192
+ 3. If it fails β†’ refine using the critique, then critique again.
193
+ 4. Stop after max_iterations even if still imperfect.
194
+ """
195
+ trace = ReflectionTrace()
196
+ cur_rating, cur_review = rating, review
197
+
198
+ for i in range(max_iterations):
199
+ try:
200
+ critique = _critique_review(llm, persona, item_title, item_domain,
201
+ cur_rating, cur_review)
202
+ except Exception as e:
203
+ log.warning(f"Review critique failed ({type(e).__name__}); "
204
+ f"keeping current review")
205
+ break
206
+
207
+ trace.iterations_run = i + 1
208
+ if critique.passed:
209
+ trace.critiques.append("passed")
210
+ trace.passed_final = True
211
+ log.info(f"Review reflection: passed on iteration {i + 1}")
212
+ break
213
+
214
+ trace.critiques.append(critique.issues)
215
+ log.info(f"Review reflection iter {i + 1}: issues = {critique.issues}")
216
+
217
+ # Refine
218
+ try:
219
+ cur_rating, cur_review = _refine_review(
220
+ llm, persona, item_title, item_domain,
221
+ cur_rating, cur_review, critique.issues,
222
+ )
223
+ trace.refined = True
224
+ except Exception as e:
225
+ log.warning(f"Review refine failed ({type(e).__name__}); "
226
+ f"keeping pre-refine review")
227
+ break
228
+
229
+ return cur_rating, cur_review, trace
230
+
231
+
232
+ # ──────────────────────────────────────────────────────────────────────────────
233
+ # Task B β€” recommendation reflection
234
+ # ──────────────────────────────────────────────────────────────────────────────
235
+
236
+ def _critique_recommendations(llm: LLMClient, persona: UserPersona,
237
+ recommendations: list[dict],
238
+ mode: str) -> RecommendationCritique:
239
+ """One critique pass over a recommendation list."""
240
+ rec_block = "\n".join(
241
+ f" #{i+1} [{r['domain']}] {r['title']}\n Why: {r['reasoning']}"
242
+ for i, r in enumerate(recommendations)
243
+ )
244
+ prompt = (
245
+ f"You are a strict reviewer checking the quality of a recommendation "
246
+ f"list. Be critical β€” catch problems.\n\n"
247
+ f"{'=' * 55}\n"
248
+ f"THE USER\n"
249
+ f"{'=' * 55}\n"
250
+ f"{persona.to_prompt_block()}\n\n"
251
+ f"{'=' * 55}\n"
252
+ f"THE RECOMMENDATIONS (mode: {mode})\n"
253
+ f"{'=' * 55}\n"
254
+ f"{rec_block}\n\n"
255
+ f"{'=' * 55}\n"
256
+ f"YOUR CHECKS\n"
257
+ f"{'=' * 55}\n"
258
+ f"1. titles_are_real: Do these look like real product titles? FAIL if any "
259
+ f"are review-headline fragments like 'Fast paced great read' or 'An "
260
+ f"enjoyable read' or 'Loved it!'.\n"
261
+ f"2. well_matched: Do the picks genuinely fit this user's tastes?\n"
262
+ f"3. reasoning_grounded: Does each 'Why' cite specific persona signals, "
263
+ f"or is it generic filler?\n"
264
+ f"4. diverse_enough: Is there real variety, or are these 10 near-identical "
265
+ f"items?\n\n"
266
+ f"If any check fails, describe specifically what to fix in 'issues' "
267
+ f"(e.g. 'items #4, #7, #9 have review-headline titles β€” replace them'). "
268
+ f"If all pass, set 'issues' to 'none'."
269
+ )
270
+ return llm.structured(
271
+ prompt, RecommendationCritique, model="reasoning",
272
+ system="You are a meticulous recommendation-quality auditor.",
273
+ )
274
+
275
+
276
+ def reflect_on_recommendations(llm: LLMClient, persona: UserPersona,
277
+ recommendations: list[dict], mode: str,
278
+ refine_fn,
279
+ max_iterations: int = 2,
280
+ ) -> tuple[list[dict], ReflectionTrace]:
281
+ """Critique a recommendation list and refine if needed.
282
+
283
+ Unlike review reflection, refinement here can't just rewrite text β€” it
284
+ needs to re-run reranking with feedback. So the caller passes a
285
+ `refine_fn(issues: str) -> list[dict]` that re-runs the rerank with the
286
+ critique injected, and this function orchestrates the loop.
287
+
288
+ Returns: (final_recommendations, trace)
289
+ """
290
+ trace = ReflectionTrace()
291
+ cur_recs = recommendations
292
+
293
+ for i in range(max_iterations):
294
+ try:
295
+ critique = _critique_recommendations(llm, persona, cur_recs, mode)
296
+ except Exception as e:
297
+ log.warning(f"Recommendation critique failed ({type(e).__name__}); "
298
+ f"keeping current list")
299
+ break
300
+
301
+ trace.iterations_run = i + 1
302
+ if critique.passed:
303
+ trace.critiques.append("passed")
304
+ trace.passed_final = True
305
+ log.info(f"Recommendation reflection: passed on iteration {i + 1}")
306
+ break
307
+
308
+ trace.critiques.append(critique.issues)
309
+ log.info(f"Recommendation reflection iter {i + 1}: issues = {critique.issues}")
310
+
311
+ # Refine via the caller-supplied function
312
+ try:
313
+ refined = refine_fn(critique.issues)
314
+ if refined:
315
+ cur_recs = refined
316
+ trace.refined = True
317
+ except Exception as e:
318
+ log.warning(f"Recommendation refine failed ({type(e).__name__}); "
319
+ f"keeping pre-refine list")
320
+ break
321
+
322
+ return cur_recs, trace