Add Dependencies to Agent Run

This example demonstrates how to inject dependencies into agent runs, allowing the agent to access dynamic context like user profiles and current time information for personalized responses.

Create a Python file

1from datetime import datetime
2
3from kern.agent import Agent
4from kern.models.openai import OpenAIResponses
5
6
7def get_user_profile(user_id: str = "john_doe") -> dict:
8 """Get user profile information that can be referenced in responses.
9
10 Args:
11 user_id: The user ID to get profile for
12 Returns:
13 Dictionary containing user profile information
14 """
15 profiles = {
16 "john_doe": {
17 "name": "John Doe",
18 "preferences": {
19 "communication_style": "professional",
20 "topics_of_interest": ["AI/ML", "Software Engineering", "Finance"],
21 "experience_level": "senior",
22 },
23 "location": "San Francisco, CA",
24 "role": "Senior Software Engineer",
25 }
26 }
27
28 return profiles.get(user_id, {"name": "Unknown User"})
29
30
31def get_current_context() -> dict:
32 """Get current contextual information like time, weather, etc."""
33 return {
34 "current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
35 "timezone": "PST",
36 "day_of_week": datetime.now().strftime("%A"),
37 }
38
39
40agent = Agent(
41 model=OpenAIResponses(id="gpt-5.2"),
42 markdown=True,
43)
44
45response = agent.run(
46 "Please provide me with a personalized summary of today's priorities based on my profile and interests.",
47 dependencies={
48 "user_profile": get_user_profile,
49 "current_context": get_current_context,
50 },
51 add_dependencies_to_context=True,
52 debug_mode=True,
53)
54
55print(response.content)

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

Export your OpenAI API key

1export OPENAI_API_KEY=your_openai_api_key_here

Run Agent

1python add_dependencies_on_run.py