Instructions With State
Example demonstrating how to use a function as instructions for an agent.
1"""2Instructions With State3=============================45Example demonstrating how to use a function as instructions for an agent.6"""78from textwrap import dedent910from kern.agent import Agent11from kern.models.openai import OpenAIResponses12from kern.run import RunContext131415# This will be our instructions function16def get_run_instructions(run_context: RunContext) -> str:17 """Build instructions for the Agent based on the run context."""18 if not run_context.session_state:19 return "You are a helpful game development assistant that can answer questions about coding and game design."2021 game_genre = run_context.session_state.get("game_genre", "")22 difficulty_level = run_context.session_state.get("difficulty_level", "")2324 return dedent(25 f"""26 You are a specialized game development assistant.27 The team is currently working on a {game_genre} game.28 The current project difficulty level is set to {difficulty_level}.29 Please tailor your responses to match this genre and complexity level when providing30 coding advice, design suggestions, or technical guidance."""31 )323334# ---------------------------------------------------------------------------35# Create Agent36# ---------------------------------------------------------------------------37game_development_agent = Agent(38 model=OpenAIResponses(id="gpt-5.2"),39 instructions=get_run_instructions,40)4142# ---------------------------------------------------------------------------43# Run Agent44# ---------------------------------------------------------------------------45if __name__ == "__main__":46 game_development_agent.print_response(47 "What genre are we working on and what should I focus on for the core mechanics?",48 session_state={"game_genre": "platformer", "difficulty_level": "hard"},49 )Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/03_context_management45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python instructions_with_state.py