Skip to content

Conversation

chyroc
Copy link
Contributor

@chyroc chyroc commented Aug 5, 2025

Summary

This PR adds usage field support to all workflow interfaces in the Java SDK, aligning with the Python and Go SDK implementations and the official API documentation.

Changes

  • Workflow Run Interface: Added field to and classes
  • Workflow Stream Interface: Added field to class
  • Workflow History Interface: Added field to class
  • Tests: Updated test cases to verify usage field functionality with proper assertions

Usage Field Details

The usage field provides token consumption information with the following structure:

  • : Total tokens used in the workflow execution
  • : Tokens used for input processing
  • : Tokens used for output generation

API Alignment

This implementation follows the same pattern as the existing class and aligns with:

  • Python SDK implementation patterns
  • Go SDK implementation patterns
  • Official Coze API documentation for workflow endpoints

Testing

  • All existing tests continue to pass
  • New test cases verify usage field presence and values
  • Streaming tests include usage field validation
  • History tests verify usage field in workflow run records

Backward Compatibility

The usage field is optional and won't break existing implementations. Users can access usage information when available from the API responses.

Copy link

coderabbitai bot commented Aug 5, 2025

Walkthrough

This update introduces a new usage field of type ChatUsage to several workflow-related response and event classes in the API, enabling tracking of token usage metrics. Corresponding test classes are updated to validate this new field. Additionally, version numbers are incremented in Maven POM files, and .gitignore rules are expanded.

Changes

Cohort / File(s) Change Summary
Git Ignore Updates
.gitignore
Added .serena/ directory and CLAUDE.md file to the ignore list.
Maven Version Bump
api/pom.xml, example/pom.xml
Updated coze-api artifact version from 0.4.1 to 0.4.2.
API Usage Field Additions
api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowResp.java,
api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventMessage.java,
api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunHistory.java,
api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunResult.java
Added private ChatUsage usage field (with @JsonProperty("usage")) for token usage tracking.
Test Enhancements for Usage
api/src/test/java/com/coze/openapi/service/service/workflow/WorkFlowRunServiceTest.java,
api/src/test/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryServiceTest.java
Updated tests to create, inject, and assert the new usage field and its token/input/output counts.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant WorkflowService

    Client->>API: Run workflow request
    API->>WorkflowService: Execute workflow
    WorkflowService-->>API: Workflow result + usage (token counts)
    API-->>Client: Response (includes usage)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

In the meadow of code where the workflows run,
A new field named usage now tracks every one.
Tokens are counted, input and out,
With tests that assert it, removing all doubt.
The version hops forward, the git stays neat—
Another fine patch, so review is a treat! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/workflow-usage-field

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests 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.

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.

@chyroc chyroc added the feature label Aug 5, 2025
@chyroc chyroc force-pushed the feat/workflow-usage-field branch 4 times, most recently from 0f0603c to 561fd33 Compare August 5, 2025 15:16
- Add usage field to workflow run interface (RunWorkflowResp, WorkflowRunResult)
- Add usage field to workflow stream_run interface (WorkflowEventMessage)
- Add usage field to workflow get history interface (WorkflowRunHistory)
- Update test cases to verify usage field functionality
- Follow same pattern as existing ChatUsage class
- Align with Python and Go SDK implementations

Usage field provides token consumption information:
- token_count: Total tokens used
- input_count: Tokens used for input
- output_count: Tokens used for output

Fixes: Support for usage field in workflow APIs as per API documentation
@chyroc chyroc force-pushed the feat/workflow-usage-field branch from 561fd33 to 5cb2fa5 Compare August 5, 2025 15:17
@chyroc chyroc requested a review from hanzeINGH August 5, 2025 15:24
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 (6)
.gitignore (1)

44-46: Nit: Capitalize the section header for consistency

