State in Instructions

This example demonstrates how to use session state variables directly in agent instructions. It shows how to initialize session state and reference those variables in the instruction templates.

Create a Python file

1from kern.agent import Agent
2from kern.models.openai import OpenAIResponses
3
4agent = Agent(
5 model=OpenAIResponses(id="gpt-5.2"),
6 session_state={"user_name": "John"},
7 instructions="Users name is {user_name}",
8 markdown=True,
9)
10
11agent.print_response("What is my name?", stream=True)

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

Set OpenAI Key

Set your OPENAI_API_KEY as an environment variable. You can get one from OpenAI.

1export OPENAI_API_KEY=sk-***
1setx OPENAI_API_KEY sk-***

Run Agent

1python session_state_in_instructions.py