Commit ·
7e9f264
1
Parent(s): 32f8638
rate limit and semantic drift fixed
Browse files- agents/semantic_scholar_client.py +7 -2
- config/prompts.py +14 -11
- main.py +1 -0
- services/discovery_service.py +6 -0
agents/semantic_scholar_client.py
CHANGED
|
@@ -103,7 +103,12 @@ class SemanticScholarClient:
|
|
| 103 |
logger.info(f"multi_query_search entry: queries= {[q[:80] for q in queries]}")
|
| 104 |
|
| 105 |
session = await self._get_session()
|
| 106 |
-
tasks = [self._run_query(session, q, limit_per_query, fields) for q in queries]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
start = time.perf_counter()
|
| 109 |
raw_results = await asyncio.gather(*tasks, return_exceptions=True)
|
|
@@ -233,7 +238,7 @@ class SemanticScholarClient:
|
|
| 233 |
) -> List[Dict[str, Any]]:
|
| 234 |
"""Wrapper around _fetch_query that handles retries and backoff."""
|
| 235 |
max_retries = 3
|
| 236 |
-
backoff =
|
| 237 |
for attempt in range(1, max_retries + 1):
|
| 238 |
try:
|
| 239 |
return await self._fetch_query(session, query, limit, fields)
|
|
|
|
| 103 |
logger.info(f"multi_query_search entry: queries= {[q[:80] for q in queries]}")
|
| 104 |
|
| 105 |
session = await self._get_session()
|
| 106 |
+
# tasks = [self._run_query(session, q, limit_per_query, fields) for q in queries]
|
| 107 |
+
# Stagger the requests by 0.2 seconds to prevent burst rate-limiting
|
| 108 |
+
tasks = []
|
| 109 |
+
for q in queries:
|
| 110 |
+
tasks.append(self._run_query(session, q, limit_per_query, fields))
|
| 111 |
+
await asyncio.sleep(0.2)
|
| 112 |
|
| 113 |
start = time.perf_counter()
|
| 114 |
raw_results = await asyncio.gather(*tasks, return_exceptions=True)
|
|
|
|
| 238 |
) -> List[Dict[str, Any]]:
|
| 239 |
"""Wrapper around _fetch_query that handles retries and backoff."""
|
| 240 |
max_retries = 3
|
| 241 |
+
backoff = 2
|
| 242 |
for attempt in range(1, max_retries + 1):
|
| 243 |
try:
|
| 244 |
return await self._fetch_query(session, query, limit, fields)
|
config/prompts.py
CHANGED
|
@@ -21,7 +21,8 @@ CITATION_QA_TEMPLATE = (
|
|
| 21 |
" * *Definitional:* **Core Concept: [Phrase].**\n"
|
| 22 |
" * *Methodological:* **Standard Protocol: [Method].**\n"
|
| 23 |
" * *Open:* **Scientific Consensus: [Theme].**\n"
|
| 24 |
-
" - Follow with a high-level thesis sentence summarizing the answer.\n
|
|
|
|
| 25 |
"2. **THE EVIDENCE (Structured & Rigorous):**\n"
|
| 26 |
" - **Evidence Synthesis:** Synthesize the high-authority agreement. What is the established truth? (Cite support).\n"
|
| 27 |
" - **Critical Nuances:** Discuss conflicts, sexual dimorphism, in vivo vs in vitro discrepancies, or major limitations.\n\n"
|
|
@@ -62,17 +63,17 @@ QUERY_OPTIMIZATION_TEMPLATE = """You are a query optimization expert for scienti
|
|
| 62 |
|
| 63 |
**INTENT ANALYSIS (Crucial):**
|
| 64 |
Analyze the user's intent to optimize the 'broad' field:
|
| 65 |
-
1. **Overview/Consensus needed?**
|
| 66 |
-
2. **Latest News needed?**
|
| 67 |
-
3. **Specific Details?** ->
|
| 68 |
|
| 69 |
Output Format (JSON):
|
| 70 |
{{
|
| 71 |
"strategy": "expansion",
|
| 72 |
"final_rephrase": "Clear natural language question for semantic search",
|
| 73 |
-
"primary": "
|
| 74 |
-
"broad": "
|
| 75 |
-
"alternative": "
|
| 76 |
}}
|
| 77 |
|
| 78 |
**Strategy B: Decomposition**
|
|
@@ -84,14 +85,16 @@ QUERY_OPTIMIZATION_TEMPLATE = """You are a query optimization expert for scienti
|
|
| 84 |
"strategy": "decomposition",
|
| 85 |
"final_rephrase": "The overarching question in clear natural language",
|
| 86 |
"sub_queries": [
|
| 87 |
-
"
|
| 88 |
-
"
|
| 89 |
"..."
|
| 90 |
]
|
| 91 |
}}
|
| 92 |
|
| 93 |
**CRITICAL RULES:**
|
| 94 |
-
-
|
| 95 |
-
-
|
|
|
|
|
|
|
| 96 |
- Return ONLY valid JSON.
|
| 97 |
"""
|
|
|
|
| 21 |
" * *Definitional:* **Core Concept: [Phrase].**\n"
|
| 22 |
" * *Methodological:* **Standard Protocol: [Method].**\n"
|
| 23 |
" * *Open:* **Scientific Consensus: [Theme].**\n"
|
| 24 |
+
" - Follow with a high-level thesis sentence summarizing the answer.\n"
|
| 25 |
+
" - Relevance Filter: Before citing a source, verify it discusses the SPECIFIC topic requested. If a retrieved chunk is off-topic, ignore it.\n\n"
|
| 26 |
"2. **THE EVIDENCE (Structured & Rigorous):**\n"
|
| 27 |
" - **Evidence Synthesis:** Synthesize the high-authority agreement. What is the established truth? (Cite support).\n"
|
| 28 |
" - **Critical Nuances:** Discuss conflicts, sexual dimorphism, in vivo vs in vitro discrepancies, or major limitations.\n\n"
|
|
|
|
| 63 |
|
| 64 |
**INTENT ANALYSIS (Crucial):**
|
| 65 |
Analyze the user's intent to optimize the 'broad' field:
|
| 66 |
+
1. **Overview/Consensus needed?** -> Set 'broad' to Subject + "review" (pick ONE term).
|
| 67 |
+
2. **Latest News needed?** -> Set 'broad' to Subject + "recent" (pick ONE term).
|
| 68 |
+
3. **Specific Details?** -> Set 'broad' to Subject + "analysis" (pick ONE term).
|
| 69 |
|
| 70 |
Output Format (JSON):
|
| 71 |
{{
|
| 72 |
"strategy": "expansion",
|
| 73 |
"final_rephrase": "Clear natural language question for semantic search",
|
| 74 |
+
"primary": "Subject + Context (MAX 4 WORDS)",
|
| 75 |
+
"broad": "Subject + Intent (MAX 3 WORDS)",
|
| 76 |
+
"alternative": "Subject + Controversy (MAX 3 WORDS)"
|
| 77 |
}}
|
| 78 |
|
| 79 |
**Strategy B: Decomposition**
|
|
|
|
| 85 |
"strategy": "decomposition",
|
| 86 |
"final_rephrase": "The overarching question in clear natural language",
|
| 87 |
"sub_queries": [
|
| 88 |
+
"Subject + Subtopic 1 (MAX 4 WORDS)",
|
| 89 |
+
"Subject + Subtopic 2 (MAX 4 WORDS)",
|
| 90 |
"..."
|
| 91 |
]
|
| 92 |
}}
|
| 93 |
|
| 94 |
**CRITICAL RULES:**
|
| 95 |
+
- **ABSOLUTELY NO boolean operators** (AND, OR, NOT).
|
| 96 |
+
- **ABSOLUTELY NO parentheses** or special characters.
|
| 97 |
+
- **Keep it Short:** Queries longer than 4 words often return 0 results.
|
| 98 |
+
- **Broad/Alternative:** Do not copy the full primary query. Use only the main subject + 1 modifier.
|
| 99 |
- Return ONLY valid JSON.
|
| 100 |
"""
|
main.py
CHANGED
|
@@ -85,6 +85,7 @@ async def lifespan(app: FastAPI):
|
|
| 85 |
Lifespan context manager that handles startup and shutdown logic.
|
| 86 |
Replaces @app.on_event("startup").
|
| 87 |
"""
|
|
|
|
| 88 |
# Initialize state attributes to avoid AttributeErrors if startup fails
|
| 89 |
app.state.search_queue = asyncio.Queue()
|
| 90 |
app.state.query_service = None
|
|
|
|
| 85 |
Lifespan context manager that handles startup and shutdown logic.
|
| 86 |
Replaces @app.on_event("startup").
|
| 87 |
"""
|
| 88 |
+
|
| 89 |
# Initialize state attributes to avoid AttributeErrors if startup fails
|
| 90 |
app.state.search_queue = asyncio.Queue()
|
| 91 |
app.state.query_service = None
|
services/discovery_service.py
CHANGED
|
@@ -101,6 +101,12 @@ class DiscoveryService:
|
|
| 101 |
) from e
|
| 102 |
raise SemanticScholarError(f"Failed to search papers: {str(e)}") from e
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
# Quality Gate
|
| 105 |
logger.info(
|
| 106 |
"Stage 3{}: Quality gate validation - {} papers to validate",
|
|
|
|
| 101 |
) from e
|
| 102 |
raise SemanticScholarError(f"Failed to search papers: {str(e)}") from e
|
| 103 |
|
| 104 |
+
if not papers:
|
| 105 |
+
logger.warning(
|
| 106 |
+
"Search{} returned 0 papers. Skipping Quality Gate.", attempt_label
|
| 107 |
+
)
|
| 108 |
+
return [], {"passed": False, "reason": "No papers found"}
|
| 109 |
+
|
| 110 |
# Quality Gate
|
| 111 |
logger.info(
|
| 112 |
"Stage 3{}: Quality gate validation - {} papers to validate",
|