mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
.NET: Add FoundryAgentFactory which uses AgentClient (#2123)
* Add FoundryAgentFactory which uses AgentClient * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/FoundryAgentFactory.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/FoundryAgentFactory.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/FoundryAgentFactory.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/FoundryAgentFactory.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/FunctionToolExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/FileSearchToolExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/CodeInterpreterToolExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/PromptAgentExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Code review feedback * Add sample showing use of FoundryAgentFactory * Add sample showing use of FoundryAgentFactory * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/CodeInterpreterToolExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/FunctionToolExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/McpServerToolExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/CodeInterpreterToolExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/FileSearchToolExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/WebSearchToolExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/Extensions/PromptAgentExtensions.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Fix issue to get FoundryAgentFactory sample working * Run dotnet format * Undo changes made by dotnet format * Update dotnet/src/Microsoft.Agents.AI.Declarative.AzureAI/FoundryAgentFactory.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
Unverified
parent
faf648e7da
commit
f74131ef61
@@ -86,6 +86,7 @@
|
||||
<Project Path="samples/GettingStarted/DeclarativeAgents/Azure/DeclarativeAzureAgents.csproj" />
|
||||
<Project Path="samples/GettingStarted/DeclarativeAgents/ChatClient/DeclarativeChatClientAgents.csproj" />
|
||||
<Project Path="samples/GettingStarted/DeclarativeAgents/Foundry/DeclarativeFoundryAgents.csproj" />
|
||||
<Project Path="samples/GettingStarted/DeclarativeAgents/FoundryPersistent/DeclarativeFoundryPersistentAgents.csproj" />
|
||||
<Project Path="samples/GettingStarted/DeclarativeAgents/OpenAI/DeclarativeOpenAIAgents.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/GettingStarted/AgentWithRAG/">
|
||||
|
||||
@@ -16,7 +16,7 @@ const string JokerName = "JokerAgent";
|
||||
var agentsClient = new AgentClient(new Uri(endpoint), new AzureCliCredential());
|
||||
|
||||
// Define the agent you want to create. (Prompt Agent in this case)
|
||||
var agentVersionCreationOptions = new AgentVersionCreationOptions(new PromptAgentDefinition(model: deploymentName) { Instructions = JokerInstructions });
|
||||
var agentVersionCreationOptions = new AgentVersionCreationOptions(new PromptAgentDefinition(model: deploymentName) { Instructions = JokerInstructions, Temperature = 0.9f });
|
||||
// Azure.AI.Agents SDK creates and manages agent by name and versions.
|
||||
// You can create a server side agent version with the Azure.AI.Agents SDK client below.
|
||||
var agentVersion = agentsClient.CreateAgentVersion(agentName: JokerName, options: agentVersionCreationOptions);
|
||||
@@ -39,12 +39,14 @@ var latestVersion = jokerAgentLatest.GetService<AgentVersion>()!;
|
||||
// The AIAgent version can be accessed via the GetService method.
|
||||
Console.WriteLine($"Latest agent version id: {latestVersion.Id}");
|
||||
|
||||
var options = new ChatClientAgentRunOptions();
|
||||
|
||||
// Once you have the AIAgent, you can invoke it like any other AIAgent.
|
||||
AgentThread thread = jokerAgentLatest.GetNewThread();
|
||||
Console.WriteLine(await jokerAgentLatest.RunAsync("Tell me a joke about a pirate.", thread));
|
||||
Console.WriteLine(await jokerAgentLatest.RunAsync("Tell me a joke about a pirate.", thread, options));
|
||||
|
||||
// This will use the same thread to continue the conversation.
|
||||
Console.WriteLine(await jokerAgentLatest.RunAsync("Now tell me a joke about a cat and a dog using last joke as the anchor.", thread));
|
||||
Console.WriteLine(await jokerAgentLatest.RunAsync("Now tell me a joke about a cat and a dog using last joke as the anchor.", thread, options));
|
||||
|
||||
// Cleanup by agent name removes both agent versions created (jokerAgentV1 + jokerAgentV2).
|
||||
agentsClient.DeleteAgent(jokerAgentV1.Name);
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
|
||||
// This sample shows how to load an AI agent from a YAML file and process a prompt using Foundry Agents as the backend.
|
||||
|
||||
using System.ComponentModel;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
var endpoint = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_FOUNDRY_PROJECT_ENDPOINT is not set.");
|
||||
@@ -40,22 +38,9 @@ IConfiguration configuration = new ConfigurationBuilder()
|
||||
})
|
||||
.Build();
|
||||
|
||||
// Example function tool that can be used by the agent.
|
||||
[Description("Get the weather for a given location.")]
|
||||
static string GetWeather(
|
||||
[Description("The city and state, e.g. San Francisco, CA")] string location,
|
||||
[Description("The unit of temperature. Possible values are 'celsius' and 'fahrenheit'.")] string unit)
|
||||
=> $"The weather in {location} is cloudy with a high of {(unit.Equals("celsius", StringComparison.Ordinal) ? "15°C" : "59°F")}.";
|
||||
|
||||
// Create the agent from the YAML definition.
|
||||
var agentFactory = new FoundryPersistentAgentFactory(new AzureCliCredential(), configuration);
|
||||
var agentFactory = new FoundryAgentFactory(new AzureCliCredential(), configuration);
|
||||
var agent = await agentFactory.CreateFromYamlAsync(text);
|
||||
|
||||
// Create agent run options
|
||||
var options = new ChatClientAgentRunOptions(new()
|
||||
{
|
||||
Tools = [AIFunctionFactory.Create(GetWeather, name: nameof(GetWeather))]
|
||||
});
|
||||
|
||||
// Invoke the agent and output the text result.
|
||||
Console.WriteLine(await agent!.RunAsync(prompt, options: options));
|
||||
Console.WriteLine(await agent!.RunAsync(prompt));
|
||||
|
||||
+2
-6
@@ -1,12 +1,8 @@
|
||||
{
|
||||
"profiles": {
|
||||
"PersistentAgent": {
|
||||
"FoundryAgent": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "..\\..\\..\\..\\..\\..\\..\\..\\agent-samples\\foundry\\PersistentAgent.yaml \"What is the weather in Cambridge, MA in °C?\""
|
||||
},
|
||||
"MicrosoftLearnAgent": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "..\\..\\..\\..\\..\\..\\..\\..\\agent-samples\\foundry\\MicrosoftLearnAgent.yaml \"Tell me a joke about a pirate in Italian.\""
|
||||
"commandLineArgs": "..\\..\\..\\..\\..\\..\\..\\..\\agent-samples\\foundry\\FoundryAgent.yaml \"Tell me a recipe for chocolate chip cookies?\""
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="Azure.AI.Agents.Persistent" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Bot.ObjectModel" />
|
||||
<PackageReference Include="Microsoft.Bot.ObjectModel.Json" />
|
||||
<PackageReference Include="Microsoft.Bot.ObjectModel.PowerFx" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Declarative.AzureAI\Microsoft.Agents.AI.Declarative.AzureAI.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,61 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// This sample shows how to load an AI agent from a YAML file and process a prompt using Foundry Agents as the backend.
|
||||
|
||||
using System.ComponentModel;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
var endpoint = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_FOUNDRY_PROJECT_ENDPOINT is not set.");
|
||||
|
||||
// Read command-line arguments
|
||||
if (args.Length < 2)
|
||||
{
|
||||
Console.WriteLine("Usage: DeclarativeAgents <yaml-file-path> <prompt>");
|
||||
Console.WriteLine(" <yaml-file-path>: The path to the YAML file containing the agent definition");
|
||||
Console.WriteLine(" <prompt>: The prompt to send to the agent");
|
||||
return;
|
||||
}
|
||||
|
||||
var yamlFilePath = args[0];
|
||||
var prompt = args[1];
|
||||
|
||||
// Verify the YAML file exists
|
||||
if (!File.Exists(yamlFilePath))
|
||||
{
|
||||
Console.WriteLine($"Error: File not found: {yamlFilePath}");
|
||||
return;
|
||||
}
|
||||
|
||||
// Read the YAML content from the file
|
||||
var text = await File.ReadAllTextAsync(yamlFilePath);
|
||||
|
||||
// Set up configuration with the Azure Foundry project endpoint
|
||||
IConfiguration configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["AZURE_FOUNDRY_PROJECT_ENDPOINT"] = endpoint
|
||||
})
|
||||
.Build();
|
||||
|
||||
// Example function tool that can be used by the agent.
|
||||
[Description("Get the weather for a given location.")]
|
||||
static string GetWeather(
|
||||
[Description("The city and state, e.g. San Francisco, CA")] string location,
|
||||
[Description("The unit of temperature. Possible values are 'celsius' and 'fahrenheit'.")] string unit)
|
||||
=> $"The weather in {location} is cloudy with a high of {(unit.Equals("celsius", StringComparison.Ordinal) ? "15°C" : "59°F")}.";
|
||||
|
||||
// Create the agent from the YAML definition.
|
||||
var agentFactory = new FoundryPersistentAgentFactory(new AzureCliCredential(), configuration);
|
||||
var agent = await agentFactory.CreateFromYamlAsync(text);
|
||||
|
||||
// Create agent run options
|
||||
var options = new ChatClientAgentRunOptions(new()
|
||||
{
|
||||
Tools = [AIFunctionFactory.Create(GetWeather, name: nameof(GetWeather))]
|
||||
});
|
||||
|
||||
// Invoke the agent and output the text result.
|
||||
Console.WriteLine(await agent!.RunAsync(prompt, options: options));
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"profiles": {
|
||||
"FoundryAgent": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "..\\..\\..\\..\\..\\..\\..\\..\\agent-samples\\foundry\\FoundryAgent.yaml \"What is the weather in Cambridge, MA in °C?\""
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -23,6 +23,21 @@ internal static class CodeInterpreterToolExtensions
|
||||
return new CodeInterpreterToolDefinition();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="CodeInterpreterTool"/> to an <see cref="OpenAI.Responses.CodeInterpreterTool"/>.
|
||||
/// </summary>
|
||||
/// <param name="tool">Instance of <see cref="CodeInterpreterTool"/></param>
|
||||
/// <returns>A new <see cref="OpenAI.Responses.CodeInterpreterTool"/> instance configured with the container ID from the tool's extension data.</returns>
|
||||
internal static OpenAI.Responses.CodeInterpreterTool CreateCodeInterpreterTool(this CodeInterpreterTool tool)
|
||||
{
|
||||
Throw.IfNull(tool);
|
||||
|
||||
var containerId = tool.ExtensionData?.GetPropertyOrNull<StringDataValue>(InitializablePropertyPath.Create("containerId"))?.Value;
|
||||
Throw.IfNull(containerId, "The 'containerId' property must be specified in the CodeInterpreterTool's extension data to create a code interpreter tool.");
|
||||
|
||||
return new OpenAI.Responses.CodeInterpreterTool(new OpenAI.Responses.CodeInterpreterToolContainer(containerId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collects the file IDs from the extension data of a <see cref="CodeInterpreterTool"/>.
|
||||
/// </summary>
|
||||
|
||||
+12
@@ -25,6 +25,18 @@ internal static class FileSearchToolExtensions
|
||||
return new FileSearchToolDefinition();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="OpenAI.Responses.FileSearchTool"/> from a <see cref="FileSearchTool"/>.
|
||||
/// </summary>
|
||||
/// <param name="tool">Instance of <see cref="FileSearchTool"/></param>
|
||||
/// <returns>A new <see cref="OpenAI.Responses.FileSearchTool"/> instance configured with the vector store IDs.</returns>
|
||||
internal static OpenAI.Responses.FileSearchTool CreateFileSearchTool(this FileSearchTool tool)
|
||||
{
|
||||
Throw.IfNull(tool);
|
||||
|
||||
return new OpenAI.Responses.FileSearchTool(tool.GetVectorStoreIds());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the vector store IDs for the specified <see cref="FileSearchTool"/>.
|
||||
/// </summary>
|
||||
|
||||
+22
@@ -3,6 +3,7 @@
|
||||
using System;
|
||||
using Azure.AI.Agents.Persistent;
|
||||
using Microsoft.Shared.Diagnostics;
|
||||
using OpenAI.Responses;
|
||||
|
||||
namespace Microsoft.Bot.ObjectModel;
|
||||
|
||||
@@ -28,6 +29,27 @@ public static class FunctionToolExtensions
|
||||
parameters: parameters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="FunctionTool"/> from a <see cref="InvokeClientTaskAction"/>.
|
||||
/// </summary>
|
||||
/// <param name="tool">Instance of <see cref="InvokeClientTaskAction"/></param>
|
||||
/// <returns>A new <see cref="FunctionTool"/> instance configured with the function name, parameters, and description.</returns>
|
||||
internal static FunctionTool CreateFunctionTool(this InvokeClientTaskAction tool)
|
||||
{
|
||||
Throw.IfNull(tool);
|
||||
Throw.IfNull(tool.Name);
|
||||
|
||||
BinaryData parameters = tool.GetParameters();
|
||||
|
||||
return new FunctionTool(
|
||||
functionName: tool.Name,
|
||||
functionParameters: parameters,
|
||||
strictModeEnabled: null)
|
||||
{
|
||||
FunctionDescription = tool.Description
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the parameters schema for a <see cref="InvokeClientTaskAction"/>.
|
||||
/// </summary>
|
||||
|
||||
+22
-1
@@ -3,6 +3,7 @@
|
||||
using System;
|
||||
using Azure.AI.Agents.Persistent;
|
||||
using Microsoft.Shared.Diagnostics;
|
||||
using OpenAI.Responses;
|
||||
|
||||
namespace Microsoft.Bot.ObjectModel;
|
||||
|
||||
@@ -23,10 +24,30 @@ internal static class McpServerToolExtensions
|
||||
|
||||
// TODO: Add support for additional properties
|
||||
|
||||
var connection = tool.Connection as AnonymousConnection ?? throw new ArgumentException("Only AnonymousConnection is supported for MCP Server Tool connections.", nameof(tool));
|
||||
var connection = tool.Connection as AnonymousConnection ?? throw new ArgumentException($"Only AnonymousConnection is supported for MCP Server Tool connections. Actual connection type: {tool.Connection.GetType().Name}", nameof(tool));
|
||||
var serverUrl = connection.Endpoint?.LiteralValue;
|
||||
Throw.IfNullOrEmpty(serverUrl, nameof(connection.Endpoint));
|
||||
|
||||
return new MCPToolDefinition(tool.ServerName?.LiteralValue, serverUrl);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="McpTool"/> from a <see cref="McpServerTool"/>.
|
||||
/// </summary>
|
||||
/// <param name="tool">Instance of <see cref="McpServerTool"/></param>
|
||||
/// <returns>A new <see cref="McpTool"/> instance configured with the server name and URL.</returns>
|
||||
internal static McpTool CreateMcpTool(this McpServerTool tool)
|
||||
{
|
||||
Throw.IfNull(tool);
|
||||
Throw.IfNull(tool.ServerName?.LiteralValue);
|
||||
Throw.IfNull(tool.Connection);
|
||||
|
||||
// TODO: Add support for headers
|
||||
|
||||
var connection = tool.Connection as AnonymousConnection ?? throw new ArgumentException("Only AnonymousConnection is supported for MCP Server Tool connections.", nameof(tool));
|
||||
var serverUrl = connection.Endpoint?.LiteralValue;
|
||||
Throw.IfNullOrEmpty(serverUrl, nameof(connection.Endpoint));
|
||||
|
||||
return new McpTool(tool.ServerName?.LiteralValue, serverUrl);
|
||||
}
|
||||
}
|
||||
|
||||
+33
-5
@@ -4,6 +4,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Azure.AI.Agents.Persistent;
|
||||
using Microsoft.Shared.Diagnostics;
|
||||
using OpenAI.Responses;
|
||||
|
||||
namespace Microsoft.Bot.ObjectModel;
|
||||
|
||||
@@ -24,11 +25,11 @@ internal static class PromptAgentExtensions
|
||||
{
|
||||
return tool switch
|
||||
{
|
||||
CodeInterpreterTool => ((CodeInterpreterTool)tool).CreateCodeInterpreterToolDefinition(),
|
||||
InvokeClientTaskAction => ((InvokeClientTaskAction)tool).CreateFunctionToolDefinition(),
|
||||
FileSearchTool => ((FileSearchTool)tool).CreateFileSearchToolDefinition(),
|
||||
WebSearchTool => ((WebSearchTool)tool).CreateBingGroundingToolDefinition(),
|
||||
McpServerTool => ((McpServerTool)tool).CreateMcpToolDefinition(),
|
||||
CodeInterpreterTool codeInterpreterTool => codeInterpreterTool.CreateCodeInterpreterToolDefinition(),
|
||||
InvokeClientTaskAction functionTool => functionTool.CreateFunctionToolDefinition(),
|
||||
FileSearchTool fileSearchTool => fileSearchTool.CreateFileSearchToolDefinition(),
|
||||
WebSearchTool webSearchTool => webSearchTool.CreateBingGroundingToolDefinition(),
|
||||
McpServerTool mcpServerTool => mcpServerTool.CreateMcpToolDefinition(),
|
||||
// TODO: Add other tool types as custom tools
|
||||
// AzureAISearch
|
||||
// AzureFunction
|
||||
@@ -65,6 +66,33 @@ internal static class PromptAgentExtensions
|
||||
return toolResources;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the Foundry response tools which correspond with the provided <see cref="GptComponentMetadata"/>.
|
||||
/// </summary>
|
||||
/// <param name="promptAgent">Instance of <see cref="GptComponentMetadata"/>.</param>
|
||||
/// <returns>A collection of <see cref="ResponseTool"/> instances corresponding to the tools defined in the agent.</returns>
|
||||
internal static IEnumerable<ResponseTool> GetResponseTools(this GptComponentMetadata promptAgent)
|
||||
{
|
||||
Throw.IfNull(promptAgent);
|
||||
|
||||
return promptAgent.Tools.Select<TaskAction, ResponseTool>(tool =>
|
||||
{
|
||||
return tool switch
|
||||
{
|
||||
CodeInterpreterTool codeInterpreterTool => codeInterpreterTool.CreateCodeInterpreterTool(),
|
||||
InvokeClientTaskAction functionTool => functionTool.CreateFunctionTool(),
|
||||
FileSearchTool fileSearchTool => fileSearchTool.CreateFileSearchTool(),
|
||||
WebSearchTool webSearchTool => webSearchTool.CreateWebSearchTool(),
|
||||
McpServerTool mcpServerTool => mcpServerTool.CreateMcpTool(),
|
||||
// TODO: Add other tool types as custom tools
|
||||
// AzureAISearch
|
||||
// AzureFunction
|
||||
// OpenApi
|
||||
_ => throw new NotSupportedException($"Unable to create response tool because of unsupported tool type: {tool.Kind}"),
|
||||
};
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
#region private
|
||||
private static CodeInterpreterToolResource? GetCodeInterpreterToolResource(this GptComponentMetadata promptAgent)
|
||||
{
|
||||
|
||||
+12
@@ -23,4 +23,16 @@ internal static class WebSearchToolExtensions
|
||||
|
||||
return new BingGroundingToolDefinition(parameters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="OpenAI.Responses.WebSearchTool"/> from a <see cref="WebSearchTool"/>.
|
||||
/// </summary>
|
||||
/// <param name="tool">Instance of <see cref="WebSearchTool"/></param>
|
||||
/// <returns>A new <see cref="OpenAI.Responses.WebSearchTool"/> instance.</returns>
|
||||
internal static OpenAI.Responses.WebSearchTool CreateWebSearchTool(this WebSearchTool tool)
|
||||
{
|
||||
Throw.IfNull(tool);
|
||||
|
||||
return new OpenAI.Responses.WebSearchTool();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Azure.AI.Agents;
|
||||
using Azure.AI.Agents.Persistent;
|
||||
using Azure.Core;
|
||||
using Microsoft.Bot.ObjectModel;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Shared.Diagnostics;
|
||||
|
||||
namespace Microsoft.Agents.AI;
|
||||
|
||||
/// <summary>
|
||||
/// Provides an <see cref="AgentFactory"/> which creates instances of <see cref="AIAgent"/> using a <see cref="AgentClient"/>.
|
||||
/// </summary>
|
||||
public sealed class FoundryAgentFactory : AgentFactory
|
||||
{
|
||||
private readonly AgentClient? _agentClient;
|
||||
private readonly TokenCredential? _tokenCredential;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FoundryAgentFactory"/> class with an associated <see cref="AgentClient"/>.
|
||||
/// </summary>
|
||||
/// <param name="agentClient">The <see cref="AgentClient"/> instance to use for creating agents.</param>
|
||||
/// <param name="configuration">The <see cref="IConfiguration"/> instance to use for configuration.</param>
|
||||
public FoundryAgentFactory(AgentClient agentClient, IConfiguration? configuration = null) : base(configuration)
|
||||
{
|
||||
Throw.IfNull(agentClient);
|
||||
|
||||
this._agentClient = agentClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FoundryAgentFactory"/> class with an associated <see cref="TokenCredential"/>.
|
||||
/// </summary>
|
||||
/// <param name="tokenCredential">The <see cref="TokenCredential"/> to use for authenticating requests.</param>
|
||||
/// <param name="configuration">The <see cref="IConfiguration"/> instance to use for configuration.</param>
|
||||
public FoundryAgentFactory(TokenCredential tokenCredential, IConfiguration? configuration = null) : base(configuration)
|
||||
{
|
||||
Throw.IfNull(tokenCredential);
|
||||
|
||||
this._tokenCredential = tokenCredential;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task<AIAgent?> TryCreateAsync(GptComponentMetadata promptAgent, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Throw.IfNull(promptAgent);
|
||||
|
||||
var agentClient = this._agentClient ?? this.CreateAgentClient(promptAgent);
|
||||
|
||||
var modelId = promptAgent.Model?.ModelNameHint;
|
||||
if (string.IsNullOrEmpty(modelId))
|
||||
{
|
||||
throw new InvalidOperationException("The model id must be specified in the agent definition model to create a foundry agent.");
|
||||
}
|
||||
|
||||
var modelOptions = promptAgent.Model?.Options;
|
||||
|
||||
var promptAgentDefinition = new PromptAgentDefinition(model: modelId)
|
||||
{
|
||||
Instructions = promptAgent.Instructions?.ToTemplateString(),
|
||||
Temperature = (float?)modelOptions?.Temperature?.LiteralValue,
|
||||
TopP = (float?)modelOptions?.TopP?.LiteralValue,
|
||||
};
|
||||
|
||||
foreach (var tool in promptAgent.GetResponseTools())
|
||||
{
|
||||
promptAgentDefinition.Tools.Add(tool);
|
||||
}
|
||||
|
||||
var agentVersionCreationOptions = new AgentVersionCreationOptions(promptAgentDefinition);
|
||||
|
||||
var metadata = promptAgent.Metadata?.ToDictionary();
|
||||
if (metadata is not null)
|
||||
{
|
||||
foreach (var kvp in metadata)
|
||||
{
|
||||
agentVersionCreationOptions.Metadata.Add(kvp.Key, kvp.Value);
|
||||
}
|
||||
}
|
||||
|
||||
var agentVersion = await agentClient.CreateAgentVersionAsync(agentName: promptAgent.Name, options: agentVersionCreationOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return agentClient.GetAIAgent(agentVersion, cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
private AgentClient CreateAgentClient(GptComponentMetadata promptAgent)
|
||||
{
|
||||
var externalModel = promptAgent.Model as CurrentModels;
|
||||
var connection = externalModel?.Connection as RemoteConnection;
|
||||
if (connection is not null)
|
||||
{
|
||||
var endpoint = connection.Endpoint?.Eval(this.Engine);
|
||||
if (string.IsNullOrEmpty(endpoint))
|
||||
{
|
||||
throw new InvalidOperationException("The endpoint must be specified in the agent definition model connection to create an AgentClient.");
|
||||
}
|
||||
|
||||
if (this._tokenCredential is null)
|
||||
{
|
||||
throw new InvalidOperationException("A TokenCredential must be registered in the service provider to create an AgentClient.");
|
||||
}
|
||||
|
||||
return new AgentClient(new Uri(endpoint), this._tokenCredential);
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("An AgentClient must be registered in the service provider or a RemoteConnection must be specified in the agent definition model connection to create an AgentClient.");
|
||||
}
|
||||
}
|
||||
@@ -19,8 +19,10 @@ public sealed class FoundryPersistentAgentFactory : AgentFactory
|
||||
private readonly TokenCredential? _tokenCredential;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FoundryPersistentAgentFactory"/> class.
|
||||
/// Creates a new instance of the <see cref="FoundryPersistentAgentFactory"/> class with an associated <see cref="PersistentAgentsClient"/>.
|
||||
/// </summary>
|
||||
/// <param name="agentClient">The <see cref="PersistentAgentsClient"/> instance to use for creating agents.</param>
|
||||
/// <param name="configuration">The <see cref="IConfiguration"/> instance to use for configuration.</param>
|
||||
public FoundryPersistentAgentFactory(PersistentAgentsClient agentClient, IConfiguration? configuration = null) : base(configuration)
|
||||
{
|
||||
Throw.IfNull(agentClient);
|
||||
@@ -29,8 +31,10 @@ public sealed class FoundryPersistentAgentFactory : AgentFactory
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FoundryPersistentAgentFactory"/> class.
|
||||
/// Creates a new instance of the <see cref="FoundryPersistentAgentFactory"/> class with an associated <see cref="TokenCredential"/>.
|
||||
/// </summary>
|
||||
/// <param name="tokenCredential">The <see cref="TokenCredential"/> to use for authenticating requests.</param>
|
||||
/// <param name="configuration">The <see cref="IConfiguration"/> instance to use for configuration.</param>
|
||||
public FoundryPersistentAgentFactory(TokenCredential tokenCredential, IConfiguration? configuration = null) : base(configuration)
|
||||
{
|
||||
Throw.IfNull(tokenCredential);
|
||||
|
||||
+3
-1
@@ -24,6 +24,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="Azure.AI.Agents" />
|
||||
<PackageReference Include="Azure.AI.OpenAI" />
|
||||
<PackageReference Include="System.Diagnostics.DiagnosticSource" />
|
||||
<PackageReference Include="Azure.AI.Agents.Persistent" />
|
||||
@@ -31,7 +32,7 @@
|
||||
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
|
||||
<PackageReference Include="Microsoft.Bot.ObjectModel" />
|
||||
<PackageReference Include="Microsoft.Bot.ObjectModel.Json" />
|
||||
<PackageReference Include="Microsoft.Bot.ObjectModel.PowerFx" />
|
||||
<PackageReference Include="Microsoft.Bot.ObjectModel.PowerFx" />
|
||||
<PackageReference Include="Microsoft.PowerFx.Interpreter" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
</ItemGroup>
|
||||
@@ -39,6 +40,7 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Microsoft.Agents.AI.Abstractions\Microsoft.Agents.AI.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\Microsoft.Agents.AI.AzureAI.Persistent\Microsoft.Agents.AI.AzureAI.Persistent.csproj" />
|
||||
<ProjectReference Include="..\Microsoft.Agents.AI.AzureAI\Microsoft.Agents.AI.AzureAI.csproj" />
|
||||
<ProjectReference Include="..\Microsoft.Agents.AI.Declarative\Microsoft.Agents.AI.Declarative.csproj" />
|
||||
<ProjectReference Include="..\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -7,7 +7,6 @@ using Microsoft.Bot.ObjectModel;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.PowerFx;
|
||||
using Microsoft.PowerFx.Types;
|
||||
|
||||
namespace Microsoft.Agents.AI.Declarative.UnitTests;
|
||||
|
||||
|
||||
+4
-4
@@ -19,7 +19,7 @@ public sealed class ChatClientAgentFactoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TryCreateAsync_WithChatClientInConstructor_CreatesAgent()
|
||||
public async Task TryCreateAsync_WithChatClientInConstructor_CreatesAgentAsync()
|
||||
{
|
||||
// Arrange
|
||||
var promptAgent = PromptAgents.CreateTestPromptAgent();
|
||||
@@ -36,7 +36,7 @@ public sealed class ChatClientAgentFactoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TryCreateAsync_Creates_ChatClientAgent()
|
||||
public async Task TryCreateAsync_Creates_ChatClientAgentAsync()
|
||||
{
|
||||
// Arrange
|
||||
var promptAgent = PromptAgents.CreateTestPromptAgent();
|
||||
@@ -56,7 +56,7 @@ public sealed class ChatClientAgentFactoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TryCreateAsync_Creates_ChatOptions()
|
||||
public async Task TryCreateAsync_Creates_ChatOptionsAsync()
|
||||
{
|
||||
// Arrange
|
||||
var promptAgent = PromptAgents.CreateTestPromptAgent();
|
||||
@@ -87,7 +87,7 @@ public sealed class ChatClientAgentFactoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TryCreateAsync_Creates_Tools()
|
||||
public async Task TryCreateAsync_Creates_ToolsAsync()
|
||||
{
|
||||
// Arrange
|
||||
var promptAgent = PromptAgents.CreateTestPromptAgent();
|
||||
|
||||
Reference in New Issue
Block a user