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 RunContext
2
3def add_item(run_context: RunContext, item: str) -> str:
4 """Add an item to the shopping list and return confirmation.
5
6 Args:
7 item (str): The item to add to the shopping list.
8 """
9 # Add the item if it's not already in the list
10 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"
Note

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 OpenAIResponses
2from kern.agent import Agent
3from kern.team import Team
4from kern.run import RunContext
5
6
7# Define tools that work with shared team state
8def 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 = {}
12
13 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"
20
21
22def 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 = {}
26
27 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"
31
32 return f"'{item}' was not found in the shopping list"
33
34
35# Create an agent that manages the shopping list
36shopping_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)
42
43
44# Define team-level tools
45def 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 = {}
49
50 # Access shared state (not private state)
51 shopping_list = run_context.session_state["shopping_list"]
52
53 if not shopping_list:
54 return "The shopping list is empty."
55
56 items_text = "\n".join([f"- {item}" for item in shopping_list])
57 return f"Current shopping list:\n{items_text}"
58
59
60def 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 = {}
64
65 # Access team's private state
66 if "chores" not in run_context.session_state:
67 run_context.session_state["chores"] = []
68
69 run_context.session_state["chores"].append(chore)
70 return f"Logged chore: {chore}"
71
72
73# Create a team with both shared and private state
74shopping_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)
87
88# Example usage
89shopping_team.print_response("Add milk, eggs, and bread", stream=True)
90print(f"Shared state: {shopping_team.get_session_state()}")
91
92shopping_team.print_response("What's on my list?", stream=True)
93
94shopping_team.print_response("I got the eggs", stream=True)
95print(f"Shared state: {shopping_team.get_session_state()}")
Tip

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 Agent
2from kern.db.sqlite import SqliteDb
3from kern.models.openai import OpenAIResponses
4from kern.team.team import Team
5
6db = 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 state
13 enable_agentic_state=True,
14)
15
16team = 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 state
21 enable_agentic_state=True,
22 description="You are a team that manages a shopping list and chores",
23 show_members_responses=True,
24)
25
26
27team.print_response("Add milk, eggs, and bread to the shopping list")
28
29team.print_response("I picked up the eggs, now what's on my list?")
30
31print(f"Session state: {team.get_session_state()}")
Tip

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.

Tip

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 Team
2
3team = Team(
4 members=[],
5 # Initialize the session state with a variable
6 session_state={"user_name": "John"},
7 instructions="Users name is {user_name}",
8 markdown=True,
9)
10
11team.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 Team
2from kern.models.openai import OpenAIResponses
3from kern.db.in_memory import InMemoryDb
4
5team = 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)
11
12# 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})
14
15# 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")
17
18# 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})
20
21# 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 Agent
2from kern.db.sqlite import SqliteDb
3from kern.models.openai import OpenAIResponses
4
5# Create an Agent that maintains state
6agent = 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 it
13 add_session_state_to_context=True,
14 # Allow overwriting the stored session state with the session state provided in the run
15 overwrite_db_session_state=True,
16)
17
18# 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()}")
25
26# 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 Agent
2from kern.models.openai import OpenAIResponses
3from kern.team.team import Team
4
5from kern.db.sqlite import SqliteDb
6from kern.tools.duckduckgo import DuckDuckGoTools
7
8db = SqliteDb(db_file="tmp/agents.db")
9
10web_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)
16
17report_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)
22
23team = 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)
36
37team.print_response("How are LEDs made?")

Developer Resources