Skip to content
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

feat: Add WebSocket conversation.chat.cancel support #191

Merged
merged 7 commits into from
Mar 5, 2025

Conversation

mbb1234567890
Copy link
Contributor

@mbb1234567890 mbb1234567890 commented Mar 4, 2025

support cancel chat event ‘conversation.chat.cancel’ and callback canceled event ‘conversation.chat.canceled’

Summary by CodeRabbit

  • New Features
    • Introduced enhanced handling for chat cancellations, allowing conversations to be interrupted and managed more effectively.
    • Added support for both synchronous and asynchronous chat workflows, ensuring smoother user experiences during chat interruptions.
    • Expanded chat event capabilities to improve responsiveness and control within the chat interface.
    • New event handler methods for handling chat cancellation events have been added to various components.

Copy link

coderabbitai bot commented Mar 4, 2025

Walkthrough

The changes introduce new event classes and methods to facilitate conversation chat cancellation. Specifically, two new event types, ConversationChatCancelEvent and ConversationChatCanceledEvent, are added to the main module and WebSocket-related submodules. The public API is expanded, event loading is enhanced, and both synchronous and asynchronous handler methods are implemented across relevant client and example modules.

Changes

File(s) Change Summary
cozepy/__init__.py Imported ConversationChatCancelEvent and ConversationChatCanceledEvent; updated __all__ to include these events.
cozepy/websockets/chat/__init__.py Added new classes for chat cancellation events extending WebsocketsEvent; updated WebsocketsChatEventHandler and client classes (sync and async) with new cancellation methods and event loading.
cozepy/websockets/ws.py Added two new enum values: CONVERSATION_CHAT_CANCEL and CONVERSATION_CHAT_CANCELED in WebsocketsEventType.
examples/websockets_chat.py Added an asynchronous event handler method on_conversation_chat_canceled in AsyncWebsocketsChatEventHandlerSub and imported ConversationChatCanceledEvent.
examples/websockets_chat_realtime_gui.py Added an asynchronous method on_conversation_chat_canceled in ChatEventHandler with try-except handling and imported ConversationChatCanceledEvent.

Sequence Diagram(s)

sequenceDiagram
    participant C as Chat Client (Sync/Async)
    participant E as Event Enqueuer
    participant L as Event Loader (_load_event)
    participant H as Chat Event Handler

    C->>E: conversation_chat_cancel()
    E->>L: Enqueue ConversationChatCancelEvent
    L->>H: Identify "conversation.chat.canceled" event
    H->>H: on_conversation_chat_canceled(cli, event)
Loading

Poem

I'm a little rabbit, hopping by your code,
New chat cancel events now brightens our road!
Sync and async, our messages flow,
With deliberate steps, cancellations now show.
In fields of events, I twitch with delight,
Hoppy updates keep our code ever so light!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 531bf6e and 0e337c3.

