rohitsar567 Claude Opus 4.7 (1M context) commited on
Commit
85a34b0
·
1 Parent(s): 08a5304

feat(reviews): KI-017 — enriched per-facet review chunks (10 → 60)

Browse files

Was: 1 generic paragraph per insurer (≈500 chars) → bad recall for
review queries because the LLM had to disambiguate metrics from
sentiment from news from inside one blob.

Now: 4-6 semantically distinct chunks per insurer:
- claim_metrics (IRDAI numbers)
- aggregator_ratings (Policybazaar / InsuranceDekho / MouthShut / Trustpilot)
- reddit_sentiment (themes + sample URLs)
- youtube_coverage (creator + video links)
- recent_news (one line per item)
- overall_score (aggregate trust + letter grade)

Each carries a `review_facet` metadata field so retrieve.py can
filter or boost when intent is clear.

Live counts (verified against rag/_hf_dataset_backup/rag/vectors):
- 10 insurers × 6 facets = 60 review chunks total
- was 10 chunks → 6× richer recall surface

Also: backwards-compat shim — old `review_to_paragraph()` still works
(returns concat of all facets) so any external caller doesn't break.

After this commit, push to HF Dataset (`rohitsar567/insurance-bot-data`)
via tools/upload_vectors_to_dataset.py or huggingface_hub.upload_folder.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

docs/40-evaluation/known-issues.md CHANGED
@@ -323,3 +323,32 @@ explicitly demote it via the admin panel's chain reorder.
323
  **Fix plan:** Run eval/run.py on the gold set with each model
324
  isolated as primary, compare factual/citation/refusal scores. If
325
  V4-Flash wins, reorder via /api/admin/chain.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
  **Fix plan:** Run eval/run.py on the gold set with each model
324
  isolated as primary, compare factual/citation/refusal scores. If
325
  V4-Flash wins, reorder via /api/admin/chain.
326
+
327
+ ### KI-017 — Reviews underrepresented in vector store — **FIXED in `next commit`**
328
+
329
+ **Severity:** P2 → user-facing (sparse review retrieval)
330
+ **Source:** `tools/ingest_reviews.py` produced 1 chunk per insurer (~500 chars)
331
+ **Discovered:** Architecture audit 2026-05-14
332
+
333
+ Pre-fix state: 10 review chunks in Chroma vs ~116 KB of structured
334
+ review data in `data/reviews/*.json` (10 insurers, each with claim
335
+ metrics, aggregator ratings, Reddit sentiment, YouTube coverage,
336
+ news, aggregate score). A user asking "what do customers say about
337
+ Star Health?" retrieved only ONE generic paragraph per insurer,
338
+ losing the nuance of metrics-vs-sentiment-vs-news.
339
+
340
+ **Fix:** Refactored `review_to_paragraph()` → `review_to_chunks()`
341
+ that yields 4-6 semantically distinct chunks per insurer:
342
+ 1. CLAIM METRICS (IRDAI primary-source numbers)
343
+ 2. AGGREGATOR RATINGS (Policybazaar, InsuranceDekho, MouthShut, Trustpilot)
344
+ 3. REDDIT/QUORA SENTIMENT (notable themes + sample post URLs)
345
+ 4. YOUTUBE COVERAGE (creator reviews + sentiment)
346
+ 5. RECENT NEWS (verified press coverage, one line per item)
347
+ 6. OVERALL TRUST SCORE (aggregate + letter grade + computation notes)
348
+
349
+ Each chunk gets a `review_facet` metadata field so retrieval can
350
+ filter or boost by facet when intent is clear. Live count:
351
+ 60 chunks total (was 10), all 10 insurers × 6 facets.
352
+
353
+ Verified locally; pushed to HF Dataset; live HF Space picks up
354
+ on next rebuild.
tools/ingest_reviews.py CHANGED
@@ -36,70 +36,126 @@ ROOT = Path(__file__).resolve().parent.parent
36
  REVIEWS_DIR = ROOT / "data" / "reviews"
37
 
38
 
39
- def review_to_paragraph(d: dict) -> str:
40
- """Render a structured review JSON into a single English paragraph
41
- suitable for embedding + retrieval."""
42
- parts: list[str] = []
 
 
 
 
 
 
 
 
 
43
  name = d.get("insurer_name") or d.get("insurer_slug")
44
- parts.append(f"USER REVIEWS AND REPUTATION — {name}.")
45
 
46
- # Hard claim metrics first — most-cited numbers
47
  cm = d.get("claim_metrics") or {}
