Velamuvi AIAcademy

Lesson 13 of 39 · Sessions, Memory and Context

History Providers and Storage

Choose where an agent keeps its chat history: InMemoryHistoryProvider, FileHistoryProvider, Redis, Cosmos DB, vector stores, or your own HistoryProvider.

  • 10 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain what a history provider does before and after every run
  • Keep history in files with FileHistoryProvider so it survives restarts
  • Write a copy of every conversation with a store-only provider
  • Build your own HistoryProvider on top of a database
  • Configure Redis, Cosmos DB and vector-store history for production

Where the messages go

In the last lesson the session kept the conversation. But a session only holds an id and some state; the messages themselves are loaded and saved by a history provider.

Here is the whole idea in plain Python:

Try it yourselfPython
# A history provider in plain Python: load the old messages before a run, save the new ones after it.
class DictHistory:
    def __init__(self):
        self.rows = {}                      # session id -> list of messages

    def get_messages(self, session_id):
        return list(self.rows.get(session_id, []))

    def save_messages(self, session_id, messages):
        self.rows.setdefault(session_id, []).extend(messages)


def model(messages):
    # A stateless "model": it only knows the messages in this one call.
    last = messages[-1]["text"]
    names = [m["text"].split("I'm ")[1].rstrip(".") for m in messages if "I'm " in m["text"]]
    if "I'm " in last:
        return f"Nice to meet you, {names[-1]}."
    return f"You're {names[-1]}." if names else "I don't know you yet."


def run(history, session_id, text):
    new = [{"role": "user", "text": text}]
    reply = model(history.get_messages(session_id) + new)   # before the run: load
    new.append({"role": "assistant", "text": reply})
    history.save_messages(session_id, new)                   # after the run: save
    return reply


history = DictHistory()
print(run(history, "chat-asha", "Hi, I'm Asha."))
print(run(history, "chat-asha", "Who am I?"))
print(run(history, "chat-ben", "Who am I?"))
print({session_id: len(messages) for session_id, messages in history.rows.items()})

Agent Framework does the same with two methods, get_messages() and save_messages(), and calls them for you around every run().

The default: InMemoryHistoryProvider

When an agent has no history provider and the service doesn't store the conversation (for example with store=False), the agent adds an InMemoryHistoryProvider by itself. It keeps the messages in session.state["in_memory"], so they live exactly as long as the session object, or as long as you keep the session's to_dict() data. You can also add it yourself, as you'll see below.

History in files: FileHistoryProvider

FileHistoryProvider(storage_path) writes one file per session into a folder, one message per line in JSON Lines. Because the history lives in a file named after the session id, a brand-new session object with the same id picks up the conversation, even after your program restarts.

import asyncio
from pathlib import Path

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


def make_agent():
    return Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto.",
        context_providers=[FileHistoryProvider("history")],   # one file per session, in ./history
        default_options={"store": False},                      # keep the history here, not on the service
    )


async def main():
    agent = make_agent()
    session = AgentSession(session_id="chat-asha")
    print((await agent.run("Hi, I'm Asha. I'd like to rent a City E tomorrow.", session=session)).text)

    # Later, even after a restart: a new agent and a new session object with the same id.
    agent = make_agent()
    session = AgentSession(session_id="chat-asha")
    print((await agent.run("Which bike did I ask about, and what's my name?", session=session)).text)

    for path in sorted(Path("history").iterdir()):
        print(path.name, "holds", len(path.read_text().splitlines()), "messages")


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.jsonl holds 4 messages

The first use prints ExperimentalWarning: [FILE_HISTORY] FileHistoryProvider is experimental and may change or be removed in future versions without notice. Pass serialization_format="msgpack" for smaller binary files. The files are plain text and not encrypted, so keep them in a folder that only your app can read, and remember that they contain everything your users typed.

Store-only providers: an audit log

Every history provider has the same switches:

ArgumentDefaultWhat it does
load_messagesTrueLoad earlier messages before each run
store_inputsTrueSave the user's messages
store_outputsTrueSave the agent's replies
store_context_messagesFalseAlso save messages that other context providers added

With load_messages=False, a provider only writes. That makes a simple audit log next to the real history:

import asyncio
from pathlib import Path

from agent_framework import Agent, FileHistoryProvider, InMemoryHistoryProvider
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.",
        context_providers=[
            InMemoryHistoryProvider(),                                         # loads and saves the chat
            FileHistoryProvider("audit", source_id="audit", load_messages=False),  # only writes a copy
        ],
        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)
    reply = await agent.run("Which bike did I ask about, and what's my name?", session=session)
    print(reply.text)

    print("in session.state:", len(session.state["in_memory"]["messages"]), "messages")
    audit_file = next(Path("audit").iterdir())
    print("in the audit file:", len(audit_file.read_text().splitlines()), "messages")


asyncio.run(main())
Output
You asked about the City E, Asha.
in session.state: 4 messages
in the audit file: 4 messages

The in-memory provider feeds the conversation to the model; the file provider just keeps a copy. The source_id="audit" gives it its own name, so the two providers never mix their data.

Your own HistoryProvider

To keep history in a database you already run, subclass HistoryProvider and write two async methods. Message.to_dict() and Message.from_dict() turn messages into plain data and back. Here is a complete provider on SQLite, which comes with Python:

import asyncio
import json
import sqlite3
from collections.abc import Sequence
from typing import Any

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


