Dependencies In Tools

Example showing how tools can access dependencies passed to the agent.

1"""
2Dependencies In Tools
3=============================
4
5Example showing how tools can access dependencies passed to the agent.
6"""
7
8from datetime import datetime
9
10from kern.agent import Agent
11from kern.models.openai import OpenAIResponses
12from kern.run import RunContext
13
14
15def get_current_context() -> dict:
16 """Get current contextual information like time, weather, etc."""
17 return {
18 "current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
19 "timezone": "PST",
20 "day_of_week": datetime.now().strftime("%A"),
21 }
22
23
24def analyze_user(user_id: str, run_context: RunContext) -> str:
25 """
26 Analyze a specific user's profile and provide insights.
27
28 This tool analyzes user behavior and preferences using available data sources.
29 Call this tool with the user_id you want to analyze.
30
31 Args:
32 user_id: The user ID to analyze (e.g., 'john_doe', 'jane_smith')
33 run_context: The run context containing dependencies (automatically provided)
34
35 Returns:
36 Detailed analysis and insights about the user
37 """
38 dependencies = run_context.dependencies
39 if not dependencies:
40 return "No data sources available for analysis."
41
42 print(f"--> Tool received data sources: {list(dependencies.keys())}")
43
44 results = [f"=== USER ANALYSIS FOR {user_id.upper()} ==="]
45
46 # Use user profile data if available
47 if "user_profile" in dependencies:
48 profile_data = dependencies["user_profile"]
49 results.append(f"Profile Data: {profile_data}")
50
51 # Add analysis based on the profile
52 if profile_data.get("role"):
53 results.append(
54 f"Professional Analysis: {profile_data['role']} with expertise in {', '.join(profile_data.get('preferences', []))}"
55 )
56
57 # Use current context data if available
58 if "current_context" in dependencies:
59 context_data = dependencies["current_context"]
60 results.append(f"Current Context: {context_data}")
61 results.append(
62 f"Time-based Analysis: Analysis performed on {context_data['day_of_week']} at {context_data['current_time']}"
63 )
64
65 print(f"--> Tool returned results: {results}")
66
67 return "\n\n".join(results)
68
69
70# Create an agent with the analysis tool function
71# ---------------------------------------------------------------------------
72# Create Agent
73# ---------------------------------------------------------------------------
74agent = Agent(
75 model=OpenAIResponses(id="gpt-5.2"),
76 tools=[analyze_user],
77 name="User Analysis Agent",
78 description="An agent specialized in analyzing users using integrated data sources.",
79 instructions=[
80 "You are a user analysis expert with access to user analysis tools.",
81 "When asked to analyze any user, use the analyze_user tool.",
82 "This tool has access to user profiles and current context through integrated data sources.",
83 "After getting tool results, provide additional insights and recommendations based on the analysis.",
84 "Be thorough in your analysis and explain what the tool found.",
85 ],
86)
87
88# ---------------------------------------------------------------------------
89# Run Agent
90# ---------------------------------------------------------------------------
91if __name__ == "__main__":
92 print("=== Tool Dependencies Access Example ===\n")
93
94 response = agent.run(
95 input="Please analyze user 'john_doe' and provide insights about their professional background and preferences.",
96 dependencies={
97 "user_profile": {
98 "name": "John Doe",
99 "preferences": ["AI/ML", "Software Engineering", "Finance"],
100 "location": "San Francisco, CA",
101 "role": "Senior Software Engineer",
102 },
103 "current_context": get_current_context,
104 },
105 session_id="test_tool_dependencies",
106 )
107
108 print(f"\nAgent Response: {response.content}")

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_tools.py