Access Dependencies in Tool

This example demonstrates how tools can access dependencies passed to the agent, allowing tools to utilize dynamic context like user profiles and current time information for enhanced functionality.

Create a Python file

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