moazx commited on
Commit
3699d7c
·
1 Parent(s): 015dc58

Update assess and assess/text endpoints to simplify context handling

Browse files

- Removed RAG pipeline step: "Retrieve relevant guidelines from vector store using hybrid_search"
- Included page contents with page numbers directly as prompt context
- Ensured outputs cite corresponding page numbers as usual
- Context now explicitly includes SASLT guideline pages 3–10 for HBV phases, risk factors, treatment indications, monitoring, and therapy recommendations

api/routers/hbv_assessment.py CHANGED
@@ -23,10 +23,9 @@ async def assess_patient(patient: HBVPatientInput) -> HBVAssessmentResponse:
23
 
24
  This endpoint:
25
  1. Validates patient data
26
- 2. Creates intelligent search query based on patient parameters
27
- 3. Retrieves relevant SASLT 2021 guidelines from vector store
28
- 4. Uses LLM to analyze patient against retrieved guidelines
29
- 5. Returns structured assessment with eligibility and comprehensive recommendations
30
 
31
  Returns:
32
  HBVAssessmentResponse containing:
@@ -63,8 +62,9 @@ async def assess_patient_from_text(text_input: TextAssessmentInput) -> HBVAssess
63
  This endpoint:
64
  1. Parses free-form text to extract structured patient data using LLM
65
  2. Validates the extracted data
66
- 3. Performs the same assessment as /assess endpoint
67
- 4. Returns structured assessment with eligibility and recommendations
 
68
 
69
  Example text input:
70
  "45-year-old male patient
 
23
 
24
  This endpoint:
25
  1. Validates patient data
26
+ 2. Provides SASLT 2021 guideline pages (3, 4, 6, 7, 8, 9, 10) directly as context
27
+ 3. Uses LLM to analyze patient against the guidelines
28
+ 4. Returns structured assessment with eligibility and comprehensive recommendations
 
29
 
30
  Returns:
31
  HBVAssessmentResponse containing:
 
62
  This endpoint:
63
  1. Parses free-form text to extract structured patient data using LLM
64
  2. Validates the extracted data
65
+ 3. Provides SASLT 2021 guideline pages directly as context
66
+ 4. Uses LLM to analyze patient against the guidelines
67
+ 5. Returns structured assessment with eligibility and recommendations
68
 
69
  Example text input:
70
  "45-year-old male patient
core/hbv_assessment.py CHANGED
@@ -6,7 +6,6 @@ import logging
6
  import json
7
  import re
8
  from typing import Dict, Any
9
- from .retrievers import hybrid_search
10
  from .config import get_llm
11
 
12
  logger = logging.getLogger(__name__)
@@ -72,74 +71,319 @@ def clean_json_string(json_str: str) -> str:
72
  return ''.join(result)
73
 
74
 
75
- def create_patient_query(patient_data: Dict[str, Any]) -> str:
76
- """
77
- Create a comprehensive search query based on patient parameters
78
-
79
- Args:
80
- patient_data: Dictionary containing patient clinical parameters
81
-
82
- Returns:
83
- Optimized search query string for guideline retrieval
84
- """
85
- query_parts = []
86
-
87
- # Add HBeAg status to query
88
- if patient_data.get("hbeag_status") == "Positive":
89
- query_parts.append("HBeAg-positive chronic hepatitis B treatment eligibility")
90
- else:
91
- query_parts.append("HBeAg-negative chronic hepatitis B treatment eligibility")
92
-
93
- # Add viral load context
94
- hbv_dna = patient_data.get("hbv_dna_level", 0)
95
- if hbv_dna > 20000:
96
- query_parts.append("high HBV DNA level")
97
- elif hbv_dna > 2000:
98
- query_parts.append("moderate HBV DNA level")
99
-
100
- # Add ALT context
101
- sex = patient_data.get("sex", "Male")
102
- alt_level = patient_data.get("alt_level", 0)
103
- alt_uln = 35 if sex == "Male" else 25
104
- if alt_level > 2 * alt_uln:
105
- query_parts.append("significantly elevated ALT")
106
- elif alt_level > alt_uln:
107
- query_parts.append("elevated ALT")
108
-
109
- # Add fibrosis context
110
- fibrosis_stage = patient_data.get("fibrosis_stage", "")
111
- if fibrosis_stage == "F4":
112
- query_parts.append("cirrhosis treatment criteria")
113
- elif fibrosis_stage == "F2-F3":
114
- query_parts.append("significant fibrosis")
115
-
116
- # Add special populations
117
- if patient_data.get("pregnancy_status") == "Pregnant":
118
- query_parts.append("pregnancy antiviral prophylaxis")
119
-
120
- immunosuppression = patient_data.get("immunosuppression_status")
121
- if immunosuppression and immunosuppression != "None":
122
- query_parts.append("immunosuppression prophylactic therapy")
123
-
124
- coinfections = patient_data.get("coinfections", [])
125
- if coinfections:
126
- query_parts.append("coinfection management")
127
-
128
- if patient_data.get("extrahepatic_manifestations"):
129
- query_parts.append("extrahepatic manifestations")
130
-
131
- if patient_data.get("family_history_cirrhosis_hcc"):
132
- query_parts.append("family history HCC cirrhosis")
133
-
134
- # Combine into search query
135
- base_query = " ".join(query_parts[:3]) # Use top 3 most relevant parts
136
- return f"{base_query} treatment indications criteria SASLT 2021"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
 