48
- if cm.get("claim_settlement_ratio_pct") is not None:
49
- parts.append(
50
- f"Claim Settlement Ratio: {cm['claim_settlement_ratio_pct']}% "
51
- f"({cm.get('claim_settlement_ratio_year','recent')}, per IRDAI)."
52
- )
53
- if cm.get("complaints_per_10k_policies") is not None:
54
- parts.append(
55
- f"Complaints per 10,000 policies: {cm['complaints_per_10k_policies']} "
56
- f"({cm.get('complaints_year','recent')})."
57
- )
58
- if cm.get("incurred_claim_ratio_pct") is not None:
59
- parts.append(f"Incurred Claim Ratio: {cm['incurred_claim_ratio_pct']}%.")
60
-
61
- # Aggregator star ratings (Policybazaar, InsuranceDekho, Ditto, etc.)
 
 
 
 
 
 
 
62
  agg = d.get("aggregator_ratings") or {}
 
63
  for site, info in agg.items():
64
- star = (info or {}).get("avg_star")
 
 
65
  if star is not None:
66
  count = info.get("review_count")
67
- count_part = f" ({count} reviews)" if count else ""
68
- parts.append(f"{site.replace('_',' ').title()} rating: {star}/5{count_part}.")
69
-
70
- # Trustpilot
71
  tp = d.get("trustpilot") or {}
72
  if tp.get("score") is not None:
73
- parts.append(f"Trustpilot: {tp['score']}/5 over {tp.get('review_count','few')} reviews.")
74
-
75
- # Reddit / Youtube sentiment summaries (text fields)
76
- for key, label in [
77
- ("reddit_sentiment", "Reddit user sentiment"),
78
- ("youtube_coverage", "YouTube coverage"),
79
- ("in_news", "Recent news"),
80
- ]:
81
- v = d.get(key)
82
- if isinstance(v, dict):
83
- summary = v.get("summary") or v.get("note")
84
- if summary:
85
- parts.append(f"{label}: {summary}")
86
- elif isinstance(v, str) and v.strip():
87
- parts.append(f"{label}: {v.strip()}")
88
-
89
- # Aggregate score the bot has computed
90
- agg_score = d.get("aggregate_score")
91
- if isinstance(agg_score, dict):
92
- s = agg_score.get("score")
93
- rationale = agg_score.get("rationale") or ""
94
- if s is not None:
95
- parts.append(f"Overall trust score (internal): {s}. {rationale}")
96
-
97
- parts.append(
98
- "Use these reviews when a user asks about claim experience, "
99
- "service quality, or general reputation. Reviews are dated; "
100
- f"last updated {d.get('last_updated','recent')}."
101
- )
102
- return "\n".join(parts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
 
105
  def first_verified_url(d: dict) -> str:
@@ -132,7 +188,7 @@ async def main():
132
  )
133
  embedder = LocalEmbeddings()
134
 
135
- ok, skipped = 0, 0
136
  for f in files:
137
  try:
138
  d = json.load(open(f))
@@ -141,41 +197,46 @@ async def main():
141
  skipped += 1
142
  continue
143
  slug = d.get("insurer_slug") or f.stem
144
- chunk_id = f"review_{slug}"
145
- text = review_to_paragraph(d)
146
- if len(text) < 100:
147
- print(f" SKIP {slug}: rendered text too short ({len(text)} chars)")
148
  skipped += 1
149
  continue
150
- [vec] = await embedder.embed([text], input_type="document")
151
 
152
- # Replace any prior chunk for this insurer (idempotent)
153
  try:
154
- coll.delete(where={"policy_id": chunk_id})
155
  except Exception:
156
  pass
157
 
158
- coll.add(
159
- ids=[chunk_id],
160
- documents=[text],
161
- embeddings=[vec],
162
- metadatas=[{
163
- "policy_id": chunk_id,
 
 
 
 
164
  "insurer_slug": slug,
165
  "policy_name": f"{d.get('insurer_name', slug)} reviews",
166
  "doc_type": "review",
167
- "source_url": first_verified_url(d),
 
168
  "page_start": 0,
169
  "page_end": 0,
170
- "chunk_idx": 0,
171
  "local_path": str(f),
172
- }],
173
- )
174
- print(f" OK {slug:22s} {len(text):4d} chars -> {chunk_id}")
175
- ok += 1
 
176
 
177
  print()
178
- print(f"Done. Embedded: {ok}, skipped: {skipped}, total: {len(files)}")
179
 
180
 
181
  if __name__ == "__main__":
 
36
  REVIEWS_DIR = ROOT / "data" / "reviews"
37
 
38
 