Other comment headers in the file use capitalized words (e.g., # Log file). To keep the style uniform, consider capitalizing this header as well.

-# ai
+# AI artifacts
api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunHistory.java (2)

3-3: Import ordering

ChatUsage import is grouped with other third-party imports but precedes com.fasterxml.*. Adopt the existing ordering (Jackson first, then project classes) to keep import style consistent.


91-94: Consider null-handling & serialization hints for usage

usage is optional per the PR description, but the model doesn’t currently advertise that:

+@JsonInclude(JsonInclude.Include.NON_NULL)
+private ChatUsage usage;

Adding @JsonInclude (and optionally annotating with @Nullable) avoids emitting an empty object and clarifies intent to consumers.

api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowResp.java (2)

3-3: Unused wildcard imports

Only ChatUsage is required from com.coze.openapi.client.chat.model; confirm there isn’t an IntelliJ wildcard rule creeping in elsewhere.


41-44: Redundant token-metrics fields

RunWorkflowResp now exposes both legacy token/cost fields and the richer usage structure. Flag one of the following to avoid future confusion:

  1. Mark token/cost as @Deprecated, or
  2. Remove them in the next breaking release and rely solely on usage.

Clear deprecation messaging will steer clients toward the preferred field.

api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventMessage.java (1)

5-5: Import ordering

Same minor ordering nit as above—keep Jackson imports together for consistency.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 03314ae and a293959.

📒 Files selected for processing (9)
  • .gitignore (1 hunks)
  • api/pom.xml (1 hunks)
  • api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowResp.java (2 hunks)
  • api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventMessage.java (2 hunks)
  • api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunHistory.java (2 hunks)
  • api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunResult.java (2 hunks)
  • api/src/test/java/com/coze/openapi/service/service/workflow/WorkFlowRunServiceTest.java (5 hunks)
  • api/src/test/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryServiceTest.java (3 hunks)
  • example/pom.xml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test (Java 17 on Windows)
  • GitHub Check: test (Java 11 on Windows)
  • GitHub Check: Analyze (java-kotlin)
🔇 Additional comments (25)
api/pom.xml (1)

46-46: Cross-module version alignment

Bumping coze-api to 0.4.2 here is correct, but remember to update every internal module (parent POMs, BOM, CI publishing scripts, docs) that declares an explicit 0.4.1 reference; otherwise mixed versions will slip through in multi-module builds.

example/pom.xml (1)

19-19: Dependency version update looks good

The example module now consumes coze-api 0.4.2; no other changes needed.

api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventMessage.java (1)

45-47: Streaming messages: verify partial frames

usage appears on each streamed event. Confirm backend actually populates it on the final frame only; otherwise summing per-frame usage client-side could double-count tokens. If behaviour isn’t guaranteed, document it in Javadoc.

api/src/test/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryServiceTest.java (8)

18-18: LGTM!

Necessary import addition to support the new usage field testing.


48-50: LGTM!

Well-structured test data creation with distinct usage metrics for comprehensive testing. The token count calculations are mathematically consistent.


54-55: LGTM!

Correct assignment of usage objects to WorkflowRunHistory test data using the builder pattern.


79-86: LGTM!

Comprehensive assertions properly validate the usage field presence and values for both history entries. The test coverage is thorough and follows good testing practices.


18-18: LGTM: Import added for ChatUsage support.

The import statement correctly brings in the ChatUsage class needed for the new usage field functionality.


48-50: LGTM: Well-structured test data for usage validation.

The ChatUsage instances are created with distinct values that will help validate the correct assignment and retrieval of usage metrics for different workflow history entries.


54-55: LGTM: Usage field properly integrated into test mock data.

The WorkflowRunHistory builders correctly include the usage field, ensuring the test data reflects the updated model structure.


79-86: LGTM: Comprehensive assertions for usage field validation.

The test assertions thoroughly validate:

  • Non-null usage objects for both history entries
  • Correct token, input, and output counts matching the test data
  • Complete coverage of all usage metrics

This ensures the usage field is properly populated and accessible through the service layer.

api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunResult.java (4)

3-3: LGTM!

Necessary import addition for the ChatUsage class to support the new usage field.


34-36: LGTM!

Well-implemented usage field addition with proper JSON mapping annotation and clear documentation. The implementation is consistent with existing code patterns and maintains backward compatibility.


3-3: LGTM: Import correctly added for ChatUsage.

The import statement properly includes the ChatUsage class needed for the new usage field.


34-36: LGTM: Usage field implementation follows best practices.

The usage field is properly implemented with:

  • Clear documentation explaining its purpose
  • Correct @JsonProperty annotation for JSON mapping
  • Consistent placement and formatting with other fields
  • Optional nature maintaining backward compatibility
api/src/test/java/com/coze/openapi/service/service/workflow/WorkFlowRunServiceTest.java (10)

18-18: LGTM!

Necessary import addition to support usage field testing functionality.


57-57: LGTM!

Appropriate addition of usage metrics to SSE event data with consistent token counts (input + output = total). The JSON structure matches the expected ChatUsage format for testing.


108-112: LGTM!

Comprehensive assertions properly validate usage field parsing from SSE events. The token count validations match the test data and provide thorough coverage for streaming usage functionality.


131-131: LGTM!

Proper test data creation with consistent token counts and builder pattern usage for synchronous workflow testing.


140-140: LGTM!

Correct assignment of usage object to response builder following established patterns.


154-157: LGTM!

Comprehensive assertions properly validate usage field presence and values in synchronous workflow responses. The test coverage is thorough and follows consistent testing patterns.


18-18: LGTM: Import added for ChatUsage test support.

The import statement correctly includes the ChatUsage class needed for testing the new usage field functionality.


57-57: LGTM: Event data enhanced with usage metrics.

The SSE event data string is properly updated to include the usage JSON object with token_count, input_count, and output_count fields, matching the expected API response format for workflow execution metrics.


108-112: LGTM: Comprehensive usage validation in stream parsing test.

The assertions thoroughly validate the usage field in streaming events:

  • Non-null usage object verification
  • Correct token count matching the event data (1230)
  • Proper input and output count parsing (615 each)

This ensures the streaming event parsing correctly handles the new usage metrics.


131-131: LGTM: Complete usage field testing in synchronous workflow execution.

The test properly:

  • Creates ChatUsage mock data with specific values
  • Includes usage in the mock response
  • Validates all usage metrics in the returned response

This ensures the usage field works correctly in synchronous workflow execution scenarios, complementing the streaming test coverage.

Also applies to: 140-140, 154-157

@chyroc chyroc merged commit 064d6bd into main Aug 7, 2025
15 checks passed
@chyroc chyroc deleted the feat/workflow-usage-field branch August 7, 2025 13:47
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.

1 participant