Chat History

Manage and access agent chat history.

Chat History.

1"""
2Chat History
3=============================
4
5Chat History.
6"""
7
8from kern.agent.agent import Agent
9from kern.db.postgres import PostgresDb
10from kern.models.openai import OpenAIResponses
11
12db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
13
14db = PostgresDb(db_url=db_url, session_table="sessions")
15
16# ---------------------------------------------------------------------------
17# Create Agent
18# ---------------------------------------------------------------------------
19agent = Agent(
20 model=OpenAIResponses(id="gpt-5-mini"),
21 db=db,
22 session_id="chat_history",
23 instructions="You are a helpful assistant that can answer questions about space and oceans.",
24 add_history_to_context=True,
25)
26
27# ---------------------------------------------------------------------------
28# Run Agent
29# ---------------------------------------------------------------------------
30if __name__ == "__main__":
31 agent.print_response("Tell me a new interesting fact about space")
32 print(agent.get_chat_history())
33
34 agent.print_response("Tell me a new interesting fact about oceans")
35 print(agent.get_chat_history())

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/05_state_and_session
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python chat_history.py