fierce-zoo-69908
11/08/2025, 3:25 AMtall-airline-16756
11/08/2025, 3:25 AMtall-airline-16756
11/08/2025, 3:26 AMllm_node and tts_node to parse those JSON replies and handle any termination signals gracefully.
• Implement termination logic: When it’s time to wrap up, use session.interrupt() to stop any ongoing responses, and then session.say() to deliver a final message before ending the session. Alternatively, tool calls or handoff patterns can be handy to signal the session’s end.
For a full example that walks you through defining JSON schemas, parsing structured replies, and applying TTS directives, check out this complete implementation here. It’s a great resource to see everything in action.
If you have any questions or want to dive deeper into specific parts, please don’t hesitate to reach out—I’m here to help!
Sources: Tool definition and use | LiveKit docs | docs/index.yaml | Agents telephony integration | LiveKit docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...fierce-zoo-69908
11/08/2025, 3:28 AMllm_node and tts_node to parse those JSON replies and handle any termination signals gracefully.
• Implement termination logic: When it’s time to wrap up, use session.interrupt() to stop any ongoing responses, and then session.say() to deliver a final message before ending the session. Alternatively, tool calls or handoff patterns can be handy to signal the session’s end.
give me code examplestall-airline-16756
11/08/2025, 3:28 AMllm_node and tts_node so you can parse JSON replies and handle termination signals smoothly. Let's walk through them together:
1. Overriding llm_node for JSON Parsing
from typing_extensions import TypedDict
from pydantic import Field
class ResponseEmotion(TypedDict):
voice_instructions: Annotated[
str,
Field(..., description="Concise TTS directive for tone, emotion, intonation, and speed"),
]
response: str
async def llm_node(
self, chat_ctx: ChatContext, tools: list[FunctionTool], model_settings: ModelSettings
):
# Cast LLM to OpenAI type to access structured output
llm = cast(openai.LLM, self.llm)
async with llm.chat(
chat_ctx=chat_ctx,
tools=tools,
response_format=ResponseEmotion,
) as stream:
async for chunk in stream:
yield chunk
2. Overriding tts_node to Parse JSON and Apply Instructions
async def process_structured_output(
text: AsyncIterable[str],
callback: Optional[Callable[[ResponseEmotion], None]] = None,
) -> AsyncIterable[str]:
last_response = ""
acc_text = ""
async for chunk in text:
acc_text += chunk
try:
resp: ResponseEmotion = from_json(acc_text, allow_partial="trailing-strings")
except ValueError:
continue
if callback:
callback(resp)
if not resp.get("response"):
continue
new_delta = resp["response"][len(last_response):]
if new_delta:
yield new_delta
last_response = resp["response"]
async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
instruction_updated = False
def output_processed(resp: ResponseEmotion):
nonlocal instruction_updated
if resp.get("voice_instructions") and resp.get("response") and not instruction_updated:
instruction_updated = True
tts = cast(openai.TTS, self.tts)
tts.update_options(instructions=resp["voice_instructions"])
# Pass parsed text (without JSON structure) to default TTS node
return Agent.default.tts_node(
self, process_structured_output(text, callback=output_processed), model_settings
)
3. Handling Termination Signals
To gracefully handle termination signals, you can use session.interrupt() and session.say() like this:
MAX_CHUNKS = 20
chunk_count = 0
async def process_text():
nonlocal chunk_count
interrupted = False
async for chunk in text:
chunk_count += 1
if chunk_count > MAX_CHUNKS and not interrupted:
self.session.interrupt()
self.session.say("Response too long, stopping.")
interrupted = True
break
yield chunk
If you'd like to see everything in action, feel free to check out the Structured Output Example. And of course, if you have any questions or need a hand with anything else, just let me know—I’m here to help!
Sources: docs/index.yaml | Tool definition and use | LiveKit docs | Pipeline nodes and hooks | LiveKit docs | LiveKit Docs | Tool definition and use | LiveKit docs