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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ # imports
3
+
4
+ import os
5
+ import json
6
+ from dotenv import load_dotenv
7
+ from openai import OpenAI
8
+ import gradio as gr
9
+ import requests
10
+ import urllib.parse
11
+ from datetime import datetime
12
+
13
+ # %%
14
+ # Initialization
15
+
16
+ load_dotenv(override=True)
17
+
18
+ openai_api_key = os.getenv('OPENAI_API_KEY')
19
+ if openai_api_key:
20
+ print(f"OpenAI API Key exists and begins {openai_api_key[:8]}")
21
+ else:
22
+ print("OpenAI API Key not set")
23
+
24
+ MODEL = "gpt-4o-mini"
25
+ openai = OpenAI()
26
+
27
+ # %%
28
+ system_message = (
29
+ "You are a clinical trials assistant that uses the ClinicalTrials.gov API to answer questions. "
30
+ "If the user asks for study data, you must always call the `search_studies` tool. "
31
+ "Only use your own knowledge for greetings or general questions."
32
+ "Always return detailed and structured responses."
33
+ )
34
+
35
+ # %%
36
+ def search_studies(query):
37
+ import urllib.parse
38
+ import requests
39
+
40
+ print("\n==============================")
41
+ print(f"[DEBUG] Received query: {query} (type: {type(query)})")
42
+ print("==============================")
43
+
44
+ if isinstance(query, dict):
45
+ filters = []
46
+ query_parts = []
47
+
48
+ if "query" in query:
49
+ query_string = urllib.parse.quote_plus(query["query"])
50
+ query_parts.append(f"query.cond={query_string}")
51
+
52
+ if "phase" in query:
53
+ filters.append(f"AREA[Phase]{query['phase']}")
54
+ if "country" in query:
55
+ filters.append(f"AREA[LocationCountry]{query['country']}")
56
+ if "study_type" in query:
57
+ filters.append(f"AREA[StudyType]{query['study_type']}")
58
+ if "sex" in query:
59
+ filters.append(f"AREA[Sex]{query['sex']}")
60
+ if "age_group" in query:
61
+ filters.append(f"AREA[StdAge]{query['age_group']}")
62
+ if "status" in query:
63
+ filters.append(f"AREA[OverallStatus]{query['status']}")
64
+ if "sampling_method" in query:
65
+ filters.append(f"AREA[SamplingMethod]{query['sampling_method']}")
66
+ if "ipd_sharing" in query:
67
+ filters.append(f"AREA[IPDSharing]{query['ipd_sharing']}")
68
+
69
+ if "start_date_from" in query:
70
+ filters.append(f"AREA[StartDate]RANGE[{query['start_date_from']},MAX]")
71
+ if "start_date_to" in query:
72
+ filters.append(f"AREA[StartDate]RANGE[MIN,{query['start_date_to']}]")
73
+ if "completion_date_from" in query:
74
+ filters.append(f"AREA[CompletionDate]RANGE[{query['completion_date_from']},MAX]")
75
+ if "completion_date_to" in query:
76
+ filters.append(f"AREA[CompletionDate]RANGE[MIN,{query['completion_date_to']}]")
77
+
78
+ def normalize_sponsor(s):
79
+ for suffix in ["Inc.", "Inc", "Ltd.", "Ltd", "GmbH", "LLC", "Corp.", "Corp"]:
80
+ s = s.replace(suffix, "")
81
+ return s.strip()
82
+
83
+ if "sponsor" in query:
84
+ sponsor_name = normalize_sponsor(query["sponsor"])
85
+ sponsor_string = urllib.parse.quote_plus(sponsor_name)
86
+ query_parts.append(f"query.spons={sponsor_string}")
87
+
88
+ page_size = query.get("max_results", 3)
89
+ if ("city" in query or "facility" in query) and "max_results" not in query:
90
+ page_size = 30 # ensure enough studies for post-filtering
91
+
92
+ filter_advanced = " AND ".join(filters)
93
+ if filter_advanced:
94
+ filter_advanced = f"({filter_advanced})"
95
+ encoded_filter = urllib.parse.quote(filter_advanced, safe="[]*")
96
+
97
+ url = (
98
+ f"https://clinicaltrials.gov/api/v2/studies?"
99
+ f"{'&'.join(query_parts)}"
100
+ f"{f'&filter.advanced={encoded_filter}' if filter_advanced else ''}"
101
+ f"&pageSize={page_size}"
102
+ )
103
+
104
+ else:
105
+ encoded_query = urllib.parse.quote_plus(query)
106
+ url = f"https://clinicaltrials.gov/api/v2/studies?query.cond={encoded_query}&pageSize=3"
107
+
108
+ print("Requesting:", url)
109
+
110
+ try:
111
+ response = requests.get(url)
112
+ print("Status Code:", response.status_code)
113
+
114
+ if response.status_code == 400 and any("query.cond=" in part for part in query_parts):
115
+ print("[⚠️ Fallback] Retrying with query.text instead of query.cond...")
116
+ query_parts = [p.replace("query.cond=", "query.text=") for p in query_parts]
117
+ url = (
118
+ f"https://clinicaltrials.gov/api/v2/studies?"
119
+ f"{'&'.join(query_parts)}"
120
+ f"{f'&filter.advanced={encoded_filter}' if filter_advanced else ''}"
121
+ f"&pageSize={page_size}"
122
+ )
123
+ print("Retrying:", url)
124
+ response = requests.get(url)
125
+ print("Retry Status Code:", response.status_code)
126
+
127
+ if response.status_code == 200:
128
+ data = response.json()
129
+ trials = data.get("studies", [])
130
+ if not trials:
131
+ return "No studies found."
132
+
133
+ def matches(study, key, value):
134
+ section = study.get("protocolSection", {})
135
+ if key == "sponsor":
136
+ return value.lower() in section.get("sponsorCollaboratorsModule", {}).get("leadSponsor", {}).get("name", "").lower()
137
+ elif key == "intervention":
138
+ interventions = section.get("armsInterventionsModule", {}).get("interventions", [])
139
+ return any(value.lower() in i.get("name", "").lower() for i in interventions)
140
+ elif key == "city":
141
+ locs = section.get("contactsLocationsModule", {}).get("locations", [])
142
+ return any(value.lower() in loc.get("city", "").lower() for loc in locs)
143
+ elif key == "facility":
144
+ locs = section.get("contactsLocationsModule", {}).get("locations", [])
145
+ return any(value.lower() in loc.get("facility", "").lower() for loc in locs)
146
+ return True
147
+
148
+ for key in ["sponsor", "intervention", "city", "facility"]:
149
+ if key in query:
150
+ trials = [s for s in trials if matches(s, key, query[key])]
151
+
152
+ if not trials:
153
+ return "No studies found after applying filters."
154
+
155
+ result = []
156
+ for study in trials:
157
+ ps = study.get("protocolSection", {})
158
+ id_module = ps.get("identificationModule", {})
159
+ design_module = ps.get("designModule", {})
160
+ status_module = ps.get("statusModule", {})
161
+ elig_module = ps.get("eligibilityModule", {})
162
+ ipd_module = ps.get("ipdSharingStatementModule", {})
163
+ desc_module = ps.get("descriptionModule", {})
164
+ contact_module = ps.get("contactsLocationsModule", {})
165
+ sponsor_module = ps.get("sponsorCollaboratorsModule", {})
166
+ outcomes_module = ps.get("outcomesModule", {})
167
+ arms_module = ps.get("armsInterventionsModule", {})
168
+
169
+ nct_id = id_module.get("nctId", "N/A")
170
+ title = id_module.get("briefTitle", "No Title")
171
+ official_title = id_module.get("officialTitle", "N/A")
172
+ phases = design_module.get("phases", [])
173
+ study_type = design_module.get("studyType", "N/A")
174
+ status = status_module.get("overallStatus", "N/A")
175
+ start_date = status_module.get("startDateStruct", {}).get("date", "N/A")
176
+ completion_date = status_module.get("completionDateStruct", {}).get("date", "N/A")
177
+ sex = elig_module.get("sex", "N/A")
178
+ std_ages = elig_module.get("stdAges", [])
179
+ sampling_method = elig_module.get("samplingMethod", "N/A")
180
+ criteria = elig_module.get("eligibilityCriteria", "N/A")
181
+ locations = contact_module.get("locations", [])
182
+ countries = sorted({loc.get("country") for loc in locations if loc.get("country")})
183
+
184
+ # Format location info (first 2 entries, truncate the rest)
185
+ location_text_lines = []
186
+ for loc in locations:
187
+ parts = [loc.get("facility"), loc.get("city"), loc.get("state"), loc.get("country")]
188
+ clean = [p for p in parts if p]
189
+ if clean:
190
+ location_text_lines.append(", ".join(clean))
191
+ if location_text_lines:
192
+ if len(location_text_lines) > 3:
193
+ display_lines = location_text_lines[:2]
194
+ location_text = "\n".join(f"- {line}" for line in display_lines)
195
+ location_text += f"\n...and {len(location_text_lines)-2} more site(s)"
196
+ else:
197
+ location_text = "\n".join(f"- {line}" for line in location_text_lines)
198
+ else:
199
+ location_text = "N/A"
200
+
201
+ description = desc_module.get("detailedDescription", "N/A")
202
+ interventions = arms_module.get("interventions", [])
203
+ intervention_names = [iv.get("name", "") for iv in interventions if iv.get("name")]
204
+ intervention_text = ", ".join(intervention_names) if intervention_names else "N/A"
205
+ sponsor = sponsor_module.get("leadSponsor", {}).get("name", "N/A")
206
+ collaborators = sponsor_module.get("collaborators", [])
207
+ collaborator_names = [c.get("name", "") for c in collaborators]
208
+
209
+ result.append(
210
+ f"### πŸ§ͺ {title}\n\n"
211
+ f"**NCT ID:** `{nct_id}`\n"
212
+ f"πŸ”— [View on ClinicalTrials.gov](https://clinicaltrials.gov/study/{nct_id})\n\n"
213
+ f"**Start Date:** {start_date}\n"
214
+ f"**Completion Date:** {completion_date}\n\n"
215
+ f"**Official Title:** {official_title}\n"
216
+ f"**Type:** {study_type.title()}\n"
217
+ f"**Phase:** {', '.join(phases) if phases else 'Not reported'}\n"
218
+ f"**Status:** {status}\n"
219
+ f"**Countries:** {', '.join(countries) if countries else 'N/A'}\n"
220
+ f"**Locations:**\n{location_text}\n"
221
+ f"**Interventions:** {intervention_text}\n"
222
+ f"**Sponsor:** {sponsor}\n"
223
+ f"**Collaborators:** {', '.join(collaborator_names) if collaborator_names else 'None'}\n"
224
+ )
225
+
226
+ return "\n\n---\n\n".join(result).strip()
227
+
228
+ return f"API returned error: {response.status_code}"
229
+
230
+ except Exception as e:
231
+ print("Exception occurred:", e)
232
+ return "Error fetching study data."
233
+
234
+ # %%
235
+ # There's a particular dictionary structure that's required to describe our function:
236
+
237
+ search_function = {
238
+ "name": "search_studies",
239
+ "description": "Search for clinical trials with strict filtering on all key metadata fields such as condition, country, phase, study type, sex, age group, sampling method, sponsor, intervention, locations, start dates, completion dates, etc.",
240
+ "parameters": {
241
+ "type": "object",
242
+ "properties": {
243
+ "query": {
244
+ "type": "string",
245
+ "description": "Condition or keyword to search for. (e.g., 'lung cancer', 'IBD')"
246
+ },
247
+ "phase": {
248
+ "type": "string",
249
+ "description": "Clinical trial phase. (e.g., 'Phase 1', 'Phase 2', 'Phase 3')"
250
+ },
251
+ "status": {
252
+ "type": "string",
253
+ "description": "Recruitment status. (e.g., 'RECRUITING', 'COMPLETED')"
254
+ },
255
+ "country": {
256
+ "type": "string",
257
+ "description": "Country where the trial is conducted. (e.g., 'Italy')"
258
+ },
259
+ "study_type": {
260
+ "type": "string",
261
+ "description": "Type of study. (e.g., 'INTERVENTIONAL', 'OBSERVATIONAL')"
262
+ },
263
+ "sex": {
264
+ "type": "string",
265
+ "description": "Sex eligibility. (e.g., 'Male', 'Female', 'All')"
266
+ },
267
+ "age_group": {
268
+ "type": "string",
269
+ "description": "Standard age group. (e.g., 'CHILD', 'ADULT', 'OLDER_ADULT')"
270
+ },
271
+ "sampling_method": {
272
+ "type": "string",
273
+ "description": "Participant sampling method. (e.g., 'PROBABILITY_SAMPLE', 'NON_PROBABILITY_SAMPLE')"
274
+ },
275
+ "intervention": {
276
+ "type": "string",
277
+ "description": "Intervention or treatment keyword. (e.g., 'aspirin', 'TAE')"
278
+ },
279
+ "sponsor": {
280
+ "type": "string",
281
+ "description": "Name of the lead sponsor or organization. (e.g., 'Pfizer', 'NIH')"
282
+ },
283
+ "ipd_sharing": {
284
+ "type": "string",
285
+ "description": "Will individual participant data (IPD) be shared? (e.g., 'YES', 'NO', 'UND')"
286
+ },
287
+ "city": {
288
+ "type": "string",
289
+ "description": "City where the trial site is located. (e.g., 'Chicago')"
290
+ },
291
+ "facility": {
292
+ "type": "string",
293
+ "description": "Facility or hospital name where trial is conducted. (e.g., 'Mayo Clinic')"
294
+ },
295
+ "start_date_from": {
296
+ "type": "string",
297
+ "description": "Earliest start date allowed (format: YYYY-MM or YYYY-MM-DD)"
298
+ },
299
+ "start_date_to": {
300
+ "type": "string",
301
+ "description": "Latest start date allowed"
302
+ },
303
+ "completion_date_from": {
304
+ "type": "string",
305
+ "description": "Earliest completion date allowed"
306
+ },
307
+ "completion_date_to": {
308
+ "type": "string",
309
+ "description": "Latest completion date allowed"
310
+ },
311
+ "max_results": {
312
+ "type": "integer",
313
+ "description": "Maximum number of studies to return"
314
+ }
315
+ },
316
+ "required": ["query"],
317
+ "additionalProperties": False
318
+ }
319
+ }
320
+
321
+ # %%
322
+ # And this is included in a list of tools:
323
+
324
+ tools = [{"type": "function", "function": search_function}]
325
+
326
+ # %%
327
+ def chat(message, history):
328
+ messages = [{"role": "system", "content": system_message}] + history + [{"role": "user", "content": message}]
329
+
330
+ # πŸ”„ First attempt: try to stream the LLM output
331
+ response_stream = openai.chat.completions.create(
332
+ model=MODEL,
333
+ messages=messages,
334
+ tools=tools,
335
+ tool_choice="auto",
336
+ stream=True
337
+ )
338
+
339
+ full_response = ""
340
+ tool_call_detected = False
341
+
342
+ for chunk in response_stream:
343
+ choice = chunk.choices[0]
344
+ delta = choice.delta
345
+
346
+ # 🧠 Detect tool call request during stream
347
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
348
+ tool_call_detected = True
349
+ break # Exit streaming β€” can't continue past tool call
350
+
351
+ if delta.content:
352
+ full_response += delta.content
353
+ yield full_response # Live stream to user
354
+
355
+ # 🧰 Tool call fallback (non-streamed)
356
+ if tool_call_detected:
357
+ fallback = openai.chat.completions.create(
358
+ model=MODEL,
359
+ messages=messages,
360
+ tools=tools,
361
+ tool_choice="auto" # No stream here, required to get tool_calls
362
+ )
363
+
364
+ message = fallback.choices[0].message
365
+ print("Finish reason:", fallback.choices[0].finish_reason)
366
+ print("Tool calls:", message.tool_calls if hasattr(message, 'tool_calls') else None)
367
+
368
+ # πŸ”§ Call the tool(s)
369
+ tool_responses = handle_tool_call(message)
370
+
371
+ # Add the assistant tool call message and all corresponding tool responses
372
+ messages.append(message)
373
+ messages.extend(tool_responses)
374
+
375
+ # 🧠 Now ask GPT to summarize the tool result(s)
376
+ final_response_stream = openai.chat.completions.create(
377
+ model=MODEL,
378
+ messages=messages,
379
+ stream=True
380
+ )
381
+
382
+ final_output = ""
383
+ for chunk in final_response_stream:
384
+ delta = chunk.choices[0].delta
385
+ if delta.content:
386
+ final_output += delta.content
387
+ yield final_output # Stream final GPT summary
388
+
389
+ # 🧯 Final fallback if nothing streamed
390
+ elif not full_response:
391
+ fallback = openai.chat.completions.create(
392
+ model=MODEL,
393
+ messages=messages,
394
+ tools=tools,
395
+ tool_choice="auto"
396
+ )
397
+ yield fallback.choices[0].message.content
398
+
399
+ # %%
400
+ def handle_tool_call(message):
401
+ import json
402
+
403
+ tool_responses = []
404
+
405
+ for tool_call in message.tool_calls:
406
+ arguments = json.loads(tool_call.function.arguments)
407
+ result = search_studies(arguments)
408
+
409
+ tool_responses.append({
410
+ "role": "tool",
411
+ "tool_call_id": tool_call.id,
412
+ "content": result if isinstance(result, str) else json.dumps(result)
413
+ })
414
+
415
+ return tool_responses
416
+
417
+ # %%
418
+ example_prompts = [
419
+ "Show me trials in Taiwan studying Vedolizumab.",
420
+ "List studies for Crohn's disease that started after 2015.",
421
+ "Give me 5 completed trials on lung cancer in Japan.",
422
+ "Provide latest Perennial Allergic Rhinitis study from Eli Lily",
423
+ "Find interventional Phase 3 studies for breast cancer in France.",
424
+ "List observational studies in Thailand with female participants over 65.",
425
+ "Show me trials in United States, Houston, at MD Anderson.",
426
+ "Show studies that started after 2022 for Asthma and are still ongoing.",
427
+ "Show me studies that use HS135 in Canada.",
428
+ "Show me trials that share individual participant data (IPD) in the USA.",
429
+ "Get trial details for NCT06083857.",
430
+ "Find completed prostate cancer trials for adults in Germany.",
431
+ "List Phase 4 trials with probability sampling in South Korea."
432
+ ]
433
+
434
+ description = """\
435
+ <div style="font-family: sans-serif; line-height: 1.8;">
436
+ <strong>Ask about any of the following criteria to find clinical trials:</strong><br><br>
437
+
438
+ <style>
439
+ table.ctg-guide-table, table.ctg-guide-table td {
440
+ border: none !important;
441
+ padding: 6px;
442
+ vertical-align: top;
443
+ }
444
+ </style>
445
+
446
+ <table class="ctg-guide-table" style="width: 100%; table-layout: fixed; border-collapse: collapse;">
447
+ <tr>
448
+ <td>🩺 <strong>Medical Conditions</strong><br><small>e.g., 'lung cancer', 'prostate cancer'</small></td>
449
+ <td>πŸ”’ <strong>NCT ID</strong><br><small>e.g., 'NCT01234567'</small></td>
450
+ <td>πŸ§ͺ <strong>Trial Phase</strong><br><small>e.g., 'Phase 1', 'Phase 2', 'Phase 3', 'Phase 4'</small></td>
451
+ </tr>
452
+ <tr>
453
+ <td>🧫 <strong>Study Type</strong><br><small>e.g., 'INTERVENTIONAL', 'OBSERVATIONAL'</small></td>
454
+ <td>πŸ“‹ <strong>Status</strong><br><small>e.g., 'RECRUITING', 'COMPLETED', 'TERMINATED'</small></td>
455
+ <td>πŸ’Š <strong>Interventions</strong><br><small>e.g., 'aspirin', 'HS135', 'Vedolizumab'</small></td>
456
+ </tr>
457
+ <tr>
458
+ <td>🏒 <strong>Sponsor</strong><br><small>e.g., 'Pfizer', 'NIH', 'Amgen'</small></td>
459
+ <td>🚻 <strong>Sex</strong><br><small>e.g., 'Male', 'Female', 'All'</small></td>
460
+ <td>🧍 <strong>Age Group</strong><br><small>e.g., 'CHILD', 'ADULT', 'OLDER_ADULT'</small></td>
461
+ </tr>
462
+ <tr>
463
+ <td>🎯 <strong>Sampling Method</strong><br><small>e.g., 'PROBABILITY_SAMPLE', 'NON_PROBABILITY_SAMPLE'</small></td>
464
+ <td>πŸ“€ <strong>IPD Sharing</strong><br><small>e.g., 'YES', 'NO', 'UNDECIDED' (Individual Participant Data)</small></td>
465
+ <td>🌍 <strong>Location</strong><br><small>e.g., country, city, or facility</small></td>
466
+ </tr>
467
+ <tr>
468
+ <td colspan="3">πŸ“… <strong>Start/Completion Date</strong><br><small>e.g., '2020', '2020-05', or '2020-05-20'</small></td>
469
+ </tr>
470
+ </table>
471
+
472
+ <br>
473
+ πŸ’¬ Ask your question naturally, but include keywords like condition, location, phase, sex, or sponsor for best results.<br>
474
+ You can combine filters (e.g., <em>'recruiting lung cancer trials in Canada by Pfizer'</em>) for more precise answers.<br><br>
475
+ πŸ’‘ <em>Try one of the examples below to get started!</em>
476
+ </div>
477
+ """
478
+
479
+ gr.ChatInterface(
480
+ fn=chat, # Your actual function
481
+ type="messages",
482
+ title="ClinicalTrials.gov Agent",
483
+ description=description,
484
+ chatbot=gr.Chatbot(label="CTGagent", type="messages", height=1000),
485
+ examples=example_prompts
486
+ ).launch(app_kwargs={"title": "CTGagent"})
487
+
488
+ # %%
489
+
490
+
491
+