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(GoogleGemini): added api usage with costs #316

Merged
merged 1 commit into from
May 22, 2024
Merged

Conversation

gunpal5
Copy link
Contributor

@gunpal5 gunpal5 commented May 22, 2024

Summary by CodeRabbit

  • New Features

    • Updated to version 1.0.0 of the Google_GenerativeAI package, enhancing overall functionality and capabilities.
    • Enhanced GoogleChatModel with new parameters for context length and token prices, providing more detailed usage and cost calculations.
  • Improvements

    • Simplified JSON serialization in GoogleGeminiExtensions, improving performance and maintainability.
    • Adjusted parameters for various Gemini models to include additional values, ensuring consistency and accuracy.
  • Tests

    • Updated tests to use GeminiProModel and added assertions for InputTokens, OutputTokens, and PriceInUsd for improved test coverage.

Copy link
Contributor

coderabbitai bot commented May 22, 2024

Walkthrough

This update primarily focuses on enhancing the Google Generative AI integration by upgrading the package version and refining various functionalities. Key changes include modifying the GoogleChatModel constructor to accept additional parameters, simplifying JSON serialization in GoogleGeminiExtensions, and updating predefined Gemini models to use new constructor parameters. Additionally, test cases have been improved to include assertions for token usage and pricing.

Changes

File Path Change Summary
src/Directory.Packages.props Updated Google_GenerativeAI package version from 0.1.20 to 1.0.0.
src/Providers/Google/src/Extensions/... Simplified JsonSerializer.Serialize call in GetString extension method.
src/Providers/Google/src/GoogleChatModel.cs Enhanced constructor with additional parameters for context length and token prices; added methods for usage and price calculation.
src/Providers/Google/src/Predefined/... Updated parameters for GoogleChatModel constructors in various Gemini models.
src/Providers/Google/test/Tests.cs Imported GeminiProModel and added assertions for InputTokens, OutputTokens, and PriceInUsd.

🌟 In fields of code where changes bloom,
A rabbit hops, dispelling gloom.
With updates fresh, the models grow,
New versions set to steal the show.
Tokens counted, prices told,
In every line, the future bold.
🐇✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@HavenDV HavenDV enabled auto-merge (squash) May 22, 2024 13:04
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: 3

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 520a8c8 and 40f8aa9.
Files selected for processing (5)
  • src/Directory.Packages.props (1 hunks)
  • src/Providers/Google/src/Extensions/GoogleGeminiExtensions.cs (1 hunks)
  • src/Providers/Google/src/GoogleChatModel.cs (5 hunks)
  • src/Providers/Google/src/Predefined/GeminiModels.cs (1 hunks)
  • src/Providers/Google/test/Tests.cs (3 hunks)
Files skipped from review due to trivial changes (2)
  • src/Directory.Packages.props
  • src/Providers/Google/src/Extensions/GoogleGeminiExtensions.cs
Additional comments not posted (5)
src/Providers/Google/src/Predefined/GeminiModels.cs (3)

21-21: Constructor now correctly includes parameters for token pricing and context length, aligning with new features.


27-27: Constructor now correctly includes parameters for token pricing and context length, aligning with new features.


15-15: Constructor now correctly includes parameters for token pricing and context length, aligning with new features.

src/Providers/Google/src/GoogleChatModel.cs (2)

213-228: The GetUsage method now correctly calculates usage based on the new token pricing parameters, aligning with new features.

Verification successful

The rg command output shows multiple instances of the GetUsage method across different files and models. To ensure the correct usage of the new parameters, we need to focus on the instances within GoogleChatModel.cs.


The instances of GetUsage in GoogleChatModel.cs show that the method is being used correctly with the new parameters. The GetUsage method is called, and the resulting Usage object is modified with additional properties like Time before being added to the usage tracking.

  • GetUsage is called with response and the resulting Usage object is modified with Time = watch.Elapsed.
  • The modified Usage object is then added to the usage tracking via AddUsage(usage2) and provider.AddUsage(usage2).

