A programming framework for agentic AI
.NET update oai and aoai package version (#6239)
Xiaoyun Zhang223016144784
diff --git a/dotnet/Directory.Packages.props b/dotnet/Directory.Packages.propsindex aca7a136d..ea8f50875 100644--- a/dotnet/Directory.Packages.props+++ b/dotnet/Directory.Packages.props@@ -2,10 +2,12 @@<PropertyGroup><ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally><MicrosoftSemanticKernelVersion>1.22.0</MicrosoftSemanticKernelVersion>- <MicrosoftSemanticKernelExperimentalVersion>1.22.0-alpha</MicrosoftSemanticKernelExperimentalVersion>- <MicrosoftExtensionsAIVersion>9.0.0-preview.9.24525.1</MicrosoftExtensionsAIVersion>+ <MicrosoftSemanticKernelStableVersion>1.45.0</MicrosoftSemanticKernelStableVersion>+ <MicrosoftSemanticKernelPreviewVersion>$(MicrosoftSemanticKernelStableVersion)-preview</MicrosoftSemanticKernelPreviewVersion>+ <MicrosoftSemanticKernelAlphaVersion>$(MicrosoftSemanticKernelStableVersion)-alpha</MicrosoftSemanticKernelAlphaVersion>+ <MicrosoftExtensionsAIVersion>9.3.0-preview.1.25161.3</MicrosoftExtensionsAIVersion><MicrosoftExtensionConfiguration>9.0.0</MicrosoftExtensionConfiguration>- <MicrosoftExtensionDependencyInjection>9.0.0</MicrosoftExtensionDependencyInjection>+ <MicrosoftExtensionDependencyInjection>9.0.3</MicrosoftExtensionDependencyInjection><MicrosoftExtensionLogging>9.0.0</MicrosoftExtensionLogging><MicrosoftExtensionOptions>9.0.0</MicrosoftExtensionOptions><MicrosoftOrleans>9.0.1</MicrosoftOrleans>@@ -18,7 +20,7 @@<PackageVersion Include="Aspire.Hosting" Version="9.0.0" /><PackageVersion Include="Aspire.Hosting.Python" Version="9.0.0" /><PackageVersion Include="Aspire.Hosting.Testing" Version="9.0.0" />- <PackageVersion Include="Aspire.Azure.AI.OpenAI" Version="8.0.1-preview.8.24267.1" />+ <PackageVersion Include="Aspire.Azure.AI.OpenAI" Version="9.0.0-preview.5.24551.3" /><PackageVersion Include="Aspire.Hosting.AppHost" Version="9.0.0" /><PackageVersion Include="Aspire.Hosting.Azure.ApplicationInsights" Version="9.0.0" /><PackageVersion Include="Aspire.Hosting.Azure.CognitiveServices" Version="9.0.0" />@@ -27,9 +29,10 @@<PackageVersion Include="Aspire.Hosting.Qdrant" Version="9.0.0" /><PackageVersion Include="Aspire.Hosting.Redis" Version="8.2.0" /><PackageVersion Include="AspNetCore.Authentication.ApiKey" Version="8.0.1" />- <PackageVersion Include="Azure.AI.OpenAI" Version="2.1.0-beta.2" />+ <PackageVersion Include="Azure.AI.OpenAI" Version="2.2.0-beta.4" /><PackageVersion Include="Azure.AI.Inference" Version="1.0.0-beta.1" /><PackageVersion Include="Azure.Data.Tables" Version="12.9.1" />+ <PackageVersion Include="Azure.Core" Version="1.44.1" /><PackageVersion Include="Azure.Identity" Version="1.13.1" /><PackageVersion Include="Azure.ResourceManager.ContainerInstance" Version="1.2.1" /><PackageVersion Include="Azure.Storage.Files.Shares" Version="12.21.0" />@@ -100,18 +103,18 @@<PackageVersion Include="Microsoft.Orleans.Streaming.EventHubs" Version="$(MicrosoftOrleans)" /><PackageVersion Include="Microsoft.Orleans.TestingHost" Version="9.0.1" /><PackageVersion Include="Microsoft.PowerShell.SDK" Version="7.5.0" />- <PackageVersion Include="Microsoft.SemanticKernel" Version="1.29.0" />- <PackageVersion Include="Microsoft.SemanticKernel.Agents.Core" Version="$(MicrosoftSemanticKernelExperimentalVersion)" />- <PackageVersion Include="Microsoft.SemanticKernel.Connectors.AzureOpenAI" Version="1.29.0" />- <PackageVersion Include="Microsoft.SemanticKernel.Connectors.Qdrant" Version="$(MicrosoftSemanticKernelExperimentalVersion)" />- <PackageVersion Include="Microsoft.SemanticKernel.Plugins.Memory" Version="$(MicrosoftSemanticKernelExperimentalVersion)" />- <PackageVersion Include="Microsoft.SemanticKernel.Plugins.Web" Version="$(MicrosoftSemanticKernelExperimentalVersion)" />+ <PackageVersion Include="Microsoft.SemanticKernel" Version="$(MicrosoftSemanticKernelStableVersion)" />+ <PackageVersion Include="Microsoft.SemanticKernel.Agents.Core" Version="$(MicrosoftSemanticKernelStableVersion)" />+ <PackageVersion Include="Microsoft.SemanticKernel.Connectors.AzureOpenAI" Version="$(MicrosoftSemanticKernelStableVersion)" />+ <PackageVersion Include="Microsoft.SemanticKernel.Connectors.Qdrant" Version="$(MicrosoftSemanticKernelPreviewVersion)" />+ <PackageVersion Include="Microsoft.SemanticKernel.Plugins.Memory" Version="$(MicrosoftSemanticKernelAlphaVersion)" />+ <PackageVersion Include="Microsoft.SemanticKernel.Plugins.Web" Version="$(MicrosoftSemanticKernelAlphaVersion)" /><PackageVersion Include="Microsoft.SourceLink.GitHub" Version="8.0.0" /><PackageVersion Include="Moq" Version="4.20.72" /><PackageVersion Include="Newtonsoft.Json" Version="13.0.3" /><PackageVersion Include="Octokit" Version="13.0.1" /><PackageVersion Include="Octokit.Webhooks.AspNetCore" Version="2.4.1" />- <PackageVersion Include="OpenAI" Version="2.1.0-beta.2" />+ <PackageVersion Include="OpenAI" Version="2.2.0-beta.4" /><PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.10.0" /><PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.10.0" /><PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="$(OpenTelemetryInstrumentation)" />@@ -127,7 +130,7 @@<PackageVersion Include="System.IdentityModel.Tokens.Jwt" Version="8.2.1" /><PackageVersion Include="System.IO.Packaging" Version="9.0.0" /><PackageVersion Include="System.Memory.Data" Version="9.0.0" />- <PackageVersion Include="System.Text.Json" Version="9.0.0" />+ <PackageVersion Include="System.Text.Json" Version="9.0.3" /><PackageVersion Include="xunit" Version="2.9.2" /><PackageVersion Include="xunit.runner.console" Version="2.9.2" /><PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />diff --git a/dotnet/src/AutoGen.Core/Function/FunctionAttribute.cs b/dotnet/src/AutoGen.Core/Function/FunctionAttribute.csindex 9367f5c6f..644c899c1 100644--- a/dotnet/src/AutoGen.Core/Function/FunctionAttribute.cs+++ b/dotnet/src/AutoGen.Core/Function/FunctionAttribute.cs@@ -4,6 +4,8 @@using System;using System.Collections.Generic;using System.Linq;+using System.Reflection;+using System.Text.Json;using System.Text.Json.Serialization;using Microsoft.Extensions.AI;@@ -69,36 +71,48 @@ public class FunctionContract/// </summary>public string? ReturnDescription { get; set; }- public static implicit operator FunctionContract(AIFunctionMetadata metadata)+ public static implicit operator FunctionContract(AIFunction function){- return new FunctionContract+ var openapiScheme = function.JsonSchema;+ var parameters = new List<FunctionParameterContract>();+ string[] isRequiredProperties = [];+ if (openapiScheme.TryGetProperty("required", out var requiredElement)){- Namespace = metadata.AdditionalProperties.ContainsKey(NamespaceKey) ? metadata.AdditionalProperties[NamespaceKey] as string : null,- ClassName = metadata.AdditionalProperties.ContainsKey(ClassNameKey) ? metadata.AdditionalProperties[ClassNameKey] as string : null,- Name = metadata.Name,- Description = metadata.Description,- Parameters = metadata.Parameters?.Select(p => (FunctionParameterContract)p).ToList(),- ReturnType = metadata.ReturnParameter.ParameterType,- ReturnDescription = metadata.ReturnParameter.Description,- };- }+ isRequiredProperties = requiredElement.Deserialize<string[]>() ?? [];+ }- public static implicit operator AIFunctionMetadata(FunctionContract contract)- {- return new AIFunctionMetadata(contract.Name)+ var parameterList = function.UnderlyingMethod?.GetParameters() ?? Array.Empty<ParameterInfo>();++ if (openapiScheme.TryGetProperty("properties", out var propertiesElement)){- Description = contract.Description,- ReturnParameter = new AIFunctionReturnParameterMetadata()+ var properties = propertiesElement.Deserialize<Dictionary<string, JsonElement>>() ?? new Dictionary<string, JsonElement>();+ foreach (var property in properties){- Description = contract.ReturnDescription,- ParameterType = contract.ReturnType,- },- AdditionalProperties = new Dictionary<string, object?>- {- [NamespaceKey] = contract.Namespace,- [ClassNameKey] = contract.ClassName,- },- Parameters = [.. contract.Parameters?.Select(p => (AIFunctionParameterMetadata)p)!],+ var parameterType = parameterList.FirstOrDefault(p => p.Name == property.Key)?.ParameterType;+ var parameter = new FunctionParameterContract+ {+ Name = property.Key,+ ParameterType = parameterType, // TODO: Need to get the type from the schema+ IsRequired = isRequiredProperties.Contains(property.Key),+ };+ if (property.Value.TryGetProperty("description", out var descriptionElement))+ {+ parameter.Description = descriptionElement.GetString();+ }+ if (property.Value.TryGetProperty("default", out var defaultValueElement))+ {+ parameter.DefaultValue = defaultValueElement.Deserialize<object>();+ }+ parameters.Add(parameter);+ }+ }+ return new FunctionContract+ {+ Namespace = function.AdditionalProperties.ContainsKey(NamespaceKey) ? function.AdditionalProperties[NamespaceKey] as string : null,+ ClassName = function.AdditionalProperties.ContainsKey(ClassNameKey) ? function.AdditionalProperties[ClassNameKey] as string : null,+ Name = function.Name,+ Description = function.Description,+ Parameters = parameters,};}}@@ -132,29 +146,4 @@ public class FunctionParameterContract/// The default value of the parameter./// </summary>public object? DefaultValue { get; set; }-- // convert to/from FunctionParameterMetadata- public static implicit operator FunctionParameterContract(AIFunctionParameterMetadata metadata)- {- return new FunctionParameterContract- {- Name = metadata.Name,- Description = metadata.Description,- ParameterType = metadata.ParameterType,- IsRequired = metadata.IsRequired,- DefaultValue = metadata.DefaultValue,- };- }-- public static implicit operator AIFunctionParameterMetadata(FunctionParameterContract contract)- {- return new AIFunctionParameterMetadata(contract.Name!)- {- DefaultValue = contract.DefaultValue,- Description = contract.Description,- IsRequired = contract.IsRequired,- ParameterType = contract.ParameterType,- HasDefaultValue = contract.DefaultValue != null,- };- }}diff --git a/dotnet/src/AutoGen.Core/Middleware/FunctionCallMiddleware.cs b/dotnet/src/AutoGen.Core/Middleware/FunctionCallMiddleware.csindex 266155316..3c68e9545 100644--- a/dotnet/src/AutoGen.Core/Middleware/FunctionCallMiddleware.cs+++ b/dotnet/src/AutoGen.Core/Middleware/FunctionCallMiddleware.cs@@ -53,9 +53,9 @@ public class FunctionCallMiddleware : IStreamingMiddlewarepublic FunctionCallMiddleware(IEnumerable<AIFunction> functions, string? name = null){this.Name = name ?? nameof(FunctionCallMiddleware);- this.functions = functions.Select(f => (FunctionContract)f.Metadata).ToArray();+ this.functions = functions.Select(f => (FunctionContract)f).ToArray();- this.functionMap = functions.Select(f => (f.Metadata.Name, this.AIToolInvokeWrapper(f.InvokeAsync))).ToDictionary(f => f.Name, f => f.Item2);+ this.functionMap = functions.Select(f => (f.Name, this.AIToolInvokeWrapper(f.InvokeAsync))).ToDictionary(f => f.Name, f => f.Item2);}public string? Name { get; }diff --git a/dotnet/src/AutoGen.DotnetInteractive/DotnetInteractiveKernelBuilder.cs b/dotnet/src/AutoGen.DotnetInteractive/DotnetInteractiveKernelBuilder.csindex 98b3e547d..8d1f5ec8f 100644--- a/dotnet/src/AutoGen.DotnetInteractive/DotnetInteractiveKernelBuilder.cs+++ b/dotnet/src/AutoGen.DotnetInteractive/DotnetInteractiveKernelBuilder.cs@@ -14,9 +14,7 @@ public static class DotnetInteractiveKernelBuilderpublic static InProccessDotnetInteractiveKernelBuilder CreateDefaultInProcessKernelBuilder(){- return new InProccessDotnetInteractiveKernelBuilder()- .AddCSharpKernel()- .AddFSharpKernel();+ return new InProccessDotnetInteractiveKernelBuilder();}#endifdiff --git a/dotnet/src/AutoGen.SemanticKernel/SemanticKernelChatCompletionAgent.cs b/dotnet/src/AutoGen.SemanticKernel/SemanticKernelChatCompletionAgent.csindex 947807806..2744bfdce 100644--- a/dotnet/src/AutoGen.SemanticKernel/SemanticKernelChatCompletionAgent.cs+++ b/dotnet/src/AutoGen.SemanticKernel/SemanticKernelChatCompletionAgent.cs@@ -26,8 +26,9 @@ public class SemanticKernelChatCompletionAgent : IAgentpublic async Task<IMessage> GenerateReplyAsync(IEnumerable<IMessage> messages, GenerateReplyOptions? options = null,CancellationToken cancellationToken = default){- ChatMessageContent[] reply = await _chatCompletionAgent- .InvokeAsync(BuildChatHistory(messages), cancellationToken: cancellationToken)+ var agentThread = new ChatHistoryAgentThread(BuildChatHistory(messages));+ var reply = await _chatCompletionAgent+ .InvokeAsync(agentThread, cancellationToken: cancellationToken).ToArrayAsync(cancellationToken: cancellationToken);return reply.Length > 1diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.csindex 97e1d5b76..74edaf3e0 100644--- a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.cs+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.cs@@ -124,7 +124,7 @@ public struct MultiModalData/// <param name="item">The <see cref="AIContent"/> to wrap.</param>/// <returns>A <see cref="MultiModalData"/> instance wrapping the <paramref name="item"/>.</returns>/// <exception cref="ArgumentException">- /// Thrown if the <paramref name="item"/> is not a <see cref="TextContent"/> or <see cref="ImageContent"/>.+ /// Thrown if the <paramref name="item"/> is not a <see cref="TextContent"/> or <see cref="DataContent"/>./// </exception>public static MultiModalData CheckTypeAndCreate(AIContent item){@@ -132,7 +132,7 @@ public struct MultiModalData{return new MultiModalData(text);}- else if (item is ImageContent image)+ else if (item is DataContent image){return new MultiModalData(image);}@@ -163,10 +163,10 @@ public struct MultiModalData}/// <summary>- /// Initializes a new instance of the <see cref="MultiModalData"/> with an <see cref="ImageContent"/>.+ /// Initializes a new instance of the <see cref="MultiModalData"/> with an <see cref="DataContent"/>./// </summary>/// <param name="image">The image to wrap.</param>- public MultiModalData(ImageContent image)+ public MultiModalData(DataContent image){ContentType = Type.Image;AIContent = image;@@ -254,12 +254,12 @@ public class MultiModalMessage : ChatMessage, IList<AIContent>}/// <summary>- /// Adds a range of <see cref="ImageContent"/> to the message.+ /// Adds a range of <see cref="DataContent"/> to the message./// </summary>/// <param name="images">The items to add.</param>- public void AddRange(IEnumerable<ImageContent> images)+ public void AddRange(IEnumerable<DataContent> images){- foreach (ImageContent image in images)+ foreach (DataContent image in images){this.Add(image);}@@ -287,7 +287,7 @@ public class MultiModalMessage : ChatMessage, IList<AIContent>/// Adds a <see cref="TextContent"/> to the message./// </summary>/// <param name="image">The image to add.</param>- public void Add(ImageContent image)+ public void Add(DataContent image){this.Content.Add(new(image));}@@ -374,7 +374,7 @@ public class MultiModalMessage : ChatMessage, IList<AIContent>}/// <inheritdoc cref="IList{ImageContent}.Insert(int, ImageContent)"/>- public void Insert(int index, ImageContent image)+ public void Insert(int index, DataContent image){this.Content.Insert(index, new(image));}@@ -610,7 +610,7 @@ public static class CompletionChatMessageExtensions{contentBuilder.AppendLine(textContent.Text);}- else if (content is ImageContent)+ else if (content is DataContent){contentBuilder.AppendLine("[Image]");}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Tools.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Tools.csindex 1c0c276b7..893c3392b 100644--- a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Tools.cs+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Tools.cs@@ -1,7 +1,6 @@// Copyright (c) Microsoft Corporation. All rights reserved.// Tools.cs-using System.ComponentModel;using System.Reflection;using Microsoft.Extensions.AI;@@ -10,37 +9,6 @@ namespace Microsoft.AutoGen.AgentChat.Abstractions;// TODO: This likely should live as a "Component" in an Agent-building ClassLib?// It seems like it could have applicability beyond AgentChat.-public static class ReflectionExtensions-{- public static AIFunctionParameterMetadata ToAIFunctionMetadata(this ParameterInfo pi)- {- return new AIFunctionParameterMetadata(pi.Name!)- {- Description = pi.GetCustomAttribute<DescriptionAttribute>()?.Description,-- ParameterType = pi.ParameterType,-- HasDefaultValue = pi.HasDefaultValue,- IsRequired = !pi.HasDefaultValue,- DefaultValue = pi.DefaultValue,-- // Schema = JSONSchema of type- };- }-- public static AIFunctionReturnParameterMetadata ToAIFunctionReturnMetadata(this ParameterInfo rpi)- {- return new AIFunctionReturnParameterMetadata- {- Description = rpi.GetCustomAttribute<DescriptionAttribute>()?.Description,-- ParameterType = rpi.ParameterType-- //Schema = JSONSchema of type- };- }-}-public class ParameterSchema(string name, Type type, bool isRequired = false, object? defaultValue = default){public string Name { get; } = name;@@ -54,15 +22,6 @@ public class ParameterSchema(string name, Type type, bool isRequired = false, obType parameterType = parameterInfo.ParameterType;return ParameterSchema<object>.Create(parameterType, parameterInfo.Name!, parameterInfo.HasDefaultValue, parameterInfo.DefaultValue);}-- public static implicit operator ParameterSchema(AIFunctionParameterMetadata parameterMetadata)- {- Type parameterType = parameterMetadata.ParameterType!; // TODO: Deal with missing ParameterTypes- return ParameterSchema<object>.Create(parameterType,- parameterMetadata.Name,- parameterMetadata.IsRequired,- parameterMetadata.DefaultValue);- }}// TODO: Can this be obviated by AIFunctionParameter?@@ -86,7 +45,6 @@ public interface IToolpublic string Description { get; }public IEnumerable<ParameterSchema> Parameters { get; }- public Type ReturnType { get; }// TODO: State serialization@@ -136,18 +94,15 @@ public class AIFunctionTool(AIFunction aiFunction) : IToolpublic AIFunction AIFunction { get; } = aiFunction;/// <inheritdoc cref="ITool.Name" />- public string Name => this.AIFunction.Metadata.Name;+ public string Name => this.AIFunction.Name;/// <inheritdoc cref="ITool.Description" />- public string Description => this.AIFunction.Metadata.Description;+ public string Description => this.AIFunction.Description;/// <inheritdoc cref="ITool.Parameters" />- public IEnumerable<ParameterSchema> Parameters => from rawParameter in this.AIFunction.Metadata.Parameters+ public IEnumerable<ParameterSchema> Parameters => from rawParameter in this.AIFunction.UnderlyingMethod!.GetParameters()select (ParameterSchema)rawParameter;- /// <inheritdoc cref="ITool.ReturnType" />- public Type ReturnType => this.AIFunction.Metadata.ReturnParameter.ParameterType!; // TODO: Deal with missing return types-/// <inheritdoc cref="ITool.ExecuteAsync" />public Task<object> ExecuteAsync(IEnumerable<object> parameters, CancellationToken cancellationToken = default)=> this.ExecuteAsync(parameters, cancellationToken);@@ -164,23 +119,6 @@ public class CallableTool(string name, string description, Delegate callable){internal static AIFunction CreateAIFunction(string name, string description, Delegate callable){- MethodInfo methodInfo = callable.Method;-- IEnumerable<AIFunctionParameterMetadata> parameters =- from parameterInfo in methodInfo.GetParameters()- select parameterInfo.ToAIFunctionMetadata();-- AIFunctionReturnParameterMetadata returnParameter = methodInfo.ReturnParameter.ToAIFunctionReturnMetadata();-- AIFunctionFactoryCreateOptions createOptions = new()- {- Name = name,- Description = description,- Parameters = parameters.ToList(),- ReturnParameter = returnParameter,- // SerializerOptions = TODO: How do we maintain consistency with Python?- };-- return AIFunctionFactory.Create(callable, createOptions);+ return AIFunctionFactory.Create(callable, name: name, description: description);}}diff --git a/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/InferenceAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/InferenceAgent.csindex d3dc10001..8e753766b 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/InferenceAgent.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/InferenceAgent.cs@@ -26,19 +26,19 @@ public abstract class InferenceAgent<T>({protected IChatClient ChatClient { get; } = client;private ILogger<InferenceAgent<T>>? Logger => _logger as ILogger<InferenceAgent<T>>;- private Task<ChatCompletion> CompleteAsync(+ private Task<ChatResponse> CompleteAsync(IList<ChatMessage> chatMessages,ChatOptions? options = null,CancellationToken cancellationToken = default){- return ChatClient.CompleteAsync(chatMessages, options, cancellationToken);+ return ChatClient.GetResponseAsync(chatMessages, options, cancellationToken);}- private IAsyncEnumerable<StreamingChatCompletionUpdate> CompleteStreamingAsync(+ private IAsyncEnumerable<ChatResponseUpdate> CompleteStreamingAsync(IList<ChatMessage> chatMessages,ChatOptions? options = null,CancellationToken cancellationToken = default){- return ChatClient.CompleteStreamingAsync(chatMessages, options, cancellationToken);+ return ChatClient.GetStreamingResponseAsync(chatMessages, options, cancellationToken);}}diff --git a/dotnet/src/Microsoft.AutoGen/Extensions/MEAI/ServiceCollectionChatCompletionExtensions.cs b/dotnet/src/Microsoft.AutoGen/Extensions/MEAI/ServiceCollectionChatCompletionExtensions.csindex 114562993..2b398ac28 100644--- a/dotnet/src/Microsoft.AutoGen/Extensions/MEAI/ServiceCollectionChatCompletionExtensions.cs+++ b/dotnet/src/Microsoft.AutoGen/Extensions/MEAI/ServiceCollectionChatCompletionExtensions.cs@@ -41,12 +41,13 @@ public static class ServiceCollectionChatClientExtensionsFunc<ChatClientBuilder, ChatClientBuilder>? builder = null){uri ??= new Uri("http://localhost:11434");- return services.AddChatClient(pipeline =>+ services.AddChatClient(service =>{- builder?.Invoke(pipeline);- var httpClient = pipeline.Services.GetService<HttpClient>() ?? new();- return pipeline.Use(new OllamaChatClient(uri, modelName, httpClient));+ var httpClient = service.GetService<HttpClient>() ?? new();+ return new OllamaChatClient(uri, modelName, httpClient);});++ return services;}public static IServiceCollection AddOpenAIChatClient(this IHostApplicationBuilder hostBuilder,@@ -81,16 +82,17 @@ public static class ServiceCollectionChatClientExtensionsUri? endpoint = null,Func<ChatClientBuilder, ChatClientBuilder>? builder = null){- return services+ services.AddSingleton(_ => endpoint is null? new OpenAIClient(apiKey): new AzureOpenAIClient(endpoint, new ApiKeyCredential(apiKey)))- .AddChatClient(pipeline =>+ .AddChatClient(service =>{- builder?.Invoke(pipeline);- var openAiClient = pipeline.Services.GetRequiredService<OpenAIClient>();- return pipeline.Use(openAiClient.AsChatClient(modelOrDeploymentName));+ var openAiClient = service.GetRequiredService<OpenAIClient>();+ return openAiClient.AsChatClient(modelOrDeploymentName);});++ return services;}public static IServiceCollection AddAzureChatClient(this IHostApplicationBuilder hostBuilder,@@ -109,12 +111,10 @@ public static class ServiceCollectionChatClientExtensions}var endpoint = $"{serviceName}:Endpoint" ?? throw new InvalidOperationException($"No endpoint was specified for the Azure Inference Chat Client");var endpointUri = string.IsNullOrEmpty(endpoint) ? null : new Uri(endpoint);- return hostBuilder.Services.AddChatClient(pipeline =>- {- builder?.Invoke(pipeline);- var token = Environment.GetEnvironmentVariable("GH_TOKEN") ?? throw new InvalidOperationException("No model access token was found in the environment variable GH_TOKEN");- return pipeline.Use(new ChatCompletionsClient(- endpointUri, new AzureKeyCredential(token)).AsChatClient(modelOrDeploymentName));- });+ var token = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? throw new InvalidOperationException("No model access token was found in the environment variable AZURE_OPENAI_API_KEY");+ var chatClient = new ChatCompletionsClient(endpointUri, new AzureKeyCredential(token)).AsChatClient(modelOrDeploymentName);+ hostBuilder.Services.AddChatClient(chatClient);++ return hostBuilder.Services;}}diff --git a/dotnet/test/AutoGen.OpenAI.Tests/ApprovalTests/OpenAIMessageTests.BasicMessageTest.approved.txt b/dotnet/test/AutoGen.OpenAI.Tests/ApprovalTests/OpenAIMessageTests.BasicMessageTest.approved.txtindex 5b113c3f6..78c374f63 100644--- a/dotnet/test/AutoGen.OpenAI.Tests/ApprovalTests/OpenAIMessageTests.BasicMessageTest.approved.txt+++ b/dotnet/test/AutoGen.OpenAI.Tests/ApprovalTests/OpenAIMessageTests.BasicMessageTest.approved.txt@@ -12,6 +12,12 @@"ImageUri": null,"ImageBytes": null,"ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,"ImageDetailLevel": null,"Refusal": null}@@ -31,6 +37,12 @@"ImageUri": null,"ImageBytes": null,"ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,"ImageDetailLevel": null,"Refusal": null}@@ -57,6 +69,12 @@"ImageUri": null,"ImageBytes": null,"ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,"ImageDetailLevel": null,"Refusal": null}@@ -78,6 +96,12 @@"ImageUri": "https://example.com/image.png","ImageBytes": null,"ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,"ImageDetailLevel": null,"Refusal": null}@@ -104,6 +128,12 @@"ImageUri": null,"ImageBytes": null,"ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,"ImageDetailLevel": null,"Refusal": null},@@ -113,6 +143,12 @@"ImageUri": "https://example.com/image.png","ImageBytes": null,"ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,"ImageDetailLevel": null,"Refusal": null}diff --git a/dotnet/test/AutoGen.OpenAI.Tests/ApprovalTests/OpenAIMessageTests.BasicMessageTest.received.txt b/dotnet/test/AutoGen.OpenAI.Tests/ApprovalTests/OpenAIMessageTests.BasicMessageTest.received.txtnew file mode 100644index 000000000..78c374f63--- /dev/null+++ b/dotnet/test/AutoGen.OpenAI.Tests/ApprovalTests/OpenAIMessageTests.BasicMessageTest.received.txt@@ -0,0 +1,260 @@+[+ {+ "OriginalMessage": "TextMessage(system, You are a helpful AI assistant, )",+ "ConvertedMessages": [+ {+ "Name": null,+ "Role": "system",+ "Content": [+ {+ "Kind": 0,+ "Text": "You are a helpful AI assistant",+ "ImageUri": null,+ "ImageBytes": null,+ "ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,+ "ImageDetailLevel": null,+ "Refusal": null+ }+ ]+ }+ ]+ },+ {+ "OriginalMessage": "TextMessage(user, Hello, user)",+ "ConvertedMessages": [+ {+ "Role": "user",+ "Content": [+ {+ "Kind": 0,+ "Text": "Hello",+ "ImageUri": null,+ "ImageBytes": null,+ "ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,+ "ImageDetailLevel": null,+ "Refusal": null+ }+ ],+ "Name": "user",+ "MultiModaItem": [+ {+ "Type": "Text",+ "Text": "Hello"+ }+ ]+ }+ ]+ },+ {+ "OriginalMessage": "TextMessage(assistant, How can I help you?, assistant)",+ "ConvertedMessages": [+ {+ "Role": "assistant",+ "Content": [+ {+ "Kind": 0,+ "Text": "How can I help you?",+ "ImageUri": null,+ "ImageBytes": null,+ "ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,+ "ImageDetailLevel": null,+ "Refusal": null+ }+ ],+ "Name": "assistant",+ "TooCall": []+ }+ ]+ },+ {+ "OriginalMessage": "ImageMessage(user, https://example.com/image.png, user)",+ "ConvertedMessages": [+ {+ "Role": "user",+ "Content": [+ {+ "Kind": 2,+ "Text": null,+ "ImageUri": "https://example.com/image.png",+ "ImageBytes": null,+ "ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,+ "ImageDetailLevel": null,+ "Refusal": null+ }+ ],+ "Name": "user",+ "MultiModaItem": [+ {+ "Type": "Image",+ "ImageUrl": "https://example.com/image.png"+ }+ ]+ }+ ]+ },+ {+ "OriginalMessage": "MultiModalMessage(assistant, user)\n\tTextMessage(user, Hello, user)\n\tImageMessage(user, https://example.com/image.png, user)",+ "ConvertedMessages": [+ {+ "Role": "user",+ "Content": [+ {+ "Kind": 0,+ "Text": "Hello",+ "ImageUri": null,+ "ImageBytes": null,+ "ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,+ "ImageDetailLevel": null,+ "Refusal": null+ },+ {+ "Kind": 2,+ "Text": null,+ "ImageUri": "https://example.com/image.png",+ "ImageBytes": null,+ "ImageBytesMediaType": null,+ "InputAudioBytes": null,+ "InputAudioFormat": null,+ "FileId": null,+ "FileBytes": null,+ "FileBytesMediaType": null,+ "Filename": null,+ "ImageDetailLevel": null,+ "Refusal": null+ }+ ],+ "Name": "user",+ "MultiModaItem": [+ {+ "Type": "Text",+ "Text": "Hello"+ },+ {+ "Type": "Image",+ "ImageUrl": "https://example.com/image.png"+ }+ ]+ }+ ]+ },+ {+ "OriginalMessage": "ToolCallMessage(assistant)\n\tToolCall(test, test, )",+ "ConvertedMessages": [+ {+ "Role": "assistant",+ "Content": [],+ "Name": null,+ "TooCall": [+ {+ "Type": "Function",+ "Name": "test",+ "Arguments": "dGVzdA==",+ "Id": "test"+ }+ ]+ }+ ]+ },+ {+ "OriginalMessage": "ToolCallResultMessage(user)\n\tToolCall(test, test, result)",+ "ConvertedMessages": [+ {+ "Role": "tool",+ "Content": "result",+ "ToolCallId": "test"+ }+ ]+ },+ {+ "OriginalMessage": "ToolCallResultMessage(user)\n\tToolCall(result, test, test)\n\tToolCall(result, test, test)",+ "ConvertedMessages": [+ {+ "Role": "tool",+ "Content": "test",+ "ToolCallId": "result_0"+ },+ {+ "Role": "tool",+ "Content": "test",+ "ToolCallId": "result_1"+ }+ ]+ },+ {+ "OriginalMessage": "ToolCallMessage(assistant)\n\tToolCall(test, test, )\n\tToolCall(test, test, )",+ "ConvertedMessages": [+ {+ "Role": "assistant",+ "Content": [],+ "Name": null,+ "TooCall": [+ {+ "Type": "Function",+ "Name": "test",+ "Arguments": "dGVzdA==",+ "Id": "test_0"+ },+ {+ "Type": "Function",+ "Name": "test",+ "Arguments": "dGVzdA==",+ "Id": "test_1"+ }+ ]+ }+ ]+ },+ {+ "OriginalMessage": "AggregateMessage(assistant)\n\tToolCallMessage(assistant)\n\tToolCall(test, test, )\n\tToolCallResultMessage(assistant)\n\tToolCall(test, test, result)",+ "ConvertedMessages": [+ {+ "Role": "assistant",+ "Content": [],+ "Name": null,+ "TooCall": [+ {+ "Type": "Function",+ "Name": "test",+ "Arguments": "dGVzdA==",+ "Id": "test"+ }+ ]+ },+ {+ "Role": "tool",+ "Content": "result",+ "ToolCallId": "test"+ }+ ]+ }+]\ No newline at end of filediff --git a/dotnet/test/AutoGen.Tests/Function/FunctionTests.cs b/dotnet/test/AutoGen.Tests/Function/FunctionTests.csindex adb97e1c5..b8024e0a3 100644--- a/dotnet/test/AutoGen.Tests/Function/FunctionTests.cs+++ b/dotnet/test/AutoGen.Tests/Function/FunctionTests.cs@@ -60,7 +60,7 @@ public class FunctionTestsGetWeatherAsyncStatic,];- var functionContracts = availableDelegates.Select(function => (FunctionContract)AIFunctionFactory.Create(function).Metadata).ToList();+ var functionContracts = availableDelegates.Select(function => (FunctionContract)AIFunctionFactory.Create(function)).ToList();// Verify the function contractsfunctionContracts.Should().HaveCount(4);diff --git a/dotnet/test/AutoGen.Tests/Orchestrator/RolePlayOrchestratorTests.cs b/dotnet/test/AutoGen.Tests/Orchestrator/RolePlayOrchestratorTests.csindex 256d704cc..521cd711a 100644--- a/dotnet/test/AutoGen.Tests/Orchestrator/RolePlayOrchestratorTests.cs+++ b/dotnet/test/AutoGen.Tests/Orchestrator/RolePlayOrchestratorTests.cs@@ -18,7 +18,6 @@ using AutoGen.Mistral.Extension;using AutoGen.OpenAI;using AutoGen.OpenAI.Extension;using Azure.AI.Inference;-using Azure.AI.OpenAI;using FluentAssertions;using Moq;using OpenAI;@@ -217,21 +216,6 @@ public class RolePlayOrchestratorTestsspeaker.Should().Be(bob);}- [ApiKeyFact("AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT", "AZURE_OPENAI_DEPLOY_NAME")]- public async Task GPT_3_5_CoderReviewerRunnerTestAsync()- {- var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new Exception("Please set AZURE_OPENAI_ENDPOINT environment variable.");- var key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? throw new Exception("Please set AZURE_OPENAI_API_KEY environment variable.");- var deployName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOY_NAME") ?? throw new Exception("Please set AZURE_OPENAI_DEPLOY_NAME environment variable.");- var openaiClient = new AzureOpenAIClient(new Uri(endpoint), new System.ClientModel.ApiKeyCredential(key));- var openAIChatAgent = new OpenAIChatAgent(- chatClient: openaiClient.GetChatClient(deployName),- name: "assistant")- .RegisterMessageConnector();-- await CoderReviewerRunnerTestAsync(openAIChatAgent);- }-[ApiKeyFact("OPENAI_API_KEY")]public async Task GPT_4o_CoderReviewerRunnerTestAsync(){diff --git a/dotnet/test/AutoGen.Tests/SingleAgentTest.cs b/dotnet/test/AutoGen.Tests/SingleAgentTest.csindex 8611714c3..2f014236c 100644--- a/dotnet/test/AutoGen.Tests/SingleAgentTest.cs+++ b/dotnet/test/AutoGen.Tests/SingleAgentTest.cs@@ -20,11 +20,11 @@ public partial class SingleAgentTest_output = output;}- private ILLMConfig CreateAzureOpenAIGPT35TurboConfig()+ private ILLMConfig CreateAzureOpenAIGPT4oMiniConfig(){var key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? throw new ArgumentException("AZURE_OPENAI_API_KEY is not set");var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new ArgumentException("AZURE_OPENAI_ENDPOINT is not set");- var deployName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOY_NAME") ?? throw new ArgumentException("AZURE_OPENAI_DEPLOY_NAME is not set");+ var deployName = "gpt-4o-mini";return new AzureOpenAIConfig(endpoint, deployName, key);}@@ -37,7 +37,7 @@ public partial class SingleAgentTest[ApiKeyFact("AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT", "AZURE_OPENAI_DEPLOY_NAME")]public async Task AssistantAgentFunctionCallTestAsync(){- var config = this.CreateAzureOpenAIGPT35TurboConfig();+ var config = this.CreateAzureOpenAIGPT4oMiniConfig();var llmConfig = new ConversableAgentConfig{@@ -77,7 +77,7 @@ public partial class SingleAgentTest[ApiKeyFact("AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT", "AZURE_OPENAI_DEPLOY_NAME")]public async Task AssistantAgentFunctionCallSelfExecutionTestAsync(){- var config = this.CreateAzureOpenAIGPT35TurboConfig();+ var config = this.CreateAzureOpenAIGPT4oMiniConfig();var llmConfig = new ConversableAgentConfig{FunctionContracts = new[]diff --git a/dotnet/test/AutoGen.Tests/TwoAgentTest.cs b/dotnet/test/AutoGen.Tests/TwoAgentTest.csindex 8ba4a3fed..ed24dabef 100644--- a/dotnet/test/AutoGen.Tests/TwoAgentTest.cs+++ b/dotnet/test/AutoGen.Tests/TwoAgentTest.cs@@ -32,7 +32,7 @@ public partial class TwoAgentTest{var key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? throw new ArgumentException("AZURE_OPENAI_API_KEY is not set");var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new ArgumentException("AZURE_OPENAI_ENDPOINT is not set");- var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOY_NAME") ?? throw new ArgumentException("AZURE_OPENAI_DEPLOY_NAME is not set");+ var deploymentName = "gpt-4o-mini";var config = new AzureOpenAIConfig(endpoint, deploymentName, key);var assistant = new AssistantAgent(