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 json
2
3import httpx
4
5from kern.agent import Agent
6from kern.models.openai import OpenAIResponses
7
8
9def get_top_hackernews_stories(num_stories: int = 5) -> str:
10 """Fetch and return the top stories from HackerNews.
11
12 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: v
20 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)
32
33
34agent = 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)
40
41agent.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.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Install dependencies

1uv pip install -U kern-ai openai httpx

Export your OpenAI API key

1export OPENAI_API_KEY=your_openai_api_key_here

Run Agent

1python add_dependencies_to_context.py