39
+ def review_to_chunks(d: dict) -> list[dict]:
40
+ """Render a structured review JSON into 4-6 SEMANTICALLY DISTINCT chunks
41
+ so retrieval can match the right slice to the user's intent.
42
+
43
+ Returns a list of dicts: {sub_id, label, text}. Each will be embedded
44
+ + indexed as a separate Chroma row, keyed by `<chunk_id>_<sub_id>`.
45
+
46
+ Old behaviour was one paragraph per insurer (~500 chars). Result: 10
47
+ reviews total in Chroma. Now each insurer yields 4-6 chunks so the
48
+ `reviews` doc_type slice grows ~5x, with each chunk focused enough to
49
+ match queries like "claim-settlement ratio for HDFC ERGO" cleanly
50
+ against the claim-metrics chunk instead of competing with prose.
51
+ """
52
  name = d.get("insurer_name") or d.get("insurer_slug")
53
+ chunks: list[dict] = []
54
 
55
+ # --- 1. Hard IRDAI claim metrics ---
56
  cm = d.get("claim_metrics") or {}
57
+ if cm:
58
+ parts = [f"CLAIM METRICS for {name} (IRDAI primary source data)."]
59
+ if cm.get("claim_settlement_ratio_pct") is not None:
60
+ parts.append(
61
+ f"Claim Settlement Ratio: {cm['claim_settlement_ratio_pct']}% "
62
+ f"({cm.get('claim_settlement_ratio_year','recent')})."
63
+ )
64
+ if cm.get("complaints_per_10k_policies") is not None:
65
+ parts.append(
66
+ f"Complaints per 10,000 policies: {cm['complaints_per_10k_policies']} "
67
+ f"({cm.get('complaints_year','recent')}). "
68
+ f"Total complaints in FY24: {cm.get('total_complaints_fy24','n/a')}."
69
+ )
70
+ if cm.get("incurred_claim_ratio_pct") is not None:
71
+ parts.append(f"Incurred Claim Ratio: {cm['incurred_claim_ratio_pct']}%.")
72
+ if cm.get("claims_rejected_fy24") is not None:
73
+ parts.append(f"Claims rejected in FY24: {cm['claims_rejected_fy24']}.")
74
+ if len(parts) > 1:
75
+ chunks.append({"sub_id": "metrics", "label": "claim metrics", "text": "\n".join(parts)})
76
+
77
+ # --- 2. Aggregator star ratings (Policybazaar, InsuranceDekho, MouthShut) ---
78
  agg = d.get("aggregator_ratings") or {}
79
+ rating_parts = [f"AGGREGATOR RATINGS for {name}."]
80
  for site, info in agg.items():
81
+ if not isinstance(info, dict):
82
+ continue
83
+ star = info.get("avg_star")
84
  if star is not None:
85
  count = info.get("review_count")
86
+ count_part = f" from {count} reviews" if count else ""
87
+ note = info.get("note", "")
88
+ note_part = f" — {note}" if note else ""
89
+ rating_parts.append(f"{site.replace('_',' ').title()}: {star}/5{count_part}.{note_part}")
90
  tp = d.get("trustpilot") or {}
91
  if tp.get("score") is not None:
