Python Function As Tool
Pass a plain Python function to an agent as a tool to fetch top HackerNews stories.
"""
Python Function As Tool
=============================
Demonstrates python function as tool.
"""
import json
import httpx
from agno.agent import Agent
# ---------------------------------------------------------------------------
# Create Agent
# ---------------------------------------------------------------------------
def get_top_hackernews_stories(num_stories: int = 10) -> str:
"""Use this function to get top stories from Hacker News.
Args:
num_stories (int): Number of stories to return. Defaults to 10.
Returns:
str: JSON string of top stories.
"""
# Fetch top story IDs
response = httpx.get("https://hacker-news.firebaseio.com/v0/topstories.json")
story_ids = response.json()
# Fetch story details
stories = []
for story_id in story_ids[:num_stories]:
story_response = httpx.get(
f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json"
)
story = story_response.json()
if "text" in story:
story.pop("text", None)
stories.append(story)
return json.dumps(stories)
agent = Agent(tools=[get_top_hackernews_stories], markdown=True)
# ---------------------------------------------------------------------------
# Run Agent
# ---------------------------------------------------------------------------
if __name__ == "__main__":
agent.print_response("Summarize the top 5 stories on hackernews?", stream=True)The function returns Hacker News story metadata, including each story's title and URL. It removes the text field and does not fetch the linked articles, so the response can summarize the listings but cannot ground a summary of the full articles.
Run the Example
Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activateInstall dependencies
uv pip install -U agno openaiExport your OpenAI API key
export OPENAI_API_KEY="your_openai_api_key_here"Run the example
Save the code above as python_function_as_tool.py, then run:
python python_function_as_tool.pyFull source: cookbook/91_tools/python_function_as_tool.py