The most common use case for streaming from inside a node is to stream LLM tokens, but you may also want to stream custom data.
For example, if you have a long-running tool call, you can dispatch custom events between the steps and use these custom events to monitor progress. You could also surface these custom events to an end user of your application to show them how the current task is progressing.
You can do so in two ways:
using your graph's .stream method with streamMode: "custom"
Sign up for LangSmith to quickly spot issues and improve the performance of your LangGraph projects. LangSmith lets you use trace data to debug, test, and monitor your LLM apps built with LangGraph — read more about how to get started here.
import{StateGraph,MessagesAnnotation,LangGraphRunnableConfig,}from"@langchain/langgraph";constmyNode=async(_state:typeofMessagesAnnotation.State,config:LangGraphRunnableConfig)=>{constchunks=["Four","score","and","seven","years","ago","our","fathers","...",];for(constchunkofchunks){// write the chunk to be streamed using streamMode=custom// Only populated if one of the passed stream modes is "custom".config.writer?.(chunk);}return{messages:[{role:"assistant",content:chunks.join(" "),}],};};constgraph=newStateGraph(MessagesAnnotation).addNode("model",myNode).addEdge("__start__","model").compile();
constinputs=[{role:"user",content:"What are you thinking about?",}];conststream=awaitgraph.stream({messages:inputs},{streamMode:"custom"});forawait(constchunkofstream){console.log(chunk);}
Fourscoreandsevenyearsagoourfathers...
You will likely need to use multiple streaming modes as you will
want access to both the custom data and the state updates.
If you are already using graph's .streamEvents method in your workflow, you can also stream custom data by emitting custom events using dispatchCustomEvents
consteventStream=awaitgraphWithDispatch.streamEvents({messages:[{role:"user",content:"What are you thinking about?",}]},{version:"v2",},);forawait(const{event,name,data}ofeventStream){if(event==="on_custom_event"&&name==="my_custom_event"){console.log(`${data.chunk}|`);}}