This confirms that the integration of the GetUsage method with other components is correct and aligns with the new token pricing parameters.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify integration of `GetUsage` method with other components.

# Test: Search for the usage of `GetUsage` method. Expect: Correct usage of new parameters.
rg --type csharp $'GetUsage'

Length of output: 1608



Script:

#!/bin/bash
# Description: Review instances of `GetUsage` in `GoogleChatModel.cs` to verify correct usage of new parameters.

# Extract lines around the usage of `GetUsage` in `GoogleChatModel.cs`
rg --type csharp --context 5 'GetUsage' src/Providers/Google/src/GoogleChatModel.cs

Length of output: 1261


230-243: The CalculatePriceInUsd method now includes logic for calculating prices based on the new token pricing parameters, aligning with new features.

Verification successful

The CalculatePriceInUsd method is correctly integrated with the new parameters across different files.

  • OpenAiChatModel.cs: The method is called with outputTokens and inputTokens parameters.
  • GoogleChatModel.cs: The method is called with outputTokens and inputTokens parameters.
  • ApiHelpers.cs: The method is implemented with a different signature but is used correctly.
  • AnthropicModel.cs: The method is called with outputTokens and inputTokens parameters.
  • IPaidLargeLanguageModel.cs: The method is declared with the correct parameters.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify integration of `CalculatePriceInUsd` method with other components.

# Test: Search for the usage of `CalculatePriceInUsd` method. Expect: Correct usage of new parameters.
rg --type csharp $'CalculatePriceInUsd'

Length of output: 1098



Script:

#!/bin/bash
# Extract the context of `CalculatePriceInUsd` usage in OpenAiChatModel.cs
rg --context 5 'CalculatePriceInUsd' src/Providers/OpenAI/src/Chat/OpenAiChatModel.cs

# Extract the context of `CalculatePriceInUsd` usage in GoogleChatModel.cs
rg --context 5 'CalculatePriceInUsd' src/Providers/Google/src/GoogleChatModel.cs

# Extract the context of `CalculatePriceInUsd` usage in ApiHelpers.cs
rg --context 5 'CalculatePriceInUsd' src/Providers/Anthropic/libs/Anthropic/Helpers/ApiHelpers.cs

# Extract the context of `CalculatePriceInUsd` usage in AnthropicModel.cs
rg --context 5 'CalculatePriceInUsd' src/Providers/Anthropic/libs/Anthropic/AnthropicModel.cs

# Extract the context of `CalculatePriceInUsd` usage in IPaidLargeLanguageModel.cs
rg --context 5 'CalculatePriceInUsd' src/Providers/Abstractions/src/Chat/IPaidLargeLanguageModel.cs

Length of output: 3316

@@ -6,10 +6,22 @@ namespace LangChain.Providers.Google.Predefined;
public class GeminiProModel(GoogleProvider provider)
: GoogleChatModel(
provider,
GoogleAIModels.GeminiPro);
GoogleAIModels.GeminiPro, 32 * 1024, 0.5 * 0.000001, 1.5 * 0.000001);
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The GeminiProModel constructor calls in GenerativeModelTests.cs and Tests.cs do not include the new parameters for token pricing and context length. Please update these test files to reflect the changes in the constructor.

  • src/Providers/Google/test/GenerativeModelTests.cs
  • src/Providers/Google/test/Tests.cs
Analysis chain

Constructor now correctly includes parameters for token pricing and context length, aligning with new features.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify integration of `GeminiProModel` with other components.

# Test: Search for the usage of `GeminiProModel` constructor. Expect: Correct usage of new parameters.
rg --type csharp $'new GeminiProModel'

Length of output: 252



Script:

#!/bin/bash
# Extract lines around the usage of `GeminiProModel` constructor in `GenerativeModelTests.cs`
rg --context 5 'new GeminiProModel' src/Providers/Google/test/GenerativeModelTests.cs

# Extract lines around the usage of `GeminiProModel` constructor in `Tests.cs`
rg --context 5 'new GeminiProModel' src/Providers/Google/test/Tests.cs

Length of output: 1181

@@ -1,4 +1,5 @@
using GenerativeAI.Models;
using GeminiProModel = LangChain.Providers.Google.Predefined.GeminiProModel;
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The GetWeather method implementations across different providers have been successfully extracted. The Google provider's test method includes the new assertions for token counts and pricing, which aligns with the PR objectives. However, the other providers' test methods do not include these new assertions.

  • Google Provider: The GetWeather method includes assertions for InputTokens and OutputTokens.
  • Other Providers: The GetWeather methods do not include the new assertions for token counts and pricing.

Locations that need attention:

  • src/Providers/TogetherAI/tests/Tests.cs
  • src/Providers/OpenRouter/tests/Tests.cs
  • src/Providers/OpenAI/test/Tests.cs
  • src/Providers/DeepInfra/tests/Tests.cs
  • src/Providers/Anthropic/tests/Tests.cs

These files should be updated to include the new assertions for token counts and pricing in their respective GetWeather methods.

Analysis chain

Updated import and added assertions for token counts and pricing in the GetWeather test method align with the new features.

Also applies to: 17-17, 29-31

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify integration of `GetWeather` test method with other components.

# Test: Search for the usage of `GetWeather` method. Expect: Correct usage of new assertions.
rg --type csharp $'GetWeather'

Length of output: 467



Script:

#!/bin/bash
# Extract the implementation of the `GetWeather` method from each identified file.

# Define the pattern to match the `GetWeather` method.
pattern=$'public async Task GetWeather() { $$$ }'

# Search and extract the `GetWeather` method implementations.
ast-grep --lang csharp --pattern "$pattern" src/Providers/TogetherAI/tests/Tests.cs
ast-grep --lang csharp --pattern "$pattern" src/Providers/OpenRouter/tests/Tests.cs
ast-grep --lang csharp --pattern "$pattern" src/Providers/OpenAI/test/Tests.cs
ast-grep --lang csharp --pattern "$pattern" src/Providers/Google/test/Tests.cs
ast-grep --lang csharp --pattern "$pattern" src/Providers/DeepInfra/tests/Tests.cs
ast-grep --lang csharp --pattern "$pattern" src/Providers/Anthropic/tests/Tests.cs

Length of output: 734



Script:

#!/bin/bash
# Extract the implementation of the `GetWeather` method from each identified file.

# Define a more flexible pattern to match the `GetWeather` method.
pattern=$'public async Task GetWeather() { $$$ }'

# Search and extract the `GetWeather` method implementations.
ast-grep --lang csharp --pattern 'public async Task GetWeather() { $$$ }' src/Providers/TogetherAI/tests/Tests.cs
ast-grep --lang csharp --pattern 'public async Task GetWeather() { $$$ }' src/Providers/OpenRouter/tests/Tests.cs
ast-grep --lang csharp --pattern 'public async Task GetWeather() { $$$ }' src/Providers/OpenAI/test/Tests.cs
ast-grep --lang csharp --pattern 'public async Task GetWeather() { $$$ }' src/Providers/Google/test/Tests.cs
ast-grep --lang csharp --pattern 'public async Task GetWeather() { $$$ }' src/Providers/DeepInfra/tests/Tests.cs
ast-grep --lang csharp --pattern 'public async Task GetWeather() { $$$ }' src/Providers/Anthropic/tests/Tests.cs

Length of output: 734



Script:

#!/bin/bash
# Extract the implementation of the `GetWeather` method from each identified file using a more general approach.

# Search for the `GetWeather` method and extract surrounding lines.
rg 'public async Task GetWeather' -A 20 src/Providers/TogetherAI/tests/Tests.cs
rg 'public async Task GetWeather' -A 20 src/Providers/OpenRouter/tests/Tests.cs
rg 'public async Task GetWeather' -A 20 src/Providers/OpenAI/test/Tests.cs
rg 'public async Task GetWeather' -A 20 src/Providers/Google/test/Tests.cs
rg 'public async Task GetWeather' -A 20 src/Providers/DeepInfra/tests/Tests.cs
rg 'public async Task GetWeather' -A 20 src/Providers/Anthropic/tests/Tests.cs

Length of output: 5376

Comment on lines +12 to +17
string id,
int contextLength = 0,
double inputTokenPriceUsd = 0,
double outputTokenPriceUsd = 0,
double secondaryInputTokenPrice = 0,
double secondaryOutputTokenPrice = 0)
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Constructor calls in src/Providers/Google/test/Tests.cs do not include the new parameters for token pricing and context length. Please update the test cases to reflect the changes in the GoogleChatModel constructor.

  • src/Providers/Google/test/Tests.cs: Lines where new GoogleChatModel is called.
Analysis chain

Constructor now correctly includes parameters for token pricing and context length, aligning with new features.

Also applies to: 23-23

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify integration of `GoogleChatModel` constructor with other components.

# Test: Search for the usage of `GoogleChatModel` constructor. Expect: Correct usage of new parameters.
rg --type csharp $'new GoogleChatModel'

Length of output: 270



Script:

#!/bin/bash
# Extract and review the relevant lines from `src/Providers/Google/test/Tests.cs` to verify the usage of new parameters in `GoogleChatModel` constructor.

# Display lines around the constructor usage to check parameter usage.
rg --type csharp --context 5 'new GoogleChatModel' src/Providers/Google/test/Tests.cs

Length of output: 1163

Copy link
Contributor

sweep-ai bot commented May 22, 2024

Sweep: PR Review

Authors of pull request: @gunpal5

src/Directory.Packages.props

Updated the version of the "Google_GenerativeAI" package from "0.1.20" to "1.0.0".

Sweep Found These Issues

  • Updating the "Google_GenerativeAI" package to version "1.0.0" may introduce breaking changes or incompatibilities with existing code that relies on version "0.1.20".
  • <PackageVersion Include="Google_GenerativeAI" Version="1.0.0" />

    View Diff


src/Providers/Google/src/Extensions/GoogleGeminiExtensions.cs

Removed the custom serialization context for the arguments dictionary in the GetString method, defaulting to the standard JsonSerializer settings.

Sweep Found These Issues


src/Providers/Google/src/GoogleChatModel.cs

Added configurable parameters to the GoogleChatModel constructor, introduced methods for calculating usage and price, and ensured consistent recording of usage metrics.

Sweep Found These Issues

  • The CalculatePriceInUsd method does not handle cases where inputTokenPriceUsd or outputTokenPriceUsd are zero, which could lead to incorrect pricing calculations.
  • public double CalculatePriceInUsd(int inputTokens, int outputTokens)
    {
    if (inputTokens < 128 * 1024)
    {
    var inputCost = inputTokenPriceUsd * inputTokens;
    var outputCost = outputTokenPriceUsd * outputTokens;
    return inputCost + outputCost;
    }
    else
    {
    var inputCost = secondaryInputTokenPrice * inputTokens;
    var outputCost = secondaryOutputTokenPrice * outputTokens;
    return inputCost + outputCost;

    View Diff

  • Sweep has identified a redundant function: The new function is redundant because its functionality is already covered by the existing GetUsage methods in OpenAiChatModel and AnthropicModel.
  • private Usage GetUsage(EnhancedGenerateContentResponse response)
    {
    var outputTokens = response.UsageMetadata?.CandidatesTokenCount ?? 0;
    var inputTokens = response.UsageMetadata?.PromptTokenCount ?? 0;
    var priceInUsd = CalculatePriceInUsd(
    outputTokens: outputTokens,
    inputTokens: inputTokens);
    return Usage.Empty with
    {
    InputTokens = inputTokens,
    OutputTokens = outputTokens,
    Messages = 1,
    PriceInUsd = priceInUsd,
    };

    View Diff

  • Sweep has identified a redundant function: The new function is redundant because its purpose and functionality are already covered by the existing CalculatePriceInUsd methods in OpenAiChatModel and AnthropicModel.
  • public double CalculatePriceInUsd(int inputTokens, int outputTokens)
    {
    if (inputTokens < 128 * 1024)
    {
    var inputCost = inputTokenPriceUsd * inputTokens;
    var outputCost = outputTokenPriceUsd * outputTokens;
    return inputCost + outputCost;
    }
    else
    {
    var inputCost = secondaryInputTokenPrice * inputTokens;
    var outputCost = secondaryOutputTokenPrice * outputTokens;
    return inputCost + outputCost;

    View Diff

Potential Issues

Sweep isn't 100% sure if the following are issues or not but they may be worth taking a look at.

  • The CalculatePriceInUsd method does not handle cases where inputTokenPriceUsd, outputTokenPriceUsd, secondaryInputTokenPrice, or secondaryOutputTokenPrice are zero or negative, which could lead to incorrect price calculations.
  • public double CalculatePriceInUsd(int inputTokens, int outputTokens)
    {
    if (inputTokens < 128 * 1024)
    {
    var inputCost = inputTokenPriceUsd * inputTokens;
    var outputCost = outputTokenPriceUsd * outputTokens;
    return inputCost + outputCost;
    }
    else
    {
    var inputCost = secondaryInputTokenPrice * inputTokens;
    var outputCost = secondaryOutputTokenPrice * outputTokens;
    return inputCost + outputCost;
    }

    View Diff


src/Providers/Google/src/Predefined/GeminiModels.cs

Added new parameters to existing model constructors and introduced two new model classes with specific configurations.

Sweep Found These Issues

  • The Gemini15ProModel class incorrectly uses GoogleAIModels.Gemini15Flash instead of GoogleAIModels.Gemini15Pro.
  • public class Gemini15ProModel(GoogleProvider provider)
    : GoogleChatModel(
    provider,
    GoogleAIModels.Gemini15Flash, 2 * 1024 * 1024, 3.5 * 0.000001, 10.50 * 0.000001, 7.0 * 0.000001, 21.00 * 0.000001);

    View Diff

  • Sweep has identified a redundant function: The new function Gemini15FlashModel is redundant as it performs similar tasks to existing functions like GeminiProModel and GeminiProVisionModel but with different parameters.
  • /// <inheritdoc cref="GoogleAIModels.GeminiProVision" />
    public class Gemini15FlashModel(GoogleProvider provider)
    : GoogleChatModel(
    provider,
    GoogleAIModels.Gemini15Flash, 1024 * 1024, 0.35 * 0.000001, 1.05 * 0.000001, 0.70 * 0.000001, 2.1 * 0.000001);

    View Diff


src/Providers/Google/test/Tests.cs

Replaced GoogleChatModel with GeminiProModel in the GetWeather test and added assertions for input tokens, output tokens, and price in USD.

Potential Issues

Sweep isn't 100% sure if the following are issues or not but they may be worth taking a look at.

  • Commenting out the second parameter GoogleAIModels.GeminiPro in the instantiation of GeminiProModel might affect its behavior if the constructor relies on that parameter.
  • var model = new GeminiProModel(apiKey);//, GoogleAIModels.GeminiPro);

    View Diff


@HavenDV HavenDV disabled auto-merge May 22, 2024 13:14
@HavenDV HavenDV merged commit efc68b7 into tryAGI:main May 22, 2024
2 of 3 checks passed
@HavenDV
Copy link
Contributor

HavenDV commented May 22, 2024

image
I think need to replace Flash to Pro inside

vikhyat90 pushed a commit to vikhyat90/LangChain that referenced this pull request May 30, 2024
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.

2 participants