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 generic Stream interface and improve code quality #6

Merged
merged 8 commits into from
Dec 27, 2024

Conversation

hanzeINGH
Copy link
Contributor

@hanzeINGH hanzeINGH commented Dec 27, 2024

  • Implement generic Stream interface for streaming APIs
  • Refactor 'chats' to 'chat' for consistency
  • Integrate gofumpt check into CI pipeline

Change-Id: Ia203ef08f24be23111baa628fcb234c812b50cd1
Copy link

coderabbitai bot commented Dec 27, 2024

Walkthrough

This pull request introduces several significant changes across the Coze Go SDK, primarily focusing on refactoring method and struct names from plural to singular forms (e.g., Chats to Chat), updating response structures, and adding a new generic Stream interface. Additionally, the CI workflow is enhanced with the introduction of gofumpt for code formatting checks. These modifications aim to streamline the SDK's API and improve code consistency.

Changes

File Change Summary
.github/workflows/ci.yml Added steps to install and run gofumpt for code formatting checks
CONTRIBUTING.md Added instructions for checking code format using gofumpt
README.md, Multiple Example Files Updated method calls from cozeCli.Chats to cozeCli.Chat
base_model.go Added new Responser interface
chats.go Renamed chats struct to chat, updated method signatures
client.go Changed Chats field to Chat in CozeAPI struct
stream_reader.go Introduced generic Stream[T] interface
Various Test Files Updated mock response structures to remove unnecessary Data wrappers and align with new API structures

Possibly related PRs

  • refactor: Enhance OAuth-related functions with context and struct params #3: The changes in this PR involve updating method signatures to use structured request objects for OAuth-related functions, which aligns with the main PR's focus on enhancing the CI workflow for Go projects by enforcing code formatting standards, including the use of gofumpt. Both PRs emphasize improving code quality and maintainability through structured approaches.

Poem

🐰 Hop, hop, refactoring we go!
From plural to singular, watch code flow
Streams of changes, clean and bright
Gofumpt checks our syntax tight
A rabbit's dance of clean code might! 🌟


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. (Beta)
  • @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.

Change-Id: Ibc204a0ea18c40f7cc0508ed0527a3cda05acb57
@chyroc chyroc added the feature label Dec 27, 2024
.github/workflows/ci.yml Outdated Show resolved Hide resolved
base_model.go Outdated Show resolved Hide resolved
chats.go Show resolved Hide resolved
Change-Id: I6dd7a13e0f7dc63353ebc16ca164250ea32c2967
@chyroc chyroc changed the title fix: stream interface feat: Add generic Stream interface and improve code quality Dec 27, 2024
Change-Id: Id288bf098cc8999256e806ad474610b04b8a13a3
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 (22)
base_model.go (1)

5-7: Add brief doc comments for clarity.

The new Responser interface is straightforward, but it would be helpful to document its purpose. Consider adding a short comment to explain when and how to implement Response() HTTPResponse.

stream_reader.go (1)

15-19: Great abstraction for a generic stream.

Introducing Stream[T] simplifies handling of chat or workflow events. However, consider adding doc comments summarizing how Responser and Close()/Recv() interplay to help future maintainers.

client.go (2)

10-10: Field rename aligns with the new singular naming convention.
Changing Chats to Chat is coherent with the rest of the refactor.

Consider renaming the type from chat to Chat for complete consistency if that doesn’t conflict with other naming patterns.


80-80: Constructor name mismatch
While the field is now singular, the constructor function remains newChats. For consistency:

- Chat:          newChats(core),
+ Chat:          newChat(core),
examples/chats/chat/main.go (2)

70-70: Ensure thorough error reporting for cancellation failures.
Consider adding more detailed logs or user-facing messages in case cozeCli.Chat.Cancel fails. This will help in diagnosing partial cancellations or other errors in production environments.


110-110: Use context-based timeouts in addition to poll timeouts.
You could further enhance reliability by deriving a context with a timeout (via context.WithTimeout) for CreateAndPoll, ensuring you can gracefully handle cases when operations exceed the poll duration.

examples/auth/pkce_oauth/main.go (1)

70-71: Remove or justify commented-out code.
Leaving commented-out lines (such as printing oauthURL.AuthorizationURL) can clutter the file. If no longer required, consider removing them to keep the code clean.

chats.go (11)

Line range hint 13-25: Ensure consistent naming in request and response structs.
Currently, the method name is Create but the request/response structs retain plural naming (CreateChatsReq, CreateChatsResp). Consider renaming them to align with the new singular convention (CreateChatReq, CreateChatResp) for clarity.


