-
Notifications
You must be signed in to change notification settings - Fork 2.3k
create dedicated documentation for nostream tag #2916
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Naomi Pentrel (npentrel)
merged 10 commits into
main
from
naomi/doc-507-create-dedicated-documentation-for-nostream-tag
Apr 2, 2026
Merged
Changes from 6 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
3d3a8ba
docs: add docs for nostream tag
npentrel 0b83eaa
update lint
npentrel cd21f58
update github action
npentrel 4b436b2
Merge branch 'main' into naomi/doc-507-create-dedicated-documentation…
npentrel b19b0cf
Apply suggestion from @npentrel
npentrel 17ab3bb
update
npentrel d82787f
simplify example
npentrel 42b732b
update
npentrel 313cc38
Merge branch 'main' into naomi/doc-507-create-dedicated-documentation…
npentrel 8cdf7ad
try
npentrel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| """Example of using nostream tag to exclude LLM output from the stream.""" | ||
|
|
||
| # :snippet-start: nostream-tag-py | ||
| from typing import Any, TypedDict | ||
|
|
||
| from langchain_anthropic import ChatAnthropic | ||
| from langchain_core.messages import BaseMessage | ||
| from langgraph.graph import START, StateGraph | ||
|
|
||
| # Create two models: one that streams, one that doesn't | ||
| streaming_model = ChatAnthropic( | ||
| model_name="claude-3-haiku-20240307", timeout=None, stop=None | ||
| ) | ||
| internal_model = ChatAnthropic( | ||
| model_name="claude-3-haiku-20240307", timeout=None, stop=None | ||
| ).with_config({"tags": ["nostream"]}) | ||
|
|
||
|
|
||
| class State(TypedDict): | ||
| """State for the graph.""" | ||
|
|
||
| topic: str | ||
| public_response: str | ||
| internal_analysis: str | ||
|
|
||
|
|
||
| def generate_response(state: State) -> dict[str, Any]: | ||
| """Generate a public response that will be streamed.""" | ||
| topic = state["topic"] | ||
| response = streaming_model.invoke( | ||
| [{"role": "user", "content": f"Write a short response about {topic}"}] | ||
| ) | ||
| return {"public_response": response.content} | ||
|
|
||
|
|
||
| def analyze_internally(state: State) -> dict[str, Any]: | ||
| """Analyze internally without streaming tokens.""" | ||
| topic = state["topic"] | ||
| # This model has the "nostream" tag, so its tokens won't appear in the stream | ||
| analysis = internal_model.invoke( | ||
| [{"role": "user", "content": f"Analyze the topic: {topic}"}] | ||
| ) | ||
| return {"internal_analysis": analysis.content} | ||
|
|
||
|
|
||
| graph = ( | ||
| StateGraph(State) | ||
| .add_node("generate_response", generate_response) | ||
| .add_node("analyze_internally", analyze_internally) | ||
| .add_edge(START, "generate_response") | ||
| .add_edge(START, "analyze_internally") | ||
| .compile() | ||
| ) | ||
|
|
||
| initial_state: State = { | ||
| "topic": "AI", | ||
| "public_response": "", | ||
| "internal_analysis": "", | ||
| } | ||
| stream = graph.stream(initial_state, stream_mode="messages") # type: ignore[arg-type] | ||
|
|
||
| # :remove-start: | ||
| # Stream with "messages" mode - only tokens from streaming_model will appear | ||
| streamed_nodes: list[str] = [] | ||
| for msg, metadata in stream: | ||
| if isinstance(msg, BaseMessage) and msg.content and isinstance(metadata, dict): | ||
| streamed_nodes.append(metadata["langgraph_node"]) | ||
| # print(msg.content, end="|", flush=True) | ||
| assert "analyze_internally" not in streamed_nodes, ( | ||
| "No tokens from the non-streaming model should appear in the stream" | ||
| ) | ||
|
|
||
| if __name__ == "__main__": | ||
| print("\n✓ nostream tag example works as expected") # noqa: T201 | ||
| # :remove-end: | ||
| # :snippet-end: | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| /** | ||
| * Example of using nostream tag to exclude LLM output from the stream. | ||
| */ | ||
|
|
||
| // :snippet-start: nostream-tag-js | ||
| import { ChatAnthropic } from "@langchain/anthropic"; | ||
| import { StateGraph, StateSchema, START } from "@langchain/langgraph"; | ||
| import * as z from "zod"; | ||
|
|
||
| // Create two models: one that streams, one that doesn't | ||
| const streamingModel = new ChatAnthropic({ model: "claude-3-haiku-20240307" }); | ||
| const internalModel = new ChatAnthropic({ | ||
| model: "claude-3-haiku-20240307", | ||
| }).withConfig({ | ||
| tags: ["nostream"], | ||
| }); | ||
|
|
||
| const State = new StateSchema({ | ||
| topic: z.string(), | ||
| publicResponse: z.string().optional(), | ||
| internalAnalysis: z.string().optional(), | ||
| }); | ||
|
|
||
| const generateResponse = async (state: typeof State.State) => { | ||
| const topic = state.topic; | ||
| // This response will be streamed | ||
| const response = await streamingModel.invoke([ | ||
| { role: "user", content: `Write a short response about ${topic}` }, | ||
| ]); | ||
| return { publicResponse: response.content }; | ||
| }; | ||
|
|
||
| const analyzeInternally = async (state: typeof State.State) => { | ||
| const topic = state.topic; | ||
| // This model has the "nostream" tag, so its tokens won't appear in the stream | ||
| const analysis = await internalModel.invoke([ | ||
| { role: "user", content: `Analyze the topic: ${topic}` }, | ||
| ]); | ||
| return { internalAnalysis: analysis.content }; | ||
| }; | ||
|
|
||
| const graph = new StateGraph(State) | ||
| .addNode("generateResponse", generateResponse) | ||
| .addNode("analyzeInternally", analyzeInternally) | ||
| .addEdge(START, "generateResponse") | ||
| .addEdge(START, "analyzeInternally") | ||
| .compile(); | ||
|
|
||
| const stream = await graph.stream({ topic: "AI" }, { streamMode: "messages" }); | ||
| // :snippet-end: | ||
|
|
||
| // :remove-start: | ||
| // Stream with "messages" mode - only tokens from streamingModel will appear | ||
| const streamedNodes: string[] = []; | ||
| for await (const [msg, metadata] of stream) { | ||
| if (msg.content) { | ||
| streamedNodes.push(metadata.langgraph_node); | ||
| } | ||
| } | ||
|
|
||
| if (streamedNodes.includes("analyzeInternally")) { | ||
| throw new Error( | ||
| "No tokens from the non-streaming model should appear in the stream", | ||
| ); | ||
| } | ||
|
|
||
| console.log("\n✓ nostream tag example works as expected"); | ||
| // :remove-end: |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| ```ts | ||
| import { ChatAnthropic } from "@langchain/anthropic"; | ||
| import { StateGraph, StateSchema, START } from "@langchain/langgraph"; | ||
| import * as z from "zod"; | ||
|
|
||
| // Create two models: one that streams, one that doesn't | ||
| const streamingModel = new ChatAnthropic({ model: "claude-3-haiku-20240307" }); | ||
| const internalModel = new ChatAnthropic({ | ||
| model: "claude-3-haiku-20240307", | ||
| }).withConfig({ | ||
| tags: ["nostream"], | ||
| }); | ||
|
|
||
| const State = new StateSchema({ | ||
| topic: z.string(), | ||
| publicResponse: z.string().optional(), | ||
| internalAnalysis: z.string().optional(), | ||
| }); | ||
|
|
||
| const generateResponse = async (state: typeof State.State) => { | ||
| const topic = state.topic; | ||
| // This response will be streamed | ||
| const response = await streamingModel.invoke([ | ||
| { role: "user", content: `Write a short response about ${topic}` }, | ||
| ]); | ||
| return { publicResponse: response.content }; | ||
| }; | ||
|
|
||
| const analyzeInternally = async (state: typeof State.State) => { | ||
| const topic = state.topic; | ||
| // This model has the "nostream" tag, so its tokens won't appear in the stream | ||
| const analysis = await internalModel.invoke([ | ||
| { role: "user", content: `Analyze the topic: ${topic}` }, | ||
| ]); | ||
| return { internalAnalysis: analysis.content }; | ||
| }; | ||
|
|
||
| const graph = new StateGraph(State) | ||
| .addNode("generateResponse", generateResponse) | ||
| .addNode("analyzeInternally", analyzeInternally) | ||
| .addEdge(START, "generateResponse") | ||
| .addEdge(START, "analyzeInternally") | ||
| .compile(); | ||
|
|
||
| const stream = await graph.stream({ topic: "AI" }, { streamMode: "messages" }); | ||
| ``` |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.