Skip to content

Commit aa4eb81

Browse files
committed
pubmed tool added
1 parent 55e23d4 commit aa4eb81

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
from openagi.actions.base import ConfigurableAction
2+
from openagi.exception import OpenAGIException
3+
from pydantic import Field
4+
5+
try:
6+
from Bio import Entrez
7+
except ImportError:
8+
raise OpenAGIException("Install Biopython with cmd `pip install biopython`")
9+
10+
class PubMedSearch(ConfigurableAction):
11+
"""PubMed Search tool for querying biomedical literature.
12+
13+
This action uses the Bio.Entrez module to search PubMed and retrieve
14+
scientific articles based on user queries. Requires an email address
15+
to be configured for NCBI's tracking purposes.
16+
"""
17+
18+
query: str = Field(..., description="Search query for PubMed")
19+
max_results: int = Field(
20+
default=5,
21+
description="Maximum number of results to return (default: 5)"
22+
)
23+
sort: str = Field(
24+
default="relevance",
25+
description="Sort order: 'relevance', 'pub_date', or 'first_author'"
26+
)
27+
28+
def execute(self) -> str:
29+
email: str = self.get_config('email')
30+
if not email:
31+
raise OpenAGIException(
32+
"Email not configured. Use PubMedSearch.set_config(email='[email protected]')"
33+
)
34+
35+
Entrez.email = email
36+
37+
try:
38+
# Search PubMed
39+
search_handle = Entrez.esearch(
40+
db="pubmed",
41+
term=self.query,
42+
retmax=self.max_results,
43+
sort=self.sort
44+
)
45+
search_results = Entrez.read(search_handle)
46+
search_handle.close()
47+
48+
if not search_results["IdList"]:
49+
return "No results found for the given query."
50+
51+
# Fetch details for found articles
52+
ids = ",".join(search_results["IdList"])
53+
fetch_handle = Entrez.efetch(
54+
db="pubmed",
55+
id=ids,
56+
rettype="medline",
57+
retmode="text"
58+
)
59+
60+
results = fetch_handle.read()
61+
fetch_handle.close()
62+
63+
# Process and format results
64+
formatted_results = (
65+
f"Found {len(search_results['IdList'])} results for query: {self.query}\n\n"
66+
f"{results}"
67+
)
68+
69+
return formatted_results
70+
71+
except Exception as e:
72+
return f"Error searching PubMed: {str(e)}"

0 commit comments

Comments
 (0)