File size: 7,416 Bytes
601f310
e46883d
601f310
 
 
 
 
 
 
 
 
 
 
 
565148b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
601f310
 
 
 
 
 
 
 
 
 
 
 
 
 
565148b
601f310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565148b
601f310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565148b
601f310
94adbfa
 
 
 
 
601f310
565148b
 
e46883d
601f310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565148b
601f310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565148b
601f310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565148b
 
601f310
 
 
 
 
 
 
 
e46883d
601f310
e46883d
601f310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565148b
601f310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""Parlant tool definitions for the TrialPath agent."""

import json

from parlant.sdk import ToolContext, ToolResult, tool

from trialpath.config import (
    GEMINI_API_KEY,
    GEMINI_MODEL,
    HF_TOKEN,
    MCP_URL,
    MEDGEMMA_ENDPOINT_URL,
)

# ---------------------------------------------------------------------------
# Lazy singletons — one instance per service, reused across tool calls.
# ---------------------------------------------------------------------------

_extractor = None
_planner = None
_mcp_client = None


def _get_extractor():
    global _extractor
    if _extractor is None:
        from trialpath.services.medgemma_extractor import MedGemmaExtractor

        _extractor = MedGemmaExtractor(
            endpoint_url=MEDGEMMA_ENDPOINT_URL,
            hf_token=HF_TOKEN,
        )
    return _extractor


def _get_planner():
    global _planner
    if _planner is None:
        from trialpath.services.gemini_planner import GeminiPlanner

        _planner = GeminiPlanner(model=GEMINI_MODEL, api_key=GEMINI_API_KEY)
    return _planner


def _get_mcp_client():
    global _mcp_client
    if _mcp_client is None:
        from trialpath.services.mcp_client import ClinicalTrialsMCPClient

        _mcp_client = ClinicalTrialsMCPClient(mcp_url=MCP_URL)
    return _mcp_client


# ---------------------------------------------------------------------------
# Tools
# ---------------------------------------------------------------------------


@tool
async def extract_patient_profile(
    context: ToolContext,
    document_urls: str,
    metadata: str,
) -> ToolResult:
    """Extract a structured patient profile from uploaded medical documents.

    Args:
        context: Parlant tool context.
        document_urls: JSON list of document file paths.
        metadata: JSON object with known patient metadata (age, sex).
    """
    extractor = _get_extractor()
    urls = json.loads(document_urls)
    meta = json.loads(metadata)
    profile = await extractor.extract(urls, meta)

    return ToolResult(
        data=profile,
        metadata={"source": "medgemma", "doc_count": len(urls)},
    )


@tool
async def generate_search_anchors(
    context: ToolContext,
    patient_profile: str,
) -> ToolResult:
    """Generate search parameters from a patient profile for ClinicalTrials.gov.

    Args:
        context: Parlant tool context.
        patient_profile: JSON string of PatientProfile data.
    """
    planner = _get_planner()
    profile = json.loads(patient_profile)
    anchors = await planner.generate_search_anchors(profile)

    return ToolResult(
        data=anchors.model_dump(),
        metadata={"source": "gemini"},
    )


@tool
async def search_clinical_trials(
    context: ToolContext,
    search_anchors: str,
) -> ToolResult:
    """Search ClinicalTrials.gov for matching trials using search anchors.

    Args:
        context: Parlant tool context.
        search_anchors: JSON string of SearchAnchors data.
    """
    from trialpath.models.search_anchors import SearchAnchors

    client = _get_mcp_client()
    anchors = SearchAnchors.model_validate(json.loads(search_anchors))
    try:
        raw_studies = await client.search(anchors)
    except Exception:
        # Fallback to direct ClinicalTrials.gov API v2 when MCP unavailable
        raw_studies = await client.search_direct(anchors)

    from trialpath.services.mcp_client import ClinicalTrialsMCPClient

    trials = [ClinicalTrialsMCPClient.normalize_trial(s).model_dump() for s in raw_studies]

    return ToolResult(
        data={"trials": trials, "count": len(trials)},
        metadata={"source": "clinicaltrials_mcp"},
    )


@tool
async def refine_search_query(
    context: ToolContext,
    search_anchors: str,
    result_count: str,
) -> ToolResult:
    """Refine search parameters when too many results returned.

    Args:
        context: Parlant tool context.
        search_anchors: JSON string of current SearchAnchors.
        result_count: Number of results from last search.
    """
    from trialpath.models.search_anchors import SearchAnchors

    planner = _get_planner()
    anchors = SearchAnchors.model_validate(json.loads(search_anchors))
    refined = await planner.refine_search(anchors, int(result_count))

    return ToolResult(
        data=refined.model_dump(),
        metadata={"action": "refine", "prev_count": int(result_count)},
    )


@tool
async def relax_search_query(
    context: ToolContext,
    search_anchors: str,
    result_count: str,
) -> ToolResult:
    """Relax search parameters when too few results returned.

    Args:
        context: Parlant tool context.
        search_anchors: JSON string of current SearchAnchors.
        result_count: Number of results from last search.
    """
    from trialpath.models.search_anchors import SearchAnchors

    planner = _get_planner()
    anchors = SearchAnchors.model_validate(json.loads(search_anchors))
    relaxed = await planner.relax_search(anchors, int(result_count))

    return ToolResult(
        data=relaxed.model_dump(),
        metadata={"action": "relax", "prev_count": int(result_count)},
    )


@tool
async def evaluate_trial_eligibility(
    context: ToolContext,
    patient_profile: str,
    trial_candidate: str,
) -> ToolResult:
    """Evaluate patient eligibility for a clinical trial using dual-model approach.

    Medical criteria evaluated by MedGemma, structural by Gemini.

    Args:
        context: Parlant tool context.
        patient_profile: JSON string of PatientProfile data.
        trial_candidate: JSON string of TrialCandidate data.
    """
    profile = json.loads(patient_profile)
    trial = json.loads(trial_candidate)

    planner = _get_planner()
    extractor = _get_extractor()

    # Step 1: Slice criteria into atomic items
    criteria = await planner.slice_criteria(trial)

    # Step 2: Evaluate each criterion with appropriate model
    assessments = []
    for criterion in criteria:
        if criterion.get("category") == "medical":
            result = await extractor.evaluate_medical_criterion(criterion["text"], profile, [])
        else:
            result = await planner.evaluate_structural_criterion(criterion["text"], profile)
        assessments.append({**criterion, **result})

    # Step 3: Aggregate into overall assessment
    ledger = await planner.aggregate_assessments(profile, trial, assessments)

    return ToolResult(
        data=ledger.model_dump(),
        metadata={"source": "dual_model", "criteria_count": len(criteria)},
    )


@tool
async def analyze_gaps(
    context: ToolContext,
    patient_profile: str,
    eligibility_ledgers: str,
) -> ToolResult:
    """Analyze eligibility gaps across all evaluated trials.

    Args:
        context: Parlant tool context.
        patient_profile: JSON string of PatientProfile data.
        eligibility_ledgers: JSON list of EligibilityLedger data.
    """
    planner = _get_planner()
    profile = json.loads(patient_profile)
    ledgers = json.loads(eligibility_ledgers)
    gaps = await planner.analyze_gaps(profile, ledgers)

    return ToolResult(
        data={"gaps": gaps, "count": len(gaps)},
        metadata={"source": "gemini"},
    )


ALL_TOOLS = [
    extract_patient_profile,
    generate_search_anchors,
    search_clinical_trials,
    refine_search_query,
    relax_search_query,
    evaluate_trial_eligibility,
    analyze_gaps,
]