Velamuvi AIAcademy

Lesson 12 of 39 · Sessions, Memory and Context

Sessions and Multi-Turn Chat

Hold multi-turn conversations with AgentSession: local and service-managed history, saving and restoring sessions, and FileSessionStore in Agent Framework.

  • 10 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why an agent forgets between runs and what a session holds
  • Hold a multi-turn chat with create_session and run(session=...)
  • Tell local history from service-managed history and service_session_id
  • Save and restore a session with to_dict and from_dict
  • Keep sessions between requests and restarts with SessionStore and FileSessionStore

Why the agent forgets

A model has no memory of its own. Every call sends it a list of messages, and it answers from that list alone. If your second question doesn't carry the first one with it, the model has never heard of you.

The difference, in plain Python:

Try it yourselfPython
# A stateless "model" answers only from the messages it gets in this one call.
def model(messages):
    said = " ".join(m["text"] for m in messages if m["role"] == "user")
    return "You're Asha." if "I'm Asha" in said else "I don't know who you are."

# Without memory: each call sends only the new message.
model([{"role": "user", "text": "Hi, I'm Asha."}])
print("no history:  ", model([{"role": "user", "text": "Who am I?"}]))

# With memory: keep a history and send all of it every time.
history = []
for text in ["Hi, I'm Asha.", "Who am I?"]:
    history.append({"role": "user", "text": text})
    reply = model(history)
    history.append({"role": "assistant", "text": reply})
print("with history:", reply)
print("messages kept:", len(history))

Your first multi-turn chat

Create a session with agent.create_session() and pass the same session to every run of the conversation.

import asyncio

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.",
    )

    print("Without a session:")
    print(" ", (await agent.run("Hi, I'm Asha. I'd like to rent a City E tomorrow.")).text)
    print(" ", (await agent.run("Which bike did I ask about, and what's my name?")).text)

    print("With a session:")
    session = agent.create_session()
    print(" ", (await agent.run("Hi, I'm Asha. I'd like to rent a City E tomorrow.", session=session)).text)
    print(" ", (await agent.run("Which bike did I ask about, and what's my name?", session=session)).text)


asyncio.run(main())
Output
Without a session:
  Hi Asha! A City E costs 35 EUR a day. Shall I reserve one for you?
  I don't know yet. What's your name, and which bike would you like?
With a session:
  Hi Asha! A City E costs 35 EUR a day. Shall I reserve one for you?
  You asked about the City E, Asha.

Without a session, each run() starts a new conversation, so the second question got nowhere. With the session, the agent remembered both the name and the bike.

Where the history lives

A session doesn't always hold the messages itself. There are two places the history can live:

  • On the provider's service. OpenAIChatClient uses OpenAI's Responses API, which stores each conversation on OpenAI's side by default. After a run, session.service_session_id holds the id of the latest response (it starts with resp_), and the agent sends that id with the next run instead of the old messages.
  • Locally. With store=False, or with a client that doesn't store anything, the agent adds an InMemoryHistoryProvider for you. It keeps the messages in session.state, under the provider's own key, "in_memory".
import asyncio

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    service = Agent(client=client, instructions="You are Velo's rental desk in Porto.")
    local = Agent(client=client, instructions="You are Velo's rental desk in Porto.", default_options={"store": False})

    for label, agent in (("service", service), ("local", local)):
        session = agent.create_session()
        await agent.run("Hi, I'm Asha. I'd like to rent a City E tomorrow.", session=session)
        reply = await agent.run("Which bike did I ask about, and what's my name?", session=session)
        print(f"{label}: {reply.text}")
        print("  service_session_id starts with:", str(session.service_session_id)[:5])
        stored = session.state.get("in_memory", {}).get("messages", [])
        print("  messages kept in session.state:", len(stored))


asyncio.run(main())
Output
service: You asked about the City E, Asha.
  service_session_id starts with: resp_
  messages kept in session.state: 0
local: You asked about the City E, Asha.
  service_session_id starts with: None
  messages kept in session.state: 4

Both agents remembered the conversation, but in different places. Local history costs more tokens, because every run sends all earlier messages again. Service history needs the provider to keep your data, and it only works with that provider.

service_session_id is usually a string. Some providers need more than one value to continue a conversation; their id is a ServiceSessionId, a dictionary. The A2A client, for example, stores a context id and a task id. To continue a service conversation whose id you saved somewhere else, call agent.get_session(service_session_id).

