|
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
conversation_search_tools.py
|
|
|
|
|
|
This module combines TWO search tools over the same cleaned
|
|
|
doctor–patient conversation dataset:
|
|
|
|
|
|
1. Semantic (vector) search using FAISS + embeddings.
|
|
|
2. Keyword search using simple substring matching + scoring.
|
|
|
|
|
|
It is designed to be used both:
|
|
|
|
|
|
- As a library/module for LLM tools:
|
|
|
- search_conversations_semantic_tool(...)
|
|
|
- search_conversations_keyword_tool(...)
|
|
|
|
|
|
- And as a local CLI for debugging:
|
|
|
python conversation_search_tools.py --mode semantic
|
|
|
python conversation_search_tools.py --mode keyword
|
|
|
"""
|
|
|
|
|
|
import argparse
|
|
|
import os
|
|
|
from typing import List, Dict, Any, Optional
|
|
|
|
|
|
import numpy as np
|
|
|
import pandas as pd
|
|
|
import faiss
|
|
|
|
|
|
try:
|
|
|
from openai import OpenAI
|
|
|
client = OpenAI()
|
|
|
except ImportError:
|
|
|
client = None
|
|
|
|
|
|
|
|
|
|
|
|
EMBEDDING_MODEL = "text-embedding-3-small"
|
|
|
|
|
|
|
|
|
_GLOBAL_DF: Optional[pd.DataFrame] = None
|
|
|
_GLOBAL_DATA_PATH: Optional[str] = None
|
|
|
|
|
|
_GLOBAL_INDEX: Optional[faiss.Index] = None
|
|
|
_GLOBAL_INDEX_PATH: Optional[str] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _load_data_internal(data_path: str) -> pd.DataFrame:
|
|
|
"""
|
|
|
Low-level function to load the cleaned CSV file.
|
|
|
It does NOT enforce keyword-specific columns here; those are checked
|
|
|
in the keyword tool function.
|
|
|
"""
|
|
|
if not os.path.exists(data_path):
|
|
|
raise FileNotFoundError(f"Data CSV not found: {data_path}")
|
|
|
|
|
|
df = pd.read_csv(data_path)
|
|
|
|
|
|
|
|
|
base_required_cols = [
|
|
|
"conversation_id",
|
|
|
"description",
|
|
|
"patient_text",
|
|
|
"doctor_text",
|
|
|
]
|
|
|
for col in base_required_cols:
|
|
|
if col not in df.columns:
|
|
|
raise ValueError(
|
|
|
f"Required column '{col}' not in CSV. "
|
|
|
f"Available columns: {list(df.columns)}"
|
|
|
)
|
|
|
|
|
|
|
|
|
df = df.reset_index(drop=True)
|
|
|
return df
|
|
|
|
|
|
|
|
|
def _ensure_data_loaded(data_path: str) -> None:
|
|
|
"""
|
|
|
Ensure that the global DataFrame is loaded into memory.
|
|
|
Reload if the path changes.
|
|
|
"""
|
|
|
global _GLOBAL_DF, _GLOBAL_DATA_PATH
|
|
|
|
|
|
if _GLOBAL_DF is None or _GLOBAL_DATA_PATH != data_path:
|
|
|
_GLOBAL_DF = _load_data_internal(data_path)
|
|
|
_GLOBAL_DATA_PATH = data_path
|
|
|
|
|
|
|
|
|
def _load_index_internal(index_path: str) -> faiss.Index:
|
|
|
"""
|
|
|
Low-level function to load the FAISS index from disk.
|
|
|
"""
|
|
|
if not os.path.exists(index_path):
|
|
|
raise FileNotFoundError(f"FAISS index file not found: {index_path}")
|
|
|
index = faiss.read_index(index_path)
|
|
|
return index
|
|
|
|
|
|
|
|
|
def _ensure_index_loaded(index_path: str) -> None:
|
|
|
"""
|
|
|
Ensure that the global FAISS index is loaded into memory.
|
|
|
Reload if the path changes.
|
|
|
"""
|
|
|
global _GLOBAL_INDEX, _GLOBAL_INDEX_PATH
|
|
|
|
|
|
if _GLOBAL_INDEX is None or _GLOBAL_INDEX_PATH != index_path:
|
|
|
_GLOBAL_INDEX = _load_index_internal(index_path)
|
|
|
_GLOBAL_INDEX_PATH = index_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def embed_query(query: str) -> np.ndarray:
|
|
|
"""
|
|
|
Convert a text query into an embedding vector (float32 numpy array).
|
|
|
|
|
|
By default this uses OpenAI embeddings. You can replace this with any
|
|
|
other embedding backend as long as you keep the same dimension and
|
|
|
normalization as when the FAISS index was built.
|
|
|
"""
|
|
|
if client is None:
|
|
|
raise RuntimeError(
|
|
|
"OpenAI client not available. "
|
|
|
"Install `openai` and set OPENAI_API_KEY, or modify "
|
|
|
"embed_query() to use your own embedding model."
|
|
|
)
|
|
|
|
|
|
resp = client.embeddings.create(
|
|
|
model=EMBEDDING_MODEL,
|
|
|
input=[query]
|
|
|
)
|
|
|
emb = np.array(resp.data[0].embedding, dtype="float32")
|
|
|
|
|
|
faiss.normalize_L2(emb.reshape(1, -1))
|
|
|
return emb
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _semantic_search_core(
|
|
|
index: faiss.Index,
|
|
|
df: pd.DataFrame,
|
|
|
query: str,
|
|
|
top_k: int = 5,
|
|
|
) -> List[Dict[str, Any]]:
|
|
|
"""
|
|
|
Run vector search in FAISS to find conversations semantically
|
|
|
similar to the query.
|
|
|
"""
|
|
|
if not query:
|
|
|
return []
|
|
|
|
|
|
q_emb = embed_query(query)
|
|
|
q_emb = q_emb.reshape(1, -1)
|
|
|
|
|
|
scores, indices = index.search(q_emb, top_k)
|
|
|
scores = scores[0]
|
|
|
indices = indices[0]
|
|
|
|
|
|
results: List[Dict[str, Any]] = []
|
|
|
for idx, score in zip(indices, scores):
|
|
|
if idx < 0:
|
|
|
continue
|
|
|
row = df.iloc[idx]
|
|
|
results.append(
|
|
|
{
|
|
|
"conversation_id": str(row["conversation_id"]),
|
|
|
"description": str(row.get("description", "")),
|
|
|
"patient_text": str(row.get("patient_text", "")),
|
|
|
"doctor_text": str(row.get("doctor_text", "")),
|
|
|
"score": float(score),
|
|
|
}
|
|
|
)
|
|
|
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _keyword_search_core(
|
|
|
df: pd.DataFrame,
|
|
|
query: str,
|
|
|
top_k: int = 5,
|
|
|
) -> List[Dict[str, Any]]:
|
|
|
"""
|
|
|
Perform simple keyword-based search over the "text_for_keyword_lower"
|
|
|
column, then score and rank results.
|
|
|
|
|
|
Ranking priorities:
|
|
|
1. Whether patient_text contains the query (case-insensitive).
|
|
|
2. Whether doctor_text contains the query (case-insensitive).
|
|
|
3. Shorter text_for_keyword is ranked slightly higher.
|
|
|
"""
|
|
|
if not query:
|
|
|
return []
|
|
|
|
|
|
required_cols = [
|
|
|
"text_for_keyword",
|
|
|
"text_for_keyword_lower",
|
|
|
]
|
|
|
for col in required_cols:
|
|
|
if col not in df.columns:
|
|
|
raise ValueError(
|
|
|
f"Required column '{col}' for keyword search is missing. "
|
|
|
f"Available columns: {list(df.columns)}"
|
|
|
)
|
|
|
|
|
|
q = query.lower()
|
|
|
|
|
|
mask = df["text_for_keyword_lower"].str.contains(q, na=False)
|
|
|
hits = df[mask].copy()
|
|
|
|
|
|
if hits.empty:
|
|
|
return []
|
|
|
|
|
|
|
|
|
hits["score"] = 0.0
|
|
|
|
|
|
|
|
|
hits.loc[
|
|
|
hits["patient_text"].str.lower().str.contains(q, na=False),
|
|
|
"score"
|
|
|
] += 2.0
|
|
|
|
|
|
|
|
|
hits.loc[
|
|
|
hits["doctor_text"].str.lower().str.contains(q, na=False),
|
|
|
"score"
|
|
|
] += 1.0
|
|
|
|
|
|
|
|
|
hits["length_penalty"] = hits["text_for_keyword"].str.len()
|
|
|
|
|
|
hits = hits.sort_values(
|
|
|
by=["score", "length_penalty"],
|
|
|
ascending=[False, True],
|
|
|
).head(top_k)
|
|
|
|
|
|
results: List[Dict[str, Any]] = []
|
|
|
for _, row in hits.iterrows():
|
|
|
results.append(
|
|
|
{
|
|
|
"conversation_id": str(row["conversation_id"]),
|
|
|
"description": str(row.get("description", "")),
|
|
|
"patient_text": str(row.get("patient_text", "")),
|
|
|
"doctor_text": str(row.get("doctor_text", "")),
|
|
|
"score": float(row["score"]),
|
|
|
}
|
|
|
)
|
|
|
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def search_conversations_semantic_tool(
|
|
|
query: str,
|
|
|
top_k: int = 5,
|
|
|
data_path: str = "conversations_clean.csv",
|
|
|
index_path: str = "conversation_vectors.index",
|
|
|
) -> List[Dict[str, Any]]:
|
|
|
"""
|
|
|
LLM TOOL #1: Semantic (vector) search.
|
|
|
|
|
|
Args:
|
|
|
query: User's natural-language question (any language).
|
|
|
top_k: Number of most similar conversations to retrieve.
|
|
|
data_path: Path to the cleaned conversations CSV file.
|
|
|
index_path: Path to the FAISS index file.
|
|
|
|
|
|
Returns:
|
|
|
A list of dicts, each with:
|
|
|
- conversation_id: str
|
|
|
- description: str
|
|
|
- patient_text: str
|
|
|
- doctor_text: str
|
|
|
- score: float (similarity score; larger = more similar)
|
|
|
"""
|
|
|
if not query or not query.strip():
|
|
|
return []
|
|
|
|
|
|
_ensure_data_loaded(data_path)
|
|
|
_ensure_index_loaded(index_path)
|
|
|
|
|
|
assert _GLOBAL_DF is not None
|
|
|
assert _GLOBAL_INDEX is not None
|
|
|
|
|
|
return _semantic_search_core(
|
|
|
index=_GLOBAL_INDEX,
|
|
|
df=_GLOBAL_DF,
|
|
|
query=query.strip(),
|
|
|
top_k=top_k,
|
|
|
)
|
|
|
|
|
|
|
|
|
def search_conversations_keyword_tool(
|
|
|
query: str,
|
|
|
top_k: int = 5,
|
|
|
data_path: str = "conversations_clean.csv",
|
|
|
) -> List[Dict[str, Any]]:
|
|
|
"""
|
|
|
LLM TOOL #2: Keyword search.
|
|
|
|
|
|
Args:
|
|
|
query: User's keyword query or phrase (any language).
|
|
|
top_k: Number of top results to return.
|
|
|
data_path: Path to the cleaned conversations CSV file.
|
|
|
|
|
|
Returns:
|
|
|
A list of dicts, each with:
|
|
|
- conversation_id: str
|
|
|
- description: str
|
|
|
- patient_text: str
|
|
|
- doctor_text: str
|
|
|
- score: float (simple keyword-based score)
|
|
|
"""
|
|
|
if not query or not query.strip():
|
|
|
return []
|
|
|
|
|
|
_ensure_data_loaded(data_path)
|
|
|
assert _GLOBAL_DF is not None
|
|
|
|
|
|
return _keyword_search_core(
|
|
|
df=_GLOBAL_DF,
|
|
|
query=query.strip(),
|
|
|
top_k=top_k,
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _pretty_print_results(results: List[Dict[str, Any]], title: str = "Results") -> None:
|
|
|
if not results:
|
|
|
print("No results found.")
|
|
|
return
|
|
|
|
|
|
print(f"\n=== {title} ===")
|
|
|
for i, item in enumerate(results, start=1):
|
|
|
print(f"\n[{i}] conversation_id = {item['conversation_id']}")
|
|
|
print(f"Score: {item['score']:.4f}")
|
|
|
if item["description"]:
|
|
|
print(f"Description: {item['description']}")
|
|
|
print(f"Patient: {item['patient_text']}")
|
|
|
print(f"Doctor: {item['doctor_text']}")
|
|
|
print(f"\n{'=' * 30}\n")
|
|
|
|
|
|
|
|
|
def main():
|
|
|
parser = argparse.ArgumentParser(
|
|
|
description=(
|
|
|
"Combined search tools over cleaned doctor-patient conversations. "
|
|
|
"Mode can be 'semantic' (vector search) or 'keyword'."
|
|
|
)
|
|
|
)
|
|
|
parser.add_argument(
|
|
|
"--mode",
|
|
|
type=str,
|
|
|
choices=["semantic", "keyword"],
|
|
|
default="semantic",
|
|
|
help="Search mode: 'semantic' (vector FAISS) or 'keyword'. Default: semantic",
|
|
|
)
|
|
|
parser.add_argument(
|
|
|
"--data",
|
|
|
type=str,
|
|
|
default="conversations_clean.csv",
|
|
|
help="Path to cleaned CSV file. Default: conversations_clean.csv",
|
|
|
)
|
|
|
parser.add_argument(
|
|
|
"--index",
|
|
|
type=str,
|
|
|
default="conversation_vectors.index",
|
|
|
help="Path to FAISS index file (semantic mode only).",
|
|
|
)
|
|
|
parser.add_argument(
|
|
|
"--top_k",
|
|
|
type=int,
|
|
|
default=5,
|
|
|
help="Number of top results to show. Default: 5",
|
|
|
)
|
|
|
parser.add_argument(
|
|
|
"--query",
|
|
|
type=str,
|
|
|
default=None,
|
|
|
help="Optional single query (non-interactive). "
|
|
|
"If omitted, run in interactive loop.",
|
|
|
)
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
_ensure_data_loaded(args.data)
|
|
|
if args.mode == "semantic":
|
|
|
_ensure_index_loaded(args.index)
|
|
|
|
|
|
if args.query:
|
|
|
|
|
|
if args.mode == "semantic":
|
|
|
results = search_conversations_semantic_tool(
|
|
|
query=args.query,
|
|
|
top_k=args.top_k,
|
|
|
data_path=args.data,
|
|
|
index_path=args.index,
|
|
|
)
|
|
|
_pretty_print_results(results, title="Semantic Search Results")
|
|
|
else:
|
|
|
results = search_conversations_keyword_tool(
|
|
|
query=args.query,
|
|
|
top_k=args.top_k,
|
|
|
data_path=args.data,
|
|
|
)
|
|
|
_pretty_print_results(results, title="Keyword Search Results")
|
|
|
return
|
|
|
|
|
|
|
|
|
print(f"{args.mode.capitalize()} search is ready.")
|
|
|
print("Type your query and press Enter to search.")
|
|
|
print("Type 'q' or empty line to exit.\n")
|
|
|
|
|
|
while True:
|
|
|
try:
|
|
|
query = input("Query> ").strip()
|
|
|
except (KeyboardInterrupt, EOFError):
|
|
|
print("\nExiting.")
|
|
|
break
|
|
|
|
|
|
if query == "" or query.lower() == "q":
|
|
|
print("Bye.")
|
|
|
break
|
|
|
|
|
|
if args.mode == "semantic":
|
|
|
results = search_conversations_semantic_tool(
|
|
|
query=query,
|
|
|
top_k=args.top_k,
|
|
|
data_path=args.data,
|
|
|
index_path=args.index,
|
|
|
)
|
|
|
_pretty_print_results(results, title="Semantic Search Results")
|
|
|
else:
|
|
|
results = search_conversations_keyword_tool(
|
|
|
query=query,
|
|
|
top_k=args.top_k,
|
|
|
data_path=args.data,
|
|
|
)
|
|
|
_pretty_print_results(results, title="Keyword Search Results")
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
main() |