139
  def assess_hbv_eligibility(patient_data: Dict[str, Any]) -> Dict[str, Any]:
140
  """
141
  Assess patient eligibility for HBV treatment based on SASLT 2021 guidelines
142
- using retrieval from vector store and LLM analysis
143
 
144
  Args:
145
  patient_data: Dictionary containing patient clinical parameters
@@ -157,39 +401,8 @@ def assess_hbv_eligibility(patient_data: Dict[str, Any]) -> Dict[str, Any]:
157
  "recommendations": "Patient is HBsAg negative. HBV treatment is not indicated. HBsAg positivity is required for HBV treatment consideration according to SASLT 2021 guidelines."
158
  }
159
 
160
- # Create search query based on patient parameters
161
- search_query = create_patient_query(patient_data)
162
- logger.info(f"Generated search query: {search_query}")
163
-
164
- # Retrieve relevant guidelines from vector store
165
- docs = hybrid_search(search_query, provider="SASLT", k_vector=8, k_bm25=2)
166
-
167
- if not docs:
168
- logger.warning("No documents retrieved from vector store")
169
- return {
170
- "eligible": False,
171
- "recommendations": "Unable to retrieve SASLT 2021 guidelines. Please try again."
172
- }
173
-
174
- # Log retrieved documents
175
- logger.info(f"\n{'='*80}")
176
- logger.info(f"RETRIEVED DOCUMENTS ({len(docs)} documents)")
177
- logger.info(f"{'='*80}")
178
- for i, doc in enumerate(docs, 1):
179
- source = doc.metadata.get('source', 'Unknown')
180
- page = doc.metadata.get('page_number', 'N/A')
181
- content_preview = doc.page_content[:200] + "..." if len(doc.page_content) > 200 else doc.page_content
182
- logger.info(f"\n📄 Document {i}:")
183
- logger.info(f" Source: {source}")
184
- logger.info(f" Page: {page}")
185
- logger.info(f" Content Preview: {content_preview}")
186
- logger.info(f"{'='*80}\n")
187
-
188
- # Format retrieved documents for LLM
189
- context = "\n\n".join([
190
- f"[Source: {doc.metadata.get('source', 'Unknown')}, Page: {doc.metadata.get('page_number', 'N/A')}]\n{doc.page_content}"
191
- for doc in docs
192
- ])
193
 
194
  # Define ALT ULN for context
195
  sex = patient_data.get("sex", "Male")
@@ -213,7 +426,6 @@ def assess_hbv_eligibility(patient_data: Dict[str, Any]) -> Dict[str, Any]:
213
 
214
  # Create prompt for LLM to analyze patient against guidelines
215
  analysis_prompt = f"""You are an HBV treatment eligibility assessment system. Analyze the patient data against SASLT 2021 guidelines.
216
-
217
  PATIENT DATA:
218
  - Sex: {sex}
219
  - Age: {age} years
@@ -231,40 +443,20 @@ PATIENT DATA:
231
  - Family History (Cirrhosis/HCC): {family_history}
232
  - Other Comorbidities: {', '.join(comorbidities) if comorbidities else 'None'}
233
 
