nikeshn commited on
Commit
3abe8dd
Β·
verified Β·
1 Parent(s): 6790061

Update src/api/agent.py

Browse files
Files changed (1) hide show
  1. src/api/agent.py +154 -11
src/api/agent.py CHANGED
@@ -415,6 +415,7 @@ def _source_badge(source: str, url: str = "") -> str:
415
  "rag": ("πŸ“–", "KU Library Knowledge Base", "#fef3c7", "#92400e"),
416
  "primo": ("πŸ“š", "KU Library PRIMO", "#eff6ff", "#1e40af"),
417
  "semantic": ("πŸŽ“", "Semantic Scholar", "#f0fdf4", "#166534"),
 
418
  "pubmed": ("πŸ₯", "PubMed", "#d1fae5", "#065f46"),
419
  "web": ("🌐", "Web Search", "#f5f3ff", "#4c1d95"),
420
  "web_live": ("🌐", "Web Search Β· Live", "#fdf4ff", "#86198f"),
@@ -1395,7 +1396,139 @@ async def _semantic_scholar_search(topic: str, limit: int = 8) -> List[dict]:
1395
  return []
1396
 
1397
 
1398
- async def _generate_cited_summary(topic: str, papers: List[dict], model: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1399
  settings = get_settings()
1400
  if not settings.openai_api_key and not settings.anthropic_api_key:
1401
  return ""
@@ -2259,21 +2392,26 @@ def _highly_cited_note(topic_escaped: str) -> str:
2259
  async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple[str, List[dict], List[dict]]:
2260
  """
2261
  Research snapshot:
2262
- - Reasoning block at the top (collapsible).
2263
- - Cited summary in the middle.
2264
- - PRIMO results below that.
2265
- - AI tools recommendation panel always at the very end.
2266
- - Silent fallback if Semantic Scholar returns nothing.
2267
  """
2268
  import asyncio as _asyncio
2269
  topic = context.topic
2270
  references: List[dict] = []
2271
 
2272
- # Parallel fetch
2273
  papers, (primo_result, primo_url) = await _asyncio.gather(
2274
- _semantic_scholar_search(topic, limit=8),
2275
  _search_primo_catalog(context, limit=6),
2276
  )
 
 
 
 
 
 
2277
  search_results = primo_result.get("results", []) or []
2278
 
2279
  # ── Top: reasoning block ──────────────────────────────────────────────────
@@ -2286,6 +2424,10 @@ async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple
2286
  _safe_metrics_increment("summary_fallbacks")
2287
  summary = _extractive_snapshot_from_papers(topic, papers)
2288
 
 
 
 
 
2289
  # ── Middle: cited summary ─────────────────────────────────────────────
2290
  answer += f"<strong>πŸ“– Research Snapshot: {_escape(topic)}</strong><br><br>{summary}"
2291
 
@@ -2304,7 +2446,9 @@ async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple
2304
  f'{_escape(paper["authors"])} Β· {paper["year"]} Β· {_escape(paper["venue"] or "")}'
2305
  f"</span>"
2306
  )
2307
- answer += _source_badge("semantic", "https://www.semanticscholar.org/")
 
 
2308
  if search_results:
2309
  answer += _source_badge("primo", primo_url)
2310
 
@@ -2313,7 +2457,7 @@ async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple
2313
  references = [{"title": p["title"], "url": p["link"]} for p in papers[:6]]
2314
  return answer, search_results, references
2315
 
2316
- # Semantic Scholar returned nothing β€” silent fallback
2317
  if search_results:
2318
  answer += (
2319
  f"<strong>πŸ“š Research starting points: {_escape(topic)}</strong><br><br>"
@@ -2325,7 +2469,6 @@ async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple
2325
  "I didn't find direct results right now β€” try the AI research tools below."
2326
  )
2327
  answer += _source_badge("primo", primo_url)
2328
- # ── Bottom: AI tools ──────────────────────────────────────────────────────
2329
  answer += _ai_tools_footer(context)
2330
  return answer, search_results, []
2331
 
 
415
  "rag": ("πŸ“–", "KU Library Knowledge Base", "#fef3c7", "#92400e"),
416
  "primo": ("πŸ“š", "KU Library PRIMO", "#eff6ff", "#1e40af"),
417
  "semantic": ("πŸŽ“", "Semantic Scholar", "#f0fdf4", "#166534"),
418
+ "consensus_badge": ("🧬", "Consensus", "#fdf4ff", "#86198f"),
419
  "pubmed": ("πŸ₯", "PubMed", "#d1fae5", "#065f46"),
420
  "web": ("🌐", "Web Search", "#f5f3ff", "#4c1d95"),
421
  "web_live": ("🌐", "Web Search Β· Live", "#fdf4ff", "#86198f"),
 
