Agent Tools
Equip agents with functions and toolkits for external actions.
Agents use tools to take actions and interact with external systems.
Tools are functions that an Agent can run to achieve tasks. For example: searching the web, running SQL, sending an email or calling APIs. You can use any python function as a tool or use a pre-built Kern toolkit.
The general syntax is:
1from kern.agent import Agent23agent = Agent(4 # Add functions or Toolkits5 tools=[...],6)Tools can be a callable factory and are resolved at run time.
Using a Toolkit
Kern provides many pre-built toolkits that you can add to your Agents. For example, let's use the HackerNews toolkit to fetch tech news.
You can find more toolkits in the Toolkits guide.
Create News Agent
Create a file news_agent.py
1from kern.agent import Agent2from kern.tools.hackernews import HackerNewsTools34agent = Agent(tools=[HackerNewsTools()], markdown=True)5agent.print_response("What are the top stories on HackerNews?", stream=True)Run the agent
Install dependencies
1uv pip install openai kern-aiRun the agent
1python news_agent.pyWriting your own Tools
For more control, write your own python functions and add them as tools to an Agent. For example, here's how to add a get_top_hackernews_stories tool to an Agent.
1import json2import httpx34from kern.agent import Agent56def get_top_hackernews_stories(num_stories: int = 10) -> str:7 """Use this function to get top stories from Hacker News.89 Args:10 num_stories (int): Number of stories to return. Defaults to 10.11 """1213 # Fetch top story IDs14 response = httpx.get('https://hacker-news.firebaseio.com/v0/topstories.json')15 story_ids = response.json()1617 # Fetch story details18 stories = []19 for story_id in story_ids[:num_stories]:20 story_response = httpx.get(f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json')21 story = story_response.json()22 if "text" in story:23 story.pop("text", None)24 stories.append(story)25 return json.dumps(stories)2627agent = Agent(tools=[get_top_hackernews_stories], markdown=True)28agent.print_response("Summarize the top 5 stories on hackernews?", stream=True)Read more about: