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: added Amazon Bedrock Cohere R plus and Cohere R models #285

Merged
merged 2 commits into from
May 2, 2024

Conversation

curlyfro
Copy link
Contributor

@curlyfro curlyfro commented May 2, 2024

fix: fixed small issues

Summary by CodeRabbit

  • New Features

    • Introduced new chat and embedding models for enhanced interaction and data processing capabilities.
    • Added new settings for chat and embedding functionalities to allow more customized user experiences.
  • Enhancements

    • Improved the chat model's response generation with new asynchronous methods.
    • Enhanced embedding models with the ability to process input strings asynchronously.
  • Bug Fixes

    • Corrected the token limit setting in chat configurations to optimize performance.
  • Refactor

    • Updated class identifiers and constructors to align with new functionalities.
    • Modified tests to incorporate new models and settings effectively.

Copy link
Contributor

coderabbitai bot commented May 2, 2024

Walkthrough

The updates across various files in the Amazon Bedrock module focus on enhancing chat and embedding functionalities, adjusting settings for maximal tokens, and refining model identifiers. New classes and methods are introduced to support asynchronous operations and JSON body creation, improving interaction with Cohere and Amazon Titan models.

Changes

File Path Change Summary
.../Chat/CohereCommandRModel.cs, .../Predefined/Cohere.cs Introduced CohereCommandRModel and derived classes for enhanced chat functionalities using Cohere models.
.../Chat/Settings/MetaLlama2ChatSettings.cs Reduced MaxTokens from 4000 to 2048.
.../Embedding/..., .../Predefined/Amazon.cs Added new embedding models and settings, including constructors and asynchronous methods.
.../Predefined/Mistral.cs Corrected a typo in model identifier.
.../test/BedrockTests.cs, .../test/BedrockTextModelTests.cs Updated tests, imports, and instantiation parameters. Adjusted exception handling and syntax.

🐰✨
In the land of code where the Bedrock lies,
The models chat and the data flies.
With tweaks and changes, small and grand,
A rabbit hops through this digital land.
Celebrate the code, so craftily spun,
For in the world of zeros, we all are one. 🌟
🐰💻


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.

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

Out of diff range and nitpick comments (3)
src/Providers/Amazon.Bedrock/src/Embedding/Settings/AmazonV2EmbeddingSettings.cs (1)

4-55: Introduced AmazonV2EmbeddingSettings with default settings and dynamic calculation capabilities.

Consider adding detailed comments explaining the use of the new keyword in static members to avoid confusion.

src/Providers/Amazon.Bedrock/src/Chat/Settings/MetaLlama2ChatSettings.cs (1)

Line range hint 1-12: Introduced MetaLlama2ChatSettings with default settings and dynamic calculation capabilities.

Consider adding detailed comments explaining the use of the new keyword in static members to avoid confusion.

src/Providers/Amazon.Bedrock/test/BedrockTextModelTests.cs (1)

[!TIP]
Codebase Verification

The verification process has revealed that the transition to the new instantiation method using RegionEndpoint.USWest2 in BedrockProvider is incomplete. Several files still use the old instantiation method without the RegionEndpoint parameter. Here are the files where issues were found:

  • src/Providers/Amazon.Bedrock/test/BedrockTextModelTests.cs
  • src/Providers/Amazon.Bedrock/test/BedrockTests.cs
  • src/Meta/test/CrewTests.cs
  • src/Providers/Amazon.Sagemaker/test/SageMakerTests.cs
  • src/Databases/IntegrationTests/DatabaseTests.OpenSearch.cs
Analysis chain

Line range hint 24-61: Updated test setup in BedrockTextModelTests to include RegionEndpoint parameter, enhancing specificity in AWS region selection.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the new `RegionEndpoint` parameter is correctly used in all relevant test setups.

# Search for the old instantiation without the `RegionEndpoint` to ensure it's no longer used.
rg --files-with-matches --type cs 'new BedrockProvider()' | while read file; do
  # Expect: No matches.
  echo "Old instantiation found in $file"
done

# Search for the new instantiation to validate usage.
rg --files-with-matches --type cs 'new BedrockProvider(RegionEndpoint.USWest2)' | while read file; do
  # Expect: Matches.
  echo "New instantiation used in $file"
done

Length of output: 1038

Comment on lines +22 to +75
public async Task<EmbeddingResponse> CreateEmbeddingsAsync(
EmbeddingRequest request,
EmbeddingSettings? settings = null,
CancellationToken cancellationToken = default)
{
request = request ?? throw new ArgumentNullException(nameof(request));

var watch = Stopwatch.StartNew();

var usedSettings = AmazonV2EmbeddingSettings.Calculate(
requestSettings: settings,
modelSettings: Settings,
providerSettings: provider.EmbeddingSettings);

var embeddings = new List<float[]>(capacity: request.Strings.Count);

var tasks = request.Strings.Select(text =>
{
var bodyJson = CreateBodyJson(text, usedSettings);
return provider.Api.InvokeModelAsync(Id, bodyJson,
cancellationToken);
})
.ToList();
var results = await Task.WhenAll(tasks).ConfigureAwait(false);

foreach (var response in results)
{
var embedding = response?["embedding"]?.AsArray();
if (embedding == null) continue;

var f = new float[(int)usedSettings.Dimensions!];
for (var i = 0; i < embedding.Count; i++)
{
f[i] = (float)embedding[(Index)i]?.AsValue()!;
}

embeddings.Add(f);
}

var usage = Usage.Empty with
{
Time = watch.Elapsed,
};
AddUsage(usage);
provider.AddUsage(usage);

return new EmbeddingResponse
{
Values = embeddings.ToArray(),
Usage = Usage.Empty,
UsedSettings = usedSettings,
Dimensions = embeddings.FirstOrDefault()?.Length ?? 0,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Implemented CreateEmbeddingsAsync in AmazonTitanEmbeddingV2Model with comprehensive error handling and efficient asynchronous operations.

Optimize JSON body construction by directly using JsonObject properties instead of intermediate conversions.

- var bodyJson = new JsonObject
- {
-     ["inputText"] = prompt,
-     ["dimensions"] = usedSettings.Dimensions,
-     ["normalize"] = usedSettings.Normalize
- };
+ var bodyJson = new JsonObject
+ {
+     { "inputText", prompt },
+     { "dimensions", usedSettings.Dimensions },
+     { "normalize", usedSettings.Normalize }
+ };

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.

Suggested change
public async Task<EmbeddingResponse> CreateEmbeddingsAsync(
EmbeddingRequest request,
EmbeddingSettings? settings = null,
CancellationToken cancellationToken = default)
{
request = request ?? throw new ArgumentNullException(nameof(request));
var watch = Stopwatch.StartNew();
var usedSettings = AmazonV2EmbeddingSettings.Calculate(
requestSettings: settings,
modelSettings: Settings,
providerSettings: provider.EmbeddingSettings);
var embeddings = new List<float[]>(capacity: request.Strings.Count);
var tasks = request.Strings.Select(text =>
{
var bodyJson = CreateBodyJson(text, usedSettings);
return provider.Api.InvokeModelAsync(Id, bodyJson,
cancellationToken);
})
.ToList();
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var response in results)
{
var embedding = response?["embedding"]?.AsArray();
if (embedding == null) continue;
var f = new float[(int)usedSettings.Dimensions!];
for (var i = 0; i < embedding.Count; i++)
{
f[i] = (float)embedding[(Index)i]?.AsValue()!;
}
embeddings.Add(f);
}
var usage = Usage.Empty with
{
Time = watch.Elapsed,
};
AddUsage(usage);
provider.AddUsage(usage);
return new EmbeddingResponse
{
Values = embeddings.ToArray(),
Usage = Usage.Empty,
UsedSettings = usedSettings,
Dimensions = embeddings.FirstOrDefault()?.Length ?? 0,
};
}
public async Task<EmbeddingResponse> CreateEmbeddingsAsync(
EmbeddingRequest request,
EmbeddingSettings? settings = null,
CancellationToken cancellationToken = default)
{
request = request ?? throw new ArgumentNullException(nameof(request));
var watch = Stopwatch.StartNew();
var usedSettings = AmazonV2EmbeddingSettings.Calculate(
requestSettings: settings,
modelSettings: Settings,
providerSettings: provider.EmbeddingSettings);
var embeddings = new List<float[]>(capacity: request.Strings.Count);
var tasks = request.Strings.Select(text =>
{
var bodyJson = new JsonObject
{
{ "inputText", text },
{ "dimensions", usedSettings.Dimensions },
{ "normalize", usedSettings.Normalize }
};
return provider.Api.InvokeModelAsync(Id, bodyJson,
cancellationToken);
})
.ToList();
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var response in results)
{
var embedding = response?["embedding"]?.AsArray();
if (embedding == null) continue;
var f = new float[(int)usedSettings.Dimensions!];
for (var i = 0; i < embedding.Count; i++)
{
f[i] = (float)embedding[(Index)i]?.AsValue()!;
}
embeddings.Add(f);
}
var usage = Usage.Empty with
{
Time = watch.Elapsed,
};
AddUsage(usage);
provider.AddUsage(usage);
return new EmbeddingResponse
{
Values = embeddings.ToArray(),
Usage = Usage.Empty,
UsedSettings = usedSettings,
Dimensions = embeddings.FirstOrDefault()?.Length ?? 0,
};
}

