Sborole-Final-Assignment / tools /SemanticScholar.py
Sborole's picture
Create SemanticScholar.py
c7429cc verified
raw
history blame
1.62 kB
from smolagents import Tool
from semanticscholar import SemanticScholar
class AcademicPaperSearchTool(Tool):
name = "academic_paper_search"
description = "Searches academic papers via Semantic Scholar and returns the most relevant titles and abstracts."
inputs = {
"query": {"type": "string", "description": "Search query for academic papers (title, keywords, etc.)"}
}
output_type = "string"
def forward(self, query: str) -> str:
sch = SemanticScholar()
try:
# Use query=query to avoid potential keyword issues with the SemanticScholar method
papers = sch.search_paper(query, limit=3) # get top-3 matching papers
except Exception as e:
return f"An error occurred during search: {e}"
if not papers:
return "No papers found."
# Format results concisely
lines = []
for p in papers:
# --- THE FIX IS HERE ---
# Access attributes directly using dot notation (p.title, p.year, p.abstract)
# instead of the dictionary method p.get(...)
title = p.title
year = p.year
abstract = p.abstract if p.abstract else "" # Check if abstract exists
# Only take the first sentence or two of the abstract
abstract_snip = abstract.split(". ")[0] if abstract else ""
# Ensure 'year' is handled gracefully (it can sometimes be None)
year_str = str(year) if year else "N/A"
lines.append(f"**{title}** ({year_str}): {abstract_snip}...")
return "\n".join(lines)