class SQLiteHistoryProvider(HistoryProvider):
    """Keeps the messages of every session in one SQLite table."""

    def __init__(self, path: str):
        super().__init__("sqlite_history")
        self.db = sqlite3.connect(path)
        self.db.execute("CREATE TABLE IF NOT EXISTS messages (session_id TEXT, body TEXT)")

    async def get_messages(self, session_id: str | None, *, state: Any = None, **kwargs: Any) -> list[Message]:
        rows = self.db.execute("SELECT body FROM messages WHERE session_id = ? ORDER BY rowid", (session_id,))
        return [Message.from_dict(json.loads(body)) for (body,) in rows]

    async def save_messages(
        self, session_id: str | None, messages: Sequence[Message], *, state: Any = None, **kwargs: Any
    ) -> None:
        rows = [(session_id, json.dumps(message.to_dict())) for message in messages]
        self.db.executemany("INSERT INTO messages VALUES (?, ?)", rows)
        self.db.commit()


async def main():
    history = SQLiteHistoryProvider("velo.db")
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto.",
        context_providers=[history],
        default_options={"store": False},
    )
    session = AgentSession(session_id="chat-asha")
    await agent.run("Hi, I'm Asha. I'd like to rent a City E tomorrow.", session=session)
    print((await agent.run("Which bike did I ask about, and what's my name?", session=session)).text)

    for role, count in history.db.execute(
        "SELECT json_extract(body, '$.role'), COUNT(*) FROM messages GROUP BY 1 ORDER BY 1"
    ):
        print(f"{role}: {count} rows")


asyncio.run(main())
Output
You asked about the City E, Asha.
assistant: 2 rows
user: 2 rows

The first argument to super().__init__() is the provider's source_id. The agent passes the session id to both methods, so one table can hold every conversation.

Redis, Cosmos DB and vector stores

For apps with several servers, keep history in a shared service. All three providers come with pip install agent-framework; on their own they are agent-framework-redis, agent-framework-azure-cosmos and the core package.

  • RedisHistoryProvider keeps each session in a Redis list. max_messages drops the oldest messages once a session grows past the limit.
  • CosmosHistoryProvider keeps messages in an Azure Cosmos DB container. Its settings can also come from AZURE_COSMOS_ENDPOINT, AZURE_COSMOS_DATABASE_NAME, AZURE_COSMOS_CONTAINER_NAME and AZURE_COSMOS_KEY.
from agent_framework.azure import CosmosHistoryProvider
from agent_framework.redis import RedisHistoryProvider
from azure.identity.aio import DefaultAzureCredential

redis_history = RedisHistoryProvider(
    redis_url="redis://localhost:6379",
    application_id="velo-desk",   # required: part of every Redis key
    max_messages=200,             # keep only the newest 200 messages per session
)

cosmos_history = CosmosHistoryProvider(
    endpoint="https://velo.documents.azure.com:443/",
    database_name="velo",
    container_name="chat_history",
    credential=DefaultAzureCredential(),
)

These two need a running Redis server or a Cosmos DB account, so this code only creates the providers. Pass either one in context_providers=[...] exactly like the file provider.

  • VectorStoreHistoryProvider keeps the history in a collection of any vector store, such as InMemoryStore or a Redis vector store. With include_search_tool=True it also gives the agent a search_history tool, so it can look up older parts of a long conversation. Here it runs on InMemoryStore:
import asyncio

from agent_framework import Agent, InMemoryStore, VectorStoreHistoryProvider
from agent_framework.openai import OpenAIChatClient


async def main():
    history = VectorStoreHistoryProvider(
        InMemoryStore(),              # swap in a real vector store in production
        application_id="velo-desk",   # required: keeps this app's history apart from others
    )
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto.",
        context_providers=[history],
        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)
    print((await agent.run("Which bike did I ask about, and what's my name?", session=session)).text)

    stored = await history.get_messages(session.session_id)
    print("stored messages:", [message.role for message in stored])


asyncio.run(main())
Output
You asked about the City E, Asha.
stored messages: ['user', 'assistant', 'user', 'assistant']

Common mistakes

Practice exercise

Give this history provider a message limit: after saving, each session keeps only its newest max_messages messages.

Your solutionPython
class TrimmedHistory:
    def __init__(self, max_messages):
        self.max_messages = max_messages
        self.rows = {}

    def get_messages(self, session_id):
        return list(self.rows.get(session_id, []))

    def save_messages(self, session_id, messages):
        # Add the new messages to this session's list, then keep only
        # the newest self.max_messages of them, like RedisHistoryProvider's max_messages.
        pass


history = TrimmedHistory(max_messages=3)
history.save_messages("chat-asha", ["user: hi", "assistant: hello"])
history.save_messages("chat-asha", ["user: rent a City E", "assistant: done"])
history.save_messages("chat-ben", ["user: hi"])
print(history.get_messages("chat-asha"))
print(history.get_messages("chat-ben"))

Knowledge check

What does load_messages=False do on a history provider?

Summary

  • A HistoryProvider loads a session's messages before each run and saves the new ones after it.
  • InMemoryHistoryProvider is the default and keeps messages in session.state. FileHistoryProvider writes one file per session that survives restarts.
  • load_messages=False makes a store-only provider, such as an audit log.
  • Subclass HistoryProvider with get_messages() and save_messages() to use your own database.
  • RedisHistoryProvider, CosmosHistoryProvider and VectorStoreHistoryProvider share history between servers; set store=False so the service doesn't keep a second copy.

Next: Compaction: Keeping Context Small.

Finished reading? Tick it off to track your progress.