1396
  return []
1397
 
1398
 
1399
+ async def _consensus_mcp_search(topic: str, model: str, limit: int = 8) -> List[dict]:
1400
+ """
1401
+ Search Consensus via Anthropic MCP to get real peer-reviewed papers with abstracts.
1402
+ Returns papers in the same dict format as _semantic_scholar_search so the rest of
1403
+ _research_snapshot works unchanged.
1404
+ Falls back silently to Semantic Scholar if Consensus MCP fails.
1405
+ """
1406
+ settings = get_settings()
1407
+ if not settings.anthropic_api_key:
1408
+ return []
1409
+
1410
+ prompt = (
1411
+ f"Search for {limit} high-quality peer-reviewed papers on this topic: {topic}\n\n"
1412
+ f"For each paper return: title, authors, year, abstract (2-3 sentences), "
1413
+ f"journal/venue, and DOI or URL. Focus on influential and recent papers."
1414
+ )
1415
+ try:
1416
+ async with httpx.AsyncClient(timeout=30) as client:
1417
+ r = await client.post(
1418
+ "https://api.anthropic.com/v1/messages",
1419
+ headers={
1420
+ "Content-Type": "application/json",
1421
+ "x-api-key": settings.anthropic_api_key,
1422
+ "anthropic-version": "2023-06-01",
1423
+ "anthropic-beta": "mcp-client-2025-04-04",
1424
+ },
1425
+ json={
1426
+ "model": "claude-haiku-4-5-20251001",
1427
+ "max_tokens": 2000,
1428
+ "messages": [{"role": "user", "content": prompt}],
1429
+ "mcp_servers": [{
1430
+ "type": "url",
1431
+ "url": "https://mcp.consensus.app/mcp",
1432
+ "name": "consensus"
1433
+ }],
1434
+ },
1435
+ )
1436
+ if r.status_code != 200:
1437
+ logger.warning(f"Consensus MCP returned {r.status_code}")
1438
+ return []
1439
+
1440
+ data = r.json()
1441
+ # Collect all text blocks (tool results + final text)
1442
+ text_parts = []
1443
+ for block in data.get("content", []):
1444
+ if block.get("type") == "text":
1445
+ text_parts.append(block["text"])
1446
+ elif block.get("type") == "mcp_tool_result":
1447
+ for item in block.get("content", []):
1448
+ if item.get("type") == "text":
1449
+ text_parts.append(item["text"])
1450
+ full_text = "\n".join(text_parts)
1451
+ if not full_text.strip():
1452
+ return []
1453
+
1454
+ # Parse the structured text into paper dicts using LLM
1455
+ papers = await _parse_consensus_response(full_text, topic, settings.anthropic_api_key)
1456
+ logger.info(f"Consensus MCP returned {len(papers)} papers for: {topic[:50]}")
1457
+ return papers[:limit]
1458
+
1459
+ except Exception as e:
1460
+ logger.warning(f"Consensus MCP search failed: {e} β€” will fall back to Semantic Scholar")
1461
+ return []
1462
+
1463
+
1464
+ async def _parse_consensus_response(text: str, topic: str, api_key: str) -> List[dict]:
1465
+ """Parse Consensus MCP response text into structured paper dicts."""
1466
+ try:
1467
+ async with httpx.AsyncClient(timeout=15) as client:
1468
+ r = await client.post(
1469
+ "https://api.anthropic.com/v1/messages",
1470
+ headers={
1471
+ "Content-Type": "application/json",
1472
+ "x-api-key": api_key,
1473
+ "anthropic-version": "2023-06-01",
1474
+ },
1475
+ json={
1476
+ "model": "claude-haiku-4-5-20251001",
1477
+ "max_tokens": 1500,
1478
+ "messages": [{
1479
+ "role": "user",
1480
+ "content": (
1481
+ "Extract the research papers from this text into a JSON array. "
1482
+ "Each paper object must have: title, authors (string), year (string), "
1483
+ "abstract (string, keep it), venue (journal name), doi (string or null), url (string or null). "
1484
+ "Return ONLY valid JSON array, no markdown, no preamble.\n\n"
1485
+ f"Text:\n{text[:4000]}"
1486
+ )
1487
+ }],
1488
+ },
1489
+ )
1490
+ if r.status_code != 200:
1491
+ return []
1492
+ raw = "".join(
1493
+ b["text"] for b in r.json().get("content", []) if b.get("type") == "text"
1494
+ ).strip()
1495
+ # Strip markdown fences if present
1496
+ if raw.startswith("```"):
1497
+ raw = raw.split("\n", 1)[1].rsplit("```", 1)[0].strip()
1498
+ papers_raw = json.loads(raw)
1499
+ if not isinstance(papers_raw, list):
1500
+ return []
1501
+
1502
+ results = []
1503
+ for p in papers_raw:
1504
+ if not isinstance(p, dict) or not p.get("title"):
1505
+ continue
1506
+ doi = (p.get("doi") or "").strip()
1507
+ url = (p.get("url") or "").strip()
1508
+ link = (
1509
+ url if url and url.startswith("http")
1510
+ else (f"https://doi.org/{doi}" if doi else "")
1511
+ or f"https://consensus.app/results/?q={quote(p.get('title', ''))}"
1512
+ )
1513
+ authors_raw = p.get("authors", "Unknown")
1514
+ author_list = [a.strip() for a in str(authors_raw).split(",")]
1515
+ first_last = author_list[0].split()[-1] if author_list else "Unknown"
1516
+ year = str(p.get("year", "n.d.") or "n.d.")
1517
+ results.append({
1518
+ "title": p.get("title", "Untitled"),
1519
+ "authors": ", ".join(author_list[:3]) + (" et al." if len(author_list) > 3 else ""),
1520
+ "first_author": first_last,
1521
+ "year": year,
1522
+ "citation_key": f"{first_last}, {year}",
1523
+ "venue": p.get("venue", "") or "",
1524
+ "abstract": (p.get("abstract") or "")[:700],
1525
+ "link": link,
1526
+ "_source": "Consensus",
1527
+ })
1528
+ return results
1529
+ except Exception as e:
1530
+ logger.warning(f"_parse_consensus_response failed: {e}")
1531
+ return []
1532
  settings = get_settings()
