How can I implement the following (I am using agen...
# ask-ai
f
How can I implement the following (I am using agents python sdk) When LLM replies with json only, I want to intercept that call and finish the call
t
Thanks for reaching out, Dmitry. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're exploring how to intercept LLM replies with JSON and finish the call using the Python SDK! You can definitely make use of structured output capabilities from supported LLMs like OpenAI, which lets the model return JSON payloads. This way, you can easily parse and work with the responses to create your own custom logic. Here’s a friendly guide on how to get this done: • Configure OpenAI for structured output: Start by setting up your LLM to emit JSON responses and define a JSON schema that matches the structure you expect. • Override agent nodes: You can add your own custom logic in the
llm_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...
f
I want to explore this: • Override agent nodes: You can add your own custom logic in the
llm_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 examples
t
I'm happy to share some helpful code examples for overriding
llm_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
Copy code
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
Copy code
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:
Copy code
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