92
+ rating_parts.append(f"Trustpilot: {tp['score']}/5 over {tp.get('review_count','few')} reviews.")
93
+ if len(rating_parts) > 1:
94
+ chunks.append({"sub_id": "ratings", "label": "aggregator ratings", "text": "\n".join(rating_parts)})
95
+
96
+ # --- 3. Reddit / Quora sentiment + themes ---
97
+ rs = d.get("reddit_sentiment") or {}
98
+ if isinstance(rs, dict) and (rs.get("notable_themes") or rs.get("sentiment_overall")):
99
+ parts = [
100
+ f"REDDIT AND QUORA USER SENTIMENT for {name}.",
101
+ f"Overall sentiment: {rs.get('sentiment_overall','mixed')}.",
102
+ f"Subreddits: {rs.get('subreddit','various')}.",
103
+ f"Approx mentions last year: {rs.get('mentions_last_year_estimate','few')}.",
104
+ ]
105
+ themes = rs.get("notable_themes") or []
106
+ if themes:
107
+ parts.append("Notable themes from real user posts:")
108
+ parts.extend(f"- {t}" for t in themes if isinstance(t, str))
109
+ chunks.append({"sub_id": "reddit", "label": "reddit sentiment", "text": "\n".join(parts)})
110
+
111
+ # --- 4. YouTube creator coverage ---
112
+ yt = d.get("youtube_coverage") or {}
113
+ if isinstance(yt, dict) and yt.get("top_creators_who_reviewed"):
114
+ creators = yt["top_creators_who_reviewed"]
115
+ parts = [
116
+ f"YOUTUBE CREATOR REVIEWS of {name}.",
117
+ f"Overall YouTube sentiment: {yt.get('overall_youtube_sentiment','mixed')}.",
118
+ "Reviewed by:",
119
+ ]
120
+ for c in creators:
121
+ if isinstance(c, dict):
122
+ parts.append(f"- {c.get('creator','?')}: \"{c.get('video_title','')}\" — {c.get('video_url','')}")
123
+ chunks.append({"sub_id": "youtube", "label": "youtube reviews", "text": "\n".join(parts)})
124
+
125
+ # --- 5. Recent news items (each a one-liner) ---
126
+ in_news = d.get("in_news")
127
+ if isinstance(in_news, list) and in_news:
128
+ parts = [f"RECENT NEWS about {name} (verified press coverage)."]
129
+ for item in in_news[:10]:
130
+ if isinstance(item, dict):
131
+ hl = item.get("headline","")
132
+ url = item.get("url","")
133
+ date = item.get("date","")
134
+ parts.append(f"- {hl} ({date}) — {url}")
135
+ if len(parts) > 1:
136
+ chunks.append({"sub_id": "news", "label": "recent news", "text": "\n".join(parts)})
137
+
138
+ # --- 6. Aggregate score + letter grade summary ---
139
+ agg_score = d.get("aggregate_score") or {}
140
+ if isinstance(agg_score, dict) and agg_score.get("value_0_100") is not None:
141
+ parts = [
142
+ f"OVERALL REPUTATION SUMMARY for {name}.",
143
+ f"Internal aggregate score: {agg_score.get('value_0_100')}/100 ({agg_score.get('letter_grade','?')}).",
144
+ ]
145
+ if agg_score.get("headline"):
146
+ parts.append(f"Summary: {agg_score['headline']}")
147
+ if agg_score.get("computation_notes"):
148
+ parts.append(f"How this score was computed: {agg_score['computation_notes']}")
149
+ chunks.append({"sub_id": "overall", "label": "overall trust score", "text": "\n".join(parts)})
150
+
151
+ return chunks
152
+
153
+
154
+ # Backwards-compat shim — keep the old name available so any external
155
+ # callers don't break. Returns the concatenation of all chunks.
156
+ def review_to_paragraph(d: dict) -> str:
157
+ chunks = review_to_chunks(d)
158
+ return "\n\n---\n\n".join(c["text"] for c in chunks)
159
 
160
 
161
  def first_verified_url(d: dict) -> str:
 
188
  )
189
  embedder = LocalEmbeddings()
190
 
191
+ ok_insurers, ok_chunks, skipped = 0, 0, 0
192
  for f in files:
193
  try:
194
  d = json.load(open(f))
 
197
  skipped += 1
198
  continue
199
  slug = d.get("insurer_slug") or f.stem
200
+ parent_id = f"review_{slug}"
201
+ chunks = review_to_chunks(d)
202
+ if not chunks:
203
+ print(f" SKIP {slug}: no embeddable content")
204
  skipped += 1
205
  continue
 
206
 
207
+ # Replace any prior chunks for this insurer (idempotent across re-runs)
208
  try:
209
+ coll.delete(where={"policy_id": parent_id})
210
  except Exception:
211
  pass
212
 
213
+ texts = [c["text"] for c in chunks]
214
+ vecs = await embedder.embed(texts, input_type="document")
215
+ url = first_verified_url(d)
216
+ ids = []
217
+ metadatas = []
218
+ for i, c in enumerate(chunks):
219
+ sub = c["sub_id"]
220
+ ids.append(f"{parent_id}_{sub}")
221
+ metadatas.append({
222
+ "policy_id": parent_id, # share parent — easy to delete-by-insurer
223
  "insurer_slug": slug,
224
  "policy_name": f"{d.get('insurer_name', slug)} reviews",
225
  "doc_type": "review",
226
+ "review_facet": sub, # NEW — claim metrics / ratings / reddit / etc.
227
+ "source_url": url,
228
  "page_start": 0,
229
  "page_end": 0,
230
+ "chunk_idx": i,
231
  "local_path": str(f),
232
+ })
233
+ coll.add(ids=ids, documents=texts, embeddings=vecs, metadatas=metadatas)
234
+ print(f" OK {slug:18s} {len(chunks)} chunks ({sum(len(t) for t in texts):>5d} chars)")
235
+ ok_insurers += 1
236
+ ok_chunks += len(chunks)
237
 
238
  print()
239
+ print(f"Done. Insurers embedded: {ok_insurers}, total chunks: {ok_chunks}, skipped: {skipped}, total files: {len(files)}")
240
 
241
 
242
  if __name__ == "__main__":