Line range hint 27-47: Timeout logic might benefit from configurable polling interval.
The polling interval is hardcoded to time.Sleep(time.Second). If the chat needs more frequent or less frequent checks, a configurable interval (e.g., pollInterval) would make it more flexible without rewriting this function.


47-47: Consider adding context to the cancellation step.
When cancellation fails, the log message is helpful, but you might also want to return a more descriptive error upstream with relevant context, such as the conversation and chat IDs.


97-104: Constructor naming mismatch.
type chat and the constructor newChats is slightly inconsistent. Consider renaming the constructor to newChat or the struct name to chats for consistency.


Line range hint 161-176: SubmitToolOutputs: Only partial error logging.
If the function returns an error, there is no attempt to log any partial context about the request. Logging might help debugging in production environments.


Line range hint 177-188: Duplicated streaming pattern.
StreamSubmitToolOutputs reuses almost the same streaming logic as Stream. This duplication is fine if it’s minimal, but consider factoring out a shared helper if more streaming functionalities are planned.


212-215: Minor mismatch in naming:
ChatStatusCancelled is assigned the string "canceled" rather than "cancelled". This is purely stylistic but be consistent across the codebase.


Line range hint 330-357: Check for alignment with rename from plural to singular.
CreateChatsReq references “Chats.” If usage is indeed multiple, it’s fine. If it references a single chat, consistent naming might help.


358-365: Ensure doc lines match code changes.
The doc blocks mention “can be viewed in the 'conversation_id' field of the Response” or “chat is.” Confirm these references are accurate after rename from plural to singular.


Line range hint 386-395: Doc references for SubmitToolOutputsChatReq.
Same note about rename from chats to chat.


Line range hint 396-406: Nested responses appear consistent.
createChatsResp wraps Chat *CreateChatsResp. Just note the naming mismatch in “createChatsResp” vs. “CreateChatsResp.”

.github/workflows/ci.yml (1)

37-48: Eliminate trailing spaces detected by lint.
Trailing spaces at line 43 can cause the lint to fail. Remove them to keep the config tidy.

-          gofumpt -l -w . 
+          gofumpt -l -w .
🧰 Tools
🪛 yamllint (1.35.1)

[error] 43-43: trailing spaces

(trailing-spaces)

README.md (3)

Line range hint 103-114: Update request struct name in the example.
The code snippet references coze.CreateChatReq while the actual struct in the code is still named CreateChatsReq. Update the example for consistent naming.


Line range hint 135-156: Display partial completion info.
Printing messages as they come in is correct. You might consider indicating partial completion with a newline or spinner for clarity.


228-228: Example references still mention Chats.
Change “Chats” to “Chat” if you align with the new singular naming.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a81c6dd and 72d8e8c.

📒 Files selected for processing (29)
  • .github/workflows/ci.yml (1 hunks)
  • CONTRIBUTING.md (1 hunks)
  • README.md (4 hunks)
  • audio_rooms_test.go (0 hunks)
  • audio_voices_test.go (0 hunks)
  • base_model.go (1 hunks)
  • bots_test.go (0 hunks)
  • chats.go (22 hunks)
  • chats_messages.go (1 hunks)
  • chats_messages_test.go (0 hunks)
  • chats_test.go (2 hunks)
  • client.go (2 hunks)
  • client_test.go (1 hunks)
  • conversations_messages_test.go (0 hunks)
  • conversations_test.go (0 hunks)
  • datasets_documents_test.go (0 hunks)
  • examples/auth/pkce_oauth/main.go (2 hunks)
  • examples/chats/chat/main.go (5 hunks)
  • examples/chats/chat_with_image/main.go (2 hunks)
  • examples/chats/stream/main.go (2 hunks)
  • examples/chats/submit_tool_output/main.go (3 hunks)
  • examples/client/log/main.go (1 hunks)
  • examples/workflows/runs/stream/main.go (2 hunks)
  • files_test.go (0 hunks)
  • stream_reader.go (2 hunks)
  • workflows_runs.go (1 hunks)
  • workflows_runs_histories_test.go (0 hunks)
  • workflows_runs_test.go (0 hunks)
  • workspaces_test.go (0 hunks)
💤 Files with no reviewable changes (11)
  • workflows_runs_test.go
  • workspaces_test.go
  • audio_voices_test.go
  • workflows_runs_histories_test.go
  • files_test.go
  • conversations_messages_test.go
  • datasets_documents_test.go
  • chats_messages_test.go
  • bots_test.go
  • conversations_test.go
  • audio_rooms_test.go
✅ Files skipped from review due to trivial changes (2)
  • chats_messages.go
  • CONTRIBUTING.md
