Instructions With State

Example demonstrating how to use a function as instructions for an agent.

1"""
2Instructions With State
3=============================
4
5Example demonstrating how to use a function as instructions for an agent.
6"""
7
8from textwrap import dedent
9
10from kern.agent import Agent
11from kern.models.openai import OpenAIResponses
12from kern.run import RunContext
13
14
15# This will be our instructions function
16def 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."
20
21 game_genre = run_context.session_state.get("game_genre", "")
22 difficulty_level = run_context.session_state.get("difficulty_level", "")
23
24 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 providing
30 coding advice, design suggestions, or technical guidance."""
31 )
32
33
34# ---------------------------------------------------------------------------
35# Create Agent
36# ---------------------------------------------------------------------------
37game_development_agent = Agent(
38 model=OpenAIResponses(id="gpt-5.2"),
39 instructions=get_run_instructions,
40)
41
42# ---------------------------------------------------------------------------
43# Run Agent
44# ---------------------------------------------------------------------------
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 repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/03_context_management
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python instructions_with_state.py