Xixi679 commited on
Commit
6164f74
·
verified ·
1 Parent(s): 97651f2

Upload conversation_search_tools.py

Browse files
Files changed (1) hide show
  1. conversation_search_tools.py +450 -0
conversation_search_tools.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ conversation_search_tools.py
6
+
7
+ This module combines TWO search tools over the same cleaned
8
+ doctor–patient conversation dataset:
9
+
10
+ 1. Semantic (vector) search using FAISS + embeddings.
11
+ 2. Keyword search using simple substring matching + scoring.
12
+
13
+ It is designed to be used both:
14
+
15
+ - As a library/module for LLM tools:
16
+ - search_conversations_semantic_tool(...)
17
+ - search_conversations_keyword_tool(...)
18
+
19
+ - And as a local CLI for debugging:
20
+ python conversation_search_tools.py --mode semantic
21
+ python conversation_search_tools.py --mode keyword
22
+ """
23
+
24
+ import argparse
25
+ import os
26
+ from typing import List, Dict, Any, Optional
27
+
28
+ import numpy as np
29
+ import pandas as pd
30
+ import faiss
31
+
32
+ try:
33
+ from openai import OpenAI
34
+ client = OpenAI()
35
+ except ImportError:
36
+ client = None
37
+
38
+
39
+ # Embedding model name (must match the one used to build the FAISS index)
40
+ EMBEDDING_MODEL = "text-embedding-3-small"
41
+
42
+ # Global caches to avoid reloading large files on every tool call
43
+ _GLOBAL_DF: Optional[pd.DataFrame] = None
44
+ _GLOBAL_DATA_PATH: Optional[str] = None
45
+
46
+ _GLOBAL_INDEX: Optional[faiss.Index] = None
47
+ _GLOBAL_INDEX_PATH: Optional[str] = None
48
+
49
+
50
+ # ======================= Data / index loading =======================
51
+
52
+ def _load_data_internal(data_path: str) -> pd.DataFrame:
53
+ """
54
+ Low-level function to load the cleaned CSV file.
55
+ It does NOT enforce keyword-specific columns here; those are checked
56
+ in the keyword tool function.
57
+ """
58
+ if not os.path.exists(data_path):
59
+ raise FileNotFoundError(f"Data CSV not found: {data_path}")
60
+
61
+ df = pd.read_csv(data_path)
62
+
63
+ # Base required columns (used by both tools)
64
+ base_required_cols = [
65
+ "conversation_id",
66
+ "description",
67
+ "patient_text",
68
+ "doctor_text",
69
+ ]
70
+ for col in base_required_cols:
71
+ if col not in df.columns:
72
+ raise ValueError(
73
+ f"Required column '{col}' not in CSV. "
74
+ f"Available columns: {list(df.columns)}"
75
+ )
76
+
77
+ # Keep row order consistent with whatever was used to build the index
78
+ df = df.reset_index(drop=True)
79
+ return df
80
+
81
+
82
+ def _ensure_data_loaded(data_path: str) -> None:
83
+ """
84
+ Ensure that the global DataFrame is loaded into memory.
85
+ Reload if the path changes.
86
+ """
87
+ global _GLOBAL_DF, _GLOBAL_DATA_PATH
88
+
89
+ if _GLOBAL_DF is None or _GLOBAL_DATA_PATH != data_path:
90
+ _GLOBAL_DF = _load_data_internal(data_path)
91
+ _GLOBAL_DATA_PATH = data_path
92
+
93
+
94
+ def _load_index_internal(index_path: str) -> faiss.Index:
95
+ """
96
+ Low-level function to load the FAISS index from disk.
97
+ """
98
+ if not os.path.exists(index_path):
99
+ raise FileNotFoundError(f"FAISS index file not found: {index_path}")
100
+ index = faiss.read_index(index_path)
101
+ return index
102
+
103
+
104
+ def _ensure_index_loaded(index_path: str) -> None:
105
+ """
106
+ Ensure that the global FAISS index is loaded into memory.
107
+ Reload if the path changes.
108
+ """
109
+ global _GLOBAL_INDEX, _GLOBAL_INDEX_PATH
110
+
111
+ if _GLOBAL_INDEX is None or _GLOBAL_INDEX_PATH != index_path:
112
+ _GLOBAL_INDEX = _load_index_internal(index_path)
113
+ _GLOBAL_INDEX_PATH = index_path
114
+
115
+
116
+ # ======================= Embedding helper =======================
117
+
118
+ def embed_query(query: str) -> np.ndarray:
119
+ """
120
+ Convert a text query into an embedding vector (float32 numpy array).
121
+
122
+ By default this uses OpenAI embeddings. You can replace this with any
123
+ other embedding backend as long as you keep the same dimension and
124
+ normalization as when the FAISS index was built.
125
+ """
126
+ if client is None:
127
+ raise RuntimeError(
128
+ "OpenAI client not available. "
129
+ "Install `openai` and set OPENAI_API_KEY, or modify "
130
+ "embed_query() to use your own embedding model."
131
+ )
132
+
133
+ resp = client.embeddings.create(
134
+ model=EMBEDDING_MODEL,
135
+ input=[query]
136
+ )
137
+ emb = np.array(resp.data[0].embedding, dtype="float32")
138
+ # Normalize so that inner product approximates cosine similarity
139
+ faiss.normalize_L2(emb.reshape(1, -1))
140
+ return emb
141
+
142
+
143
+ # ======================= Semantic search core =======================
144
+
145
+ def _semantic_search_core(
146
+ index: faiss.Index,
147
+ df: pd.DataFrame,
148
+ query: str,
149
+ top_k: int = 5,
150
+ ) -> List[Dict[str, Any]]:
151
+ """
152
+ Run vector search in FAISS to find conversations semantically
153
+ similar to the query.
154
+ """
155
+ if not query:
156
+ return []
157
+
158
+ q_emb = embed_query(query)
159
+ q_emb = q_emb.reshape(1, -1)
160
+
161
+ scores, indices = index.search(q_emb, top_k)
162
+ scores = scores[0]
163
+ indices = indices[0]
164
+
165
+ results: List[Dict[str, Any]] = []
166
+ for idx, score in zip(indices, scores):
167
+ if idx < 0:
168
+ continue
169
+ row = df.iloc[idx]
170
+ results.append(
171
+ {
172
+ "conversation_id": str(row["conversation_id"]),
173
+ "description": str(row.get("description", "")),
174
+ "patient_text": str(row.get("patient_text", "")),
175
+ "doctor_text": str(row.get("doctor_text", "")),
176
+ "score": float(score),
177
+ }
178
+ )
179
+ return results
180
+
181
+
182
+ # ======================= Keyword search core =======================
183
+
184
+ def _keyword_search_core(
185
+ df: pd.DataFrame,
186
+ query: str,
187
+ top_k: int = 5,
188
+ ) -> List[Dict[str, Any]]:
189
+ """
190
+ Perform simple keyword-based search over the "text_for_keyword_lower"
191
+ column, then score and rank results.
192
+
193
+ Ranking priorities:
194
+ 1. Whether patient_text contains the query (case-insensitive).
195
+ 2. Whether doctor_text contains the query (case-insensitive).
196
+ 3. Shorter text_for_keyword is ranked slightly higher.
197
+ """
198
+ if not query:
199
+ return []
200
+
201
+ required_cols = [
202
+ "text_for_keyword",
203
+ "text_for_keyword_lower",
204
+ ]
205
+ for col in required_cols:
206
+ if col not in df.columns:
207
+ raise ValueError(
208
+ f"Required column '{col}' for keyword search is missing. "
209
+ f"Available columns: {list(df.columns)}"
210
+ )
211
+
212
+ q = query.lower()
213
+
214
+ mask = df["text_for_keyword_lower"].str.contains(q, na=False)
215
+ hits = df[mask].copy()
216
+
217
+ if hits.empty:
218
+ return []
219
+
220
+ # Base score column
221
+ hits["score"] = 0.0
222
+
223
+ # +2 if patient_text contains the query
224
+ hits.loc[
225
+ hits["patient_text"].str.lower().str.contains(q, na=False),
226
+ "score"
227
+ ] += 2.0
228
+
229
+ # +1 if doctor_text contains the query
230
+ hits.loc[
231
+ hits["doctor_text"].str.lower().str.contains(q, na=False),
232
+ "score"
233
+ ] += 1.0
234
+
235
+ # Length penalty: shorter text_for_keyword is preferred
236
+ hits["length_penalty"] = hits["text_for_keyword"].str.len()
237
+
238
+ hits = hits.sort_values(
239
+ by=["score", "length_penalty"],
240
+ ascending=[False, True],
241
+ ).head(top_k)
242
+
243
+ results: List[Dict[str, Any]] = []
244
+ for _, row in hits.iterrows():
245
+ results.append(
246
+ {
247
+ "conversation_id": str(row["conversation_id"]),
248
+ "description": str(row.get("description", "")),
249
+ "patient_text": str(row.get("patient_text", "")),
250
+ "doctor_text": str(row.get("doctor_text", "")),
251
+ "score": float(row["score"]),
252
+ }
253
+ )
254
+ return results
255
+
256
+
257
+ # ======================= PUBLIC TOOL FUNCTIONS =======================
258
+
259
+ def search_conversations_semantic_tool(
260
+ query: str,
261
+ top_k: int = 5,
262
+ data_path: str = "conversations_clean.csv",
263
+ index_path: str = "conversation_vectors.index",
264
+ ) -> List[Dict[str, Any]]:
265
+ """
266
+ LLM TOOL #1: Semantic (vector) search.
267
+
268
+ Args:
269
+ query: User's natural-language question (any language).
270
+ top_k: Number of most similar conversations to retrieve.
271
+ data_path: Path to the cleaned conversations CSV file.
272
+ index_path: Path to the FAISS index file.
273
+
274
+ Returns:
275
+ A list of dicts, each with:
276
+ - conversation_id: str
277
+ - description: str
278
+ - patient_text: str
279
+ - doctor_text: str
280
+ - score: float (similarity score; larger = more similar)
281
+ """
282
+ if not query or not query.strip():
283
+ return []
284
+
285
+ _ensure_data_loaded(data_path)
286
+ _ensure_index_loaded(index_path)
287
+
288
+ assert _GLOBAL_DF is not None
289
+ assert _GLOBAL_INDEX is not None
290
+
291
+ return _semantic_search_core(
292
+ index=_GLOBAL_INDEX,
293
+ df=_GLOBAL_DF,
294
+ query=query.strip(),
295
+ top_k=top_k,
296
+ )
297
+
298
+
299
+ def search_conversations_keyword_tool(
300
+ query: str,
301
+ top_k: int = 5,
302
+ data_path: str = "conversations_clean.csv",
303
+ ) -> List[Dict[str, Any]]:
304
+ """
305
+ LLM TOOL #2: Keyword search.
306
+
307
+ Args:
308
+ query: User's keyword query or phrase (any language).
309
+ top_k: Number of top results to return.
310
+ data_path: Path to the cleaned conversations CSV file.
311
+
312
+ Returns:
313
+ A list of dicts, each with:
314
+ - conversation_id: str
315
+ - description: str
316
+ - patient_text: str
317
+ - doctor_text: str
318
+ - score: float (simple keyword-based score)
319
+ """
320
+ if not query or not query.strip():
321
+ return []
322
+
323
+ _ensure_data_loaded(data_path)
324
+ assert _GLOBAL_DF is not None
325
+
326
+ return _keyword_search_core(
327
+ df=_GLOBAL_DF,
328
+ query=query.strip(),
329
+ top_k=top_k,
330
+ )
331
+
332
+
333
+ # ======================= CLI helpers (optional) =======================
334
+
335
+ def _pretty_print_results(results: List[Dict[str, Any]], title: str = "Results") -> None:
336
+ if not results:
337
+ print("No results found.")
338
+ return
339
+
340
+ print(f"\n=== {title} ===")
341
+ for i, item in enumerate(results, start=1):
342
+ print(f"\n[{i}] conversation_id = {item['conversation_id']}")
343
+ print(f"Score: {item['score']:.4f}")
344
+ if item["description"]:
345
+ print(f"Description: {item['description']}")
346
+ print(f"Patient: {item['patient_text']}")
347
+ print(f"Doctor: {item['doctor_text']}")
348
+ print(f"\n{'=' * 30}\n")
349
+
350
+
351
+ def main():
352
+ parser = argparse.ArgumentParser(
353
+ description=(
354
+ "Combined search tools over cleaned doctor-patient conversations. "
355
+ "Mode can be 'semantic' (vector search) or 'keyword'."
356
+ )
357
+ )
358
+ parser.add_argument(
359
+ "--mode",
360
+ type=str,
361
+ choices=["semantic", "keyword"],
362
+ default="semantic",
363
+ help="Search mode: 'semantic' (vector FAISS) or 'keyword'. Default: semantic",
364
+ )
365
+ parser.add_argument(
366
+ "--data",
367
+ type=str,
368
+ default="conversations_clean.csv",
369
+ help="Path to cleaned CSV file. Default: conversations_clean.csv",
370
+ )
371
+ parser.add_argument(
372
+ "--index",
373
+ type=str,
374
+ default="conversation_vectors.index",
375
+ help="Path to FAISS index file (semantic mode only).",
376
+ )
377
+ parser.add_argument(
378
+ "--top_k",
379
+ type=int,
380
+ default=5,
381
+ help="Number of top results to show. Default: 5",
382
+ )
383
+ parser.add_argument(
384
+ "--query",
385
+ type=str,
386
+ default=None,
387
+ help="Optional single query (non-interactive). "
388
+ "If omitted, run in interactive loop.",
389
+ )
390
+
391
+ args = parser.parse_args()
392
+
393
+ _ensure_data_loaded(args.data)
394
+ if args.mode == "semantic":
395
+ _ensure_index_loaded(args.index)
396
+
397
+ if args.query:
398
+ # Non-interactive: single query
399
+ if args.mode == "semantic":
400
+ results = search_conversations_semantic_tool(
401
+ query=args.query,
402
+ top_k=args.top_k,
403
+ data_path=args.data,
404
+ index_path=args.index,
405
+ )
406
+ _pretty_print_results(results, title="Semantic Search Results")
407
+ else:
408
+ results = search_conversations_keyword_tool(
409
+ query=args.query,
410
+ top_k=args.top_k,
411
+ data_path=args.data,
412
+ )
413
+ _pretty_print_results(results, title="Keyword Search Results")
414
+ return
415
+
416
+ # Interactive loop
417
+ print(f"{args.mode.capitalize()} search is ready.")
418
+ print("Type your query and press Enter to search.")
419
+ print("Type 'q' or empty line to exit.\n")
420
+
421
+ while True:
422
+ try:
423
+ query = input("Query> ").strip()
424
+ except (KeyboardInterrupt, EOFError):
425
+ print("\nExiting.")
426
+ break
427
+
428
+ if query == "" or query.lower() == "q":
429
+ print("Bye.")
430
+ break
431
+
432
+ if args.mode == "semantic":
433
+ results = search_conversations_semantic_tool(
434
+ query=query,
435
+ top_k=args.top_k,
436
+ data_path=args.data,
437
+ index_path=args.index,
438
+ )
439
+ _pretty_print_results(results, title="Semantic Search Results")
440
+ else:
441
+ results = search_conversations_keyword_tool(
442
+ query=query,
443
+ top_k=args.top_k,
444
+ data_path=args.data,
445
+ )
446
+ _pretty_print_results(results, title="Keyword Search Results")
447
+
448
+
449
+ if __name__ == "__main__":
450
+ main()