234
- HBV ELIGIBILITY CRITERIA & TREATMENT OPTIONS – SASLT 2021:
235
-
236
- TREATMENT ELIGIBILITY CRITERIA:
237
- 1. HBV DNA > 2,000 IU/mL, ALT > ULN, regardless of HBeAg status, and/or at least moderate liver necroinflammation or fibrosis (Grade A)
238
- 2. Patients with cirrhosis (compensated or decompensated), with any detectable HBV DNA level and regardless of ALT levels (Grade A)
239
- 3. HBV DNA > 20,000 IU/mL and ALT > 2xULN, regardless of the degree of fibrosis (Grade B)
240
- 4. HBeAg-positive chronic HBV infection (persistently normal ALT and high HBV DNA levels) may be treated if they are > 30 years, regardless of the severity of liver histological lesions (Grade D)
241
- 5. HBV DNA > 2,000 IU/mL, ALT > ULN, regardless of HBeAg status, and a family history of HCC or cirrhosis and extrahepatic manifestations (Grade D)
242
-
243
- TREATMENT CHOICES:
244
- - Preferred regimens are ETV (entecavir), TDF (tenofovir disoproxil fumarate), and TAF (tenofovir alafenamide) as monotherapies (Grade A)
245
-
246
- MANAGEMENT ALGORITHM:
247
- • HBsAg positive with chronic HBV infection and no signs of chronic hepatitis → Monitor (HBsAg, HBeAg, HBV DNA, ALT, fibrosis assessment). Consider: risk of HCC, risk of HBV reactivation, extrahepatic manifestations, risk of HBV transmission
248
- • CHB (with/without cirrhosis) → Start antiviral treatment if indicated, otherwise return to monitoring
249
- • HBsAg negative, anti-HBc positive → No specialist follow-up (inform about HBV reactivation risk). In case of immunosuppression: start oral antiviral prophylaxis or monitor
250
 
251
  SASLT 2021 GUIDELINES (Retrieved Context):
252
- {context}
253
-
254
  Based STRICTLY on the SASLT 2021 guidelines and criteria provided above, assess this patient's eligibility for HBV antiviral treatment.
255
-
256
  You MUST respond with a valid JSON object in this exact format:
257
  {{
258
  "eligible": true or false,
259
  "recommendations": "Comprehensive assessment with inline citations"
260
  }}
261
-
262
  IMPORTANT JSON FORMATTING:
263
  - Return ONLY valid JSON without markdown code blocks
264
  - Use spaces instead of literal newlines within the "recommendations" string
265
  - Separate paragraphs with double spaces or use \\n for line breaks
266
  - Do NOT include literal newline characters in the JSON string values
267
-
268
  CRITICAL CITATION REQUIREMENTS:
269
  1. The "recommendations" field must be a comprehensive narrative that includes:
270
  - Eligibility determination with rationale
@@ -273,7 +465,6 @@ CRITICAL CITATION REQUIREMENTS:
273
  - Special considerations (pregnancy, immunosuppression, coinfections, etc.)
274
  - Any additional clinical notes
275
  - **References** section at the end listing all cited pages
276
-
277
  2. EVERY statement in recommendations MUST include inline citations in this format:
278
  "[SASLT 2021, Page X]" where X is the specific page number
279
 
@@ -283,13 +474,9 @@ CRITICAL CITATION REQUIREMENTS:
283
  **References**
284
  SASLT 2021 Guidelines - Pages: 12, 15, 18
285
  (Treatment Eligibility Criteria, First-Line Antiviral Agents, Monitoring Protocols)"
286
-
287
  4. ALWAYS cite the specific page number from the [Source: ..., Page: X] markers in the guidelines above
288
-
289
  5. Include evidence grade (Grade A, B, C, D) when available in the guidelines
290
-
291
  6. END the recommendations with a **References** section that lists all cited pages in ascending order with brief description of topics covered
292
-
293
  IMPORTANT:
294
  1. Base your assessment ONLY on the SASLT 2021 guidelines provided
295
  2. Make recommendations comprehensive and detailed
@@ -299,6 +486,7 @@ IMPORTANT:
299
  6. Return ONLY the JSON object, no additional text
