What is Proper Way to Cancel A Stream? Does Cancelling the Reader Work? #5258
-
Checked other resources
Commit to Help
Example Codeconst stream = await chain.stream({ topic: "Bonobos" })
const reader = stream.getReader()
reader.read().then(function process({ done, value }) {
if (done) return
// do something with `value`
return reader.read().then(process)
})
// attempt to cancel the stream after 3 seconds
setTimeout(() => reader.cancel(), 3000) DescriptionI'm working with streams & i am interested in the proper way to cancel a stream. I have found the documentation here describing how to use an
Would the following code also work to cancel a streamed response? Or with this result in a leak? const stream = await chain.stream({ topic: "Bonobos" })
const reader = stream.getReader()
reader.read().then(function process({ done, value }) {
if (done) return
// do something with `value`
return reader.read().then(process)
})
// attempt to cancel the stream after 3 seconds
setTimeout(() => reader.cancel(), 3000) System Info[email protected] |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Using For LangChain specifically, when dealing with streams that involve external requests or operations that might be long-running, it's recommended to use an import { ChatOpenAI } from "@langchain/openai";
import { PromptTemplate } from "@langchain/core/prompts";
const controller = new AbortController();
const llm = new ChatOpenAI({ temperature: 0.9 });
const model = llm.bind({ signal: controller.signal });
const prompt = PromptTemplate.fromTemplate("Please write a 500 word essay about {topic}.");
const chain = prompt.pipe(model);
setTimeout(() => controller.abort(), 3000);
try {
const stream = await chain.stream({ topic: "Bonobos" });
for await (const chunk of stream) {
console.log(chunk);
}
} catch (e) {
console.log(e); // Handle or log the error
} This approach ensures that the cancellation signal is propagated through all layers of the request, effectively managing both local and external operations. It's particularly useful for ensuring that your application remains efficient and responsive, avoiding potential resource leaks when dealing with complex or long-running operations.
|
Beta Was this translation helpful? Give feedback.
Using
reader.cancel()
to terminate a stream, as shown in your code snippet, is indeed a correct approach for managing streams in JavaScript and will effectively cancel the stream without causing resource leaks. This method directly cancels the reading operation and should clean up resources associated with the stream.For LangChain specifically, when dealing with streams that involve external requests or operations that might be long-running, it's recommended to use an
AbortController
to manage cancellation more comprehensively. This method allows you to cancel not just the stream reading but also any ongoing external requests initiated by LangChain, ensuring a more thorough cancellation…