feat(api): add WebSocket endpoints for real-time streaming#33543
feat(api): add WebSocket endpoints for real-time streaming#33543Olauge-Secret wants to merge 1 commit intolanggenius:mainfrom
Conversation
Add WebSocket support alongside existing SSE for chat and completion message streaming, enabling persistent bidirectional connections for messaging platform integrations (WhatsApp, Telegram, Feishu, Slack). Closes langgenius#33542 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the API's real-time capabilities by integrating WebSocket support. This addition allows for more robust and persistent communication channels, which are crucial for seamless integration with various messaging platforms. The change provides a flexible alternative to Server-Sent Events, catering to applications that demand long-lived, bidirectional data streams. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces WebSocket support for real-time streaming of chat and completion messages, complementing the existing SSE implementation. This is a significant feature that enables better integration with messaging platforms requiring persistent connections. The implementation adds new WebSocket endpoints for both the service and web APIs, a utility for streaming events, and corresponding unit tests.
The overall approach is solid. However, there are a few areas for improvement:
- The error handling in the new WebSocket controllers constructs JSON responses using f-strings, which is unsafe and can lead to malformed JSON and potential information leaks. This should be changed to use
json.dumps. - The exception handling in the WebSocket streaming utility is too broad and could mask non-connection related errors.
| except Exception as exc: | ||
| ws.send(f'{{"error": "{exc}"}}') | ||
| ws.close() | ||
| return |
There was a problem hiding this comment.
Sending error messages using an f-string is unsafe as it can lead to invalid JSON if the exception message contains special characters (e.g., quotes). It can also leak sensitive information. It's better to use json.dumps to properly serialize the error data. This issue is present in multiple error handling blocks within this file (e.g., lines 117-118, 136-138, 154-155, 174-175, 194-196) and should be fixed in all occurrences.
Ideally, json should be imported at the top of the file.
| except Exception as exc: | |
| ws.send(f'{{"error": "{exc}"}}') | |
| ws.close() | |
| return | |
| except Exception as exc: | |
| import json | |
| ws.send(json.dumps({"error": str(exc)})) | |
| ws.close() | |
| return |
| except Exception as exc: | ||
| ws.send(f'{{"error": "{exc}"}}') | ||
| ws.close() | ||
| return |
There was a problem hiding this comment.
Sending error messages using an f-string is unsafe. It can produce invalid JSON if the exception message contains special characters, and it might leak internal implementation details. Please use json.dumps to ensure the error message is always correctly formatted as a JSON string. This should be applied to all similar error handling blocks in this file.
Ideally, json should be imported at the top of the file.
| except Exception as exc: | |
| ws.send(f'{{"error": "{exc}"}}') | |
| ws.close() | |
| return | |
| except Exception as exc: | |
| import json | |
| ws.send(json.dumps({"error": str(exc)})) | |
| ws.close() | |
| return |
| except Exception: | ||
| logger.debug("WebSocket connection closed by client") |
There was a problem hiding this comment.
Catching a broad Exception here might hide bugs that are not related to the client disconnecting, such as serialization errors from orjson_dumps. It would be safer to catch a more specific exception related to connection errors. The corresponding test test_client_disconnect_handled_gracefully uses ConnectionError, which would be a good, more specific exception to catch here.
| except Exception: | |
| logger.debug("WebSocket connection closed by client") | |
| except ConnectionError: | |
| logger.debug("WebSocket connection closed by client") |
Important
Fixes #<issue number>.Summary
Fixes #33542
Add WebSocket support alongside existing SSE (Server-Sent Events) for chat and completion message streaming. This enables persistent bidirectional connections for messaging platform integrations such as WhatsApp, Telegram, Feishu/Lark, and Slack, which require long-lived tunnels rather than traditional webhook-based request/response cycles.
Changes
flask-sock~=0.7.0for lightweight WebSocket support on Flaskapi/libs/websocket.py: Utility that bridges the existing Redis pub/sub event streaming generator to WebSocket framesapi/controllers/service_api/app/websocket.py: Service API WebSocket endpoints at/v1/ws/chat-messagesand/v1/ws/completion-messagesapi/controllers/web/websocket.py: Web App WebSocket endpoints at/api/ws/chat-messagesand/api/ws/completion-messagesapi/extensions/ext_blueprints.py: Register new WebSocket blueprintsapi/tests/unit_tests/libs/test_websocket.py: Unit tests for the WebSocket streaming utilityHow it works
Authorizationheader or?token=query param)ChatRequestPayload/CompletionRequestPayloadschemaUsage
Service API:
Web App:
Screenshots
Checklist
make lintandmake type-check(backend) andcd web && npx lint-staged(frontend) to appease the lint gods