🧰 Additional context used
🪛 yamllint (1.35.1)
.github/workflows/ci.yml

[error] 43-43: trailing spaces

(trailing-spaces)

🔇 Additional comments (32)
stream_reader.go (1)

84-84: Method rename aligns well with the Responser contract.

Renaming HTTPResponse() to Response() keeps naming consistent with the newly introduced interface. Good job!

examples/chats/chat_with_image/main.go (2)

58-58: Looks consistent with the new singular API naming convention.
Transitioning from Chats.Stream to Chat.Stream appears correct and aligns with the refactoring goal.


84-84: Response method usage is correctly updated.
Switching from HTTPResponse() to Response() is consistent and appears to be working properly.

examples/workflows/runs/stream/main.go (2)

47-47: Signature update to use the new generic stream type.
Switching from a dedicated WorkflowEventReader to the generic coze.Stream[coze.WorkflowEvent] simplifies the interface.


83-83: Correct usage of the renamed response method.
Invoking resp.Response().LogID() is aligned with the new naming convention.

examples/chats/submit_tool_output/main.go (3)

38-38: Method name updated to singular.
Replacing cozeCli.Chats.Stream with cozeCli.Chat.Stream matches the rest of the refactoring.


94-94: Tool output streaming method rename is correct.
Updating to Chat.StreamSubmitToolOutputs is consistent with the singular naming.


118-118: Response method usage confirmed.
Leveraging resp.Response().LogID() aligns with the new singular approach for response handling.

examples/chats/chat/main.go (3)

44-44: Consistent adoption of the singular Chat interface.
The renamed function call cozeCli.Chat.Create is aligned with the singular naming convention and helps maintain consistency across the refactored API.


82-82: Validate missing conversation or chat edge cases.
Before retrieving a chat, you may consider additional validation or error handling for non-existent conversation_id or chat_id, especially in production deployments.


101-101: Singular interface usage in CreateAndPoll is correct.
The usage of cozeCli.Chat.CreateAndPoll is confirmed to be the expected interface. Implementation looks correct.

client_test.go (1)

31-31: Correct field reference to api.Chat.
This test now properly checks the renamed Chat field, aligning with the new singular naming convention in the codebase. Looks good.

examples/auth/pkce_oauth/main.go (1)

82-85: Improved parameter formatting for clarity.
Neatly aligning parameters in oauth.GetAccessToken improves readability and follows consistent code style practices. Implementation looks fine.

chats_test.go (2)

175-175: Updated event name matches singular chat refactor.
Renaming the event to conversation.chat.created keeps it consistent with the singular Chat domain model. This enhances clarity in the streaming protocols.


343-343: Use of conversation.chat.in_progress event is consistent.
Changing to a singular event name mirrors the new interface and keeps the streaming responses uniform.

chats.go (14)

Line range hint 79-93: Streaming logic looks correct.
The code sets up a buffered reader and a parser function without obvious data races, concurrency issues, or missing error checks.


Line range hint 134-145: Potential concurrency concerns if used by multiple goroutines.
If multiple goroutines call Cancel concurrently, ensure that the underlying HTTP client usage is thread-safe (most default HTTP clients in Go are). This function itself appears safe, but consider clarifying concurrency assumptions in code comments if relevant.


Line range hint 146-160: Retrieve function’s partial usage of query parameters.
You are using withHTTPQuery("conversation_id", req.ConversationID). Ensure that calls that rely on other optional parameters also pass them in, if required (or consider a more general approach to constructing query parameters).


189-194: Validated streaming approach.
The streamReader[...] usage is consistent with Stream above. No immediate issues found.


Line range hint 216-241: Event naming is consistent and descriptive.
The enumerated event names properly match typical conversation lifecycle states.


Line range hint 242-278: Struct fields appear logically grouped.
No major issues found. The usage of MetaData, Status, and RequiredAction is intuitive and well-documented.


Line range hint 279-292: Token usage fields are sufficiently descriptive.
They clearly separate total tokens, output tokens, and input tokens.


Line range hint 293-329: Use caution with partially filled ChatSubmitToolOutputs.
Ensure that fields like ToolCalls are validated or defaulted if not provided.


369-376: Doc references for Retrieve are consistent.
No code issues found. The doc references match the new singular usage.


Line range hint 407-417: cancelChatsResp similarly structured.
No immediate issues found. Pay attention to consistent naming across multiple declarations.


Line range hint 418-439: retrieveChatsResp similarly structured.
No immediate issues found.


440-442: Comment references correct struct.
ChatEvent includes Chat *Chat. Looks correct.


Line range hint 443-475: Parsing logic for events is robust.
doParseChatEvent checks event strings and uses JSON to parse data. Seems reliable for typical events.


