miniature-nail-35141
12/04/2025, 2:17 PMtall-airline-16756
12/04/2025, 2:17 PMtall-airline-16756
12/04/2025, 2:17 PMchat_ctx and share it across multiple agents and tasks in the LiveKit Python framework, and you want a sample code snippet. Below is a concise working example and brief notes on how it works.
Sample code (Python)
from livekit.agents import (
Agent,
AgentSession,
AgentTask,
ChatContext,
)
import asyncio
from dataclasses import dataclass
@dataclass
class TaskResult:
info: str
class AgentA(Agent):
async def on_enter(self) -> None:
await self.session.generate_reply("Hello from Agent A!")
class AgentB(Agent):
async def on_enter(self) -> None:
await self.session.generate_reply("Hello from Agent B!")
class SharedTask(AgentTask[TaskResult]):
def __init__(self, chat_ctx: ChatContext = None):
super().__init__(instructions="Shared task using common chat context.", chat_ctx=chat_ctx)
async def on_enter(self) -> None:
await self.session.generate_reply("Shared task running with shared context.")
self.complete(TaskResult(info="shared-task-complete"))
async def run(job_ctx):
# 1) Create a single shared ChatContext instance
chat_ctx = ChatContext()
chat_ctx.add_message(role="system", content="Conversation started and shared across agents/tasks.")
# 2) Create a session (provide your STT/LLM/TTS/etc when needed)
session = AgentSession()
# 3) Start first agent with the shared context
await session.start(room=job_ctx.room, agent=AgentA(chat_ctx=chat_ctx))
# 4) Run a task that reuses the same chat_ctx
task = SharedTask(chat_ctx=chat_ctx)
result = await task # await task completion
print("Task result:", result.info)
# 5) Hand off to another agent, passing the same chat_ctx
await session.update_agent(AgentB(chat_ctx=chat_ctx))
# 6) Add another reply (will be appended into the same chat_ctx)
await session.generate_reply("Agent B continuing the shared conversation.")
# 7) Inspect full shared context
print("Full context messages:", [m.content for m in chat_ctx.messages])
# To run inside your agent/job runner:
# asyncio.run(run(job_ctx))
Key points
• Create one ChatContext() instance and pass it to every Agent(...) and AgentTask(...) that must share the conversation.
• Use session.update_agent(...) to switch agents while preserving the shared chat_ctx.
• Pre-populate chat_ctx with system or initial messages if you want shared starting state.
• Tasks return results but do not lose the shared chat_ctx when they complete.
Would you like this adapted to include example LLM or session initialization parameters (STT/LLM/TTS) or to show loading initial context from job_ctx.metadata?
Sources: External data and RAG | LiveKit Docs | Agents and handoffs | LiveKit docs | Tasks and task groups | LiveKit docs