Files
agent-framework/dotnet/tests/Foundry.IntegrationTests/FoundryVersionedAgentFixture.cs
T
Roger Barreto 628bb1af48 .NET: Rename Microsoft.Agents.AI.AzureAI to Microsoft.Agents.AI.Foundry and consolidate FoundryMemory (#5042)
* Update Foundry Responses as ChatClientAgent

* Migrate obsolete AzureAI integration tests to versioned agent pattern

Replace obsolete CreateAIAgentAsync/GetAIAgentAsync calls with
Agents.CreateAgentVersionAsync() + AsAIAgent(AgentVersion) in all
AzureAI integration tests.

- Rename AIProjectClient* test files to FoundryVersionedAgent*
- Register AIFunction tools in PromptAgentDefinition.Tools for
  server-side visibility via AsOpenAIResponseTool()
- Skip structured output tests (AzureAIProjectChatClient clears
  ResponseFormat for versioned agents)
- Remove all [Obsolete] attributes and #pragma warning disable CS0618

* Merge FoundryMemory package into AzureAI under Memory/ folder

Move all FoundryMemory source, unit tests, and integration tests into
the Microsoft.Agents.AI.AzureAI package. Change namespace from
Microsoft.Agents.AI.FoundryMemory to Microsoft.Agents.AI.AzureAI.

- Add [Experimental] to FoundryMemoryProviderOptions and Scope
- Rename internal AIProjectClientExtensions to MemoryStoreExtensions
- Update AzureAI .csproj with Compliance.Abstractions, Redaction
- Remove FoundryMemory from solution and release filter
- Update sample to reference AzureAI instead of FoundryMemory
- Delete old Microsoft.Agents.AI.FoundryMemory project and tests

* Add EnsureMemoryStoreCreatedAsync and memory existence checks to integration tests

- Ensure memory store is created before testing memory operations
- Add AZURE_AI_EMBEDDING_DEPLOYMENT_NAME config setting
- Assert memories exist in store via SearchMemoriesAsync before cleanup
- Verify scope isolation with direct memory store queries

* Fix and rename AzureAI unit tests for RAPI vs Versioned clarity

- Rename AsAIAgentAsync_* to AsAIAgent_* (drop Async from method group)
- Add _Rapi_ prefix to non-versioned (Responses API) tests
- Add _Versioned_ prefix to versioned agent tests where needed
- Fix RAPI tests: assert GetService<AIProjectClient>() is null
- Fix Versioned tests: assert IsType<FoundryAgent> and
  GetService<AIProjectClient>() returns the client instance
- Fix UserAgent header tests: proper HTTP handler routing
- Fix ChatClient_UsesDefaultConversationIdAsync test setup
- All 153 unit tests pass with 0 failures

* Rename Microsoft.Agents.AI.AzureAI to Microsoft.Agents.AI.Foundry

Rename the project, namespace, folder, and all references from
Microsoft.Agents.AI.AzureAI to Microsoft.Agents.AI.Foundry.
Also rename Workflows.Declarative.AzureAI to .Foundry.

- Rename src, unit test, integration test, and workflow folders
- Update namespaces in all source and test .cs files
- Update ProjectReferences in ~47 sample and test .csproj files
- Update solution files (.slnx, .slnf)
- Update sample using statements
- Update READMEs, SKILL.md, ADRs in docs/
- Disable package validation baseline for renamed packages
- Fix UTF-8 BOM encoding on all affected .cs files
- AzureAI.Persistent left completely unchanged

* Fix format: remove ImplicitUsings, add explicit usings, fix BOM encoding

- Remove ImplicitUsings=enable from Foundry csproj to resolve IDE0005
  on shared ReplacingRedactor.cs
- Add explicit System usings to all source files that relied on them
- Sort usings alphabetically per editorconfig rules
- Fix UTF-8 BOM on 12 sample Program.cs files
- Rename Azure AI Foundry Agents to Microsoft Foundry Agents in docs
2026-04-02 01:25:24 +00:00

243 lines
9.7 KiB
C#

// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AgentConformance.IntegrationTests;
using AgentConformance.IntegrationTests.Support;
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry;
using Microsoft.Extensions.AI;
using OpenAI.Responses;
using Shared.IntegrationTests;
namespace Foundry.IntegrationTests;
/// <summary>
/// Integration test fixture that creates versioned Foundry agents via
/// <c>AIProjectClient.Agents.CreateAgentVersionAsync</c> and wraps them
/// with <c>AIProjectClient.AsAIAgent(AgentVersion)</c>.
/// </summary>
public class FoundryVersionedAgentFixture : IChatClientAgentFixture
{
private FoundryAgent _agent = null!;
private AIProjectClient _client = null!;
public IChatClient ChatClient => this._agent.GetService<ChatClientAgent>()!.ChatClient;
public AIAgent Agent => this._agent;
public async Task<string> CreateConversationAsync()
{
var response = await this._client.GetProjectOpenAIClient().GetProjectConversationsClient().CreateProjectConversationAsync();
return response.Value.Id;
}
public async Task<List<ChatMessage>> GetChatHistoryAsync(AIAgent agent, AgentSession session)
{
var chatClientSession = (ChatClientAgentSession)session;
if (chatClientSession.ConversationId?.StartsWith("conv_", StringComparison.OrdinalIgnoreCase) == true)
{
return await this.GetChatHistoryFromConversationAsync(chatClientSession.ConversationId);
}
if (chatClientSession.ConversationId?.StartsWith("resp_", StringComparison.OrdinalIgnoreCase) == true)
{
return await this.GetChatHistoryFromResponsesChainAsync(chatClientSession.ConversationId);
}
var chatHistoryProvider = agent.GetService<ChatHistoryProvider>();
if (chatHistoryProvider is null)
{
return [];
}
return (await chatHistoryProvider.InvokingAsync(new(agent, session, []))).ToList();
}
private async Task<List<ChatMessage>> GetChatHistoryFromResponsesChainAsync(string conversationId)
{
var openAIResponseClient = this._client.GetProjectOpenAIClient().GetProjectResponsesClient();
var inputItems = await openAIResponseClient.GetResponseInputItemsAsync(conversationId).ToListAsync();
var response = await openAIResponseClient.GetResponseAsync(conversationId);
var responseItem = response.Value.OutputItems.FirstOrDefault()!;
// Take the messages that were the chat history leading up to the current response
// remove the instruction messages, and reverse the order so that the most recent message is last.
var previousMessages = inputItems
.Select(ConvertToChatMessage)
.Where(x => x.Text != "You are a helpful assistant.")
.Reverse();
// Convert the response item to a chat message.
var responseMessage = ConvertToChatMessage(responseItem);
// Concatenate the previous messages with the response message to get a full chat history
// that includes the current response.
return [.. previousMessages, responseMessage];
}
private static ChatMessage ConvertToChatMessage(ResponseItem item)
{
if (item is MessageResponseItem messageResponseItem)
{
var role = messageResponseItem.Role == MessageRole.User ? ChatRole.User : ChatRole.Assistant;
return new ChatMessage(role, messageResponseItem.Content.FirstOrDefault()?.Text);
}
throw new NotSupportedException("This test currently only supports text messages");
}
private async Task<List<ChatMessage>> GetChatHistoryFromConversationAsync(string conversationId)
{
List<ChatMessage> messages = [];
await foreach (AgentResponseItem item in this._client.GetProjectOpenAIClient().GetProjectConversationsClient().GetProjectConversationItemsAsync(conversationId, order: "asc"))
{
var openAIItem = item.AsResponseResultItem();
if (openAIItem is MessageResponseItem messageItem)
{
messages.Add(new ChatMessage
{
Role = new ChatRole(messageItem.Role.ToString()),
Contents = messageItem.Content
.Where(c => c.Kind is ResponseContentPartKind.OutputText or ResponseContentPartKind.InputText)
.Select(c => new TextContent(c.Text))
.ToList<AIContent>()
});
}
}
return messages;
}
public async Task<ChatClientAgent> CreateChatClientAgentAsync(
string name = "HelpfulAssistant",
string instructions = "You are a helpful assistant.",
IList<AITool>? aiTools = null)
{
var definition = new PromptAgentDefinition(TestConfiguration.GetRequiredValue(TestSettings.AzureAIModelDeploymentName))
{
Instructions = instructions
};
// Register AIFunction tool definitions in the server-side agent definition so the model
// can invoke them. The local AIFunction implementations are matched by name via AsAIAgent.
if (aiTools is not null)
{
foreach (var tool in aiTools)
{
if (tool.AsOpenAIResponseTool() is ResponseTool responseTool)
{
definition.Tools.Add(responseTool);
}
}
}
var agentVersion = await this._client.Agents.CreateAgentVersionAsync(
GenerateUniqueAgentName(name),
new AgentVersionCreationOptions(definition));
return this._client.AsAIAgent(agentVersion, tools: aiTools).GetService<ChatClientAgent>()!;
}
public async Task<ChatClientAgent> CreateChatClientAgentAsync(ChatClientAgentOptions options)
{
options.Name ??= GenerateUniqueAgentName("HelpfulAssistant");
var definition = new PromptAgentDefinition(
options.ChatOptions?.ModelId ?? TestConfiguration.GetRequiredValue(TestSettings.AzureAIModelDeploymentName))
{
Instructions = options.ChatOptions?.Instructions
};
var agentVersion = await this._client.Agents.CreateAgentVersionAsync(
options.Name,
new AgentVersionCreationOptions(definition) { Description = options.Description });
var agent = this._client.AsAIAgent(agentVersion, tools: options.ChatOptions?.Tools);
return agent.GetService<ChatClientAgent>()!;
}
public static string GenerateUniqueAgentName(string baseName) =>
$"{baseName}-{Guid.NewGuid().ToString("N").Substring(0, 8)}";
public Task DeleteAgentAsync(ChatClientAgent agent) =>
this._client.Agents.DeleteAgentAsync(agent.Name);
public async Task DeleteSessionAsync(AgentSession session)
{
var typedSession = (ChatClientAgentSession)session;
if (typedSession.ConversationId?.StartsWith("conv_", StringComparison.OrdinalIgnoreCase) == true)
{
await this._client.GetProjectOpenAIClient().GetProjectConversationsClient().DeleteConversationAsync(typedSession.ConversationId);
}
else if (typedSession.ConversationId?.StartsWith("resp_", StringComparison.OrdinalIgnoreCase) == true)
{
await this.DeleteResponseChainAsync(typedSession.ConversationId!);
}
}
private async Task DeleteResponseChainAsync(string lastResponseId)
{
var response = await this._client.GetProjectOpenAIClient().GetProjectResponsesClient().GetResponseAsync(lastResponseId);
await this._client.GetProjectOpenAIClient().GetProjectResponsesClient().DeleteResponseAsync(lastResponseId);
if (response.Value.PreviousResponseId is not null)
{
await this.DeleteResponseChainAsync(response.Value.PreviousResponseId);
}
}
public ValueTask DisposeAsync()
{
GC.SuppressFinalize(this);
if (this._client is not null && this._agent is not null)
{
return new ValueTask(this._client.Agents.DeleteAgentAsync(this._agent.Name));
}
return default;
}
public virtual async ValueTask InitializeAsync()
{
this._client = new(new Uri(TestConfiguration.GetRequiredValue(TestSettings.AzureAIProjectEndpoint)), TestAzureCliCredentials.CreateAzureCliCredential());
var agentVersion = await this._client.Agents.CreateAgentVersionAsync(
GenerateUniqueAgentName("HelpfulAssistant"),
new AgentVersionCreationOptions(
new PromptAgentDefinition(TestConfiguration.GetRequiredValue(TestSettings.AzureAIModelDeploymentName))
{
Instructions = "You are a helpful assistant."
}));
this._agent = this._client.AsAIAgent(agentVersion);
}
public async Task InitializeAsync(ChatClientAgentOptions options)
{
this._client = new(new Uri(TestConfiguration.GetRequiredValue(TestSettings.AzureAIProjectEndpoint)), TestAzureCliCredentials.CreateAzureCliCredential());
options.Name ??= GenerateUniqueAgentName("HelpfulAssistant");
var definition = new PromptAgentDefinition(
options.ChatOptions?.ModelId ?? TestConfiguration.GetRequiredValue(TestSettings.AzureAIModelDeploymentName))
{
Instructions = options.ChatOptions?.Instructions
};
var agentVersion = await this._client.Agents.CreateAgentVersionAsync(
options.Name,
new AgentVersionCreationOptions(definition) { Description = options.Description });
this._agent = this._client.AsAIAgent(agentVersion, tools: options.ChatOptions?.Tools);
}
}