翻篇收录说明
翻篇网页快照

Pipeline nodes and hooks | LiveKit Documentation

https://docs.livekit.io/agents/logic/nodes/

最近抓取:2026-12-05 01:55:16(北京时间)

最近内容变化:2026-12-05 01:55:16(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Learn how to customize the behavior of your agent with nodes and hooks in the voice pipeline.

正文摘录

OverviewYou can fully customize your agent's behavior at multiple nodes in the processing path. A node is a point in the path where one process transitions to another. Some example customizations include:Use a custom STT, LLM, or TTS provider without a plugin.Generate a custom greeting when an agent enters a session.Modify STT output to remove filler words before sending it to the LLM.Modify LLM output before sending it to TTS to customize pronunciation.Update the user interface when an agent or user finishes speaking.The Agent supports the following nodes and hooks. Some nodes are only available for STT-LLM-TTS pipeline models, and others are only available for realtime models.Lifecycle hooks:on_enter(): Called after the agent becomes the active agent in a session.on_exit(): Called before the agent gives control to another agent in the same session.on_user_turn_completed(): Called when the user's turn has ended, before the agent's reply.on_user_turn_exceeded(): Called when the user has been speaking long enough to exceed a configured user turn limit.STT-LLM-TTS pipeline nodes:stt_node(): Transcribe input audio to text.llm_node(): Perform inference and generate a new conversation turn (or tool call).tts_node(): Synthesize speech from the LLM text output.Realtime model nodes:realtime_audio_output_node(): Adjust output audio before publishing to the user.Transcription node:transcription_node(): Access transcription timestamps, or adjust pipeline or realtime model transcription before sending to the user.The following diagrams show the processing path for STT-LLM-TTS pipeline models and realtime models.STT-LLM-TTS pipelineRealtime modelHow to implementOverride the method within a custom Agent subclass, or pass hooks to Agent.create, to customize the behavior of your agent at a specific node in the processing path. Agent.create hooks receive a ctx object first and use AsyncIterable inputs and outputs for stream nodes. To use the default implementation, call Agent.default.<node-name>(). For instance, this code overrides the STT node while maintaining the default behavior.PythonNode.jsasync def stt_node(self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings) -> Optional[AsyncIterable[stt.SpeechEvent]]: # insert custom before STT processing here events = Agent.default.stt_node(self, audio, model_settings) # insert custom after STT processing here return eventsimport { voice } from '@livekit/agents'; const agent = voice.Agent.create({ instructions: 'You are a helpful assistant.', sttNode(ctx, audio, modelSettings) { // insert custom before STT processing here const events = voice.Agent.default.sttNode(ctx.agent, audio, modelSettings); // insert custom after STT processing here return events; },});Lifecycle hooksThe following lifecycle hooks are available for customization.On enterThe on_enter node is called when the agent becomes the active agent in a session. Each session can have only one active agent at a time, which can be read from the session.agent property. Change the active agent using Workflows.For example, to greet the user:PythonNode.jsasync def on_enter(self): await self.session.generate_reply( instructions="Greet the user with a warm welcome", )const agent = voice.Agent.create({ onEnter(ctx) { ctx.session.generateReply({ instructions: "Greet the user with a warm welcome", }); },});On exitThe on_exit node is called before the agent gives control to another agent in the same session as part of a workflow. Use it to save data, say goodbye, or perform other actions and cleanup.For example, to say goodbye:PythonNode.jsasync def on_exit(self): await self.session.generate_reply( instructions="Tell the user a friendly goodbye before you exit.", )const agent = voice.Agent.create({ onExit(ctx) { ctx.session.generateReply({ instructions: "Tell the user a friendly goodbye before you exit.", }); },});On user turn completed The on_user_turn_completed node is called when the user's turn has ended, before the agent's reply. Override this method to modify the content of the turn, cancel the agent's reply, or perform other actions.Realtime model turn detectionTo use the on_user_turn_completed node with a realtime model, you must configure turn detection to occur in your agent instead of within the realtime model.The node receives the following parameters:turn_ctx: The full ChatContext, up to but not including the user's latest message.new_message: The user's latest message, representing their current turn.After the node is complete, the new_message is added to the chat context.One common use of this node is retrieval-augmented generation (RAG). You can retrieve context relevant to the newest message and inject it into the chat context for the LLM.PythonNode.jsfrom livekit.agents import ChatContext, ChatMessage async def on_user_turn_completed( self, turn_ctx: ChatContext, new_message: ChatMessage,) -> None: rag_content = await my_rag_lookup(new_message.text_content) turn_ctx.add_message( role="assistant", content=f"Additional information relevant to the user's next message: {rag_content}" )import { voice } from '@livekit/agents'; const agent = voice.Agent.create({ instructions: 'You are a helpful assistant.', async onUserTurnCompleted(ctx, chatCtx, newMessage) { const ragContent = await myRagLookup(newMessage.textContent); chatCtx.addMessage({ role: 'assistant', content: `Additional information relevant to the user's next message: ${ragContent}`, }); },});Additional messages added in this way are not persisted beyond the current turn. To permanently add messages to the chat history, use the update_chat_ctx method:PythonNode.jsasync def on_user_turn_completed( self, turn_ctx: ChatContext, new_message: ChatMessage,) -> None: rag_content = await my_rag_lookup(new_message.text_content) turn_ctx.add_message(role="assistant", content=rag_content) await self.update_chat_ctx(turn_ctx)import { voice } from '@livekit/agents'; const agent = voice.Agent.create({ instructions: 'You are a helpful assistant.', async onUserTurnCompleted(ctx, chatCtx, newMessage) { const ragContent = await myRagLookup(newMessage.textContent); chatCtx.addMessage({ role: 'assistant', content: `Additional information relevant to the user's next message: ${ragContent}`, }); await ctx.agent.updateChatCtx(chatCtx); },});You can also edit the new_message object to modify the user's message before it's added to the chat context. For example, you can remove offensive content or add additional context. These changes are persisted to the chat history going forward.PythonNode.jsasync def on_user_turn_completed( self, turn_ctx: ChatContext, new_message: ChatMessage,) -> None: new_message.content = ["... modified message ..."]import { voice } from '@livekit/agents'; const agent = voice.Agent.create({ instructions: 'You are a helpful assistant.', onUserTurnCompleted(ctx, chatCtx, newMessage) { newMessage.content = ['... modified message ...']; },});To abort generation entirely — for example, in a push-to-talk interface — you can do the following:PythonNode.jsasync def on_user_turn_completed( self, turn_ctx: ChatContext, new_message: ChatMessage,) -> None: if not new_message.text_content: # for example, raise StopResponse to stop the agent from generating a reply raise StopResponse()import { voice } from '@livekit/agents'; const agent = voice.Agent.create({ instructions: 'You are a helpful assistant.', onUserTurnCompleted(ctx, chatCtx, newMessage) { if (!newMessage.textContent) { // raise StopResponse to stop the agent from generating a reply throw new voice.StopResponse(); } },});Fast pre-response Use the on_user_turn_completed node to speak a short filler phrase, such as "let me think about that", while the main reply is still generating. A smaller, faster model produces the filler. Calling say without awaiting the speech handle it returns lets the two run concurrently, which reduces the perceived gap between the user's turn and the agent's response.To implement this, override on_user_turn_completed to build a trimmed context for the fast model, then call say with add_to_chat_ctx=False so the filler stays out of the main reply's history:PythonNode.jsfrom livekit.agents import Agent, ChatContext, ChatMessage, inference, llm class PreResponseAgent(Agent): def __init__(self): super().__init__( instructions="You are a helpful assistant.", llm=inference.LLM("openai/gpt-6-sol"), ) # A smaller, faster model generates the filler phrase self._fast_llm = inference.LLM("openai/gpt-6-luna") self._fast_llm_prompt = llm.ChatMessage( role="system", content=[ "Generate a short instant response to the user's message with 5 to 10 words.", "Do not answer the question directly. Examples: let me think about that, " "wait a moment, that's a good question.", ], ) async def on_user_turn_completed( self, turn_ctx: ChatContext, new_message: ChatMessage, ) -> None: # Trim the context: drop instructions and tool-call history, keep only recent items fast_ctx = turn_ctx.copy( exclude_instructions=True, exclude_function_call=True, ).truncate(max_items=3) fast_ctx.items.insert(0, self._fast_llm_prompt) fast_ctx.items.append(new_message) # Speak the filler without awaiting, so the main reply generates concurrently self.session.say( self._fast_llm.chat(chat_ctx=fast_ctx).to_str_iterable(), add_to_chat_ctx=False, )import { inference, llm, toStream, voice } from '@livekit/agents'; const FAST_LLM_PROMPT = "Generate a short instant response to the user's message with 5 to 10 words. " + 'Do not answer the question directly. Examples: let me think about that, ' + "wait a moment, that's a good question."; // A smaller, faster model generates the filler phraseconst fastLLM = new inference.LLM({ model: 'openai/gpt-6-luna' }); const agent = voice.Agent.create({ instructions: 'You are a helpful assistant.', llm: new inference.LLM({ model: 'openai/gpt-6-sol' }), onUserTurnCompleted(ctx, turnCtx, newMessage) { // Trim the context: drop instructions and tool-call history, keep only recent items co