Comment on lines +23 to +89
public override async Task<ChatResponse> GenerateAsync(
ChatRequest request,
ChatSettings? settings = null,
CancellationToken cancellationToken = default)
{
request = request ?? throw new ArgumentNullException(nameof(request));

var watch = Stopwatch.StartNew();
var prompt = request.Messages.ToSimplePrompt();
var messages = request.Messages.ToList();

var stringBuilder = new StringBuilder();

var usedSettings = CohereCommandChatSettings.Calculate(
requestSettings: settings,
modelSettings: Settings,
providerSettings: provider.ChatSettings);

var bodyJson = CreateBodyJson(prompt, usedSettings);

if (usedSettings.UseStreaming == true)
{
var streamRequest = BedrockModelRequest.CreateStreamRequest(Id, bodyJson);
var response = await provider.Api.InvokeModelWithResponseStreamAsync(streamRequest, cancellationToken).ConfigureAwait(false);

foreach (var payloadPart in response.Body)
{
var streamEvent = (PayloadPart)payloadPart;
var chunk = await JsonSerializer.DeserializeAsync<JsonObject>(streamEvent.Bytes, cancellationToken: cancellationToken)
.ConfigureAwait(false);
var delta = chunk?["text"]?.GetValue<string>() ?? string.Empty;

OnPartialResponseGenerated(delta);
stringBuilder.Append(delta);

var finished = chunk?["finish_reason"]?.GetValue<string>() ?? string.Empty;
if (string.Equals(finished.ToUpperInvariant(), "COMPLETE", StringComparison.Ordinal))
{
OnCompletedResponseGenerated(stringBuilder.ToString());
}
}
}
else
{
var response = await provider.Api.InvokeModelAsync(Id, bodyJson, cancellationToken)
.ConfigureAwait(false);

var generatedText = response?["text"]?.GetValue<string>() ?? string.Empty;

messages.Add(generatedText.AsAiMessage());
OnCompletedResponseGenerated(generatedText);
}

var usage = Usage.Empty with
{
Time = watch.Elapsed,
};
AddUsage(usage);
provider.AddUsage(usage);

return new ChatResponse
{
Messages = messages,
UsedSettings = usedSettings,
Usage = usage,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Implemented GenerateAsync in CohereCommandRModel with comprehensive error handling and efficient asynchronous operations.

Optimize JSON body construction by directly using JsonObject properties instead of intermediate conversions.

- var bodyJson = new JsonObject
- {
-     ["message"] = prompt,
- };
+ var bodyJson = new JsonObject
+ {
+     { "message", prompt },
+ };

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.

Suggested change
public override async Task<ChatResponse> GenerateAsync(
ChatRequest request,
ChatSettings? settings = null,
CancellationToken cancellationToken = default)
{
request = request ?? throw new ArgumentNullException(nameof(request));
var watch = Stopwatch.StartNew();
var prompt = request.Messages.ToSimplePrompt();
var messages = request.Messages.ToList();
var stringBuilder = new StringBuilder();
var usedSettings = CohereCommandChatSettings.Calculate(
requestSettings: settings,
modelSettings: Settings,
providerSettings: provider.ChatSettings);
var bodyJson = CreateBodyJson(prompt, usedSettings);
if (usedSettings.UseStreaming == true)
{
var streamRequest = BedrockModelRequest.CreateStreamRequest(Id, bodyJson);
var response = await provider.Api.InvokeModelWithResponseStreamAsync(streamRequest, cancellationToken).ConfigureAwait(false);
foreach (var payloadPart in response.Body)
{
var streamEvent = (PayloadPart)payloadPart;
var chunk = await JsonSerializer.DeserializeAsync<JsonObject>(streamEvent.Bytes, cancellationToken: cancellationToken)
.ConfigureAwait(false);
var delta = chunk?["text"]?.GetValue<string>() ?? string.Empty;
OnPartialResponseGenerated(delta);
stringBuilder.Append(delta);
var finished = chunk?["finish_reason"]?.GetValue<string>() ?? string.Empty;
if (string.Equals(finished.ToUpperInvariant(), "COMPLETE", StringComparison.Ordinal))
{
OnCompletedResponseGenerated(stringBuilder.ToString());
}
}
}
else
{
var response = await provider.Api.InvokeModelAsync(Id, bodyJson, cancellationToken)
.ConfigureAwait(false);
var generatedText = response?["text"]?.GetValue<string>() ?? string.Empty;
messages.Add(generatedText.AsAiMessage());
OnCompletedResponseGenerated(generatedText);
}
var usage = Usage.Empty with
{
Time = watch.Elapsed,
};
AddUsage(usage);
provider.AddUsage(usage);
return new ChatResponse
{
Messages = messages,
UsedSettings = usedSettings,
Usage = usage,
};
}
public override async Task<ChatResponse> GenerateAsync(
ChatRequest request,
ChatSettings? settings = null,
CancellationToken cancellationToken = default)
{
request = request ?? throw new ArgumentNullException(nameof(request));
var watch = Stopwatch.StartNew();
var prompt = request.Messages.ToSimplePrompt();
var messages = request.Messages.ToList();
var stringBuilder = new StringBuilder();
var usedSettings = CohereCommandChatSettings.Calculate(
requestSettings: settings,
modelSettings: Settings,
providerSettings: provider.ChatSettings);
var bodyJson = new JsonObject
{
{ "message", prompt },
};
if (usedSettings.UseStreaming == true)
{
var streamRequest = BedrockModelRequest.CreateStreamRequest(Id, bodyJson);
var response = await provider.Api.InvokeModelWithResponseStreamAsync(streamRequest, cancellationToken).ConfigureAwait(false);
foreach (var payloadPart in response.Body)
{
var streamEvent = (PayloadPart)payloadPart;
var chunk = await JsonSerializer.DeserializeAsync<JsonObject>(streamEvent.Bytes, cancellationToken: cancellationToken)
.ConfigureAwait(false);
var delta = chunk?["text"]?.GetValue<string>() ?? string.Empty;
OnPartialResponseGenerated(delta);
stringBuilder.Append(delta);
var finished = chunk?["finish_reason"]?.GetValue<string>() ?? string.Empty;
if (string.Equals(finished.ToUpperInvariant(), "COMPLETE", StringComparison.Ordinal))
{
OnCompletedResponseGenerated(stringBuilder.ToString());
}
}
}
else
{
var response = await provider.Api.InvokeModelAsync(Id, bodyJson, cancellationToken)
.ConfigureAwait(false);
var generatedText = response?["text"]?.GetValue<string>() ?? string.Empty;
messages.Add(generatedText.AsAiMessage());
OnCompletedResponseGenerated(generatedText);
}
var usage = Usage.Empty with
{
Time = watch.Elapsed,
};
AddUsage(usage);
provider.AddUsage(usage);
return new ChatResponse
{
Messages = messages,
UsedSettings = usedSettings,
Usage = usage,
};
}

@HavenDV HavenDV merged commit 2e8aa1c into tryAGI:main May 2, 2024
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.

None yet

2 participants