This message was deleted.
# ask-ai
s
This message was deleted.
t
Thanks for reaching out, Scott. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Here's a friendly guide to help you provide initial information and a warm welcome using the Node.js v1 agent SDK: 1. Set Initial Context: Start by using the
ChatContext
class to set up system instructions or add any user-specific details. For example:
Copy code
const initialContext = new llm.ChatContext().append({
  role: llm.ChatRole.SYSTEM,
  text: 'You are a helpful voice AI assistant.',
});
2. Initiate a Welcome Greeting: Once you've started the agent session, you have a couple of friendly options: ◦ `session.say()`: Share a ready-made message:
await session.say('Hey, how can I help you today?', true);
◦ `session.generateReply()`: Let the LLM craft a natural, conversational greeting:
Copy code
await session.generateReply({
  instructions: 'greet the user and ask about their day',
});
1. Best Practices: To keep things running smoothly and quickly, try pre-loading static data in the
prewarm
function and send user-specific info through job metadata before calling
ctx.connect()
. Following these steps helps create a seamless and personalized experience right from the start. If you have any questions, I'm here to help! Sources: Docs::Agents | Agent speech and audio | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docs | External data and RAG | LiveKit Docs | examples/src/basic_agent.ts
p
i want to be able to add context to the chat after the session has been created and before the greeting.
Copy code
const agent = new voice.Agent({
      instructions,
      tools,
    });
    const llm = buildRealtimeModel();
    // Create and start session
    const session = new voice.AgentSession({
      llm,
      voiceOptions: {
        maxToolSteps: 20,
      },
    });
    sessionManager.setSession(session);
    await session.start({
      room: ctx.room,
      agent,
      inputOptions: {
        noiseCancellation: BackgroundVoiceCancellation(),
      },
    });
t
Hey there! If you want to add some context to the chat after the session is created but before the greeting, you can update the chat context dynamically. Here’s a friendly step-by-step on how to do it: 1. Initialize ChatContext: Start by creating a
ChatContext
object and add any system or user-specific messages. For example:
Copy code
const initialCtx = new ChatContext();
initialCtx.addMessage({
  role: 'system',
  content: 'The user’s name is John. Use this to personalize greetings.',
});
2. Inject Context Dynamically: Just before the agent generates a response, use the
llm_node()
method to tweak the chat context. Here’s how: `class MyAgent extends voice.Agent { async llmNode(input, modelSettings) { const ragContent = await myRagLookup('user context'); this.chatCtx.addMessage({ role: 'system', content:
Additional context: ${ragContent}
}); return await voice.Agent.default.llmNode(this, input, modelSettings); } }` 3. Trigger Greeting: Once the context is updated, call
session.generateReply()
to create a personalized greeting:
Copy code
await session.generateReply({
  instructions: 'Greet the user by name and offer assistance.',
});
This way, your agent has all the info it needs before saying hello. If you want me to walk you through any part or share more examples, just let me know—I’m here to help! Sources: Docs::Agents | Agents v0.x migration guide - Node.js | LiveKit Docs | Agents 0.x migration guide | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs | External data and RAG | LiveKit Docs
p
im convinved that agent workflow handoff does not work with oai realtime agent and sessions, can you confirm
Copy code
import { voice, llm } from '@livekit/agents';

class TechnicalSupportAgent extends voice.Agent {
  constructor(chatCtx: llm.ChatContext) {
    super({
      instructions: `You are a technical support specialist. Help customers troubleshoot 
        product issues, setup problems, and technical questions.`,
      chatCtx,
    });
  }
}

