Dependencies In Context

Exclude discussion threads.

Dependencies In Context.

1"""
2Dependencies In Context
3=============================
4
5Dependencies In Context.
6"""
7
8import json
9
10import httpx
11from kern.agent import Agent
12from kern.models.openai import OpenAIResponses
13
14
15def get_top_hackernews_stories(num_stories: int = 5) -> str:
16 """Fetch and return the top stories from HackerNews.
17
18 Args:
19 num_stories: Number of top stories to retrieve (default: 5)
20 Returns:
21 JSON string containing story details (title, url, score, etc.)
22 """
23 # Get top stories
24 stories = [
25 {
26 k: v
27 for k, v in httpx.get(
28 f"https://hacker-news.firebaseio.com/v0/item/{id}.json"
29 )
30 .json()
31 .items()
32 if k != "kids" # Exclude discussion threads
33 }
34 for id in httpx.get(
35 "https://hacker-news.firebaseio.com/v0/topstories.json"
36 ).json()[:num_stories]
37 ]
38 return json.dumps(stories, indent=4)
39
40
41# Create a Context-Aware Agent that can access real-time HackerNews data
42# ---------------------------------------------------------------------------
43# Create Agent
44# ---------------------------------------------------------------------------
45agent = Agent(
46 model=OpenAIResponses(id="gpt-5.2"),
47 # Each function in the dependencies is resolved when the agent is run,
48 # think of it as dependency injection for Agents
49 dependencies={"top_hackernews_stories": get_top_hackernews_stories},
50 # We can add the entire dependencies dictionary to the user message
51 add_dependencies_to_context=True,
52 markdown=True,
53)
54
55# ---------------------------------------------------------------------------
56# Run Agent
57# ---------------------------------------------------------------------------
58if __name__ == "__main__":
59 # Example usage
60 agent.print_response(
61 "Summarize the top stories on HackerNews and identify any interesting trends.",
62 stream=True,
63 )

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/15_dependencies
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python dependencies_in_context.py