Dependencies In Tools
Example showing how tools can access dependencies passed to the agent.
1"""2Dependencies In Tools3=============================45Example showing how tools can access dependencies passed to the agent.6"""78from datetime import datetime910from kern.agent import Agent11from kern.models.openai import OpenAIResponses12from kern.run import RunContext131415def 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 }222324def analyze_user(user_id: str, run_context: RunContext) -> str:25 """26 Analyze a specific user's profile and provide insights.2728 This tool analyzes user behavior and preferences using available data sources.29 Call this tool with the user_id you want to analyze.3031 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)3435 Returns:36 Detailed analysis and insights about the user37 """38 dependencies = run_context.dependencies39 if not dependencies:40 return "No data sources available for analysis."4142 print(f"--> Tool received data sources: {list(dependencies.keys())}")4344 results = [f"=== USER ANALYSIS FOR {user_id.upper()} ==="]4546 # Use user profile data if available47 if "user_profile" in dependencies:48 profile_data = dependencies["user_profile"]49 results.append(f"Profile Data: {profile_data}")5051 # Add analysis based on the profile52 if profile_data.get("role"):53 results.append(54 f"Professional Analysis: {profile_data['role']} with expertise in {', '.join(profile_data.get('preferences', []))}"55 )5657 # Use current context data if available58 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 )6465 print(f"--> Tool returned results: {results}")6667 return "\n\n".join(results)686970# Create an agent with the analysis tool function71# ---------------------------------------------------------------------------72# Create Agent73# ---------------------------------------------------------------------------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)8788# ---------------------------------------------------------------------------89# Run Agent90# ---------------------------------------------------------------------------91if __name__ == "__main__":92 print("=== Tool Dependencies Access Example ===\n")9394 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 )107108 print(f"\nAgent Response: {response.content}")Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/15_dependencies45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python dependencies_in_tools.py