jolly-eve-3916
07/31/2025, 10:12 AMtall-airline-16756
07/31/2025, 10:12 AMtall-airline-16756
07/31/2025, 10:14 AMChatContext with it. For example:
from livekit import agents
from livekit.agents import Agent, ChatContext, AgentSession
import json
class Assistant(Agent):
def __init__(self, chat_ctx: ChatContext) -> None:
super().__init__(chat_ctx=chat_ctx, instructions="You are a helpful voice AI assistant.")
async def entrypoint(ctx: agents.JobContext):
metadata = json.loads(ctx.job.metadata)
conversation_history = metadata.get("conversation_history", [])
initial_ctx = ChatContext()
for message in conversation_history:
initial_ctx.add_message(role=message["role"], content=message["content"])
session = AgentSession()
await session.start(
room=ctx.room,
agent=Assistant(chat_ctx=initial_ctx),
)
• Context Size Management: For 10-15 messages (~3-4KB), you can use the truncate method of ChatContext to limit the number of messages while preserving system messages:
chat_ctx.truncate(max_items=15)
• Dynamic Context Management: Implement dynamic truncation using the before_llm_cb callback to manage context size during runtime.
• Message Size Considerations: While 3-4KB of metadata should generally be manageable, some models have specific constraints, such as a 40-message limit or 1kB per message. Ensure your implementation adheres to these limits.
• Load Time Optimization: To minimize user experience impact, load metadata before calling ctx.connect(). This ensures the agent is ready to listen immediately after connecting.
• Context Merging: Use the merge method of ChatContext to combine conversation histories while avoiding duplicates.
These practices should help you effectively pass and manage conversation history for your voice agent. If you have further questions or need clarification on specific points, let me know!
Sources: External data and RAG | LiveKit Docs | livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | VoicePipelineAgent | LiveKit Docs