300
  """
301
 
 
302
  # Log the complete prompt being sent to LLM
303
  logger.info(f"\n{'='*80}")
304
  logger.info(f"LLM PROMPT")
 
6
  import json
7
  import re
8
  from typing import Dict, Any
 
9
  from .config import get_llm
10
 
11
  logger = logging.getLogger(__name__)
 
71
  return ''.join(result)
72
 
73
 
74
+ # SASLT 2021 Guidelines - Hardcoded Page Contents
75
+ SASLT_GUIDELINES = """
76
+ ----
77
+ Page 3:
78
+ ## TABLE 2: Natural history and assessment of patients with chronic HBV infection based upon HBV and liver disease markers[1,3]
79
+ | Phases | HBsAg/HBeAg | HBV DNA | ALT | Liver inflammation | Old terminology and Observations |
80
+ |--------|-------------|---------|-----|-------------------|----------------------------------|
81
+ | **PHASE 1**<br>Chronic HBV infection | High/Positive | High (>10⁷ IU/mL) | Normal | None/minimal | **"Immune tolerant"**<br>This phase is more frequent and more prolonged in subjects infected prenatally or in the first years of life. Patients are highly contagious. |
82
+ | **PHASE 2**<br>Chronic hepatitis B | High-Intermediate/Positive | Lower (10⁴-10⁷ IU/mL) | Increased | Moderate/severe | **"Immune reactive HBeAg positive"**<br>This phase may last for several weeks to years. It may occur after several years of immune tolerance and is more frequently in subjects infected during adulthood. |
83
+ | **PHASE 3**<br>Chronic HBV infection | Low/Negative | Low or undetectable (<2,000 IU/mL)ᵃ | Normal | None | **"Inactive carrier"**<br>This state confers a favorable long-term outcome with low risk of cirrhosis or HCC. |
84
+ | **PHASE 4**<br>Chronic hepatitis B | Intermediate/Negative | Fluctuating levels (>2,000 IU/mL) | Fluctuating levels/Elevated* | Moderate/severe | **"HBeAg negative chronic hepatitis"**<br>Characterized by periodic reactivations. It is sometimes difficult to distinguish true inactive HBV carriers (good prognosis) from patients with active HBeAg-negative CHB (have active liver disease with a high risk of progression to advanced hepatic fibrosis, cirrhosis, and HCC) |
85
+ | **PHASE 5**<br>Resolved HBV infection | Negative/Negative | Undetectable (<10 IU/mL) | Normal | None (HCC risk if cirrhosis has developed before HBsAg loss) | **"HBsAg negative/anti-HBc positive"**<br>Reduced risk of cirrhosis, decompensation, and HCC. Immunosuppression may reactivate HBV in these patients. |
86
+ **Footnotes:**
87
+ - ᵃHBV DNA levels can be between 2,000 and 20,000 IU/ml in some patients without signs of chronic hepatitis.
88
+ - *Persistently or intermittently
89
+ ----
90
+
91
+ Page 4
92
+ ## FIGURE 1: Risk Factors for HCC Development
93
+ ### Factors that affect the risk of developing HCC in diagnosed CHB patients
94
+ #### FACTORS RELATED WITH THE HOST
95
+ - Cirrhosis
96
+ - Chronic hepatic necroinflammation
97
+ - Older age
98
+ - Male sex
99
+ - African origin
100
+ - Alcohol abuse
101
+ - Chronic co-infections with other viral hepatitis or HIV
102
+ - Diabetes or metabolic syndrome
103
+ - Active smoking
104
+ - Positive family history
105
+ #### FACTORS RELATED WITH HBV PROPERTIES
106
+ - High HBV DNA
107
+ - High HBsAg levels
108
+ - HBV genotypes C > B
109
+ - Specific mutations
110
+ ----
111
+ Page 6:
112
+ Goal and endpoint of therapy
113
+ The main goal of treatment for chronic HBV infection is
114
+ to improve survival and quality of life by preventing disease
115
+ progression to cirrhosis‑ and liver‑related complications,
116
+ namely HCC development.[1,36] Additional goals are to
117
+ prevent mother‑to‑child transmission, hepatitis B reactivation
118
+ and prevention/treatment of associated extrahepatic
119
+ manifestations. The likelihood of achieving these goals
120
+ depends upon the timing of therapy and on the stage of
121
+ disease and patient's age when the treatment is started.
122
+ A further goal of treatment can be regression of fibrosis
123
+ or cirrhosis in patients with advanced fibrosis or cirrhosis.
124
+ In patients with HBV‑induced HCC the use of nucleos (t)
125
+ ide analogue (NA) therapy is done mainly to suppress
126
+ HBV replication, and to prevent recurrence of HCC after
127
+ curative therapies. Stabilization of the HBV‑induced liver
128
+ disease can be considered a prerequisite for the safe and
129
+ effective application of HCC treatment.[1]
130
+ For patients with acute hepatitis B the main goal of therapy
131
+ is to prevent the risk of acute or subacute liver failure.
132
+ Additional goals may consider improving the quality of
133
+ life by reducing disease‑associated symptoms and lowering
134
+ the risk of chronicity.[1]
135
+ The recommendations for endpoints of chronic HBV
136
+ therapy are shown in Table 5.
137
+ Treatment indications
138
+ Indications for treatment are in general the same for
139
+ HBeAg‑positive and HBeAg‑negative patients, and
140
+ this is based mainly upon the combination of serum
141
+ HBV DNA levels, serum ALT levels and severity of
142
+ disease[1] [Figure 2].
143
+ Non‑cirrhotic patients should be considered for treatment
144
+ if they have HBV DNA levels >2,000 IU/mL, serum
145
+ ALT >~40 IU/L and severity of liver disease assessed by
146
+ liver biopsy showing at least moderate necroinflammation
147
+ and/or at least moderate fibrosis. Patients with HBV DNA
148
+ greater than 20,000 IU/mL and ALT greater than 2x ULN
149
+ can begin treatment without a liver biopsy. Patients with
150
+ HBV DNA >2,000 IU/mL and at least moderate fibrosis
151
+ may initiate treatment even if ALT levels are normal.
152
+ In patients unwilling or unable to undergo liver biopsy,
153
+ non‑invasive markers of fibrosis may instead be used to
154
+ decide on treatment indications. Treatment indications
155
+ should also take into account patient's age, health status, risk
156
+ of HBV transmission, family history of HCC or cirrhosis
157
+ and extrahepatic manifestations [Figure 2].[1]
158
+ Recommendations for initiation of treatment
159
+ • All patients with chronic hepatitis B (HBV DNA > 2,000 IU/mL, ALT >
160
+ ULN), regardless of HBeAg status, and/or at least moderate liver
161
+ necroinflammation or fibrosis (Grade A)
162
+ • Patients with cirrhosis (compensated or decompensated), with any
163
+ detectable HBV DNA level and regardless of ALT levels (Grade A)
164
+ • Patients with HBV DNA > 20,000 IU/mL and ALT > 2xULN, regardless
165
+ of the degree of fibrosis (Grade B)
166
+ • Patients with HBeAg-positive chronic HBV infection (persistently normal
167
+ ALT and high HBV DNA levels) may be treated if they are > 30 years,
168
+ regardless of the severity of liver histological lesions (Grade D)
169
+ • Patients with chronic HBV infection (HBV DNA > 2,000 IU/mL, ALT >
170
+ ULN), regardless of HBeAg status, and a family history of HCC or
171
+ cirrhosis and extrahepatic manifestations (Grade D)
172
+ Monitoring of therapy of patients currently not treated
173
+ Patients not candidate for antiviral therapy should be
174
+ periodically assessed to determine whether an indication
175
+ for treatment has developed. Serum ALT and HBV
176
+ DNA levels as well as fibrosis severity by non‑invasive
177
+ markers should be regularly evaluated. HBeAg‑positive
178
+ untreated patients should be tested for ALT every 3 months,
179
+ Figure 2: Algorithm for the management of HBV infection:
180
+ • HBsAg positive with chronic HBV infection and no signs of chronic hepatitis → Monitor (HBsAg, HBeAg, HBV DNA, ALT, fibrosis assessment). Consider: risk of HCC, risk of HBV reactivation, extrahepatic manifestations, risk of HBV transmission
181
+ • CHB (with/without cirrhosis) → Start antiviral treatment if indicated, otherwise return to monitoring
182
+ • HBsAg negative, anti-HBc positive → No specialist follow-up (inform about HBV reactivation risk). In case of immunosuppression: start oral antiviral prophylaxis or monitor
183
+ ----
184
+ Page 7
185
+
186
+ months, HBV DNA determinants every 6–12 months
187
+ and assessment for liver fibrosis every 12 months.
188
+ HBeAg‑negative patients with HBV DNA <2,000 IU/
189
+ ml should have ALT determinations every 6–12 months
190
+ and periodical HBV DNA and liver fibrosis assessments,
191
+ every year. Determination of quantitative HBsAg
192
+ levels can help in the decision for follow‑up frequency
193
+ in these patients.[54] However, two studies with Saudi
194
+ patients have shown that correlation of qHBsAg levels
195
+ with liver fibrosis was poor in these patients, wherein
196
+ qHBsAg levels demonstrated a poor association with
197
+ histological findings. Overall, these studies have shown
198
+ that predictability based on qHBsAg levels of 1000 IU
199
+ was not supportive of fibrosis.[55,56]
200
+ For HBeAg‑negative patients with HBV DNA≥2,000 IU/ml,
201
+ ALT should be determined at least every 3 months for the
202
+ first year and every 6 months thereafter. Assessments of
203
+ HBV DNA and liver fibrosis by non‑invasive methods
204
+ every year for at least 3 years should be considered. If they
205
+ do not fulfill any treatment indication within the first 3 years
206
+ of follow‑up, they should be followed for life, similar to all
207
+ patients in this phase.
208
+ Recommendations for monitoring of therapy of
209
+ patients currently not treated
210
+ • Patients with HBeAg-positive chronic HBV infection who are younger than
211
+ 30 years should be followed at least every 3-6 months (Grade B)
212
+ • Patients with HBeAg-negative chronic HBV infection and serum HBV DNA
213
+ <2,000 IU/ml should be followed every 6-12 months (Grade B)
214
+ • Patients with HBeAg-negative chronic HBV infection and serum HBV
215
+ DNA ≥2,000 IU/ml should be followed every 3 months for the first year and
216
+ thereafter every 6 months (Grade D)
217
+ Treatment of CHB
218
+ Overall, the available NA therapies for HBV can be
219
+ categorized into medications that have low barrier for
220
+ resistance, including Lamivudine (LAM), Telbivudine (TBV)
221
+ and Adefovir (ADV),[58] and medications that have high
222
+ barrier for resistance, which include Entecavir (ETV),
223
+ Tenofovir Disoproxil Fumarate (TDF) and Tenofovir
224
+ Alafenamide (TAF).[59‑61]
225
+ LAM is one of the first medications used to treat
226
+ CHB. However, the use of LAM is associated with an
227
+ unacceptably high rate of resistance, reaching 49% at
228
+ 3 years and 70% in 5 years.[58] ADV had a better resistance
229
+ profile compared to LAM, with 11% and 29% resistance
230
+ rate in 3 and 5 years, respectively.[58] But this rate is now
231
+ considered too high when compared with the relatively
232
+ new generation of nucleot(s)ide analogues.
233
+ ETV is a potent guanosine analogue. First evaluated vs
234
+ LAM, it showed an excellent efficacy and safety profile.[62]
235
+ The virological response rate (defined as negative HBV
236
+ DNA by PCR) approaches 100% over 5 years of its use,
237
+ in both HBeAg‑negative and HBeAg‑positive patients.[59]
238
+ ETV has a high barrier for resistance, where after 5 years
239
+ of its use, only 1% had emergence of resistance.[63]
240
+ TDF is a prodrug of tenofovir which is a nucleotide
241
+ inhibitor that acts on both hepatitis B and HIV.[58] Similar to
242
+ ETV, TDF has an excellent efficacy profile. A retrospective
243
+ cohort study of treatment‑naive CHB patients who
244
+ were treated with TDF or ETV showed that both were
245
+ effective in achieving complete viral response and had a
246
+ favorable safety profile.[64] After seven years of treatment
247
+ with TDF, 99.3% of patients achieved and maintained
248
+ virological response.[58] Treatment with TDF did not result
249
+ in detectable resistance after 8 years of treatment.[65]
250
+ Due to the side-effect profile, difficulty of use, and the
251
+ presence of better alternatives, the use of "conventional
252
+ interferon" is not recommended, and peglated interferon
253
+ should be used instead.[1,36] Since the release of the last
254
+ guidelines in 2014, the concept of futility "endpoint" or
255
+ the "stopping rule" when treating hepatitis B with peglated
256
+ interferon has been introduced.[1,36,66]
257
+ The importance of pretreatment predictors of response
258
+ has been highlighted previously. The new evidence of
259
+ stopping treatment with interferon is of great importance
260
+ due to its side‑effect profile, and the excellent predictive
261
+ value for those parameters on treatment outcomes,
262
+ which are dependent on serum HBsAg levels.[67] In
263
+ HBeAg‑positive patients, the lack of decline in qHBsAg
264
+ levels (in genotypes A and D) or maintaining qHBsAg levels
265
+ to more than 20,000 (in genotypes B and C) is a strong
266
+ predictor of failure of treatment, with a negative predictive
267
+ value of 92 to 100% for HBeAg seroconversion.[67] In
268
+ HBeAg‑negative patients, the data is not as robust as is with
269
+ HBeAg‑positive patients,[53] with most of the evidence on
270
+ genotype D.[68,69] Overall, patients who have no decline in
271
+ qHBsAg levels and have no decrease in HBV DNA level
272
+ by 2‑log, will have very low chance of sustained treatment
273
+ response, defined by HBV DNA level less than 2000 IU/
274
+ mL after the end of treatment.[54]
275
+ TAF is another NA that acts by inhibiting reverse
276
+ transcription of the pregenomic RNA to HBV DNA.
277
+ Compared with TDF, it has higher plasma stability and
278
+ thus less accumulation in bone and kidney tissue. In
279
+ both HBeAg‑positive and HBeAg‑negative patients, TAF
280
+ achieved non‑inferiority to TDF in terms of efficacy
281
+ of suppressing the viral load.[70,71] For HBeAg‑positive
282
+ patients, 873 were assigned randomly to either TAF or
283
+ ----
284
+
285
+ Page 8 :
286
+
287
+ TDF in a 2:1 design. Sixty four percent of the patients
288
+ achieved virological response in the TAF group compared
289
+ to 67% in TDF group, after 48 weeks of treatment,
290
+ which met the definition of non‑inferiority.[70] The results
291
+ from HBeAg‑negative study comparing TAF to TDF
292
+ were similar. A total of 426 patients randomized in a
293
+ 2:1 distribution between TAF and TDF, the virological
294
+ response was 94% and 93% respectively between the
295
+ two groups at 48 weeks.[71] Long‑term study on the same
296
+ cohort was used for the aforementioned two trials of
297
+ TAF approval. Patients were analyzed after 96 weeks from
298
+ starting treatment. In the HBeAg‑positive patients group
299
+ the response rate was similar between TAF and TDF (73%
300
+ and 75% respectively). This was also demonstrated in the
301
+ HBeAg‑negative group, with TAF and TDF having an
302
+ insignificant difference in virological response (90% and
303
+ 91%, respectively).
304
+
305
+ ## CLINICAL RECOMMENDATIONS BOX
306
+ ### Treatment Recommendations
307
+ | **Recommendation** | **Grade** |
308
+ |-------------------|-----------||
309
+ | The treatment of choice is the long-term administration of a potent NA with a high barrier to resistance, regardless of the severity of liver disease | **Grade A** |
310
+ | Preferred regimens are ETV, TDF and TAF as monotherapies | **Grade A** |
311
+ | LAM, ADV and TBV are not recommended in the treatment of CHB | **Grade A** |
312
+
313
+ TREATMENT OF HBV IN SPECIAL POPULATIONS
314
+ HBV‑HCV coinfection
315
+ Early studies, after the introduction of direct antiviral
316
+ therapy (DAA) for the treatment of HCV, reported HBV
317
+ reactivation after initiation of DAA.[83] Based on these
318
+ studies, the US Food and Drug Administration issued a
319
+ warning about the risk of HBV reactivation. However,
320
+ subsequent studies showed that the risk of reactivation
321
+ is very low for patients with chronic or past infection
322
+ with HBV.[84] Patients who meet the criteria for HBV
323
+ treatment should be treated concurrently or before
324
+ initiation of DAA. HBV DNA and ALT should be
325
+ monitored every four to eight weeks while on DAA and
326
+ three months after completion of therapy. Patients with
327
+ positive HBsAg who do not meet the criteria for HBV
328
+ treatment should be monitored closely while on DAA.
329
+ We recommend ALT level monitoring every four weeks
330
+ while on DAA for patients who are HBsAg‑negative
331
+ but HBcAb‑positive. If ALT starts to rise, HBsAg and
332
+
333
+ ----
334
+
335
+ Page 9:
336
+
337
+ HBV DNA must be obtained to determine the need to
338
+ start HBV treatment.
339
+ Recommendations
340
+ • Treatment of HCV through DAAs may lead to reactivation of HBV. Patients
341
+ who meet the criteria for HBV treatment should be treated concurrently or
342
+ before initiation of DAA (Grade A)
343
+ • HBV DNA and ALT should be monitored every four to eight weeks while on
344
+ DAA and three months after completion of therapy (Grade D)
345
+ • ALT level should be monitored every four weeks while on DAA for patients
346
+ who are HBsAg-negative but HBcAb-positive. If ALT starts to rise, HBsAg
347
+ and HBV DNA must be obtained to determine the need to start HBV
348
+ treatment (Grade D).
349
+
350
+ ## CLINICAL RECOMMENDATIONS BOX
351
+ ### Recommendations
352
+ • All HIV-positive patients with HBV co-infection should start ART irrespective
353
+ of CD4 cell count (Grade A)
354
+ • HBV-HIV co-infected patients should be treated with TDF- or TAF-based
355
+ ART regimen (Grade A)
356
+
357
+ ## CLINICAL RECOMMENDATIONS BOX
358
+ ### Recommendations
359
+ • Prophylaxis for all patients with positive HBsAg should be done before
360
+ initiating chemotherapy or other immunosuppressive agents (Grade A)
361
+ • HBsAg-negative/anti-HBc-positive patients, should undergo HBV
362
+ prophylaxis if they are candidates for anti CD20 or are undergoing stem
363
+ cell transplantation. HBV prophylaxis should continue for at least six
364
+ months after completion of immunosuppressive treatment and for twelve
365
+ months if taking anti CD20 (Grade D).
366
+
367
+ ----
368
+ page 10
369
+ ## CLINICAL RECOMMENDATIONS BOX
370
+ ### Recommendations
371
+ • All pregnant women must be screened for HBV during the first trimester
372
+ (Grade A)
373
+ • All pregnant women with HBV DNA greater than 100,000 IU/mL in the late
374
+ second trimester (between 24-28 weeks of gestation) should start antiviral
375
+ prophylaxis with TDF, or TAF as an alternative (Grade D)
376
+ • Switch to TDF or TAF is recommended if the patient is receiving ETV, ADV,
377
+ or interferon during pregnancy (Grade D)
378
+ • Breastfeeding is not contraindicated in HBsAg-positive untreated women
379
+ or on TDF-based treatment or prophylaxis (Grade B)
380
+ """
381
 
382
 
383
  def assess_hbv_eligibility(patient_data: Dict[str, Any]) -> Dict[str, Any]:
384
  """
