Adam Cseresznye commited on
Commit ·
4823ca0
1
Parent(s): a1bbee2
Revise synthesis prompt and add citation cleaning
Browse files- agents/synthesis_agent.py +62 -41
agents/synthesis_agent.py
CHANGED
|
@@ -27,60 +27,71 @@ from loguru import logger
|
|
| 27 |
from llama_index.core.schema import NodeWithScore
|
| 28 |
|
| 29 |
from utils.llm_router import LLMRouter
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
FEW_SHOT_EXAMPLE = """
|
| 33 |
-
User Query: cardiovascular effects of intermittent fasting
|
| 34 |
-
Scientific Answer:
|
| 35 |
### Executive Summary
|
| 36 |
-
|
| 37 |
|
| 38 |
### Key Findings
|
| 39 |
-
* **
|
| 40 |
-
* **
|
| 41 |
-
* **Lipid Profile:** IF
|
| 42 |
-
|
| 43 |
-
###
|
| 44 |
-
* **
|
| 45 |
-
|
| 46 |
-
* **Study [12]:** Meta-analysis of RCTs (n=104 outcomes) confirmed moderate reductions in BMI for overweight adults.
|
| 47 |
-
* **Inflammation**
|
| 48 |
-
* **Study [6]:** Notes reductions in systemic inflammation markers.
|
| 49 |
-
* **Study [2]:** Re-feeding after 24h fast restored baseline TMAO levels, suggesting transient effects.
|
| 50 |
-
|
| 51 |
-
### Limitations & Quality of Evidence
|
| 52 |
-
* **Attrition:** The 12-month ADF trial had a 38% dropout rate, potentially biasing results toward adherent participants [3].
|
| 53 |
-
* **Short-Term Data:** Many metabolic changes (e.g., TMAO) were measured after a single 24h fast, limiting insight into long-term impact [2].
|
| 54 |
-
"""
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
CITATION_QA_TEMPLATE = (
|
| 58 |
"You are a PhD-level research assistant. Your goal is to write a highly dense, rigorous synthesis. "
|
| 59 |
-
"**Longer is NOT better.** Quality is defined by information density.\n"
|
| 60 |
"---------------------\n"
|
| 61 |
"{context_str}\n"
|
| 62 |
"---------------------\n\n"
|
| 63 |
"### INSTRUCTIONS (Follow Strictly):\n"
|
| 64 |
-
"1. **
|
| 65 |
-
" - **
|
| 66 |
-
" - **
|
| 67 |
-
" -
|
| 68 |
-
"2. **REQUIRED SECTIONS**:\n"
|
| 69 |
-
" - **Executive Summary**:
|
| 70 |
-
"
|
| 71 |
-
"
|
| 72 |
-
"
|
| 73 |
-
"
|
| 74 |
-
" -
|
| 75 |
-
" -
|
| 76 |
-
"
|
| 77 |
-
"4. **FORMATTING RULES**:\n"
|
| 78 |
" - **NO MARKDOWN TABLES**: Use nested bullet lists only.\n"
|
| 79 |
-
" - **
|
| 80 |
-
" - **
|
| 81 |
-
"
|
| 82 |
-
"
|
| 83 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
"### REQUIRED OUTPUT FORMAT:\n"
|
| 85 |
"---------------------\n"
|
| 86 |
f"{FEW_SHOT_EXAMPLE}\n"
|
|
@@ -154,15 +165,25 @@ class SynthesisAgent:
|
|
| 154 |
try:
|
| 155 |
# Call LLM via router (handles primary/fallback)
|
| 156 |
response = await self.router.generate(prompt, model_type="synthesis")
|
|
|
|
| 157 |
logger.info(
|
| 158 |
-
f"Synthesis completed successfully: response_length={len(
|
| 159 |
)
|
| 160 |
-
return
|
| 161 |
except Exception as e:
|
| 162 |
logger.exception(f"Synthesis failed with error: {e}")
|
| 163 |
# Re-raise to let caller decide how to handle
|
| 164 |
raise
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
def _format_context(self, nodes: List[NodeWithScore]) -> str:
|
| 167 |
"""Format nodes into a context string with passage indices.
|
| 168 |
|
|
|
|
| 27 |
from llama_index.core.schema import NodeWithScore
|
| 28 |
|
| 29 |
from utils.llm_router import LLMRouter
|
| 30 |
+
import re
|
| 31 |
|
| 32 |
|
| 33 |
FEW_SHOT_EXAMPLE = """
|
|
|
|
|
|
|
| 34 |
### Executive Summary
|
| 35 |
+
Intermittent fasting (IF) demonstrates consistent, modest benefits for cardiovascular health, primarily driven by weight loss (4-7% [3]) and improved lipid profiles. While acute metabolic shifts—such as rapid TMAO reduction—are documented [2], long-term cardiovascular protection remains debated due to high attrition rates in trials (up to 38% [3]) and heterogeneity in fasting protocols [6][7].
|
| 36 |
|
| 37 |
### Key Findings
|
| 38 |
+
* **Weight & BMI Reduction:** Alternate-day fasting (ADF) achieves a 7% weight loss nadir at 6 months, stabilizing at 4.5% below baseline at 12 months [3]. This efficacy is comparable to daily caloric restriction for overweight adults [12].
|
| 39 |
+
* **Biomarker Modulation:** Fasting induces rapid metabolic switching; a single 24-hour water-only fast reduced circulating TMAO from 27.1 to 14.3 ng/ml (p=0.019) [2].
|
| 40 |
+
* **Lipid Profile Improvement:** IF protocols generally lower total cholesterol and LDL-C, though the magnitude of effect varies significantly by adherence levels [6][7].
|
| 41 |
+
|
| 42 |
+
### Synthesis & Implications
|
| 43 |
+
* **Mechanism of Action:** The benefits appear linked to both systemic weight reduction [3] and acute metabolic pauses that lower inflammatory markers like TMAO [2].
|
| 44 |
+
* **Protocol Viability:** While physiologically effective, the strictness of ADF leads to lower long-term adherence compared to less rigid restrictions, potentially limiting its utility as a public health intervention [3][12].
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
### Methodological Limits
|
| 47 |
+
* **Attrition Bias:** High dropout rates (38% in ADF arms) likely inflate reported benefits by excluding non-adherent participants [3].
|
| 48 |
+
* **Transient vs. Chronic:** Key biomarkers like TMAO were often measured after acute fasting events, not reflecting long-term steady states [2].
|
| 49 |
+
"""
|
| 50 |
|
| 51 |
CITATION_QA_TEMPLATE = (
|
| 52 |
"You are a PhD-level research assistant. Your goal is to write a highly dense, rigorous synthesis. "
|
| 53 |
+
"**Longer is NOT better.** Quality is defined by information density and thematic organization.\n"
|
| 54 |
"---------------------\n"
|
| 55 |
"{context_str}\n"
|
| 56 |
"---------------------\n\n"
|
| 57 |
"### INSTRUCTIONS (Follow Strictly):\n"
|
| 58 |
+
"1. **THEMATIC SYNTHESIS**:\n"
|
| 59 |
+
" - **DO NOT** organize bullets by study (e.g., avoid 'Study [1] said...').\n"
|
| 60 |
+
" - **DO** organize by **concepts, mechanisms, or outcomes**.\n"
|
| 61 |
+
" - Cite multiple sources within a single bullet if they support the same theme.\n\n"
|
| 62 |
+
"2. **REQUIRED SECTIONS (Use ### Markdown Headers)**:\n"
|
| 63 |
+
" - **### Executive Summary**: \n"
|
| 64 |
+
" * Start with a **Bold 'Bottom Line' Sentence** summarizing the core conclusion.\n"
|
| 65 |
+
" * Add a line break.\n"
|
| 66 |
+
" * Follow with a concise, high-density paragraph (max 150 words).\n"
|
| 67 |
+
" - **### Key Findings**: Thematic bullet points with hard data.\n"
|
| 68 |
+
" - **### Synthesis & Implications**: Explain the relationship (e.g., trade-offs, complementarity). Replaces simple comparisons.\n"
|
| 69 |
+
" - **### Methodological Limits**: Brief critique (bullet points).\n\n"
|
| 70 |
+
"3. **FORMATTING RULES**:\n"
|
|
|
|
| 71 |
" - **NO MARKDOWN TABLES**: Use nested bullet lists only.\n"
|
| 72 |
+
" - **BOLD LEAD-INS**: Start every bullet point with a **Bold Category:**.\n"
|
| 73 |
+
" - **ADAPTIVE COMPARISON**: \n"
|
| 74 |
+
" * **IF** the query compares entities (2 or more), treat every bullet as a 'table row'.\n"
|
| 75 |
+
" * **Rule:** Strictly repeat the 'vs.' pattern for every entity.\n"
|
| 76 |
+
" * **Format:** '**Category:** Entity A (Detail) **vs.** Entity B (Detail).'\n"
|
| 77 |
+
" * (Example: '**Timeframe:** Metabolomics (Seconds/Minutes) [1] **vs.** Proteomics (Hours/Days) [2].')\n"
|
| 78 |
+
" - **NO IMAGES**: Do not generate image tags.\n\n"
|
| 79 |
+
"4. **QUANTITATIVE DATA & CITATION PRECISION (CRITICAL)**: \n"
|
| 80 |
+
" - **NO OUTSIDE KNOWLEDGE**: You are strictly limited to the provided text. Do not use external knowledge.\n"
|
| 81 |
+
" - **NO HALLUCINATIONS**: If the text says 'expensive', **DO NOT** invent a number like '$500'. Write 'high cost' instead.\n"
|
| 82 |
+
" - **Specifics**: Use p-values, N=, and % changes **ONLY** if explicitly stated in the provided text.\n"
|
| 83 |
+
" - **GRANULAR CITATION**: \n"
|
| 84 |
+
" * **Rule:** Cite the source [x] *immediately* after the specific statistic it supports.\n"
|
| 85 |
+
" * **Correct:** 'Method A yield is 80% [1] vs. Method B is 40% [2].'\n"
|
| 86 |
+
" * **Incorrect:** 'Method A yield is 80% vs. Method B is 40% [1][2].'\n"
|
| 87 |
+
" * **Incorrect:** 'Method A and B yields are 80% and 40% respectively [1].' (Unless [1] contains BOTH numbers).\n"
|
| 88 |
+
" - **NO CITATION DUMPING**: \n"
|
| 89 |
+
" * **Strictly Forbidden:** Never group more than 2 citations together (e.g., `[1][2][3]` is prohibited).\n"
|
| 90 |
+
" * **Requirement:** If multiple sources support a statement, split the statement so each source supports a specific part.\n"
|
| 91 |
+
" - **VERIFICATION**: Ensure the source [x] *actually contains* the specific number attached to it.\n\n"
|
| 92 |
+
"5. **START IMMEDIATELY**: \n"
|
| 93 |
+
" - Start your response directly with the header '### Executive Summary'.\n"
|
| 94 |
+
" - Do not use introductory labels like 'Scientific Answer:' or 'Here is the synthesis'.\n\n"
|
| 95 |
"### REQUIRED OUTPUT FORMAT:\n"
|
| 96 |
"---------------------\n"
|
| 97 |
f"{FEW_SHOT_EXAMPLE}\n"
|
|
|
|
| 165 |
try:
|
| 166 |
# Call LLM via router (handles primary/fallback)
|
| 167 |
response = await self.router.generate(prompt, model_type="synthesis")
|
| 168 |
+
cleaned_response = self._clean_citations(response)
|
| 169 |
logger.info(
|
| 170 |
+
f"Synthesis completed successfully: response_length={len(cleaned_response)}"
|
| 171 |
)
|
| 172 |
+
return cleaned_response.strip()
|
| 173 |
except Exception as e:
|
| 174 |
logger.exception(f"Synthesis failed with error: {e}")
|
| 175 |
# Re-raise to let caller decide how to handle
|
| 176 |
raise
|
| 177 |
|
| 178 |
+
def _clean_citations(self, text: str) -> str:
|
| 179 |
+
"""Clean OpenAI-style citation artifacts."""
|
| 180 |
+
# 1. Fix brackets
|
| 181 |
+
text = text.replace("【", "[").replace("】", "]")
|
| 182 |
+
|
| 183 |
+
# 2. Remove '†' and everything after it (like 'source') until the closing bracket
|
| 184 |
+
# This turns '[1†source]' into '[1]'
|
| 185 |
+
return re.sub(r"†[^\]]*", "", text)
|
| 186 |
+
|
| 187 |
def _format_context(self, nodes: List[NodeWithScore]) -> str:
|
| 188 |
"""Format nodes into a context string with passage indices.
|
| 189 |
|