Saving and restoring a session

A web app handles each message in a new request, and a server may restart between turns. session.to_dict() turns a session into plain data you can store as JSON, and AgentSession.from_dict() brings it back.

import asyncio
import json

from agent_framework import Agent, AgentSession
from agent_framework.openai import OpenAIChatClient


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto.",
        default_options={"store": False},
    )
    session = agent.create_session()
    await agent.run("Hi, I'm Asha. I'd like to rent a City E tomorrow.", session=session)

    saved = json.dumps(session.to_dict())          # text you can put in a database or a file
    print("saved keys:", list(json.loads(saved)))

    restored = AgentSession.from_dict(json.loads(saved))
    print("same session id:", restored.session_id == session.session_id)
    reply = await agent.run("Which bike did I ask about, and what's my name?", session=restored)
    print(reply.text)


asyncio.run(main())
Output
saved keys: ['type', 'session_id', 'service_session_id', 'state']
same session id: True
You asked about the City E, Asha.

The restored session has the same id and the same history, so the chat carries on where it stopped.

Session stores

A session store keeps sessions for you under an id you choose, such as a chat id or a user id. Its methods are async: get(id) returns a copy of the session, or None; set(id, session) saves it; delete(id) removes it.

  • SessionStore keeps sessions in memory. It's good for tests and for one process.
  • FileSessionStore(storage_path) writes one file per session, as JSON by default or as MessagePack with serialization_format="msgpack".
import asyncio
from pathlib import Path

from agent_framework import Agent, FileSessionStore
from agent_framework.openai import OpenAIChatClient


async def handle(store: FileSessionStore, agent: Agent, chat_id: str, text: str) -> str:
    # One request in a chat app: load the session, run one turn, save the session again.
    session = await store.get(chat_id) or agent.create_session()
    response = await agent.run(text, session=session)
    await store.set(chat_id, session)
    return response.text


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto.",
        default_options={"store": False},
    )
    print(await handle(FileSessionStore("sessions"), agent, "chat-asha", "Hi, I'm Asha. I'd like to rent a City E tomorrow."))

    # Later, even after a restart: a new store object reads the same folder.
    print(await handle(FileSessionStore("sessions"), agent, "chat-asha", "Which bike did I ask about, and what's my name?"))
    print(sorted(path.name for path in Path("sessions").iterdir()))


asyncio.run(main())
Output
Hi Asha! A City E costs 35 EUR a day. Shall I reserve one for you?
You asked about the City E, Asha.
['chat-asha.json']

Both store classes are experimental: the first use prints ExperimentalWarning: [SESSION_STORE] FileSessionStore is experimental and may change or be removed in future versions without notice. The files are plain text, so keep them in a folder only your app can read. For several servers, write your own store with the same three methods on top of a database.

Common mistakes

Practice exercise

Make chat() remember, the way an AgentSession does: each session keeps its own list of messages, and every call sends the whole list to the stateless model.

Your solutionPython
def model(messages):
    # A stateless "model": it only knows the messages it receives in this call.
    name = None
    for message in messages:
        if message["role"] == "user" and message["text"].startswith("My name is "):
            name = message["text"][len("My name is "):].rstrip(".")
    last = messages[-1]["text"]
    if last.startswith("My name is "):
        return f"Nice to meet you, {name}."
    return f"Your name is {name}." if name else "I don't know your name."


def chat(session, text):
    # Add the user's message to session["messages"], call model() with the whole list,
    # add the reply as an "assistant" message, and return the reply.
    return model([{"role": "user", "text": text}])


alice = {"messages": []}
bob = {"messages": []}
print(chat(alice, "My name is Alice."))
print(chat(bob, "My name is Bob."))
print(chat(alice, "What's my name?"))
print(chat(bob, "What's my name?"))
print(len(alice["messages"]))
Knowledge check

You use OpenAIChatClient with its default settings and pass a session to every run. Where is the conversation kept?

Summary

  • A model forgets everything between calls. An AgentSession passed to every run() keeps the conversation going.
  • History lives either on the provider's service (service_session_id, a string or a ServiceSessionId mapping) or locally in session.state, through an InMemoryHistoryProvider.
  • to_dict() and AgentSession.from_dict() save and restore a session as plain data.
  • SessionStore and FileSessionStore keep sessions under your own ids between requests and restarts.

Next: History Providers and Storage.

Finished reading? Tick it off to track your progress.