Adam Cseresznye commited on
Commit ·
ad79bac
1
Parent(s): 8eb0662
Improve query parsing and synthesis prompt structure
Browse files- agents/query_optimization_agent.py +36 -32
- agents/synthesis_agent.py +16 -8
agents/query_optimization_agent.py
CHANGED
|
@@ -3,19 +3,10 @@
|
|
| 3 |
Transforms a single user query into dual optimized outputs: a focused final_rephrase
|
| 4 |
for passage-level semantic retrieval, and three Semantic Scholar search variants
|
| 5 |
(primary, broad, alternative) for paper-level discovery.
|
| 6 |
-
|
| 7 |
-
Usage example:
|
| 8 |
-
agent = QueryOptimizationAgent()
|
| 9 |
-
optimized = await agent.generate_dual_queries("intermittent fasting cardiovascular risks")
|
| 10 |
-
# Returns: {
|
| 11 |
-
# "final_rephrase": "cardiovascular risks of intermittent fasting",
|
| 12 |
-
# "primary": "intermittent fasting cardiovascular risks",
|
| 13 |
-
# "broad": "fasting protocols health outcomes cardiovascular",
|
| 14 |
-
# "alternative": "time-restricted eating cardiac complications"
|
| 15 |
-
# }
|
| 16 |
"""
|
| 17 |
|
| 18 |
import json
|
|
|
|
| 19 |
from typing import Dict, Optional
|
| 20 |
from loguru import logger
|
| 21 |
|
|
@@ -87,26 +78,35 @@ class QueryOptimizationAgent:
|
|
| 87 |
return None
|
| 88 |
|
| 89 |
def _parse_json_response(self, response: str) -> Optional[Dict]:
|
| 90 |
-
"""Parse JSON response from LLM."""
|
|
|
|
| 91 |
try:
|
| 92 |
return json.loads(response)
|
| 93 |
except json.JSONDecodeError:
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
parsed = json.loads(json_block)
|
| 101 |
-
return parsed
|
| 102 |
-
except json.JSONDecodeError as e2:
|
| 103 |
-
logger.warning("Extracted JSON block parsing failed: {}", e2)
|
| 104 |
-
|
| 105 |
-
logger.exception(
|
| 106 |
-
"JSON parsing failed: response not valid JSON or no parsable JSON block found"
|
| 107 |
-
)
|
| 108 |
return None
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
def _extract_json_block(self, text: str) -> Optional[str]:
|
| 111 |
"""Extract the first balanced JSON object from text.
|
| 112 |
|
|
@@ -163,12 +163,12 @@ class QueryOptimizationAgent:
|
|
| 163 |
- Optimized for Semantic Scholar's keyword matching
|
| 164 |
- Example: "fasting protocols cardiovascular health metabolic effects time-restricted eating"
|
| 165 |
|
| 166 |
-
4. **alternative**:
|
| 167 |
-
- Purpose: Finding
|
| 168 |
-
- Format: 4-10 keywords
|
| 169 |
-
-
|
| 170 |
-
- Optimized for
|
| 171 |
-
- Example: "
|
| 172 |
|
| 173 |
**Semantic Scholar Query Best Practices:**
|
| 174 |
- Use quotes for exact phrases: "red blood cell"
|
|
@@ -178,7 +178,11 @@ class QueryOptimizationAgent:
|
|
| 178 |
- Match terminology commonly found in paper titles/abstracts
|
| 179 |
- Keep PRIMARY/BROAD/ALTERNATIVE variants focused on the core topic. Avoid expanding into loosely related subtopics.
|
| 180 |
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
{{
|
| 184 |
"final_rephrase": "...",
|
|
|
|
| 3 |
Transforms a single user query into dual optimized outputs: a focused final_rephrase
|
| 4 |
for passage-level semantic retrieval, and three Semantic Scholar search variants
|
| 5 |
(primary, broad, alternative) for paper-level discovery.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import json
|
| 9 |
+
import ast #
|
| 10 |
from typing import Dict, Optional
|
| 11 |
from loguru import logger
|
| 12 |
|
|
|
|
| 78 |
return None
|
| 79 |
|
| 80 |
def _parse_json_response(self, response: str) -> Optional[Dict]:
|
| 81 |
+
"""Parse JSON response from LLM, handling both JSON and Python-dict formats."""
|
| 82 |
+
# 1. Try strict JSON parsing first (fastest/safest)
|
| 83 |
try:
|
| 84 |
return json.loads(response)
|
| 85 |
except json.JSONDecodeError:
|
| 86 |
+
pass
|
| 87 |
+
|
| 88 |
+
# 2. Extract the block (handles markdown fences like ```json ... ```)
|
| 89 |
+
json_block = self._extract_json_block(response)
|
| 90 |
+
if not json_block:
|
| 91 |
+
logger.error("No JSON block found in response")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
return None
|
| 93 |
|
| 94 |
+
# 3. Try strict JSON parsing on the extracted block
|
| 95 |
+
try:
|
| 96 |
+
return json.loads(json_block)
|
| 97 |
+
except json.JSONDecodeError as e:
|
| 98 |
+
# 4. Fallback: Try ast.literal_eval for Python-style dicts (single quotes)
|
| 99 |
+
# This fixes "Expecting property name enclosed in double quotes"
|
| 100 |
+
try:
|
| 101 |
+
# ast.literal_eval safely evaluates a string containing a Python literal
|
| 102 |
+
return ast.literal_eval(json_block)
|
| 103 |
+
except (ValueError, SyntaxError):
|
| 104 |
+
logger.warning(
|
| 105 |
+
"Parsing failed via both json.loads and ast.literal_eval. Error: {}",
|
| 106 |
+
e,
|
| 107 |
+
)
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
def _extract_json_block(self, text: str) -> Optional[str]:
|
| 111 |
"""Extract the first balanced JSON object from text.
|
| 112 |
|
|
|
|
| 163 |
- Optimized for Semantic Scholar's keyword matching
|
| 164 |
- Example: "fasting protocols cardiovascular health metabolic effects time-restricted eating"
|
| 165 |
|
| 166 |
+
4. **alternative**: Critical perspective and comparative search
|
| 167 |
+
- Purpose: Finding conflicting evidence, limitations, and direct comparisons to standard care.
|
| 168 |
+
- Format: 4-10 keywords focusing on "vs", "safety", "side effects", or "limitations"
|
| 169 |
+
- Action: If the topic is a treatment (e.g., "fasting"), search for risks or comparisons (e.g., "intermittent fasting vs calorie restriction safety").
|
| 170 |
+
- Optimized for: Finding the "Safety" and "Comparison" sections often missing from basic searches.
|
| 171 |
+
- Example: "intermittent fasting side effects safety long-term risks vs caloric restriction"
|
| 172 |
|
| 173 |
**Semantic Scholar Query Best Practices:**
|
| 174 |
- Use quotes for exact phrases: "red blood cell"
|
|
|
|
| 178 |
- Match terminology commonly found in paper titles/abstracts
|
| 179 |
- Keep PRIMARY/BROAD/ALTERNATIVE variants focused on the core topic. Avoid expanding into loosely related subtopics.
|
| 180 |
|
| 181 |
+
**IMPORTANT FORMATTING RULES:**
|
| 182 |
+
- Return ONLY valid JSON.
|
| 183 |
+
- Use DOUBLE QUOTES for all keys and string values (e.g., "key": "value").
|
| 184 |
+
- Do not use single quotes.
|
| 185 |
+
- No markdown formatting or explanation text.
|
| 186 |
|
| 187 |
{{
|
| 188 |
"final_rephrase": "...",
|
agents/synthesis_agent.py
CHANGED
|
@@ -29,20 +29,28 @@ from llama_index.core.schema import NodeWithScore
|
|
| 29 |
from utils.llm_router import LLMRouter
|
| 30 |
|
| 31 |
|
| 32 |
-
# Citation prompt template that enforces strict sourcing
|
| 33 |
CITATION_QA_TEMPLATE = (
|
| 34 |
-
"You are an
|
| 35 |
-
"using ONLY the provided context passages.\n"
|
| 36 |
"---------------------\n"
|
| 37 |
"{context_str}\n"
|
| 38 |
"---------------------\n"
|
| 39 |
"Instructions:\n"
|
| 40 |
-
"1.
|
| 41 |
-
"
|
| 42 |
-
"
|
| 43 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
"User Query: {query_str}\n"
|
| 45 |
-
"Answer: "
|
| 46 |
)
|
| 47 |
|
| 48 |
|
|
|
|
| 29 |
from utils.llm_router import LLMRouter
|
| 30 |
|
| 31 |
|
| 32 |
+
# Citation prompt template that enforces strict sourcing AND Consensus-style structure
|
| 33 |
CITATION_QA_TEMPLATE = (
|
| 34 |
+
"You are an expert research synthesizer. Your task is to generate a comprehensive, "
|
| 35 |
+
"structured answer to the user's query using ONLY the provided context passages.\n"
|
| 36 |
"---------------------\n"
|
| 37 |
"{context_str}\n"
|
| 38 |
"---------------------\n"
|
| 39 |
"Instructions:\n"
|
| 40 |
+
"1. **Structure**: Do not output a wall of text. You MUST organize your answer into these Markdown sections:\n"
|
| 41 |
+
" - **Executive Summary**: A 2-sentence high-level overview.\n"
|
| 42 |
+
" - **Key Findings & Mechanisms**: The primary results, explaining *how* or *why* things happen (e.g., metabolic switching).\n"
|
| 43 |
+
" - **Comparison & Context**: How does this compare to standard approaches (e.g., vs. calorie restriction)? (If data exists).\n"
|
| 44 |
+
" - **Safety, Limitations & Uncertainties**: Explicitly state side effects, conflicting evidence, or gaps in the research.\n"
|
| 45 |
+
" - **Conclusion**: A final wrap-up.\n\n"
|
| 46 |
+
"2. **Formatting**: Use bullet points for readability. **Bold** key terms and important concepts.\n"
|
| 47 |
+
"3. **Strict Citation**: Cite the source passage for EVERY claim using the format [N], where N is the passage index.\n"
|
| 48 |
+
" - Example: 'Fasting improves insulin sensitivity [1] and lowers blood pressure [2, 4].'\n"
|
| 49 |
+
" - Place citations immediately after the specific claim, not just at the end of the sentence.\n"
|
| 50 |
+
"4. **Nuance**: Do not just list positive results. Highlight conflicts or specific conditions (e.g., 'works for men but not women').\n"
|
| 51 |
+
"5. **Constraints**: If the context is insufficient, state: 'I cannot answer this based on the provided sources.' Do not hallucinate external info.\n\n"
|
| 52 |
"User Query: {query_str}\n"
|
| 53 |
+
"Structured Answer: "
|
| 54 |
)
|
| 55 |
|
| 56 |
|