-
Notifications
You must be signed in to change notification settings - Fork 2.2k
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
Changes from 4 commits
3d3a8ba
0b83eaa
cd21f58
4b436b2
b19b0cf
17ab3bb
d82787f
42b732b
313cc38
8cdf7ad
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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, cast | ||
|
|
||
| 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(cast("Any", initial_state), stream_mode="messages") | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we should never do this
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. linter was unhappy without it, let me try to remove it |
||
|
|
||
| # :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 | ||
|
sydney-runkle marked this conversation as resolved.
Outdated
|
||
| # :remove-end: | ||
| # :snippet-end: | ||
| 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.
| 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" }); | ||
| ``` |
Uh oh!
There was an error while loading. Please reload this page.