-
Notifications
You must be signed in to change notification settings - Fork 681
.NET: Implement Purview middleware in dotnet #1949
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
Open
eoindoherty1
wants to merge
20
commits into
microsoft:main
Choose a base branch
from
eoindoherty1:users/eoindoherty1/PurviewIntegration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+5,705
−2
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
d5f6cc0
Move Purview integration logic into middleware
eoindoherty1 0a54c57
Improve error handling and user id management
eoindoherty1 23d65b8
Rename purview package
eoindoherty1 f36b80b
Handle 402s more explicitly; add Middleware generation methods; don't…
eoindoherty1 8f57ce1
Use DI container; pass scope id to PC
eoindoherty1 e294422
Add protection scope caching
eoindoherty1 4d31ed3
Wrap more exceptions in PurviewClient
eoindoherty1 cd04d14
Remove block check dedup; add tests
eoindoherty1 5bd5bad
Refactor PurviewWrapper intialization; Add unit tests
eoindoherty1 abc55d4
Use different .Use method and add IDisposable stub
eoindoherty1 513664b
Add background job processing for Purview
eoindoherty1 23d2704
Merge latest
eoindoherty1 1d142c9
Misc comment cleanup
eoindoherty1 9beb5aa
Merge branch 'main' into users/eoindoherty1/PurviewIntegration
eoindoherty1 1e6c878
Apply copilot comments
eoindoherty1 a92a3fb
Fix formatting
eoindoherty1 3c259b0
Formatting other files to fix pipeline
eoindoherty1 e3c07b8
Small updates to settings and exceptions
eoindoherty1 407e05c
Add README
eoindoherty1 8aa8624
Move Purview sample
eoindoherty1 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
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
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
21 changes: 21 additions & 0 deletions
21
dotnet/samples/Purview/AgentWithPurview/AgentWithPurview.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,21 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net9.0</TargetFramework> | ||
|
|
||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Azure.AI.OpenAI" /> | ||
| <PackageReference Include="Azure.Identity" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" /> | ||
| <ProjectReference Include="..\..\..\src\Microsoft.Agents.AI.Purview\Microsoft.Agents.AI.Purview.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
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,43 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| // This sample shows how to create and use a simple AI agent with Azure OpenAI Responses as the backend. | ||
|
|
||
| using Azure.AI.OpenAI; | ||
| using Azure.Core; | ||
| using Azure.Identity; | ||
| using Microsoft.Agents.AI; | ||
| using Microsoft.Agents.AI.Purview; | ||
| using Microsoft.Extensions.AI; | ||
|
|
||
| var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set."); | ||
| var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; | ||
| var purviewClientAppId = Environment.GetEnvironmentVariable("PURVIEW_CLIENT_APP_ID") ?? throw new InvalidOperationException("PURVIEW_CLIENT_APP_ID is not set."); | ||
|
|
||
| // This will get a user token for an entra app configured to call the Purview API. | ||
| // Any TokenCredential with permissions to call the Purview API can be used here. | ||
| TokenCredential browserCredential = new InteractiveBrowserCredential( | ||
| new InteractiveBrowserCredentialOptions | ||
| { | ||
| ClientId = purviewClientAppId | ||
| }); | ||
|
|
||
| IChatClient client = new AzureOpenAIClient( | ||
| new Uri(endpoint), | ||
| new AzureCliCredential()) | ||
| .GetOpenAIResponseClient(deploymentName) | ||
| .AsIChatClient() | ||
| .AsBuilder() | ||
| .WithPurview(browserCredential, new PurviewSettings("Agent Framework Test App")) | ||
| .Build(); | ||
|
|
||
| using (client) | ||
| { | ||
| Console.WriteLine("Enter a prompt to send to the client:"); | ||
| string? promptText = Console.ReadLine(); | ||
|
|
||
| if (!string.IsNullOrEmpty(promptText)) | ||
| { | ||
| // Invoke the agent and output the text result. | ||
| Console.WriteLine(await client.GetResponseAsync(promptText)); | ||
| } | ||
| } | ||
72 changes: 72 additions & 0 deletions
72
dotnet/src/Microsoft.Agents.AI.Purview/BackgroundJobRunner.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,72 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System; | ||
| using System.Threading; | ||
| using System.Threading.Channels; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Agents.AI.Purview.Models.Jobs; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Microsoft.Agents.AI.Purview; | ||
|
|
||
| /// <summary> | ||
| /// Service that runs jobs in background threads. | ||
| /// </summary> | ||
| internal sealed class BackgroundJobRunner | ||
| { | ||
| private readonly IChannelHandler _channelHandler; | ||
| private readonly IPurviewClient _purviewClient; | ||
| private readonly ILogger _logger; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="BackgroundJobRunner"/> class. | ||
| /// </summary> | ||
| /// <param name="channelHandler"></param> | ||
| /// <param name="purviewClient"></param> | ||
| /// <param name="logger"></param> | ||
| /// <param name="purviewSettings"></param> | ||
| public BackgroundJobRunner(IChannelHandler channelHandler, IPurviewClient purviewClient, ILogger logger, PurviewSettings purviewSettings) | ||
| { | ||
| this._channelHandler = channelHandler; | ||
| this._purviewClient = purviewClient; | ||
| this._logger = logger; | ||
|
|
||
| for (int i = 0; i < purviewSettings.MaxConcurrentJobConsumers; i++) | ||
| { | ||
| this._channelHandler.AddRunner(async (Channel<BackgroundJobBase> channel) => | ||
| { | ||
| await foreach (BackgroundJobBase job in channel.Reader.ReadAllAsync().ConfigureAwait(false)) | ||
| { | ||
| try | ||
| { | ||
| await this.RunJobAsync(job).ConfigureAwait(false); | ||
| } | ||
| catch (Exception e) when ( | ||
| !(e is OperationCanceledException) && | ||
| !(e is SystemException)) | ||
| { | ||
| this._logger.LogError(e, "Error running background job {BackgroundJobError}.", e.Message); | ||
| } | ||
| } | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Runs a job. | ||
| /// </summary> | ||
| /// <param name="job"></param> | ||
| /// <returns></returns> | ||
| private async Task RunJobAsync(BackgroundJobBase job) | ||
| { | ||
| switch (job) | ||
| { | ||
| case ProcessContentJob processContentJob: | ||
| _ = await this._purviewClient.ProcessContentAsync(processContentJob.Request, CancellationToken.None).ConfigureAwait(false); | ||
| break; | ||
| case ContentActivityJob contentActivityJob: | ||
| _ = await this._purviewClient.SendContentActivitiesAsync(contentActivityJob.Request, CancellationToken.None).ConfigureAwait(false); | ||
| break; | ||
| } | ||
| } | ||
| } |
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,89 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization.Metadata; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Agents.AI.Purview.Serialization; | ||
| using Microsoft.Extensions.Caching.Distributed; | ||
|
|
||
| namespace Microsoft.Agents.AI.Purview; | ||
|
|
||
| /// <summary> | ||
| /// Manages caching of values. | ||
| /// </summary> | ||
| internal sealed class CacheProvider : ICacheProvider | ||
| { | ||
| private readonly IDistributedCache _cache; | ||
| private readonly PurviewSettings _purviewSettings; | ||
|
|
||
| /// <summary> | ||
| /// Create a new instance of the <see cref="CacheProvider"/> class. | ||
| /// </summary> | ||
| /// <param name="cache"></param> | ||
| /// <param name="purviewSettings"></param> | ||
| public CacheProvider(IDistributedCache cache, PurviewSettings purviewSettings) | ||
| { | ||
| this._cache = cache; | ||
| this._purviewSettings = purviewSettings; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Get a value from the cache. | ||
| /// </summary> | ||
| /// <typeparam name="TKey">The type of the key in the cache. Used for serialization.</typeparam> | ||
| /// <typeparam name="TValue">The type of the value in the cache. Used for serialization.</typeparam> | ||
| /// <param name="key">The key to look up in the cache.</param> | ||
| /// <param name="cancellationToken">A cancellation token for the async operation.</param> | ||
| /// <returns>The value in the cache. Null or default if no value is present.</returns> | ||
| public async Task<TValue?> GetAsync<TKey, TValue>(TKey key, CancellationToken cancellationToken) | ||
| { | ||
| JsonTypeInfo<TKey> keyTypeInfo = (JsonTypeInfo<TKey>)PurviewSerializationUtils.SerializationSettings.GetTypeInfo(typeof(TKey)); | ||
| string serializedKey = JsonSerializer.Serialize(key, keyTypeInfo); | ||
| byte[]? data = await this._cache.GetAsync(serializedKey, cancellationToken).ConfigureAwait(false); | ||
| if (data == null) | ||
| { | ||
| return default; | ||
| } | ||
|
|
||
| JsonTypeInfo<TValue> valueTypeInfo = (JsonTypeInfo<TValue>)PurviewSerializationUtils.SerializationSettings.GetTypeInfo(typeof(TValue)); | ||
|
|
||
| return JsonSerializer.Deserialize(data, valueTypeInfo); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Set a value in the cache. | ||
| /// </summary> | ||
| /// <typeparam name="TKey">The type of the key in the cache. Used for serialization.</typeparam> | ||
| /// <typeparam name="TValue">The type of the value in the cache. Used for serialization.</typeparam> | ||
| /// <param name="key">The key to identify the cache entry.</param> | ||
| /// <param name="value">The value to cache.</param> | ||
| /// <param name="cancellationToken">A cancellation token for the async operation.</param> | ||
| /// <returns>A task for the async operation.</returns> | ||
| public Task SetAsync<TKey, TValue>(TKey key, TValue value, CancellationToken cancellationToken) | ||
| { | ||
| JsonTypeInfo<TKey> keyTypeInfo = (JsonTypeInfo<TKey>)PurviewSerializationUtils.SerializationSettings.GetTypeInfo(typeof(TKey)); | ||
| string serializedKey = JsonSerializer.Serialize(key, keyTypeInfo); | ||
| JsonTypeInfo<TValue> valueTypeInfo = (JsonTypeInfo<TValue>)PurviewSerializationUtils.SerializationSettings.GetTypeInfo(typeof(TValue)); | ||
| byte[] serializedValue = JsonSerializer.SerializeToUtf8Bytes(value, valueTypeInfo); | ||
|
|
||
| DistributedCacheEntryOptions cacheOptions = new() { AbsoluteExpirationRelativeToNow = this._purviewSettings.CacheTTL }; | ||
|
|
||
| return this._cache.SetAsync(serializedKey, serializedValue, cacheOptions, cancellationToken); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Removes a value from the cache. | ||
| /// </summary> | ||
| /// <typeparam name="TKey">The type of the key.</typeparam> | ||
| /// <param name="key">The key to identify the cache entry.</param> | ||
| /// <param name="cancellationToken">The cancellation token for the async operation.</param> | ||
| /// <returns>A task for the async operation.</returns> | ||
| public Task RemoveAsync<TKey>(TKey key, CancellationToken cancellationToken) | ||
| { | ||
| JsonTypeInfo<TKey> keyTypeInfo = (JsonTypeInfo<TKey>)PurviewSerializationUtils.SerializationSettings.GetTypeInfo(typeof(TKey)); | ||
| string serializedKey = JsonSerializer.Serialize(key, keyTypeInfo); | ||
|
|
||
| return this._cache.RemoveAsync(serializedKey, cancellationToken); | ||
| } | ||
| } |
101 changes: 101 additions & 0 deletions
101
dotnet/src/Microsoft.Agents.AI.Purview/ChannelHandler.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,101 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Threading.Channels; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Agents.AI.Purview.Exceptions; | ||
| using Microsoft.Agents.AI.Purview.Models.Jobs; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Microsoft.Agents.AI.Purview; | ||
|
|
||
| /// <summary> | ||
| /// Handler class for background job management. | ||
| /// </summary> | ||
| internal class ChannelHandler : IChannelHandler | ||
| { | ||
| private readonly Channel<BackgroundJobBase> _jobChannel; | ||
| private readonly List<Task> _channelListeners; | ||
| private readonly ILogger _logger; | ||
| private readonly PurviewSettings _purviewSettings; | ||
|
|
||
| /// <summary> | ||
| /// Creates a new instance of JobHandler. | ||
| /// </summary> | ||
| /// <param name="purviewSettings"></param> | ||
| /// <param name="logger"></param> | ||
| /// <param name="jobChannel"></param> | ||
| public ChannelHandler(PurviewSettings purviewSettings, ILogger logger, Channel<BackgroundJobBase> jobChannel) | ||
| { | ||
| this._purviewSettings = purviewSettings; | ||
| this._logger = logger; | ||
| this._jobChannel = jobChannel; | ||
|
|
||
| this._channelListeners = new List<Task>(this._purviewSettings.MaxConcurrentJobConsumers); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public void QueueJob(BackgroundJobBase job) | ||
| { | ||
| try | ||
| { | ||
| if (job == null) | ||
| { | ||
| throw new PurviewJobException("Cannot queue null job."); | ||
| } | ||
|
|
||
| if (this._channelListeners.Count == 0) | ||
| { | ||
| this._logger.LogWarning("No listeners are available to process the job."); | ||
| throw new PurviewJobException("No listeners are available to process the job."); | ||
| } | ||
|
|
||
| bool canQueue = this._jobChannel.Writer.TryWrite(job); | ||
|
|
||
| if (!canQueue) | ||
| { | ||
| int jobCount = this._jobChannel.Reader.Count; | ||
| this._logger.LogError("Could not queue a job for background processing."); | ||
|
|
||
| if (this._jobChannel.Reader.Completion.IsCompleted) | ||
| { | ||
| throw new PurviewJobException("Job channel is closed or completed. Cannot queue job."); | ||
| } | ||
| else if (jobCount >= this._purviewSettings.PendingBackgroundJobLimit) | ||
| { | ||
| throw new PurviewJobLimitExceededException($"Job queue is full. Current pending jobs: {jobCount}. Maximum number of queued jobs: {this._purviewSettings.PendingBackgroundJobLimit}"); | ||
| } | ||
| else | ||
| { | ||
| throw new PurviewJobException("Could not queue job for background processing."); | ||
| } | ||
| } | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| if (this._purviewSettings.IgnoreExceptions) | ||
| { | ||
| this._logger.LogError(e, "Error queuing job: {ExceptionMessage}", e.Message); | ||
| } | ||
| else | ||
| { | ||
| throw; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public void AddRunner(Func<Channel<BackgroundJobBase>, Task> runnerTask) | ||
| { | ||
| this._channelListeners.Add(Task.Run(async () => await runnerTask(this._jobChannel).ConfigureAwait(false))); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public async Task StopAndWaitForCompletionAsync() | ||
| { | ||
| this._jobChannel.Writer.Complete(); | ||
| await this._jobChannel.Reader.Completion.ConfigureAwait(false); | ||
| await Task.WhenAll(this._channelListeners).ConfigureAwait(false); | ||
| } | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure there should be a Purview sample in the "Getting Started" section, since ostensibly the samples in there should target core/basic scenarios involved in building agents (admittedly there's probably other stuff in there that can be cleaned up).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a bit niche compared to the other examples in that directory. I added a new folder for Purview and moved this there, please let me know if there's a better spot for it.