Skip to main content

Hindsight LiveKit Integration

PyPI Test

Persistent long-term memory for LiveKit Agents voice AI via Hindsight. Your agent knows what it learned in earlier calls, and stores each new conversation as it happens. Works with STT-LLM-TTS pipelines and realtime (speech-to-speech) models.

Quick Start

pip install hindsight-livekit

✨ Recommended: Hindsight Cloud — free tier, no self-hosting required. Sign up and grab an API key in under a minute.

from livekit.agents import AgentServer, AgentSession, JobContext, inference
from hindsight_livekit import HindsightAgent, HindsightMemory

server = AgentServer()


@server.rtc_session()
async def entrypoint(ctx: JobContext):
    session = AgentSession(stt=..., tts=...)

    memory = HindsightMemory(
        bank_id="user-123",                    # one memory bank per end user
        document_id=ctx.room.name,             # one transcript per call
        hindsight_api_url="https://api.hindsight.vectorize.io",
        api_key="hsk_...",                     # or set HINDSIGHT_API_KEY
    )
    memory.attach(session)                     # retain the conversation
    ctx.add_shutdown_callback(memory.aclose)   # store the end of the call on hang-up

    await session.start(
        agent=HindsightAgent(
            memory=memory,
            llm=inference.LLM(model="google/gemma-4-31b-it"),
            instructions="You are a friendly voice assistant.",
        ),
        room=ctx.room,
    )
    await ctx.connect()

HindsightAgent is a regular LiveKit Agent: subclass it, add @function_tools, override on_enter (call await super().on_enter() first), and so on.

Runnable agents built on agent-starter-python:

Self-hosting (local development)

docker run --rm -p 8888:8888 -e HINDSIGHT_API_LLM_API_KEY=$OPENAI_API_KEY ghcr.io/vectorize-io/hindsight:latest
memory = HindsightMemory(bank_id="user-123", hindsight_api_url="http://localhost:8888")

See the Hindsight installation guide for other options. LiveKit itself can be self-hosted too; the integration works the same either way.

How It Works

memory.attach(session)
  └─ Session recall starts: "who is this user?"  (overlaps with session.start)

Agent starts (on_enter)
  └─ Known facts about the user are added to the agent's instructions

Before each LLM reply (llm_node)                       — STT-LLM-TTS pipelines only
  └─ Recall memories relevant to the user's latest message
       └─ Insert them before that message, in a copy of the chat context

As the conversation happens (conversation_item_added)
  └─ Append "User (time): …" / "Assistant (time): …" lines to the call's Hindsight document
STT-LLM-TTS pipeline Realtime model
Recall when the agent starts ✅ ✅
Recall before each reply ✅ — (no step before a realtime reply; use the tools)
Memory tools (create_hindsight_tools) ✅ ✅
Retain the conversation ✅ ✅ (needs the model's input audio transcription for the user's side)

Session recall runs once per call. attach() starts it, so it overlaps with LiveKit connecting the room and the model, and HindsightAgent.on_enter adds the result to the instructions. LiveKit runs on_enter in the background, so with a pipeline the first llm_node call also waits for the lookup (up to session_recall_timeout) and uses the instructions with memories, even if the user speaks first. A realtime model has no such step: a reply that starts before the lookup finishes won't include those memories, which is rare in practice since the lookup starts before the call connects.

Per-turn recall runs in llm_node, the step every LLM call in a pipeline goes through. That means:

  • It works for spoken turns, chat text input and session.generate_reply(user_input=...). The on_user_turn_completed hook only runs for spoken turns.
  • It works with preemptive generation: recall starts while LiveKit is still confirming the end of the user's turn, and the preemptive reply is kept. Editing the context in on_user_turn_completed would make LiveKit discard it.
  • Memories are only added to a copy of the context for that call, so they never pile up in the session history. When the LLM calls a tool, the follow-up call reuses the same recall result.

As in LiveKit's RAG example, per-turn memories are added as an assistant message just before the user's message, wrapped in <hindsight_memories> tags with a note telling the model not to read them out.

Retain follows Hindsight's guidance for conversations: each call is one document (document_id), written as Name (timestamp): text lines, grown with update_mode="append" so Hindsight only extracts facts from the new part. Lines are sent once both the user and the agent have spoken, sorted by time, because realtime models can deliver the user's transcript after the reply it prompted. Appends are sent one at a time, in order, in the background, so they never delay a reply. aclose() sends whatever is left when the call ends.

Failures never break the call. If recall fails or takes longer than its time limit, the agent carries on without memories. If retain fails, the error is logged.

Memory Tools

create_hindsight_tools() gives the model hindsight_retain, hindsight_recall and hindsight_reflect tools, like the other Hindsight framework integrations. They are the way for a realtime model to look things up mid-call, and work with pipelines too:

from hindsight_livekit import HindsightAgent, create_hindsight_tools

agent = HindsightAgent(
    memory=memory,
    llm=inference.RealtimeModel(model="openai/gpt-realtime-mini"),
    tools=create_hindsight_tools(bank_id=memory.bank_id, client=memory.client, include_reflect=False),
    instructions=(
        "You have long-term memory of past calls. When the user asks about themselves, "
        "their past, or their preferences, call hindsight_recall first. When they share "
        "something worth remembering, call hindsight_retain."
    ),
)

Tell the model when to use the tools, as above: models call them far more reliably with explicit guidance. hindsight_reflect runs an LLM on the Hindsight server, so it is the slowest; leave it out for snappier calls. Tool errors are raised as LiveKit ToolError, so the model hears what went wrong and can tell the caller.

Latency