476-478: ChatPoll struct is a clean approach for poll results.
Storing both Chat and Messages together is clear for consumers.

README.md (1)

Line range hint 117-138: Unify streaming example with code.
The example references CreateChatReq for streaming. Ensure actual usage matches the code, which references CreateChatsReq.

workflows_runs.go (2)

41-54: Stream function updated similarly.
Consistent with other Stream changes. Verify that consumers are prepared for the new interface.


24-37: Method signature updated for Resume.
Refactoring from (*WorkflowEventReader, error) to (Stream[WorkflowEvent], error) is consistent with the new streaming approach. Make sure all call sites are updated.

✅ Verification successful

Let me verify the call sites by checking the actual usage of the Resume method.


All call sites are properly updated to use the new streaming interface

After reviewing both the test file and example implementation, I can confirm that all call sites are correctly using the new streaming interface. Both locations where Resume is called:

  • In workflows_runs_test.go: The test correctly uses the new streaming interface, properly calling Recv() to read events from the stream.
  • In examples/workflows/runs/stream/main.go: The example code correctly handles the returned Stream[WorkflowEvent] interface, passing it to handleEvents which properly uses the streaming methods.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Checking references to the old function signature
rg -A 3 'ResumeRunWorkflowsReq'

Length of output: 1228


Script:

#!/bin/bash
# Check the implementation of test and example files that use Resume
cat workflows_runs_test.go
cat examples/workflows/runs/stream/main.go

Length of output: 9876

examples/chats/stream/main.go Show resolved Hide resolved
examples/chats/stream/main.go Show resolved Hide resolved
examples/client/log/main.go Show resolved Hide resolved
Change-Id: Iab7fb9f9e6e6f1f00db9b79cd974013ed19951d4
Change-Id: I437b4d85ddca253ed07cd4423cfca220e44ce7f1
Change-Id: Iba6d1234571feb170d3eb4e9f0291589ff021be3
Change-Id: If588e099f31d8a2a18a88e2f4c29ce7514750c80
Copy link

codecov bot commented Dec 27, 2024

Codecov Report

Attention: Patch coverage is 94.73684% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
chats.go 95.45% 1 Missing ⚠️
stream_reader.go 0.00% 1 Missing ⚠️
Files with missing lines Coverage Δ
base_model.go 72.41% <ø> (ø)
chats_messages.go 100.00% <ø> (ø)
client.go 100.00% <100.00%> (ø)
workflows_runs.go 77.77% <100.00%> (-0.64%) ⬇️
chats.go 73.18% <95.45%> (-0.59%) ⬇️
stream_reader.go 55.00% <0.00%> (+6.11%) ⬆️

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: 0

🧹 Nitpick comments (1)
.github/workflows/ci.yml (1)

27-28: Combine dependency installation steps and fix formatting

The installation steps should be combined for better efficiency, and trailing spaces should be removed.

Apply this diff:

      - name: Install dependencies
-        run: go mod download
-          
-             go install mvdan.cc/gofumpt@v0.5.0
+        run: |
+          go mod download
+          go install mvdan.cc/gofumpt@v0.5.0
🧰 Tools
🪛 yamllint (1.35.1)

[error] 27-27: trailing spaces

(trailing-spaces)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 72d8e8c and b6b930a.

📒 Files selected for processing (2)
  • .github/workflows/ci.yml (2 hunks)
  • examples/auth/pkce_oauth/main.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/auth/pkce_oauth/main.go
🧰 Additional context used
🪛 yamllint (1.35.1)
.github/workflows/ci.yml

[error] 27-27: trailing spaces

(trailing-spaces)

🔇 Additional comments (2)
.github/workflows/ci.yml (2)

40-45: LGTM! Well-implemented formatting check

The gofumpt check implementation is robust:

  • Uses appropriate flags for diff and error reporting
  • Provides clear error messaging
  • Ensures output visibility through tee
  • Positioned appropriately in the workflow sequence

Line range hint 13-13: Verify Go version compatibility

Please verify that Go 1.23 is officially released and supported. If not, consider removing it from the version matrix until it's officially released.

🧰 Tools
🪛 actionlint (1.7.4)

31-31: the runner of "golangci/golangci-lint-action@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

🪛 yamllint (1.35.1)

[error] 24-24: trailing spaces

(trailing-spaces)


[error] 27-27: trailing spaces

(trailing-spaces)


[error] 29-29: trailing spaces

(trailing-spaces)

@chyroc chyroc merged commit 2e13d81 into coze-dev:main Dec 27, 2024
11 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Dec 27, 2024
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