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
|
|
|
|
|
|
|
| 1 |
+
# file: medical_agent_with_tools.py
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
End-to-end medical QA agent using OpenAI tools:
|
| 6 |
+
|
| 7 |
+
- Model sees two tools:
|
| 8 |
+
- search_conversations_semantic_tool
|
| 9 |
+
- search_conversations_keyword_tool
|
| 10 |
+
- Model decides which tool(s) to call and with what query.
|
| 11 |
+
- We execute the tools locally using conversation_search_tools.py,
|
| 12 |
+
then send results back to the model.
|
| 13 |
+
- Finally, the model returns a natural-language answer.
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
python medical_agent_with_tools.py
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import textwrap
|
| 21 |
+
from typing import Any, Dict, List
|
| 22 |
+
|
| 23 |
+
from dotenv import load_dotenv
|
| 24 |
+
from openai import OpenAI
|
| 25 |
+
|
| 26 |
+
from conversation_search_tools import (
|
| 27 |
+
search_conversations_semantic_tool,
|
| 28 |
+
search_conversations_keyword_tool,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# 1. Load environment variables (OPENAI_API_KEY, etc.)
|
| 32 |
+
load_dotenv()
|
| 33 |
+
|
| 34 |
+
# 2. Initialize OpenAI client
|
| 35 |
+
client = OpenAI()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ===================== TOOL SCHEMA FOR OPENAI =====================
|
| 39 |
+
|
| 40 |
+
# IMPORTANT:
|
| 41 |
+
# For the Responses API, custom tools must use this shape:
|
| 42 |
+
# {
|
| 43 |
+
# "type": "function",
|
| 44 |
+
# "name": "<tool_name>",
|
| 45 |
+
# "description": "...",
|
| 46 |
+
# "parameters": { ... JSON schema ... }
|
| 47 |
+
# }
|
| 48 |
+
# DO NOT wrap name/parameters inside an extra "function": { ... } layer,
|
| 49 |
+
# otherwise you'll get: "Missing required parameter: 'tools[0].name'."
|
| 50 |
+
|
| 51 |
+
TOOLS = [
|
| 52 |
+
{
|
| 53 |
+
"type": "function",
|
| 54 |
+
"name": "search_conversations_semantic_tool",
|
| 55 |
+
"description": (
|
| 56 |
+
"Perform semantic (vector) search over a database of "
|
| 57 |
+
"cleaned doctor–patient conversations using embeddings "
|
| 58 |
+
"and a FAISS index. Good for broad, fuzzy, or paraphrased "
|
| 59 |
+
"queries; returns conceptually similar cases."
|
| 60 |
+
),
|
| 61 |
+
"parameters": {
|
| 62 |
+
"type": "object",
|
| 63 |
+
"properties": {
|
| 64 |
+
"query": {
|
| 65 |
+
"type": "string",
|
| 66 |
+
"description": "The user's question or search query in natural language."
|
| 67 |
+
},
|
| 68 |
+
"top_k": {
|
| 69 |
+
"type": "integer",
|
| 70 |
+
"description": "Number of most similar conversations to retrieve.",
|
| 71 |
+
"default": 5
|
| 72 |
+
},
|
| 73 |
+
"data_path": {
|
| 74 |
+
"type": "string",
|
| 75 |
+
"description": (
|
| 76 |
+
"Path to the cleaned conversation CSV file. "
|
| 77 |
+
"Usually 'conversations_clean.csv'."
|
| 78 |
+
),
|
| 79 |
+
"default": "conversations_clean.csv"
|
| 80 |
+
},
|
| 81 |
+
"index_path": {
|
| 82 |
+
"type": "string",
|
| 83 |
+
"description": (
|
| 84 |
+
"Path to the FAISS index file. "
|
| 85 |
+
"Usually 'conversation_vectors.index'."
|
| 86 |
+
),
|
| 87 |
+
"default": "conversation_vectors.index"
|
| 88 |
+
},
|
| 89 |
+
},
|
| 90 |
+
"required": ["query"],
|
| 91 |
+
},
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"type": "function",
|
| 95 |
+
"name": "search_conversations_keyword_tool",
|
| 96 |
+
"description": (
|
| 97 |
+
"Perform keyword-based search over a preprocessed text "
|
| 98 |
+
"field in the same doctor–patient conversation database. "
|
| 99 |
+
"Good for exact or very specific terms (e.g., drug names, "
|
| 100 |
+
"test names, diagnoses). Returns conversations where the "
|
| 101 |
+
"query text appears directly."
|
| 102 |
+
),
|
| 103 |
+
"parameters": {
|
| 104 |
+
"type": "object",
|
| 105 |
+
"properties": {
|
| 106 |
+
"query": {
|
| 107 |
+
"type": "string",
|
| 108 |
+
"description": "The keyword or phrase to search for."
|
| 109 |
+
},
|
| 110 |
+
"top_k": {
|
| 111 |
+
"type": "integer",
|
| 112 |
+
"description": "Number of top results to return.",
|
| 113 |
+
"default": 5
|
| 114 |
+
},
|
| 115 |
+
"data_path": {
|
| 116 |
+
"type": "string",
|
| 117 |
+
"description": (
|
| 118 |
+
"Path to the cleaned conversation CSV file. "
|
| 119 |
+
"Usually 'conversations_clean.csv'."
|
| 120 |
+
),
|
| 121 |
+
"default": "conversations_clean.csv"
|
| 122 |
+
},
|
| 123 |
+
},
|
| 124 |
+
"required": ["query"],
|
| 125 |
+
},
|
| 126 |
+
},
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
SYSTEM_PROMPT = """
|
| 131 |
+
You are an AI medical assistant acting in the role of a careful, evidence-based doctor.
|
| 132 |
+
Your job is to help patients (the users) understand their symptoms, possible causes, and
|
| 133 |
+
reasonable next steps, using safe medical reasoning and the tools you have access to.
|
| 134 |
+
|
| 135 |
+
Identity and constraints:
|
| 136 |
+
- You are NOT a real human doctor, and you do NOT have access to physical examination,
|
| 137 |
+
lab tests, or the patient’s full medical record.
|
| 138 |
+
- You must never present yourself as a licensed, personal physician for the user.
|
| 139 |
+
- You must not give definitive diagnoses or prescribe/adjust medications.
|
| 140 |
+
- You must always encourage users to seek in-person medical care for serious, unclear,
|
| 141 |
+
or persistent symptoms, and for any emergency situations.
|
| 142 |
+
|
| 143 |
+
High-level task:
|
| 144 |
+
- Your main objective is to:
|
| 145 |
+
1) Clarify the patient’s problem and context.
|
| 146 |
+
2) Retrieve relevant example doctor–patient conversations from the database using the tools.
|
| 147 |
+
3) Use those examples plus your own medical knowledge to explain possible causes,
|
| 148 |
+
risks, and sensible next steps (self-care, when to see a doctor, what to discuss with them).
|
| 149 |
+
4) Communicate in a clear, empathetic, and structured way.
|
| 150 |
+
- You should always balance informativeness with safety and uncertainty: explain what is
|
| 151 |
+
likely, what is possible, and what cannot be reliably determined online.
|
| 152 |
+
|
| 153 |
+
Tooling:
|
| 154 |
+
You have access to two tools for searching a database of cleaned doctor–patient conversations:
|
| 155 |
+
|
| 156 |
+
1. search_conversations_semantic_tool
|
| 157 |
+
- Performs semantic (vector) search using embeddings and a FAISS index.
|
| 158 |
+
- Good for broad, fuzzy, or paraphrased queries.
|
| 159 |
+
- Returns conversations that are conceptually similar to the user’s
|
| 160 |
+
question, even if they use different wording.
|
| 161 |
+
|
| 162 |
+
2. search_conversations_keyword_tool
|
| 163 |
+
- Performs keyword-based search on a preprocessed text field.
|
| 164 |
+
- Good for exact or very specific terms (e.g., drug names, test
|
| 165 |
+
names, diagnoses).
|
| 166 |
+
- Returns conversations where the query text appears directly.
|
| 167 |
+
|
| 168 |
+
When the user asks medical questions, wants similar cases, or wants to
|
| 169 |
+
see example doctor–patient dialogs:
|
| 170 |
+
|
| 171 |
+
- If the query is broad or uses free natural language, prefer
|
| 172 |
+
search_conversations_semantic_tool.
|
| 173 |
+
- If the query contains a specific term that should appear literally in
|
| 174 |
+
the text (e.g. “metformin”, “ANA test”), consider calling
|
| 175 |
+
search_conversations_keyword_tool, possibly in addition to the
|
| 176 |
+
semantic tool.
|
| 177 |
+
|
| 178 |
+
Your workflow:
|
| 179 |
+
1. Understand the user’s problem:
|
| 180 |
+
- Read the user’s question carefully.
|
| 181 |
+
- If the question is unclear, briefly restate what you think they are asking
|
| 182 |
+
and focus on the medically relevant parts.
|
| 183 |
+
2. Choose tools:
|
| 184 |
+
- Decide whether to call search_conversations_semantic_tool,
|
| 185 |
+
search_conversations_keyword_tool, or both, based on the query type.
|
| 186 |
+
3. Retrieve examples:
|
| 187 |
+
- Call the tools with the user’s query.
|
| 188 |
+
- Examine patient_text and doctor_text in the results.
|
| 189 |
+
4. Reason and synthesize:
|
| 190 |
+
- Combine information from the retrieved conversations with your general
|
| 191 |
+
medical knowledge.
|
| 192 |
+
- Think through possible explanations and risks.
|
| 193 |
+
- Distinguish between likely, less likely, and dangerous possibilities.
|
| 194 |
+
5. Respond to the user:
|
| 195 |
+
- Answer in your own words. Be clear, structured, and cautious.
|
| 196 |
+
- If you quote from the retrieved dialogs, clearly say it is from an
|
| 197 |
+
example conversation in the database.
|
| 198 |
+
- Give practical next-step advice (e.g., self-care measures, what to
|
| 199 |
+
monitor, when to see a doctor, when to seek emergency care).
|
| 200 |
+
6. Safety reminders:
|
| 201 |
+
- Never treat retrieved dialogs as definitive medical advice for the
|
| 202 |
+
current user.
|
| 203 |
+
- Always recommend seeing a real doctor for diagnosis, treatment decisions,
|
| 204 |
+
or urgent symptoms (such as severe pain, difficulty breathing, chest pain,
|
| 205 |
+
confusion, loss of consciousness, or bleeding that won’t stop).
|
| 206 |
+
|
| 207 |
+
""".strip()
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# ===================== TOOL EXECUTION LOGIC =====================
|
| 212 |
+
|
| 213 |
+
def call_local_tool(name: str, arguments: Dict[str, Any]) -> Any:
|
| 214 |
+
"""
|
| 215 |
+
Execute the requested tool locally using our Python implementations.
|
| 216 |
+
"""
|
| 217 |
+
if name == "search_conversations_semantic_tool":
|
| 218 |
+
return search_conversations_semantic_tool(
|
| 219 |
+
query=arguments.get("query", ""),
|
| 220 |
+
top_k=arguments.get("top_k", 5),
|
| 221 |
+
data_path=arguments.get("data_path", "conversations_clean.csv"),
|
| 222 |
+
index_path=arguments.get("index_path", "conversation_vectors.index"),
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
elif name == "search_conversations_keyword_tool":
|
| 226 |
+
return search_conversations_keyword_tool(
|
| 227 |
+
query=arguments.get("query", ""),
|
| 228 |
+
top_k=arguments.get("top_k", 5),
|
| 229 |
+
data_path=arguments.get("data_path", "conversations_clean.csv"),
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
else:
|
| 233 |
+
raise ValueError(f"Unknown tool name: {name}")
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def run_agent_once(user_question: str, model: str = "gpt-5.1") -> str:
|
| 237 |
+
"""
|
| 238 |
+
Full tool-calling loop for a single user question.
|
| 239 |
+
|
| 240 |
+
Steps:
|
| 241 |
+
1. Send user question + tools + system prompt to OpenAI.
|
| 242 |
+
2. If model decides to call tools, we:
|
| 243 |
+
- parse tool calls
|
| 244 |
+
- execute tools locally
|
| 245 |
+
- send tool results back as new input
|
| 246 |
+
3. Repeat until model returns a final text answer.
|
| 247 |
+
"""
|
| 248 |
+
# Conversation state for Responses API: a list of turns
|
| 249 |
+
messages: List[Dict[str, Any]] = [
|
| 250 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 251 |
+
{"role": "user", "content": user_question},
|
| 252 |
+
]
|
| 253 |
+
|
| 254 |
+
while True:
|
| 255 |
+
# 1) Call OpenAI with current messages + tools
|
| 256 |
+
response = client.responses.create(
|
| 257 |
+
model=model,
|
| 258 |
+
input=messages,
|
| 259 |
+
tools=TOOLS,
|
| 260 |
+
# tool_choice 默认为 "auto",可以显式写出:
|
| 261 |
+
# tool_choice="auto",
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
# The responses API returns a structured output
|
| 265 |
+
output_item = response.output[0]
|
| 266 |
+
|
| 267 |
+
# Check if there are tool calls
|
| 268 |
+
tool_calls = getattr(output_item, "tool_calls", None)
|
| 269 |
+
|
| 270 |
+
if tool_calls:
|
| 271 |
+
# 2) The model wants to call one or more tools
|
| 272 |
+
for tool_call in tool_calls:
|
| 273 |
+
# For function tools in Responses API, tool_call.function.name / arguments
|
| 274 |
+
tool_name = tool_call.function.name
|
| 275 |
+
# arguments is a JSON string; we need to parse it
|
| 276 |
+
args = json.loads(tool_call.function.arguments or "{}")
|
| 277 |
+
|
| 278 |
+
try:
|
| 279 |
+
tool_result = call_local_tool(tool_name, args)
|
| 280 |
+
except Exception as e:
|
| 281 |
+
tool_result = {"error": str(e)}
|
| 282 |
+
|
| 283 |
+
# Append the tool result as a new message with role "tool"
|
| 284 |
+
messages.append(
|
| 285 |
+
{
|
| 286 |
+
"role": "tool",
|
| 287 |
+
"name": tool_name,
|
| 288 |
+
"content": json.dumps(tool_result, ensure_ascii=False),
|
| 289 |
+
}
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
# After executing tools, loop will send updated messages again
|
| 293 |
+
continue
|
| 294 |
+
|
| 295 |
+
else:
|
| 296 |
+
# 3) No tool calls → final answer
|
| 297 |
+
# output_item.content is a list of content blocks; we take the first text
|
| 298 |
+
final_text = output_item.content[0].text
|
| 299 |
+
return final_text
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def main():
|
| 303 |
+
print("Medical QA Agent with OpenAI tools & local search")
|
| 304 |
+
print("Type your question and press Enter.")
|
| 305 |
+
print("Empty line or Ctrl+C to exit.\n")
|
| 306 |
+
|
| 307 |
+
while True:
|
| 308 |
+
try:
|
| 309 |
+
q = input("User question> ").strip()
|
| 310 |
+
except (KeyboardInterrupt, EOFError):
|
| 311 |
+
print("\nBye.")
|
| 312 |
+
break
|
| 313 |
+
|
| 314 |
+
if not q:
|
| 315 |
+
print("Bye.")
|
| 316 |
+
break
|
| 317 |
+
|
| 318 |
+
try:
|
| 319 |
+
answer = run_agent_once(q, model="gpt-5.1")
|
| 320 |
+
except Exception as e:
|
| 321 |
+
print("Error:", e)
|
| 322 |
+
continue
|
| 323 |
+
|
| 324 |
+
print("\n=== Final Answer ===\n")
|
| 325 |
+
print(textwrap.fill(answer, width=80))
|
| 326 |
+
print("\n====================\n")
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
if __name__ == "__main__":
|
| 330 |
+
main()
|