class CustomerServiceAgent extends voice.Agent {
  constructor(chatCtx: llm.ChatContext) {
    super({
      // ... instructions, chatCtx, etc.
      tools: {
        transferToTechnicalSupport: llm.tool({
          description: 'Transfer the customer to technical support for product issues and troubleshooting.',
          execute: async (_, { ctx }) => {
            await ctx.session.generateReply({
              instructions: 'Inform the customer that you\'re transferring them to the technical support team.',
            });
            
            return llm.handoff({
              agent: new TechnicalSupportAgent(ctx.session.chatCtx),
              returns: 'Transferring to technical support team',
            });
          },
        }),
      },
    });
  }
}
t
Agent workflow handoff works great with OpenAI Realtime agents and sessions in LiveKit. The framework makes it super easy to switch between agents using the
llm.handoff()
function, which passes along all the important context and settings so nothing gets lost in the process. For instance, you can use
llm.handoff()
to move over to an agent set up with the OpenAI Realtime model. The
RealtimeModel
class is built to work smoothly with LiveKit sessions, handling things like conversation history, session updates, and streaming responses—making sure your handoffs feel seamless and natural. If you’re running into any hiccups with handoffs in your setup, just let me know! I’m here to help you sort it out. Sources: README.md | OpenAI Realtime API integration guide | LiveKit Docs
p
using the llm.handoff() instead a tool call like the docs say, we keep running into
Copy code
WARN (25205): skipping new realtime generation, the agent is draining
t
Hey there! That warning, "skipping new realtime generation, the agent is draining," pops up when an agent goes into draining mode. Basically, it means the agent is wrapping up current tasks and isn’t taking on new requests—usually during shutdown or when handing things off. Here’s how you can handle it: 1. Avoid New Operations During Drain: Try not to call methods like
say()
or
generateReply()
once
drain()
has started. 2. Use Handoff Correctly: When switching agents, make sure the new agent only kicks in after the current one has fully drained. 3. Wait for Drain Completion: Always wait for the
drain()
method to finish before starting a new session. Like this:
await agentActivity.drain();
4. Check for Unexpected Drains: Double-check that
onExit()
or session closures aren’t happening too soon. 5. Adjust Endpointing Settings: Tweak settings such as
minEndpointingDelay
or
allowInterruptions
to avoid premature turn detection. If you want, I’m here to help you walk through these steps or debug anything else. Just let me know! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | agents/src/voice/agent_activity.ts
p
if the handoff is inside a toolcool, how would you wait for the drain to be complete before you handoff
t
When you’re starting a handoff from within a tool, there’s no need to wait around for the drain to finish manually. The LiveKit framework has your back and makes sure that: • The tool execution wraps up smoothly. • Any necessary LLM replies get generated. • The current agent drains properly (finishing tasks and tidying up). • The handoff only happens once all these steps are done. To kick off a handoff, just return the new agent instance from your tool function. Here’s a quick example:
Copy code
return llm.handoff({
  agent: new TechnicalSupportAgent(ctx.session.chatCtx),
  returns: 'Transferring to technical support team',
});
The system takes care of the drain and transition safely for you. If you want me to walk you through it more or share some examples, just let me know! Sources: livekit-agents/livekit/agents/voice/speech_handle.py | Tool definition and use | LiveKit Docs | Tool definition and use | LiveKit Docs
p
This is precisely what we are doing, but still get the drain warning:
Copy code
const result = await handleNextPrompt(finalPayload, context);
              const currentAgent = session.currentAgent as voice.Agent;
              const newAgent = new voice.Agent({
                instructions: currentAgent.instructions,
                tools: currentAgent.toolCtx,
                // Preserve full conversation history for context
                chatCtx: session.chatCtx,
              });
              // Return a LiveKit handoff object; include original result as the tool return
              return llm.handoff({ agent: newAgent, returns: result });
t
Hey there! That warning message, "skipping new realtime generation, the agent is draining," pops up because the current agent is winding down during the handoff process. Basically, the agent is wrapping things up as it gets shut down, while a new agent is getting ready to take over. To keep everything running smoothly, the system pauses any new speech generations during this switch. From what you’ve shared, it looks like you’re doing the handoff just right with
llm.handoff
. The warning is just the system’s way of saying it’s managing the transition properly by skipping new tasks on the agent that’s draining. It’s totally normal and helps avoid any hiccups during the switch. If this warning is bugging you or you want me to explain anything else, just give me a shout—I’m here to help! Sources: agents/src/voice/agent_activity.ts | livekit-plugins/livekit-plugins-google/livekit/plugins/google/beta/realtime...
p
we are noticing that while the handoff seems to be working, the second agent, when it invokes a tool, invokes an old seeminly cached version of an llm execution
t
Hey there! It looks like the second agent invoking an old cached LLM execution after handoff might be due to some hiccups with context propagation or the LLM holding onto its previous state. No worries though—here are some key areas to check out and help fix this: 1. Validate Context Propagation: Make sure the previous agent’s
chatCtx
is properly passed along to the new agent during handoff. For example: `return llm.handoff({ agent: new TechnicalSupportAgent(ctx.session.chatCtx), returns: result, });`Double-check that the merged context isn’t carrying over any extra tool calls or instructions that aren’t needed. 2. Check LLM State Isolation: If you’re using the OpenAI Realtime model, it’s important each agent has its own separate LLM instance or that the model state is reset before use. Sharing the same instance can cause it to remember previous states unintentionally. 3. Inspect Run-Level Caching: Try turning on verbose logging by setting
LIVEKIT_EVALS_VERBOSE=1
. This helps spot if duplicate events (like
FunctionCallEvent
or
ChatMessageEvent
) are being replayed after handoff. You can also use the
RunAssert
interface to make sure everything’s behaving as expected. 4. Disable LLM Caching: If your LLM setup supports caching (like with
prompt_cache_key
), try disabling it to avoid the backend holding onto previous executions:
llm = LLM(model="gpt-4o", store=False);
If you want, I’m here to help walk you through these steps or clarify anything else as you debug this. Just let me know! Sources: Workflows | LiveKit Docs | Workflows | LiveKit Docs | livekit-agents/livekit/agents/llm/fallback_adapter.py | Model Context Protocol Integration | livekit/livekit_composite | DeepWiki