-
Notifications
You must be signed in to change notification settings - Fork 6k
Add the runtime libraries bits for MEAI #43985
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
aafcc19
Add the runtime libraries bits for MEAI
IEvangelist 60dc385
Apply suggestions from code review
IEvangelist b40a757
Added a mock TOC (or in article nav)
IEvangelist 87e05e2
Add all the snippets
IEvangelist 3202f36
Apply suggestions from code review
IEvangelist 5c4ab2f
Fix code includes
IEvangelist File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
docs/core/extensions/snippets/ai/AI.Shared/AI.Shared.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.Extensions.AI" Version="9.0.1-preview.1.24570.5" /> | ||
<PackageReference Include="System.Threading.RateLimiting" Version="9.0.0" /> | ||
</ItemGroup> | ||
|
||
</Project> |
55 changes: 55 additions & 0 deletions
55
docs/core/extensions/snippets/ai/AI.Shared/RateLimitingChatClient.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
using Microsoft.Extensions.AI; | ||
using System.Runtime.CompilerServices; | ||
using System.Threading.RateLimiting; | ||
|
||
public sealed class RateLimitingChatClient( | ||
IChatClient innerClient, RateLimiter rateLimiter) | ||
: DelegatingChatClient(innerClient) | ||
{ | ||
public override async Task<ChatCompletion> CompleteAsync( | ||
IList<ChatMessage> chatMessages, | ||
ChatOptions? options = null, | ||
CancellationToken cancellationToken = default) | ||
{ | ||
using var lease = await rateLimiter.AcquireAsync(permitCount: 1, cancellationToken) | ||
.ConfigureAwait(false); | ||
|
||
if (!lease.IsAcquired) | ||
{ | ||
throw new InvalidOperationException("Unable to acquire lease."); | ||
} | ||
|
||
return await base.CompleteAsync(chatMessages, options, cancellationToken) | ||
.ConfigureAwait(false); | ||
} | ||
|
||
public override async IAsyncEnumerable<StreamingChatCompletionUpdate> CompleteStreamingAsync( | ||
IList<ChatMessage> chatMessages, | ||
ChatOptions? options = null, | ||
[EnumeratorCancellation] CancellationToken cancellationToken = default) | ||
{ | ||
using var lease = await rateLimiter.AcquireAsync(permitCount: 1, cancellationToken) | ||
.ConfigureAwait(false); | ||
|
||
if (!lease.IsAcquired) | ||
{ | ||
throw new InvalidOperationException("Unable to acquire lease."); | ||
} | ||
|
||
await foreach (var update in base.CompleteStreamingAsync(chatMessages, options, cancellationToken) | ||
.ConfigureAwait(false)) | ||
{ | ||
yield return update; | ||
} | ||
} | ||
|
||
protected override void Dispose(bool disposing) | ||
{ | ||
if (disposing) | ||
{ | ||
rateLimiter.Dispose(); | ||
} | ||
|
||
base.Dispose(disposing); | ||
} | ||
} |
17 changes: 17 additions & 0 deletions
17
...ore/extensions/snippets/ai/AI.Shared/RateLimitingChatClientExtensions.OptionalOverload.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
namespace Example.Two; | ||
|
||
// <two> | ||
using Microsoft.Extensions.AI; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using System.Threading.RateLimiting; | ||
|
||
public static class RateLimitingChatClientExtensions | ||
{ | ||
public static ChatClientBuilder UseRateLimiting( | ||
this ChatClientBuilder builder, RateLimiter? rateLimiter = null) => | ||
builder.Use((innerClient, services) => | ||
new RateLimitingChatClient( | ||
innerClient, | ||
rateLimiter ?? services.GetRequiredService<RateLimiter>())); | ||
} | ||
// </two> |
13 changes: 13 additions & 0 deletions
13
docs/core/extensions/snippets/ai/AI.Shared/RateLimitingChatClientExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
namespace Example.One; | ||
|
||
// <one> | ||
using Microsoft.Extensions.AI; | ||
using System.Threading.RateLimiting; | ||
|
||
public static class RateLimitingChatClientExtensions | ||
{ | ||
public static ChatClientBuilder UseRateLimiting( | ||
this ChatClientBuilder builder, RateLimiter rateLimiter) => | ||
builder.Use(innerClient => new RateLimitingChatClient(innerClient, rateLimiter)); | ||
} | ||
// </one> |
33 changes: 33 additions & 0 deletions
33
docs/core/extensions/snippets/ai/AI.Shared/RateLimitingEmbeddingGenerator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
using Microsoft.Extensions.AI; | ||
using System.Threading.RateLimiting; | ||
|
||
public class RateLimitingEmbeddingGenerator( | ||
IEmbeddingGenerator<string, Embedding<float>> innerGenerator, RateLimiter rateLimiter) | ||
: DelegatingEmbeddingGenerator<string, Embedding<float>>(innerGenerator) | ||
{ | ||
public override async Task<GeneratedEmbeddings<Embedding<float>>> GenerateAsync( | ||
IEnumerable<string> values, | ||
EmbeddingGenerationOptions? options = null, | ||
CancellationToken cancellationToken = default) | ||
{ | ||
using var lease = await rateLimiter.AcquireAsync(permitCount: 1, cancellationToken) | ||
.ConfigureAwait(false); | ||
|
||
if (!lease.IsAcquired) | ||
{ | ||
throw new InvalidOperationException("Unable to acquire lease."); | ||
} | ||
|
||
return await base.GenerateAsync(values, options, cancellationToken); | ||
} | ||
|
||
protected override void Dispose(bool disposing) | ||
{ | ||
if (disposing) | ||
{ | ||
rateLimiter.Dispose(); | ||
} | ||
|
||
base.Dispose(disposing); | ||
} | ||
} |
58 changes: 58 additions & 0 deletions
58
docs/core/extensions/snippets/ai/AI.Shared/SampleChatClient.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
using System.Runtime.CompilerServices; | ||
using Microsoft.Extensions.AI; | ||
|
||
public sealed class SampleChatClient(Uri endpoint, string modelId) : IChatClient | ||
{ | ||
public ChatClientMetadata Metadata { get; } = new(nameof(SampleChatClient), endpoint, modelId); | ||
|
||
public async Task<ChatCompletion> CompleteAsync( | ||
IList<ChatMessage> chatMessages, | ||
ChatOptions? options = null, | ||
CancellationToken cancellationToken = default) | ||
{ | ||
// Simulate some operation. | ||
await Task.Delay(300, cancellationToken); | ||
|
||
// Return a sample chat completion response randomly. | ||
string[] responses = | ||
[ | ||
"This is the first sample response.", | ||
"Here is another example of a response message.", | ||
"This is yet another response message." | ||
]; | ||
|
||
return new([new ChatMessage() | ||
{ | ||
Role = ChatRole.Assistant, | ||
Text = responses[Random.Shared.Next(responses.Length)], | ||
}]); | ||
} | ||
|
||
public async IAsyncEnumerable<StreamingChatCompletionUpdate> CompleteStreamingAsync( | ||
IList<ChatMessage> chatMessages, | ||
ChatOptions? options = null, | ||
[EnumeratorCancellation] CancellationToken cancellationToken = default) | ||
{ | ||
// Simulate streaming by yielding messages one by one. | ||
string[] words = ["This ", "is ", "the ", "response ", "for ", "the ", "request."]; | ||
foreach (string word in words) | ||
{ | ||
// Simulate some operation. | ||
await Task.Delay(100, cancellationToken); | ||
|
||
// Yield the next message in the response. | ||
yield return new StreamingChatCompletionUpdate | ||
{ | ||
Role = ChatRole.Assistant, | ||
Text = word, | ||
}; | ||
} | ||
} | ||
|
||
public object? GetService(Type serviceType, object? serviceKey) => this; | ||
|
||
public TService? GetService<TService>(object? key = null) | ||
where TService : class => this as TService; | ||
|
||
void IDisposable.Dispose() { } | ||
} |
35 changes: 35 additions & 0 deletions
35
docs/core/extensions/snippets/ai/AI.Shared/SampleEmbeddingGenerator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
using Microsoft.Extensions.AI; | ||
|
||
public sealed class SampleEmbeddingGenerator( | ||
Uri endpoint, string modelId) | ||
: IEmbeddingGenerator<string, Embedding<float>> | ||
{ | ||
public EmbeddingGeneratorMetadata Metadata { get; } = | ||
new(nameof(SampleEmbeddingGenerator), endpoint, modelId); | ||
|
||
public async Task<GeneratedEmbeddings<Embedding<float>>> GenerateAsync( | ||
IEnumerable<string> values, | ||
EmbeddingGenerationOptions? options = null, | ||
CancellationToken cancellationToken = default) | ||
{ | ||
// Simulate some async operation | ||
await Task.Delay(100, cancellationToken); | ||
|
||
// Create random embeddings | ||
return | ||
[ | ||
.. from value in values | ||
select new Embedding<float>( | ||
Enumerable.Range(0, 384) | ||
.Select(_ => Random.Shared.NextSingle()) | ||
.ToArray()) | ||
]; | ||
} | ||
|
||
public object? GetService(Type serviceType, object? serviceKey) => this; | ||
|
||
public TService? GetService<TService>(object? key = null) | ||
where TService : class => this as TService; | ||
|
||
void IDisposable.Dispose() { } | ||
} |
18 changes: 18 additions & 0 deletions
18
docs/core/extensions/snippets/ai/ConsoleAI.CacheResponses/ConsoleAI.CacheResponses.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.0" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\AI.Shared\AI.Shared.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
24 changes: 24 additions & 0 deletions
24
docs/core/extensions/snippets/ai/ConsoleAI.CacheResponses/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
using Microsoft.Extensions.AI; | ||
using Microsoft.Extensions.Caching.Distributed; | ||
using Microsoft.Extensions.Caching.Memory; | ||
using Microsoft.Extensions.Options; | ||
|
||
var sampleChatClient = new SampleChatClient( | ||
new Uri("http://coolsite.ai"), "target-ai-model"); | ||
|
||
IChatClient client = new ChatClientBuilder(sampleChatClient) | ||
.UseDistributedCache(new MemoryDistributedCache( | ||
Options.Create(new MemoryDistributedCacheOptions()))) | ||
.Build(); | ||
|
||
string[] prompts = ["What is AI?", "What is .NET?", "What is AI?"]; | ||
|
||
foreach (var prompt in prompts) | ||
{ | ||
await foreach (var update in client.CompleteStreamingAsync(prompt)) | ||
{ | ||
Console.Write(update); | ||
} | ||
|
||
Console.WriteLine(); | ||
} |
14 changes: 14 additions & 0 deletions
14
...ore/extensions/snippets/ai/ConsoleAI.CompleteAsyncArgs/ConsoleAI.CompleteAsyncArgs.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\AI.Shared\AI.Shared.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
10 changes: 10 additions & 0 deletions
10
docs/core/extensions/snippets/ai/ConsoleAI.CompleteAsyncArgs/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
using Microsoft.Extensions.AI; | ||
|
||
IChatClient client = new SampleChatClient( | ||
new Uri("http://coolsite.ai"), "target-ai-model"); | ||
|
||
Console.WriteLine(await client.CompleteAsync( | ||
[ | ||
new(ChatRole.System, "You are a helpful AI assistant"), | ||
new(ChatRole.User, "What is AI?"), | ||
])); |
14 changes: 14 additions & 0 deletions
14
...ions/snippets/ai/ConsoleAI.CompleteStreamingAsync/ConsoleAI.CompleteStreamingAsync.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\AI.Shared\AI.Shared.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
9 changes: 9 additions & 0 deletions
9
docs/core/extensions/snippets/ai/ConsoleAI.CompleteStreamingAsync/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
using Microsoft.Extensions.AI; | ||
|
||
IChatClient client = new SampleChatClient( | ||
new Uri("http://coolsite.ai"), "target-ai-model"); | ||
|
||
await foreach (var update in client.CompleteStreamingAsync("What is AI?")) | ||
{ | ||
Console.Write(update); | ||
} |
15 changes: 15 additions & 0 deletions
15
...ns/snippets/ai/ConsoleAI.ConsumeClientMiddleware/ConsoleAI.ConsumeClientMiddleware.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.0" /> | ||
<ProjectReference Include="..\AI.Shared\AI.Shared.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.