langgraph get_stream_writer not working with livek...
# ask-ai
r
langgraph get_stream_writer not working with livekit, message is not being able to pass through stream
t
Thanks for reaching out, Umair. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! Could you share a bit more about what's going on? Specifically: • Are you seeing any error messages or logs when you use
get_stream_writer
with LiveKit? • What does your setup or integration between LangGraph and LiveKit look like? • Have you checked if the LiveKit stream is up and running as expected? Getting these details will really help us figure out what's happening and find a solution together.
r
I have graoh with tools langgraph tools. and grapph is attached with livekit through an adapter. from inside my tool when I use get stream writer and write a custom message then llm_node is not processing that message, but when the tool completes it returns both tool message and custom message which was writen using get_stream_writer writer
t
It looks like the issue is coming from how custom messages are being handled in your LangGraph workflow and the LiveKit adapter. By default, the LiveKit LangGraph adapter works with string messages and
BaseMessageChunk
objects, but it might not be set up to handle custom message types just yet. Here are a couple of ideas that might help: 1. Custom LLM Node: You could override the
llm_node
to handle your custom message types and include text streaming. This way, you can manage any custom fields in your messages and stream them smoothly. If you'd like, I’m happy to share some example code to get you started. 2. Modify LangGraph Workflow Output: Another option is to make sure your LangGraph nodes return messages in formats the adapter already understands (like strings or
BaseMessageChunk
objects). This can simplify things by avoiding extra custom processing. Also, don’t forget that LiveKit’s text streaming feature lets you send custom data alongside the main conversation, which might be useful here. Could you let me know what specific custom message types your LangGraph workflow is producing? And are you aiming to stream custom data alongside the main conversation, or are you trying to replace the conversation content entirely? Knowing this will help me give you the best advice. Sources: pipeline-llm/replacing_llm_output.py | livekit-agents/livekit/agents/voice/agent.py | livekit-rtc/livekit/rtc/participant.py | Voice pipeline nodes | LiveKit Docs
r
here is some code this prints that custom message but llm_node is speaking until that tool completes`
Copy code
print(">> Livekit stream chunk", chunk)
`
Copy code
async def llm_node(self, chat_ctx, tools, model_settings):
        """
        Process user input with streaming support.
        """
        log.info(f"Processing chat context with {len(chat_ctx.items)} items")

        # Reset for new conversation turn
        self.message_handler.reset_for_new_turn()

        # Extract and save user message
        user_content = self._extract_user_content(chat_ctx)
        if user_content:
            await self.message_handler.save_user_message(user_content, self.session.userdata)

        # Create new context with only latest message
        new_chat_ctx = self._create_new_context(chat_ctx, user_content)
        log.debug("Created new context with latest message")

        # Update configuration
        await self._update_adapter_config()

        # Get original stream
        original_stream = super().llm_node(new_chat_ctx, tools, model_settings)

        # Wrap stream to capture complete response
        return self._wrap_response_stream(original_stream)

    async def _wrap_response_stream(self, original_stream):
        """Wrap the response stream to capture and save the complete response."""
        accumulated_response = ""
        end_conversation = False
        handoff_conversation = False

        try:
            async for chunk in original_stream:
                print(">> Livekit stream chunk", chunk)
                # Check for end_conversation signal via custom attribute
                if hasattr(chunk, "_end_conversation_signal") and chunk._end_conversation_signal:
                    end_conversation = True
                elif hasattr(chunk, "_human_handoff_signal") and chunk._human_handoff_signal:
                    handoff_conversation = True
                else:
                    # Accumulate response content for non-signal chunks
                    if hasattr(chunk, "delta") and hasattr(chunk.delta, "content") and chunk.delta.content:
                        accumulated_response += chunk.delta.content

                # Yield chunk for real-time streaming
                yield chunk
t
It looks like the issue you're running into has to do with how LiveKit handles streaming when tools are part of the process. Basically, LiveKit waits for the tool execution to finish before it starts processing and streaming custom messages, which can lead to some delays. This happens because of a known limitation: LiveKit won’t start a new generation until the previous one is fully closed. This can create a bit of a deadlock, where tool results only get processed after the agent finishes speaking. Here are a couple of ways you might tackle this: 1. Override the LLM Node: You can customize the
llm_node
to handle tool calls differently, so it processes custom messages right away when a tool call happens. This way, you can bypass the default behavior and stream your messages in real-time. 2. Text Processing During Streaming: Another option is to tweak the content of each chunk as it streams, adding your custom messages on the fly. This ensures they get processed and shown without waiting for the tool execution to wrap up. Could you let me know if you’re trying to send messages to the user while the tools are still running, or if you’re looking to change how the tool execution itself flows? Also, are your custom messages text-based, audio-based, or something else? Knowing this will help me give you a more tailored solution. Sources: livekit-plugins/livekit-plugins-mistralai/livekit/plugins/mistralai/llm.py | Pipeline nodes and hooks | LiveKit Docs | pipeline-llm/replacing_llm_output.py
r
okay could you provide code how we can overide?
t
Hey there! Here’s a friendly example of how you can override the
llm_node
to handle custom messages while your tool is running, streaming them to you in real-time:
Copy code
async def llm_node(self, chat_ctx, tools, model_settings):
    """
    Override the llm_node to handle custom messages during tool calls.
    """
    tool_call_detected = False

    async for chunk in super().llm_node(chat_ctx, tools, model_settings):
        # Check if this chunk contains a tool call
        if isinstance(chunk, ChatChunk) and chunk.delta and chunk.delta.tool_calls and not tool_call_detected:
            # Process custom message immediately when tool call is detected
            tool_call_detected = True
            # Example: Stream a custom message
            custom_message = "Processing tool..."
            yield ChatChunk(
                id="custom_message",
                delta=ChoiceDelta(
                    role="assistant",
                    content=custom_message
                )
            )

        # Yield the original chunk
        yield chunk
What this does is watch the stream of chunks for any tool calls. As soon as it spots one, it sends a quick, friendly message like "Processing tool..." to keep you in the loop before continuing with the usual stream. If you have any special ideas or want the messages to do something extra, just give me a shout—I’m happy to tweak the code to fit your needs!