With OpenAI realtime, how can I maintain context d...
# ask-ai
m
With OpenAI realtime, how can I maintain context during agent handoffs?
t
Thanks for reaching out, Daniel. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
When you're passing the conversation from one agent to another using OpenAI Realtime in LiveKit, it's important to explicitly transfer the
chat_ctx
so the context stays intact. Otherwise, each agent starts fresh, and the conversation history gets lost. The easiest way to do this is by passing the current session’s
chat_ctx
to the new agent when you transfer. Here’s a quick example:
Copy code
@function_tool()
async def transfer_to_technical_support(self):
    await self.session.generate_reply(instructions="Inform the customer that you're transferring them to the technical support team.")
    return TechnicalSupportAgent(chat_ctx=self.session.chat_ctx)
If you want more control, you can choose to keep only the important parts of the conversation history. This means trimming the previous agent’s chat context to keep things relevant and avoid overloading the prompt. Here’s how you might do that:
Copy code
class BaseAgent(Agent):
    async def on_enter(self) -> None:
        chat_ctx = self.chat_ctx.copy()

        if userdata.prev_agent:
            items_copy = self._truncate_chat_ctx(
                userdata.prev_agent.chat_ctx.items, keep_function_call=True
            )
            existing_ids = {item.id for item in chat_ctx.items}
            items_copy = [item for item in items_copy if item.id not in existing_ids]
            chat_ctx.items.extend(items_copy)

        await self.update_chat_ctx(chat_ctx)
This way, you carry over just what’s really needed, keeping the conversation smooth and avoiding any clutter. If you want a hand setting this up or have any questions, just let me know—I’m here to help! Sources: Workflows | LiveKit Docs | telephony/warm_handoff.py | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | examples/src/restaurant_agent.ts | Agents 0.x migration guide | LiveKit Docs