Add Dependencies to Agent Context
This example demonstrates how to create a context-aware agent that can access real-time HackerNews data through dependency injection, enabling the agent to provide current information.
Create a Python file
1import json23import httpx45from kern.agent import Agent6from kern.models.openai import OpenAIResponses789def get_top_hackernews_stories(num_stories: int = 5) -> str:10 """Fetch and return the top stories from HackerNews.1112 Args:13 num_stories: Number of top stories to retrieve (default: 5)14 Returns:15 JSON string containing story details (title, url, score, etc.)16 """17 stories = [18 {19 k: v20 for k, v in httpx.get(21 f"https://hacker-news.firebaseio.com/v0/item/{id}.json"22 )23 .json()24 .items()25 if k != "kids"26 }27 for id in httpx.get(28 "https://hacker-news.firebaseio.com/v0/topstories.json"29 ).json()[:num_stories]30 ]31 return json.dumps(stories, indent=4)323334agent = Agent(35 model=OpenAIResponses(id="gpt-5.2"),36 dependencies={"top_hackernews_stories": get_top_hackernews_stories},37 add_dependencies_to_context=True,38 markdown=True,39)4041agent.print_response(42 "Summarize the top stories on HackerNews and identify any interesting trends.",43 stream=True,44)Set up your virtual environment
1uv venv --python 3.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateInstall dependencies
1uv pip install -U kern-ai openai httpxExport your OpenAI API key
1export OPENAI_API_KEY=your_openai_api_key_hereRun Agent
1python add_dependencies_to_context.py