385
  Assess patient eligibility for HBV treatment based on SASLT 2021 guidelines
386
+ using hardcoded guideline pages (3, 4, 6, 7, 8, 9, 10) and LLM analysis
387
 
388
  Args:
389
  patient_data: Dictionary containing patient clinical parameters
 
401
  "recommendations": "Patient is HBsAg negative. HBV treatment is not indicated. HBsAg positivity is required for HBV treatment consideration according to SASLT 2021 guidelines."
402
  }
403
 
404
+ # Use hardcoded SASLT 2021 guidelines instead of RAG retrieval
405
+ logger.info("Using hardcoded SASLT 2021 guidelines (Pages 3, 4, 6, 7, 8, 9, 10)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
 
407
  # Define ALT ULN for context
408
  sex = patient_data.get("sex", "Male")
 
426
 
427
  # Create prompt for LLM to analyze patient against guidelines
428
  analysis_prompt = f"""You are an HBV treatment eligibility assessment system. Analyze the patient data against SASLT 2021 guidelines.
 
429
  PATIENT DATA:
430
  - Sex: {sex}
431
  - Age: {age} years
 
443
  - Family History (Cirrhosis/HCC): {family_history}
444
  - Other Comorbidities: {', '.join(comorbidities) if comorbidities else 'None'}
445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446
 
447
  SASLT 2021 GUIDELINES (Retrieved Context):
448
+ {SASLT_GUIDELINES}
 
449
  Based STRICTLY on the SASLT 2021 guidelines and criteria provided above, assess this patient's eligibility for HBV antiviral treatment.
 
450
  You MUST respond with a valid JSON object in this exact format:
451
  {{
452
  "eligible": true or false,
453
  "recommendations": "Comprehensive assessment with inline citations"
454
  }}
 
455
  IMPORTANT JSON FORMATTING:
456
  - Return ONLY valid JSON without markdown code blocks
457
  - Use spaces instead of literal newlines within the "recommendations" string
458
  - Separate paragraphs with double spaces or use \\n for line breaks
459
  - Do NOT include literal newline characters in the JSON string values
 
460
  CRITICAL CITATION REQUIREMENTS:
461
  1. The "recommendations" field must be a comprehensive narrative that includes:
462
  - Eligibility determination with rationale
 
465
  - Special considerations (pregnancy, immunosuppression, coinfections, etc.)
466
  - Any additional clinical notes
467
  - **References** section at the end listing all cited pages
 
468
  2. EVERY statement in recommendations MUST include inline citations in this format:
469
  "[SASLT 2021, Page X]" where X is the specific page number
470
 
 
474
  **References**
475
  SASLT 2021 Guidelines - Pages: 12, 15, 18
476
  (Treatment Eligibility Criteria, First-Line Antiviral Agents, Monitoring Protocols)"
 
477
  4. ALWAYS cite the specific page number from the [Source: ..., Page: X] markers in the guidelines above
 
478
  5. Include evidence grade (Grade A, B, C, D) when available in the guidelines
 
479
  6. END the recommendations with a **References** section that lists all cited pages in ascending order with brief description of topics covered
 
480
  IMPORTANT:
481
  1. Base your assessment ONLY on the SASLT 2021 guidelines provided
482
  2. Make recommendations comprehensive and detailed
 
486
  6. Return ONLY the JSON object, no additional text
487
  """
488
 
489
+
490
  # Log the complete prompt being sent to LLM
491
  logger.info(f"\n{'='*80}")
492
  logger.info(f"LLM PROMPT")