Recall happens while a caller waits, so the defaults are tuned for voice:

  • recall_budget="low": Hindsight's fast lookup setting.
  • recall_max_tokens=1024: keeps the prompt small.
  • recall_timeout=1.0: the longest a reply waits on per-message recall before going ahead without memories. Hindsight benchmarks recall against a 1 second target, and a typical recall on a warm bank takes well under that.
  • session_recall_timeout=3.0: the limit for the one lookup at the start of a call. It runs while the call connects, and as the first query to the bank it's the one most likely to be slow, for example while Hindsight loads a bank that hasn't been used recently. On Hindsight's Memlake engine, that first query also warms the bank up for the lookups that follow.

LiveKit's preemptive generation (on by default in recent livekit-agents) starts the reply, and with it the per-message recall, while LiveKit is still confirming the end of the user's turn, so most recall time overlaps time that is spent anyway. Lower recall_timeout (e.g. 0.8) for a tighter budget.

Configuration

HindsightMemory(
    bank_id="user-123",                  # Required: memory bank to use
    client=None,                         # Pre-built hindsight_client.Hindsight (optional)
    hindsight_api_url="...",             # Defaults to HINDSIGHT_API_URL, then Hindsight Cloud
    api_key="hsk_...",                   # Defaults to HINDSIGHT_API_KEY
    document_id=None,                    # Defaults to a random "livekit-<uuid>"
    recall_budget="low",                 # "low", "mid", or "high"
    recall_max_tokens=1024,              # Max tokens of memories per recall
    recall_timeout=1.0,                  # Seconds before a reply goes ahead without memories
    session_recall_timeout=3.0,          # Seconds for the lookup at the start of a call
    recall_types=None,                   # e.g. ["world", "experience"]; None = all
    tags=None,                           # Tags for retained content
    recall_tags=None,                    # Tags to filter recall by
    recall_tags_match="any",             # "any", "all", "any_strict", "all_strict"
    retain_context="voice conversation", # Source label that guides fact extraction
    user_name="User",                    # Speaker labels in the stored transcript
    agent_name="Assistant",
    enable_session_recall=True,          # Recall known facts when the agent starts
    session_recall_query="Who is this user? ...",
    enable_recall=True,                  # Recall before each reply (pipelines)
    enable_retain=True,                  # Store the conversation
)

Global configuration

from hindsight_livekit import configure

configure(
    hindsight_api_url="https://api.hindsight.vectorize.io",
    api_key="hsk_...",
    recall_budget="low",
)

memory = HindsightMemory(bank_id="user-123")

Using your own Agent or llm_node

memory.attach(session) works with any Agent. To add recall to an agent that already overrides llm_node or on_enter, call the memory directly instead of subclassing HindsightAgent:

from livekit.agents import Agent

class MyAgent(Agent):
    def __init__(self, memory: HindsightMemory) -> None:
        super().__init__(instructions="...")
        self.memory = memory

    async def on_enter(self):
        if memories := await self.memory.recall_session_context():
            await self.update_instructions(f"{self.instructions}\n\n{memories}")

    async def llm_node(self, chat_ctx, tools, model_settings):
        chat_ctx = await self.memory.inject_memories(chat_ctx)
        async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
            yield chunk

Prerequisites

  • livekit-agents 1.2 or later
  • A running Hindsight instance, self-hosted or Hindsight Cloud

Running Tests

uv sync
uv run pytest tests -v

The unit tests run a real LiveKit AgentSession with a scripted LLM and a mocked Hindsight client. The live tests in tests/test_live_integration.py run against a real Hindsight server when HINDSIGHT_API_URL is set, and also against real pipeline and realtime models through LiveKit Inference when LiveKit Cloud credentials are set:

docker run --rm -p 8888:8888 -e HINDSIGHT_API_LLM_PROVIDER=none ghcr.io/vectorize-io/hindsight:latest
HINDSIGHT_API_URL=http://localhost:8888 uv run pytest tests -v

# optional: real models via LiveKit Inference
LIVEKIT_URL=wss://... LIVEKIT_API_KEY=... LIVEKIT_API_SECRET=... HINDSIGHT_API_URL=http://localhost:8888 uv run pytest tests -v

Metadata

Release files for hindsight-livekit 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hindsight-livekit 0.2.0
File Size Uploaded Provenance Actions
hindsight_livekit-0.2.0.tar.gz 192.7 kB Without provenance Details for hindsight_livekit-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for hindsight-livekit 0.2.0
File Interpreter ABI Platform Actions
hindsight_livekit-0.2.0-py3-none-any.whl Python 3 none any Details for hindsight_livekit-0.2.0-py3-none-any.whl

Total release size: 212.2 kB

Release files / hindsight_livekit-0.2.0.tar.gz

Download URL hindsight_livekit-0.2.0.tar.gz
Size 192.7 kB
Tags Source
SHA-256 checksum
How to use checksums
e2ce9076b3af0c89e62aca179c7f6819128b68457da338264d20a20aa9f03f23
BLAKE2b-256 checksum
How to use checksums
49ab3f05e51ffe75755c993cfa470c3f7e3f5fd4a056cbeb2c32cfd5c3c6ab40
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / hindsight_livekit-0.2.0-py3-none-any.whl

Download URL hindsight_livekit-0.2.0-py3-none-any.whl
Size 19.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
70cfdcb67b02b27de2cb8ea88f69010ca55daf6c18e6a3951244247a229e2f38
BLAKE2b-256 checksum
How to use checksums
0ca5ea1188a517e9063b063c60280c66f7b98516e8a07015c49737b7e0e29826
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for hindsight-livekit 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page