📒 Files selected for processing (1)
  • cozepy/websockets/chat/__init__.py (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cozepy/websockets/chat/init.py

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
examples/websockets_chat.py (1)

19-19: Unused import detected.

The ConversationChatCancelEvent is imported but not used in this file. Consider removing it if not needed for future implementations.

-from cozepy import (
-    COZE_CN_BASE_URL,
-    AsyncCoze,
-    AsyncWebsocketsChatClient,
-    AsyncWebsocketsChatEventHandler,
-    AudioFormat,
-    ConversationAudioDeltaEvent,
-    ConversationChatCompletedEvent,
-    ConversationChatCanceledEvent,
-    ConversationChatCreatedEvent,
-    ConversationChatRequiresActionEvent,
-    ConversationChatSubmitToolOutputsEvent,
-    ConversationChatCancelEvent,
-    ConversationMessageDeltaEvent,
+from cozepy import (
+    COZE_CN_BASE_URL,
+    AsyncCoze,
+    AsyncWebsocketsChatClient,
+    AsyncWebsocketsChatEventHandler,
+    AudioFormat,
+    ConversationAudioDeltaEvent,
+    ConversationChatCompletedEvent,
+    ConversationChatCanceledEvent,
+    ConversationChatCreatedEvent,
+    ConversationChatRequiresActionEvent,
+    ConversationChatSubmitToolOutputsEvent,
+    ConversationMessageDeltaEvent,
🧰 Tools
🪛 Ruff (0.8.2)

19-19: cozepy.ConversationChatCancelEvent imported but unused

Remove unused import: cozepy.ConversationChatCancelEvent

(F401)

examples/websockets_chat_realtime_gui.py (1)

299-306: Handler for chat cancellation implemented with proper error handling.

The handler follows the established pattern in the class with appropriate error handling to ensure the application remains stable even if an error occurs during event processing.

Consider adding a more descriptive message or updating the UI to reflect the canceled state, especially since this is a GUI application. For example:

async def on_conversation_chat_canceled(
    self, cli: AsyncWebsocketsChatClient, event: ConversationChatCanceledEvent
):
    try:
        print("打断")
+       # Update GUI to show chat was canceled
+       self.gui.status_label.config(text="对话已打断")
+       self.gui.update_chat_display("对话已被打断", is_user=False)
+       # Reset recording state
+       self.gui.root.after(1000, self.gui.resume_recording)
    except Exception as e:
        print(f"对话打断错误: {e}")
cozepy/websockets/chat/__init__.py (2)

216-216: Consider adding CONVERSATION_CHAT_CANCELED to wait_events

The current implementation only waits for CONVERSATION_CHAT_COMPLETED events. Since you're adding support for cancellation, you might want to also wait for CONVERSATION_CHAT_CANCELED events to ensure the client doesn't block indefinitely when a chat is canceled instead of completed.

-            wait_events=[WebsocketsEventType.CONVERSATION_CHAT_COMPLETED],
+            wait_events=[WebsocketsEventType.CONVERSATION_CHAT_COMPLETED, WebsocketsEventType.CONVERSATION_CHAT_CANCELED],

467-467: Consider adding CONVERSATION_CHAT_CANCELED to async wait_events

Similar to the sync client, the async client only waits for CONVERSATION_CHAT_COMPLETED events. Since you're adding support for cancellation, you might want to also wait for CONVERSATION_CHAT_CANCELED events here as well.

-            wait_events=[WebsocketsEventType.CONVERSATION_CHAT_COMPLETED],
+            wait_events=[WebsocketsEventType.CONVERSATION_CHAT_COMPLETED, WebsocketsEventType.CONVERSATION_CHAT_CANCELED],
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61c83d3 and e16ba1f.

📒 Files selected for processing (5)
  • cozepy/__init__.py (2 hunks)
  • cozepy/websockets/chat/__init__.py (8 hunks)
  • cozepy/websockets/ws.py (2 hunks)
  • examples/websockets_chat.py (2 hunks)
  • examples/websockets_chat_realtime_gui.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
examples/websockets_chat.py

19-19: cozepy.ConversationChatCancelEvent imported but unused

Remove unused import: cozepy.ConversationChatCancelEvent

(F401)

🔇 Additional comments (15)
cozepy/websockets/ws.py (2)

94-94: New event type for chat cancellation added correctly.

This new enum value CONVERSATION_CHAT_CANCEL appropriately defines the event type for canceling a chat conversation with a descriptive comment.


108-108: New event type for chat canceled notification added correctly.

This new enum value CONVERSATION_CHAT_CANCELED properly defines the event type that notifies when a chat has been canceled with a descriptive comment.

examples/websockets_chat.py (2)

15-15: Event import added correctly.

The ConversationChatCanceledEvent import is correctly added to support the new event handler implementation.


118-122: Event handler for chat cancellation implemented correctly.

The handler follows the established pattern in the class, taking the client and event as parameters and logging an appropriate message when a chat is canceled.

cozepy/__init__.py (4)

128-128: New event class properly exposed in module imports.

The ConversationChatCanceledEvent is correctly added to the module imports, maintaining alphabetical ordering.


132-132: New event class properly exposed in module imports.

The ConversationChatCancelEvent is correctly added to the module imports.


262-262: Export properly added to __all__ list.

The ConversationChatCancelEvent is correctly added to the __all__ list, making it part of the public API.


269-269: Export properly added to __all__ list.

The ConversationChatCanceledEvent is correctly added to the __all__ list, making it part of the public API.

examples/websockets_chat_realtime_gui.py (1)

22-22: Event import properly added.

The ConversationChatCanceledEvent import is correctly added to support the new handler implementation.

cozepy/websockets/chat/__init__.py (6)

57-59: Correctly implemented ConversationChatCancelEvent

The new class for the cancel event follows the existing pattern for websocket events, correctly extending WebsocketsEvent with the appropriate event type.


126-128: Correctly implemented ConversationChatCanceledEvent

The new class for the canceled event follows the existing pattern for websocket events, correctly extending WebsocketsEvent with the appropriate event type.


225-227: Correctly implemented conversation_chat_cancel method

The implementation follows the existing pattern for enqueueing events to the input queue.


476-478: Correctly implemented async conversation_chat_cancel method

The async implementation follows the existing pattern for enqueueing events to the input queue.


581-587: Correctly implemented _load_event handler for CONVERSATION_CHAT_CANCELED

The handling of the canceled event in the async client is correctly implemented, properly checking for the right event type and returning the appropriate event object.


57-128:

❓ Verification inconclusive

Verify if the canceled event should include a data field

Many other completed/finished events in this file include a data field (like ConversationChatCompletedEvent includes Chat data). Consider whether ConversationChatCanceledEvent should also include data about the canceled chat to maintain consistency.

Compare with other similar events:


🏁 Script executed:

#!/bin/bash
# Find patterns in other *CompletedEvent and *CanceledEvent classes to check for data field patterns
echo "Checking for data fields in other event classes:"
rg -A 3 'class \w+(?:Completed|Canceled|Created)Event' --no-filename | rg -A 2 'event_type'

Length of output: 1284


Action: Verify Consistency of Data Field in Canceled Event

After reviewing the codebase:

  • Similar conversation chat events like ConversationChatCreatedEvent, ConversationChatCompletedEvent, and ConversationChatRequiresActionEvent all include a data: Chat field.
  • The ConversationChatCanceledEvent currently only specifies the event_type without any accompanying data.

Please verify whether the omission of the data field in the canceled event is intentional. If consistency is desired, consider adding the appropriate data: Chat field to this event.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e16ba1f and 6d6d181.

📒 Files selected for processing (1)
  • cozepy/__init__.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
cozepy/__init__.py

130-130: Redefinition of unused ConversationChatCanceledEvent from line 127

Remove definition: ConversationChatCanceledEvent

(F811)


134-134: Redefinition of unused ConversationChatCancelEvent from line 128

Remove definition: ConversationChatCancelEvent

(F811)

🔇 Additional comments (2)
cozepy/__init__.py (2)

127-128: Imported new chat cancellation event classes.

The addition of these two new event classes (ConversationChatCanceledEvent and ConversationChatCancelEvent) aligns with the PR objective of implementing support for chat cancellation.


264-265: Added new event classes to the public API.

The event classes ConversationChatCancelEvent and ConversationChatCanceledEvent are correctly added to the __all__ list, making them part of the public API.

This change properly exposes the new event classes to users of the module, allowing them to work with the chat cancellation functionality.

Also applies to: 271-271

@chyroc chyroc added the feature label Mar 4, 2025
@chyroc chyroc changed the title feature for support cancel chat feat: Add WebSocket conversation.chat.cancel support Mar 5, 2025
@chyroc chyroc merged commit fa3ba2e into coze-dev:main Mar 5, 2025
12 checks passed
@mbb1234567890 mbb1234567890 deleted the feature-for-cancel-chat branch March 6, 2025 05:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants