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

add Google VertexAI provider chat #377

Merged
merged 1 commit into from
Jul 14, 2024

Conversation

danijerez
Copy link
Contributor

@danijerez danijerez commented Jul 14, 2024

Summary by CodeRabbit

  • New Features

    • Introduced Google Vertex AI integration with new models: Gemini15ProModel, Gemini15FlashModel, and Gemini1ProModel.
    • Added configuration capabilities for Google Vertex AI.
    • Implemented asynchronous chat generation using Google Cloud AI services.
  • Tests

    • Added new test project for Google Vertex AI provider functionality.
    • Introduced tests for chat generation using predefined models.

@danijerez danijerez requested a review from HavenDV July 14, 2024 22:25
Copy link
Contributor

coderabbitai bot commented Jul 14, 2024

Walkthrough

The recent updates introduce Google Vertex AI support to the LangChain solution. This includes adding new projects for Google Vertex AI provider, implementing VertexAIChatModel, and configuring project dependencies. The changes enable seamless interaction with Google Cloud AI services and ensure comprehensive testing for this integration.

Changes

Files/Paths Change Summary
LangChain.sln Added projects for VertexAI and LangChain.Providers.Google.VertexAI, with updated configurations.
src/Directory.Packages.props Added package version entry for Google.Cloud.AIPlatform.V1 (version 3.4.0).
src/Providers/Google.VertexAI/src/LangChain.Providers.Google.VertexAI.csproj, .../LangChain.Providers.Google.VertexAI.Tests.csproj Introduced project files for Google Vertex AI provider and its tests, targeting netstandard2.0 and net8.0 respectively.
src/Providers/Google.VertexAI/src/.../GeminiModels.cs Introduced classes Gemini15ProModel, Gemini15FlashModel, and Gemini1ProModel extending VertexAIChatModel.
src/Providers/Google.VertexAI/src/VertexAIChatModel.cs Implemented VertexAIChatModel to extend ChatModel and handle chat response generation using Google Cloud AI services.
src/Providers/Google.VertexAI/src/VertexAIConfiguration.cs Added VertexAIConfiguration class with properties for project configuration and generation settings.
src/Providers/Google.VertexAI/src/VertexAIProvider.cs Introduced VertexAIProvider class to initialize and provide access to Google Cloud Vertex AI API.
src/Providers/Google.VertexAI/test/VertexAITest.cs Added VertexAITests class and Chat() method to test interactions with Google Vertex AI services.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LangChain
    participant VertexAIProvider
    participant GoogleCloudAI

    User->>LangChain: Send Chat Request
    LangChain->>VertexAIProvider: Initialize Provider
    VertexAIProvider->>GoogleCloudAI: Request Chat Response
    GoogleCloudAI->>VertexAIProvider: Return Chat Response
    VertexAIProvider-->>LangChain: Forward Chat Response
    LangChain-->>User: Deliver Chat Response
Loading

Poem

In LangChain’s code, new paths unfold,
With Vertex AI, new tales are told.
Models chat with Google’s might,
Conversations now take flight.
Testing done, integrations tight,
In the cloud, we see the light. ✨


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.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @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.

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

Outside diff range, codebase verification and nitpick comments (1)
src/Providers/Google.VertexAI/test/VertexAITest.cs (1)

6-7: Consider removing the [Explicit] attribute.

The [Explicit] attribute is used to mark tests that should not be run as part of the normal test suite. Ensure this is intentional.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 34b1d68 and 2f4fcd2.

Files selected for processing (9)
  • LangChain.sln (3 hunks)
  • src/Directory.Packages.props (1 hunks)
  • src/Providers/Google.VertexAI/src/LangChain.Providers.Google.VertexAI.csproj (1 hunks)
  • src/Providers/Google.VertexAI/src/Predefined/GeminiModels.cs (1 hunks)
  • src/Providers/Google.VertexAI/src/VertexAIChatModel.cs (1 hunks)
  • src/Providers/Google.VertexAI/src/VertexAIConfiguration.cs (1 hunks)
  • src/Providers/Google.VertexAI/src/VertexAIProvider.cs (1 hunks)
  • src/Providers/Google.VertexAI/test/LangChain.Providers.Google.VertexAI.Tests.csproj (1 hunks)
  • src/Providers/Google.VertexAI/test/VertexAITest.cs (1 hunks)
Files skipped from review due to trivial changes (3)
  • src/Directory.Packages.props
  • src/Providers/Google.VertexAI/src/LangChain.Providers.Google.VertexAI.csproj
  • src/Providers/Google.VertexAI/test/LangChain.Providers.Google.VertexAI.Tests.csproj
Additional comments not posted (12)
src/Providers/Google.VertexAI/src/Predefined/GeminiModels.cs (3)

3-4: LGTM!

The class Gemini15ProModel extends VertexAIChatModel and is initialized correctly with the model identifier "gemini-1.5-pro".


6-7: LGTM!

The class Gemini15FlashModel extends VertexAIChatModel and is initialized correctly with the model identifier "gemini-1.5-flash".


9-10: LGTM!

The class Gemini1ProModel extends VertexAIChatModel and is initialized correctly with the model identifier "gemini-1.0-pro".

src/Providers/Google.VertexAI/src/VertexAIConfiguration.cs (1)

5-12: LGTM!

The VertexAIConfiguration class is well-defined with appropriate properties for Location, Publisher, ProjectId, and GenerationConfig.

src/Providers/Google.VertexAI/src/VertexAIProvider.cs (1)

6-17: LGTM!

The VertexAIProvider class is well-defined with properties for Api and Configuration. The constructor correctly initializes these properties.

src/Providers/Google.VertexAI/test/VertexAITest.cs (1)

14-14: Ensure environment variable is set.

The GOOGLE_APPLICATION_CREDENTIALS environment variable must be set with the path to the Google credentials JSON file for the test to run successfully.

src/Providers/Google.VertexAI/src/VertexAIChatModel.cs (3)

7-12: Constructor and property initialization look good.

The constructor properly initializes the Provider property and includes a null-check.


59-66: Method ConvertMessage looks good.

The method is straightforward and follows best practices.


68-77: Method ConvertRole looks good.

The method is straightforward and follows best practices.

LangChain.sln (3)

363-364: Project VertexAI added successfully.

The project VertexAI has been correctly added with the appropriate GUID.


365-366: Project LangChain.Providers.Google.VertexAI added successfully.

The project LangChain.Providers.Google.VertexAI has been correctly added with the appropriate GUID.


367-368: Project LangChain.Providers.Google.VertexAI.Tests added successfully.

The project LangChain.Providers.Google.VertexAI.Tests has been correctly added with the appropriate GUID.

Comment on lines +43 to +57
private GenerateContentRequest ToPrompt(IEnumerable<Message> messages)
{
var contents = new RepeatedField<Content>();
foreach (var message in messages)
{
contents.Add(ConvertMessage(message));
}

return new GenerateContentRequest
{
Model = $"projects/{provider.Configuration.ProjectId}/locations/{provider.Configuration.Location}/publishers/{provider.Configuration.Publisher}/models/{Id}",
Contents = { contents },
GenerationConfig = provider.Configuration.GenerationConfig
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Simplify contents initialization using LINQ.

The contents variable declaration and initialization can be simplified using LINQ.

-  var contents = new RepeatedField<Content>();
-  foreach (var message in messages)
-  {
-    contents.Add(ConvertMessage(message));
-  }
+  var contents = new RepeatedField<Content>(messages.Select(ConvertMessage));

Committable suggestion was skipped due to low confidence.

Comment on lines +13 to +41
public override async Task<ChatResponse> GenerateAsync(ChatRequest request,
ChatSettings? settings = null,
CancellationToken cancellationToken = default)
{

request = request ?? throw new ArgumentNullException(nameof(request));
var prompt = ToPrompt(request.Messages);

var watch = Stopwatch.StartNew();
var response = await Provider.Api.GenerateContentAsync(prompt).ConfigureAwait(false);

var result = request.Messages.ToList();
result.Add(response.Candidates[0].Content.Parts[0].Text.AsAiMessage());

var usage = Usage.Empty with
{
Time = watch.Elapsed,
InputTokens = response.UsageMetadata.PromptTokenCount,
OutputTokens = response.UsageMetadata.CandidatesTokenCount
};

return new ChatResponse
{
Messages = result,
Usage = usage,
UsedSettings = ChatSettings.Default,
};

}
Copy link
Contributor

Choose a reason for hiding this comment

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

Use provided settings parameter instead of hardcoding ChatSettings.Default.

The UsedSettings property of the ChatResponse object is hardcoded to ChatSettings.Default. It should use the settings parameter if provided.

-  UsedSettings = ChatSettings.Default,
+  UsedSettings = settings ?? ChatSettings.Default,
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public override async Task<ChatResponse> GenerateAsync(ChatRequest request,
ChatSettings? settings = null,
CancellationToken cancellationToken = default)
{
request = request ?? throw new ArgumentNullException(nameof(request));
var prompt = ToPrompt(request.Messages);
var watch = Stopwatch.StartNew();
var response = await Provider.Api.GenerateContentAsync(prompt).ConfigureAwait(false);
var result = request.Messages.ToList();
result.Add(response.Candidates[0].Content.Parts[0].Text.AsAiMessage());
var usage = Usage.Empty with
{
Time = watch.Elapsed,
InputTokens = response.UsageMetadata.PromptTokenCount,
OutputTokens = response.UsageMetadata.CandidatesTokenCount
};
return new ChatResponse
{
Messages = result,
Usage = usage,
UsedSettings = ChatSettings.Default,
};
}
public override async Task<ChatResponse> GenerateAsync(ChatRequest request,
ChatSettings? settings = null,
CancellationToken cancellationToken = default)
{
request = request ?? throw new ArgumentNullException(nameof(request));
var prompt = ToPrompt(request.Messages);
var watch = Stopwatch.StartNew();
var response = await Provider.Api.GenerateContentAsync(prompt).ConfigureAwait(false);
var result = request.Messages.ToList();
result.Add(response.Candidates[0].Content.Parts[0].Text.AsAiMessage());
var usage = Usage.Empty with
{
Time = watch.Elapsed,
InputTokens = response.UsageMetadata.PromptTokenCount,
OutputTokens = response.UsageMetadata.CandidatesTokenCount
};
return new ChatResponse
{
Messages = result,
Usage = usage,
UsedSettings = settings ?? ChatSettings.Default,
};
}

Remove unnecessary re-assignment of request.

The request parameter is re-assigned after the null-check, which is unnecessary.

-  request = request ?? throw new ArgumentNullException(nameof(request));
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public override async Task<ChatResponse> GenerateAsync(ChatRequest request,
ChatSettings? settings = null,
CancellationToken cancellationToken = default)
{
request = request ?? throw new ArgumentNullException(nameof(request));
var prompt = ToPrompt(request.Messages);
var watch = Stopwatch.StartNew();
var response = await Provider.Api.GenerateContentAsync(prompt).ConfigureAwait(false);
var result = request.Messages.ToList();
result.Add(response.Candidates[0].Content.Parts[0].Text.AsAiMessage());
var usage = Usage.Empty with
{
Time = watch.Elapsed,
InputTokens = response.UsageMetadata.PromptTokenCount,
OutputTokens = response.UsageMetadata.CandidatesTokenCount
};
return new ChatResponse
{
Messages = result,
Usage = usage,
UsedSettings = ChatSettings.Default,
};
}
public override async Task<ChatResponse> GenerateAsync(ChatRequest request,
ChatSettings? settings = null,
CancellationToken cancellationToken = default)
{
request = request ?? throw new ArgumentNullException(nameof(request));
var prompt = ToPrompt(request.Messages);
var watch = Stopwatch.StartNew();
var response = await Provider.Api.GenerateContentAsync(prompt).ConfigureAwait(false);
var result = request.Messages.ToList();
result.Add(response.Candidates[0].Content.Parts[0].Text.AsAiMessage());
var usage = Usage.Empty with
{
Time = watch.Elapsed,
InputTokens = response.UsageMetadata.PromptTokenCount,
OutputTokens = response.UsageMetadata.CandidatesTokenCount
};
return new ChatResponse
{
Messages = result,
Usage = usage,
UsedSettings = ChatSettings.Default,
};
}

var provider = new VertexAIProvider(config);
var model = new Gemini15ProModel(provider);

string answer = await model.GenerateAsync("Generate some random name:");
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling.

Add error handling to manage potential exceptions from the GenerateAsync method.

-  string answer = await model.GenerateAsync("Generate some random name:");
+  string answer;
+  try {
+    answer = await model.GenerateAsync("Generate some random name:");
+  } catch (Exception ex) {
+    Console.WriteLine($"Error generating response: {ex.Message}");
+    throw;
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
string answer = await model.GenerateAsync("Generate some random name:");
string answer;
try {
answer = await model.GenerateAsync("Generate some random name:");
} catch (Exception ex) {
Console.WriteLine($"Error generating response: {ex.Message}");
throw;
}

@HavenDV HavenDV merged commit 663ef9f into tryAGI:main Jul 14, 2024
2 of 3 checks passed
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