Skip to content

Conversation

@GregoireDaure
Copy link
Contributor

@GregoireDaure GregoireDaure commented Jan 28, 2025

Summary by CodeRabbit

  • New Features

    • Improved usage tracking for Anthropic Claude 3 chat interactions
    • Enhanced metrics collection for token usage during AI chat generation
  • Refactor

    • Updated usage information extraction and recording process
    • Added new method to handle usage data parsing

Introduce a `usage` variable to track usage information throughout the `AnthropicClaude3ChatModel` class. Add a `GetUsage` method to extract usage data from JSON nodes. Initialize `usage` to `null` and update it with data from JSON responses, ensuring it is non-null before use with a fallback to `Usage.Empty`. Update `usage` incrementally in streaming responses and include it in `ChatResponse`, passing it to `AddUsage` and `provider.AddUsage` methods. Remove `CONTENT_BLOCK_STOP` type handling from streaming response processing.
Modified the assignment of the `usage` variable to use `GetUsage(response?["usage"])` instead of `GetUsage(response)`. This change ensures that the `usage` variable is assigned from the "usage" field of the `response` object, if it exists, preventing potential null reference exceptions.
@CLAassistant
Copy link

CLAassistant commented Jan 28, 2025

CLA assistant check
All committers have signed the CLA.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 28, 2025

Walkthrough

The changes focus on improving usage tracking in the AnthropicClaude3ChatModel class for the Anthropic Claude 3 chat model. A new approach has been implemented to capture and manage usage metrics during both streaming and non-streaming API responses. The modifications include introducing a usage variable, updating the handling of response chunks, and adding a new private method GetUsage to extract token and usage information from JSON responses.

Changes

File Change Summary
src/Amazon.Bedrock/src/Chat/AnthropicClaude3ChatModel.cs - Added usage variable for tracking API usage metrics
- Modified streaming response handling to update usage
- Added new private GetUsage method to extract usage information
- Updated AddUsage method calls to use new usage tracking

Poem

🐰 In the realm of Claude's chat delight,
Usage metrics now shine so bright
Tokens counted, metrics clear
A rabbit's code brings knowledge near!
Tracking wisdom, line by line 🤖


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.

Copy link
Contributor

@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: 2

🧹 Nitpick comments (2)
src/Amazon.Bedrock/src/Chat/AnthropicClaude3ChatModel.cs (2)

98-105: Consider combining usage initialization and property updates.

The current implementation has multiple assignments to usage. Consider combining them for better readability.

-usage ??= Usage.Empty;
-usage = usage.Value with
-{
-    Time = watch.Elapsed,
-    Messages = messages.Count,
-};
+usage = (usage ?? Usage.Empty) with
+{
+    Time = watch.Elapsed,
+    Messages = messages.Count,
+};

175-179: Enhance XML documentation with parameter constraints and return value details.

The current documentation could be more descriptive about parameter constraints and return value composition.

 /// <summary>
-/// Extracts usage information from the provided JSON node.
+/// Extracts usage information from the provided JSON node. Returns Usage.Empty with updated token counts if the node is null.
 /// </summary>
 /// <param name="usageNode">The JSON node containing usage information.</param>
+/// <remarks>
+/// The method expects the following JSON structure:
+/// {
+///   "input_tokens": number,
+///   "output_tokens": number
+/// }
+/// </remarks>
 /// <returns>A <see cref="Usage"/> object with the extracted usage data.</returns>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27a9346 and 14408b4.

📒 Files selected for processing (1)
  • src/Amazon.Bedrock/src/Chat/AnthropicClaude3ChatModel.cs (4 hunks)
🔇 Additional comments (2)
src/Amazon.Bedrock/src/Chat/AnthropicClaude3ChatModel.cs (2)

91-91: LGTM!

The usage extraction from non-streaming response is implemented correctly.


180-193: 🛠️ Refactor suggestion

Consider making the method static and implement price calculation.

The method doesn't use any instance members and could be static. Also, the price calculation is currently hardcoded to 0.0.

-private Usage GetUsage(JsonNode? usageNode)
+private static Usage GetUsage(JsonNode? usageNode)
 {
     var inputTokens = usageNode?["input_tokens"]?.GetValue<int>() ?? 0;
     var outputTokens = usageNode?["output_tokens"]?.GetValue<int>() ?? 0;
-    var priceInUsd = 0.0;
+    // TODO: Implement price calculation based on token usage and model pricing
+    var priceInUsd = CalculatePrice(inputTokens, outputTokens);

     return Usage.Empty with
     {
         InputTokens = inputTokens,
         OutputTokens = outputTokens,
         Messages = 0,
         PriceInUsd = priceInUsd,
     };
 }

+private static double CalculatePrice(int inputTokens, int outputTokens)
+{
+    // Implement pricing logic based on Anthropic Claude 3 model rates
+    return 0.0;
+}

Would you like me to help implement the pricing calculation based on the current Anthropic Claude 3 model rates?

✅ Verification successful

The method should be static and price calculation should be implemented

The review comment is correct on both points:

  1. The GetUsage method is purely functional and doesn't use any instance members, making it safe to be static.
  2. Price calculation should be implemented as:
    • It's a standard feature across other models in the codebase
    • Other Anthropic models implement proper price calculation
    • Usage tracking and billing require accurate price calculation
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find usages of GetUsage method in the codebase
echo "=== GetUsage method usages ==="
rg "GetUsage\(" -A 2 -B 2

echo -e "\n=== Price calculation in chat models ==="
# Look for price calculation in other chat models
rg "PriceInUsd|CalculatePrice" --type cs -A 2 -B 2

echo -e "\n=== Pricing constants or utilities ==="
# Search for pricing-related code
rg "price|cost|rate" --type cs -A 2 -B 2

Length of output: 116611

@HavenDV HavenDV merged commit f69fc1a into tryAGI:main Jan 29, 2025
4 checks passed
@GregoireDaure GregoireDaure deleted the feat/bedrock-usage branch January 29, 2025 10:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants