streamed-chatgpt-api
streamed-chatgpt-api copied to clipboard
Add reader object access in callback for stream control
This PR implements the feature request to allow access to the reader object in the fetchStreamedChat callback function, enabling users to cancel streams mid-processing.
Changes Made
Core Implementation
-
Minimal Change: Modified the callback invocation in
processStreamto pass the reader object as a second parameter:// Before onChunkReceived(message); // After onChunkReceived(message, reader);
New Usage Pattern
Users can now access the reader object to control the stream:
fetchStreamedChat({
apiKey,
messageInput: 'Hello, how are you?',
}, (responseChunk, reader) => {
if (someCondition) {
reader.cancel(); // Cancel the stream
}
const content = JSON.parse(responseChunk).choices[0].delta.content;
if (content) {
process.stdout.write(content);
}
});
Backward Compatibility
Existing code continues to work unchanged:
// This still works exactly as before
fetchStreamedChat(options, (responseChunk) => {
// handle chunk
});
Documentation & Testing
- Updated README.md with examples and documentation for the new feature
- Added test case to verify reader object is properly passed to callbacks
- Created demonstration scripts showing the exact requested usage pattern
Benefits
- ✅ Enables stream cancellation via
reader.cancel() - ✅ 100% backward compatible - no breaking changes
- ✅ Minimal implementation - only 1 line of functional code changed
- ✅ Addresses the exact use case described in the issue
Fixes #2.
[!WARNING]
Firewall rules blocked me from connecting to one or more addresses
I tried to connect to the following addresses, but was blocked by firewall rules:
api.openai.com
- Triggering command:
node /home/REDACTED/work/streamed-chatgpt-api/streamed-chatgpt-api/node_modules/.bin/jest test/reader-callback.test.js(dns block)- Triggering command:
node test/compatibility-test.js(dns block)If you need me to access, download, or install something from one of these locations, you can either:
- Configure Actions setup steps to set up my environment, which run before the firewall is enabled
- Add the appropriate URLs or hosts to my firewall allow list
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.