Team Session State
Share and coordinate state across multiple agents in a team
Team Session State enables sharing and updating state data across teams of agents. Teams often need to coordinate on shared information.
Shared state propagates through nested team structures as well
How to use Shared State
You can set the session_state parameter on Team to set initial session state data.
This state data will be shared between the team leader and its members.
This state will be available to all team members and is synchronized between them.
For example:
1team = Team(2 members=[agent1, agent2, agent3],3 session_state={"shopping_list": []},4)Members can access the shared state using run_context.session_state in tools.
For example:
1from kern.run import RunContext23def add_item(run_context: RunContext, item: str) -> str:4 """Add an item to the shopping list and return confirmation.56 Args:7 item (str): The item to add to the shopping list.8 """9 # Add the item if it's not already in the list10 if item.lower() not in [11 i.lower() for i in run_context.session_state["shopping_list"]12 ]:13 run_context.session_state["shopping_list"].append(item)14 return f"Added '{item}' to the shopping list"15 else:16 return f"'{item}' is already in the shopping list"The run_context object is automatically passed to the tool as an argument. Use it to access the session state.
Any updates to run_context.session_state will be automatically persisted in the database and reflected in the shared state.
See the RunContext schema for more information.
Example
Here's a simple example of a team managing a shared shopping list:
1from kern.models.openai import OpenAIResponses2from kern.agent import Agent3from kern.team import Team4from kern.run import RunContext567# Define tools that work with shared team state8def add_item(run_context: RunContext, item: str) -> str:9 """Add an item to the shopping list."""10 if not run_context.session_state:11 run_context.session_state = {}1213 if item.lower() not in [14 i.lower() for i in run_context.session_state["shopping_list"]15 ]:16 run_context.session_state["shopping_list"].append(item)17 return f"Added '{item}' to the shopping list"18 else:19 return f"'{item}' is already in the shopping list"202122def remove_item(run_context: RunContext, item: str) -> str:23 """Remove an item from the shopping list."""24 if not run_context.session_state:25 run_context.session_state = {}2627 for i, list_item in enumerate(run_context.session_state["shopping_list"]):28 if list_item.lower() == item.lower():29 run_context.session_state["shopping_list"].pop(i)30 return f"Removed '{list_item}' from the shopping list"3132 return f"'{item}' was not found in the shopping list"333435# Create an agent that manages the shopping list36shopping_agent = Agent(37 name="Shopping List Agent",38 role="Manage the shopping list",39 model=OpenAIResponses(id="gpt-5.2"),40 tools=[add_item, remove_item],41)424344# Define team-level tools45def list_items(run_context: RunContext) -> str:46 """List all items in the shopping list."""47 if not run_context.session_state:48 run_context.session_state = {}4950 # Access shared state (not private state)51 shopping_list = run_context.session_state["shopping_list"]5253 if not shopping_list:54 return "The shopping list is empty."5556 items_text = "\n".join([f"- {item}" for item in shopping_list])57 return f"Current shopping list:\n{items_text}"585960def add_chore(run_context: RunContext, chore: str) -> str:61 """Add a completed chore to the team's private log."""62 if not run_context.session_state:63 run_context.session_state = {}6465 # Access team's private state66 if "chores" not in run_context.session_state:67 run_context.session_state["chores"] = []6869 run_context.session_state["chores"].append(chore)70 return f"Logged chore: {chore}"717273# Create a team with both shared and private state74shopping_team = Team(75 name="Shopping Team",76 model=OpenAIResponses(id="gpt-5.2"),77 members=[shopping_agent],78 session_state={"shopping_list": [], "chores": []},79 tools=[list_items, add_chore],80 instructions=[81 "You manage a shopping list.",82 "Forward add/remove requests to the Shopping List Agent.",83 "Use list_items to show the current list.",84 "Log completed tasks using add_chore.",85 ],86)8788# Example usage89shopping_team.print_response("Add milk, eggs, and bread", stream=True)90print(f"Shared state: {shopping_team.get_session_state()}")9192shopping_team.print_response("What's on my list?", stream=True)9394shopping_team.print_response("I got the eggs", stream=True)95print(f"Shared state: {shopping_team.get_session_state()}")Notice how shared tools can access and update run_context.session_state.
This allows state data to propagate and persist across the entire team — even for subteams within the team.
See a full example here.
Agentic Session State
Kern provides a way to allow the team and team members to automatically update the shared session state.
Simply set the enable_agentic_state parameter to True.
1from kern.agent import Agent2from kern.db.sqlite import SqliteDb3from kern.models.openai import OpenAIResponses4from kern.team.team import Team56db = SqliteDb(db_file="tmp/agents.db")7shopping_agent = Agent(8 name="Shopping List Agent",9 role="Manage the shopping list",10 model=OpenAIResponses(id="gpt-5.2"),11 db=db,12 add_session_state_to_context=True, # Required so the agent is aware of the session state13 enable_agentic_state=True,14)1516team = Team(17 members=[shopping_agent],18 session_state={"shopping_list": []},19 db=db,20 add_session_state_to_context=True, # Required so the team is aware of the session state21 enable_agentic_state=True,22 description="You are a team that manages a shopping list and chores",23 show_members_responses=True,24)252627team.print_response("Add milk, eggs, and bread to the shopping list")2829team.print_response("I picked up the eggs, now what's on my list?")3031print(f"Session state: {team.get_session_state()}")Don't forget to set add_session_state_to_context=True to make the session state available to the team's context.
Using state in instructions
You can reference variables from the session state in your instructions.
Don't use the f-string syntax in the instructions. Directly use the {key} syntax, Kern substitutes the values for you.
1from kern.team.team import Team23team = Team(4 members=[],5 # Initialize the session state with a variable6 session_state={"user_name": "John"},7 instructions="Users name is {user_name}",8 markdown=True,9)1011team.print_response("What is my name?", stream=True)Changing state on run
When you pass session_id to the team on team.run(), it will switch to the session with the given session_id and load any state that was set on that session.
This is useful when you want to continue a session for a specific user.
1from kern.team.team import Team2from kern.models.openai import OpenAIResponses3from kern.db.in_memory import InMemoryDb45team = Team(6 db=InMemoryDb(),7 model=OpenAIResponses(id="gpt-5.2"),8 members=[],9 instructions="Users name is {user_name} and age is {age}",10)1112# Sets the session state for the session with the id "user_1_session_1"13team.print_response("What is my name?", session_id="user_1_session_1", user_id="user_1", session_state={"user_name": "John", "age": 30})1415# Will load the session state from the session with the id "user_1_session_1"16team.print_response("How old am I?", session_id="user_1_session_1", user_id="user_1")1718# Sets the session state for the session with the id "user_2_session_1"19team.print_response("What is my name?", session_id="user_2_session_1", user_id="user_2", session_state={"user_name": "Jane", "age": 25})2021# Will load the session state from the session with the id "user_2_session_1"22team.print_response("How old am I?", session_id="user_2_session_1", user_id="user_2")Overwriting the state in the db
By default, if you pass session_state to the run methods, this new state will be merged with the session_state in the db.
You can change that behavior if you want to overwrite the session_state in the db:
1from kern.agent import Agent2from kern.db.sqlite import SqliteDb3from kern.models.openai import OpenAIResponses45# Create an Agent that maintains state6agent = Agent(7 model=OpenAIResponses(id="gpt-5.2"),8 db=SqliteDb(db_file="tmp/agents.db"),9 markdown=True,10 # Set the default session_state. The values set here won't be overwritten.11 session_state={},12 # Adding the session_state to context for the agent to easily access it13 add_session_state_to_context=True,14 # Allow overwriting the stored session state with the session state provided in the run15 overwrite_db_session_state=True,16)1718# Let's run the agent providing a session_state. This session_state will be stored in the database.19agent.print_response(20 "Can you tell me what's in your session_state?",21 session_state={"shopping_list": ["Potatoes"]},22 stream=True,23)24print(f"Stored session state: {agent.get_session_state()}")2526# Now if we pass a new session_state, it will overwrite the stored session_state.27agent.print_response(28 "Can you tell me what is in your session_state?",29 session_state={"secret_number": 43},30 stream=True,31)32print(f"Stored session state: {agent.get_session_state()}")Team Member Interactions
Agent Teams can share interactions between members, allowing agents to learn from each other's outputs:
1from kern.agent import Agent2from kern.models.openai import OpenAIResponses3from kern.team.team import Team45from kern.db.sqlite import SqliteDb6from kern.tools.duckduckgo import DuckDuckGoTools78db = SqliteDb(db_file="tmp/agents.db")910web_research_agent = Agent(11 name="Web Research Agent",12 model=OpenAIResponses(id="gpt-5.2"),13 tools=[DuckDuckGoTools()],14 instructions="You are a web research agent that can answer questions from the web.",15)1617report_agent = Agent(18 name="Report Agent",19 model=OpenAIResponses(id="gpt-5.2"),20 instructions="You are a report agent that can write a report from the web research.",21)2223team = Team(24 model=OpenAIResponses(id="gpt-5.2"),25 db=db,26 members=[web_research_agent, report_agent],27 share_member_interactions=True,28 instructions=[29 "You are a team of agents that can research the web and write a report.",30 "First, research the web for information about the topic.",31 "Then, use your report agent to write a report from the web research.",32 ],33 show_members_responses=True,34 debug_mode=True,35)3637team.print_response("How are LEDs made?")Developer Resources
- View the Team schema
- View the RunContext schema