1533
  if not settings.openai_api_key and not settings.anthropic_api_key:
1534
  return ""
 
2392
  async def _research_snapshot(context: SearchContextPayload, model: str) -> Tuple[str, List[dict], List[dict]]:
2393
  """
2394
  Research snapshot:
2395
+ - Uses Consensus MCP for peer-reviewed papers with abstracts (primary).
2396
+ - Falls back to Semantic Scholar silently if Consensus returns nothing.
2397
+ - Runs PRIMO in parallel for KU-accessible results.
2398
+ - Reasoning block at the top, cited summary in the middle, AI tools at the end.
 
2399
  """
2400
  import asyncio as _asyncio
2401
  topic = context.topic
2402
  references: List[dict] = []
2403
 
2404
+ # Parallel fetch: Consensus MCP + PRIMO
2405
  papers, (primo_result, primo_url) = await _asyncio.gather(
2406
+ _consensus_mcp_search(topic, model, limit=8),
2407
  _search_primo_catalog(context, limit=6),
2408
  )
2409
+
2410
+ # Silent fallback to Semantic Scholar if Consensus returned nothing
2411
+ if not papers:
2412
+ logger.info(f"Consensus returned no papers for '{topic}' β€” trying Semantic Scholar")
2413
+ papers = await _semantic_scholar_search(topic, limit=8)
2414
+
2415
  search_results = primo_result.get("results", []) or []
2416
 
2417
  # ── Top: reasoning block ──────────────────────────────────────────────────
 
2424
  _safe_metrics_increment("summary_fallbacks")
2425
  summary = _extractive_snapshot_from_papers(topic, papers)
2426
 
2427
+ source_label = papers[0].get("_source", "Consensus")
2428
+ source_url = "https://consensus.app" if source_label == "Consensus" else "https://www.semanticscholar.org/"
2429
+ source_key = "consensus_badge" if source_label == "Consensus" else "semantic"
2430
+
2431
  # ── Middle: cited summary ─────────────────────────────────────────────
2432
  answer += f"<strong>πŸ“– Research Snapshot: {_escape(topic)}</strong><br><br>{summary}"
2433
 
 
2446
  f'{_escape(paper["authors"])} Β· {paper["year"]} Β· {_escape(paper["venue"] or "")}'
2447
  f"</span>"
2448
  )
2449
+
2450
+ # Source badge β€” show Consensus or Semantic Scholar depending on which fired
2451
+ answer += _source_badge(source_key, source_url)
2452
  if search_results:
2453
  answer += _source_badge("primo", primo_url)
2454
 
 
2457
  references = [{"title": p["title"], "url": p["link"]} for p in papers[:6]]
2458
  return answer, search_results, references
2459
 
2460
+ # Both Consensus and Semantic Scholar returned nothing β€” PRIMO-only fallback
2461
  if search_results:
2462
  answer += (
2463
  f"<strong>πŸ“š Research starting points: {_escape(topic)}</strong><br><br>"
 
2469
  "I didn't find direct results right now β€” try the AI research tools below."
2470
  )
2471
  answer += _source_badge("primo", primo_url)
 
2472
  answer += _ai_tools_footer(context)
2473
  return answer, search_results, []
2474