Merge branch 'main' into feature-so

This commit is contained in:
SergeyMenshykh
2026-02-04 10:49:12 +00:00
Unverified
574 changed files with 9801 additions and 4199 deletions
+3 -3
View File
@@ -108,7 +108,7 @@ async def main():
# api_version=os.environ["AZURE_OPENAI_API_VERSION"],
# api_key=os.environ["AZURE_OPENAI_API_KEY"], # Optional if using AzureCliCredential
credential=AzureCliCredential(), # Optional, if using api_key
).create_agent(
).as_agent(
name="HaikuBot",
instructions="You are an upbeat assistant that writes beautifully.",
)
@@ -131,7 +131,7 @@ using OpenAI;
// Replace the <apikey> with your OpenAI API key.
var agent = new OpenAIClient("<apikey>")
.GetOpenAIResponseClient("gpt-4o-mini")
.CreateAIAgent(name: "HaikuBot", instructions: "You are an upbeat assistant that writes beautifully.");
.AsAIAgent(name: "HaikuBot", instructions: "You are an upbeat assistant that writes beautifully.");
Console.WriteLine(await agent.RunAsync("Write a haiku about Microsoft Agent Framework."));
```
@@ -150,7 +150,7 @@ var agent = new OpenAIClient(
new BearerTokenPolicy(new AzureCliCredential(), "https://ai.azure.com/.default"),
new OpenAIClientOptions() { Endpoint = new Uri("https://<resource>.openai.azure.com/openai/v1") })
.GetOpenAIResponseClient("gpt-4o-mini")
.CreateAIAgent(name: "HaikuBot", instructions: "You are an upbeat assistant that writes beautifully.");
.AsAIAgent(name: "HaikuBot", instructions: "You are an upbeat assistant that writes beautifully.");
Console.WriteLine(await agent.RunAsync("Write a haiku about Microsoft Agent Framework."));
```
+3 -3
View File
@@ -11,8 +11,8 @@
</PropertyGroup>
<ItemGroup>
<!-- Aspire.* -->
<PackageVersion Include="Anthropic" Version="12.0.1" />
<PackageVersion Include="Anthropic.Foundry" Version="0.1.0" />
<PackageVersion Include="Anthropic" Version="12.3.0" />
<PackageVersion Include="Anthropic.Foundry" Version="0.4.1" />
<PackageVersion Include="Aspire.Azure.AI.OpenAI" Version="13.0.0-preview.1.25560.3" />
<PackageVersion Include="Aspire.Hosting.AppHost" Version="$(AspireAppHostSdkVersion)" />
<PackageVersion Include="Aspire.Hosting.Azure.CognitiveServices" Version="$(AspireAppHostSdkVersion)" />
@@ -42,7 +42,7 @@
<PackageVersion Include="System.Diagnostics.DiagnosticSource" Version="10.0.2" />
<PackageVersion Include="System.Linq.AsyncEnumerable" Version="10.0.0" />
<PackageVersion Include="System.Net.Http.Json" Version="10.0.0" />
<PackageVersion Include="System.Net.ServerSentEvents" Version="10.0.0" />
<PackageVersion Include="System.Net.ServerSentEvents" Version="10.0.1" />
<PackageVersion Include="System.Text.Json" Version="10.0.2" />
<PackageVersion Include="System.Threading.Channels" Version="10.0.2" />
<PackageVersion Include="System.Threading.Tasks.Extensions" Version="4.6.3" />
@@ -42,7 +42,7 @@ public static class Program
// Create the Host agent
var hostAgent = new HostClientAgent(loggerFactory);
await hostAgent.InitializeAgentAsync(modelId, apiKey, agentUrls!.Split(";"));
AgentSession session = await hostAgent.Agent!.GetNewSessionAsync(cancellationToken);
AgentSession session = await hostAgent.Agent!.CreateSessionAsync(cancellationToken);
try
{
while (true)
@@ -88,7 +88,7 @@ public static class Program
description: "AG-UI Client Agent",
tools: [changeBackground, readClientClimateSensors]);
AgentSession session = await agent.GetNewSessionAsync(cancellationToken);
AgentSession session = await agent.CreateSessionAsync(cancellationToken);
List<ChatMessage> messages = [new(ChatRole.System, "You are a helpful assistant.")];
try
{
@@ -1,5 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.
#pragma warning disable IDE0002 // Simplify Member Access
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
@@ -19,7 +19,7 @@ public static class FunctionTriggers
public static async Task<string> RunOrchestrationAsync([OrchestrationTrigger] TaskOrchestrationContext context)
{
DurableAIAgent writer = context.GetAgent("WriterAgent");
AgentSession writerSession = await writer.GetNewSessionAsync();
AgentSession writerSession = await writer.CreateSessionAsync();
AgentResponse<TextResponse> initial = await writer.RunAsync<TextResponse>(
message: "Write a concise inspirational sentence about learning.",
@@ -1,5 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.
#pragma warning disable IDE0002 // Simplify Member Access
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
@@ -1,5 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.
#pragma warning disable IDE0002 // Simplify Member Access
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
@@ -21,7 +21,7 @@ public static class FunctionTriggers
// Get the spam detection agent
DurableAIAgent spamDetectionAgent = context.GetAgent("SpamDetectionAgent");
AgentSession spamSession = await spamDetectionAgent.GetNewSessionAsync();
AgentSession spamSession = await spamDetectionAgent.CreateSessionAsync();
// Step 1: Check if the email is spam
AgentResponse<DetectionResult> spamDetectionResponse = await spamDetectionAgent.RunAsync<DetectionResult>(
@@ -43,7 +43,7 @@ public static class FunctionTriggers
// Generate and send response for legitimate email
DurableAIAgent emailAssistantAgent = context.GetAgent("EmailAssistantAgent");
AgentSession emailSession = await emailAssistantAgent.GetNewSessionAsync();
AgentSession emailSession = await emailAssistantAgent.CreateSessionAsync();
AgentResponse<EmailResponse> emailAssistantResponse = await emailAssistantAgent.RunAsync<EmailResponse>(
message:
@@ -1,5 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.
#pragma warning disable IDE0002 // Simplify Member Access
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
@@ -24,7 +24,7 @@ public static class FunctionTriggers
// Get the writer agent
DurableAIAgent writerAgent = context.GetAgent("WriterAgent");
AgentSession writerSession = await writerAgent.GetNewSessionAsync();
AgentSession writerSession = await writerAgent.CreateSessionAsync();
// Set initial status
context.SetCustomStatus($"Starting content generation for topic: {input.Topic}");
@@ -1,5 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.
#pragma warning disable IDE0002 // Simplify Member Access
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
@@ -20,7 +20,7 @@ public static class FunctionTriggers
// Get the writer agent
DurableAIAgent writerAgent = context.GetAgent("Writer");
AgentSession writerSession = await writerAgent.GetNewSessionAsync();
AgentSession writerSession = await writerAgent.CreateSessionAsync();
// Set initial status
context.SetCustomStatus($"Starting content generation for topic: {input.Topic}");
@@ -1,5 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.
#pragma warning disable IDE0002 // Simplify Member Access
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
@@ -5,6 +5,8 @@
// generate a remote MCP endpoint for the app at /runtime/webhooks/mcp with a agent-specific
// query tool name.
#pragma warning disable IDE0002 // Simplify Member Access
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
@@ -95,7 +95,7 @@ public sealed class FunctionTriggers
AIAgent agentProxy = durableClient.AsDurableAgentProxy(context, "TravelPlanner");
// Create a new agent session
AgentSession session = await agentProxy.GetNewSessionAsync(cancellationToken);
AgentSession session = await agentProxy.CreateSessionAsync(cancellationToken);
string agentSessionId = session.GetService<AgentSessionId>().ToString();
this._logger.LogInformation("Creating new agent session: {AgentSessionId}", agentSessionId);
@@ -8,6 +8,8 @@
// This pattern is inspired by OpenAI's background mode for the Responses API, which allows clients
// to disconnect and reconnect to ongoing agent responses without losing messages.
#pragma warning disable IDE0002 // Simplify Member Access
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
@@ -61,7 +61,7 @@ Console.WriteLine("Enter a message for the Joker agent (or 'exit' to quit):");
Console.WriteLine();
// Create a session for the conversation
AgentSession session = await agentProxy.GetNewSessionAsync();
AgentSession session = await agentProxy.CreateSessionAsync();
while (true)
{
@@ -47,7 +47,7 @@ AIAgent writerAgent = client.GetChatClient(deploymentName).AsAIAgent(WriterInstr
static async Task<string> RunOrchestratorAsync(TaskOrchestrationContext context)
{
DurableAIAgent writer = context.GetAgent("WriterAgent");
AgentSession writerSession = await writer.GetNewSessionAsync();
AgentSession writerSession = await writer.CreateSessionAsync();
AgentResponse<TextResponse> initial = await writer.RunAsync<TextResponse>(
message: "Write a concise inspirational sentence about learning.",
@@ -56,7 +56,7 @@ static async Task<string> RunOrchestratorAsync(TaskOrchestrationContext context,
{
// Get the spam detection agent
DurableAIAgent spamDetectionAgent = context.GetAgent(SpamDetectionAgentName);
AgentSession spamSession = await spamDetectionAgent.GetNewSessionAsync();
AgentSession spamSession = await spamDetectionAgent.CreateSessionAsync();
// Step 1: Check if the email is spam
AgentResponse<DetectionResult> spamDetectionResponse = await spamDetectionAgent.RunAsync<DetectionResult>(
@@ -78,7 +78,7 @@ static async Task<string> RunOrchestratorAsync(TaskOrchestrationContext context,
// Generate and send response for legitimate email
DurableAIAgent emailAssistantAgent = context.GetAgent(EmailAssistantAgentName);
AgentSession emailSession = await emailAssistantAgent.GetNewSessionAsync();
AgentSession emailSession = await emailAssistantAgent.CreateSessionAsync();
AgentResponse<EmailResponse> emailAssistantResponse = await emailAssistantAgent.RunAsync<EmailResponse>(
message:
@@ -48,7 +48,7 @@ static async Task<object> RunOrchestratorAsync(TaskOrchestrationContext context,
{
// Get the writer agent
DurableAIAgent writerAgent = context.GetAgent("WriterAgent");
AgentSession writerSession = await writerAgent.GetNewSessionAsync();
AgentSession writerSession = await writerAgent.CreateSessionAsync();
// Set initial status
context.SetCustomStatus($"Starting content generation for topic: {input.Topic}");
@@ -59,7 +59,7 @@ static async Task<object> RunOrchestratorAsync(TaskOrchestrationContext context,
{
// Get the writer agent
DurableAIAgent writerAgent = context.GetAgent(WriterAgentName);
AgentSession writerSession = await writerAgent.GetNewSessionAsync();
AgentSession writerSession = await writerAgent.CreateSessionAsync();
// Set initial status
context.SetCustomStatus($"Starting content generation for topic: {input.Topic}");
@@ -299,7 +299,7 @@ Console.WriteLine("Enter a topic for the Publisher agent to write about (or 'exi
Console.WriteLine();
// Create a session for the conversation
AgentSession session = await agentProxy.GetNewSessionAsync();
AgentSession session = await agentProxy.CreateSessionAsync();
using CancellationTokenSource cts = new();
Console.CancelKeyPress += (sender, e) =>
@@ -305,7 +305,7 @@ if (string.IsNullOrWhiteSpace(prompt) || prompt.Equals("exit", StringComparison.
}
// Create a new agent session
AgentSession session = await agentProxy.GetNewSessionAsync();
AgentSession session = await agentProxy.CreateSessionAsync();
AgentSessionId sessionId = session.GetService<AgentSessionId>();
string conversationId = sessionId.ToString();
@@ -16,7 +16,7 @@ AgentCard agentCard = await agentCardResolver.GetAgentCardAsync();
// Create an instance of the AIAgent for an existing A2A agent specified by the agent card.
AIAgent agent = agentCard.AsAIAgent();
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
// Start the initial run with a long-running task.
AgentResponse response = await agent.RunAsync("Conduct a comprehensive analysis of quantum computing applications in cryptography, including recent breakthroughs, implementation challenges, and future roadmap. Please include diagrams and visual representations to illustrate complex concepts.", session);
@@ -20,7 +20,7 @@ AIAgent agent = chatClient.AsAIAgent(
name: "agui-client",
description: "AG-UI Client Agent");
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
List<ChatMessage> messages =
[
new(ChatRole.System, "You are a helpful assistant.")
@@ -20,7 +20,7 @@ AIAgent agent = chatClient.AsAIAgent(
name: "agui-client",
description: "AG-UI Client Agent");
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
List<ChatMessage> messages =
[
new(ChatRole.System, "You are a helpful assistant.")
@@ -33,7 +33,7 @@ AIAgent agent = chatClient.AsAIAgent(
description: "AG-UI Client Agent",
tools: frontendTools);
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
List<ChatMessage> messages =
[
new(ChatRole.System, "You are a helpful assistant.")
@@ -30,7 +30,7 @@ JsonSerializerOptions jsonOptions = new(JsonSerializerDefaults.Web)
};
StatefulAgent<AgentState> agent = new(baseAgent, jsonOptions, new AgentState());
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
List<ChatMessage> messages =
[
new(ChatRole.System, "You are a helpful recipe assistant.")
@@ -128,7 +128,7 @@ var agent = new ChatClientAgent(instrumentedChatClient,
.UseOpenTelemetry(SourceName, configure: (cfg) => cfg.EnableSensitiveData = true) // enable telemetry at the agent level
.Build();
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
appLogger.LogInformation("Agent created successfully with ID: {AgentId}", agent.Id);
@@ -2,15 +2,12 @@
// This sample shows how to create and use an AI agent with Anthropic as the backend.
using System.Net.Http.Headers;
using Anthropic;
using Anthropic.Foundry;
using Azure.Core;
using Azure.Identity;
using Microsoft.Agents.AI;
using Sample;
var deploymentName = Environment.GetEnvironmentVariable("ANTHROPIC_DEPLOYMENT_NAME") ?? "claude-haiku-4-5";
string deploymentName = Environment.GetEnvironmentVariable("ANTHROPIC_DEPLOYMENT_NAME") ?? "claude-haiku-4-5";
// The resource is the subdomain name / first name coming before '.services.ai.azure.com' in the endpoint Uri
// ie: https://(resource name).services.ai.azure.com/anthropic/v1/chat/completions
@@ -20,55 +17,13 @@ string? apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY");
const string JokerInstructions = "You are good at telling jokes.";
const string JokerName = "JokerAgent";
AnthropicClient? client = (resource is null)
? new AnthropicClient() { APIKey = apiKey ?? throw new InvalidOperationException("ANTHROPIC_API_KEY is required when no ANTHROPIC_RESOURCE is provided") } // If no resource is provided, use Anthropic public API
using AnthropicClient client = (resource is null)
? new AnthropicClient() { ApiKey = apiKey ?? throw new InvalidOperationException("ANTHROPIC_API_KEY is required when no ANTHROPIC_RESOURCE is provided") } // If no resource is provided, use Anthropic public API
: (apiKey is not null)
? new AnthropicFoundryClient(new AnthropicFoundryApiKeyCredentials(apiKey, resource)) // If an apiKey is provided, use Foundry with ApiKey authentication
: new AnthropicFoundryClient(new AnthropicAzureTokenCredential(new AzureCliCredential(), resource)); // Otherwise, use Foundry with Azure Client authentication
: new AnthropicFoundryClient(new AnthropicFoundryIdentityTokenCredentials(new AzureCliCredential(), resource, ["https://ai.azure.com/.default"])); // Otherwise, use Foundry with Azure TokenCredential authentication
AIAgent agent = client.AsAIAgent(model: deploymentName, instructions: JokerInstructions, name: JokerName);
// Invoke the agent and output the text result.
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));
namespace Sample
{
/// <summary>
/// Provides methods for invoking the Azure hosted Anthropic models using <see cref="TokenCredential"/> types.
/// </summary>
public sealed class AnthropicAzureTokenCredential : IAnthropicFoundryCredentials
{
private readonly TokenCredential _tokenCredential;
private readonly Lock _lock = new();
private AccessToken? _cachedAccessToken;
/// <inheritdoc/>
public string ResourceName { get; }
/// <summary>
/// Creates a new instance of the <see cref="AnthropicAzureTokenCredential"/>.
/// </summary>
/// <param name="tokenCredential">The credential provider. Use any specialization of <see cref="TokenCredential"/> to get your access token in supported environments.</param>
/// <param name="resourceName">The service resource subdomain name to use in the anthropic azure endpoint</param>
internal AnthropicAzureTokenCredential(TokenCredential tokenCredential, string resourceName)
{
this.ResourceName = resourceName ?? throw new ArgumentNullException(nameof(resourceName));
this._tokenCredential = tokenCredential ?? throw new ArgumentNullException(nameof(tokenCredential));
}
/// <inheritdoc/>
public void Apply(HttpRequestMessage requestMessage)
{
lock (this._lock)
{
// Add a 5-minute buffer to avoid using tokens that are about to expire
if (this._cachedAccessToken is null || this._cachedAccessToken.Value.ExpiresOn <= DateTimeOffset.Now.AddMinutes(5))
{
this._cachedAccessToken = this._tokenCredential.GetToken(new TokenRequestContext(scopes: ["https://ai.azure.com/.default"]), CancellationToken.None);
}
}
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", this._cachedAccessToken.Value.Token);
}
}
}
@@ -31,7 +31,7 @@ AIAgent agent2 = await persistentAgentsClient.CreateAIAgentAsync(
instructions: JokerInstructions);
// You can then invoke the agent like any other AIAgent.
AgentSession session = await agent1.GetNewSessionAsync();
AgentSession session = await agent1.CreateSessionAsync();
Console.WriteLine(await agent1.RunAsync("Tell me a joke about a pirate.", session));
// Cleanup for sample purposes.
@@ -40,7 +40,7 @@ var latestAgentVersion = jokerAgentLatest.GetService<AgentVersion>()!;
Console.WriteLine($"Latest agent version id: {latestAgentVersion.Id}");
// Once you have the AIAgent, you can invoke it like any other AIAgent.
AgentSession session = await jokerAgentLatest.GetNewSessionAsync();
AgentSession session = await jokerAgentLatest.CreateSessionAsync();
Console.WriteLine(await jokerAgentLatest.RunAsync("Tell me a joke about a pirate.", session));
// This will use the same session to continue the conversation.
@@ -28,7 +28,7 @@ namespace SampleApp
{
public override string? Name => "UpperCaseParrotAgent";
public override ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default)
public override ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default)
=> new(new CustomAgentSession());
public override ValueTask<AgentSession> DeserializeSessionAsync(JsonElement serializedSession, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
@@ -37,7 +37,7 @@ namespace SampleApp
protected override async Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentSession? session = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
{
// Create a session if the user didn't supply one.
session ??= await this.GetNewSessionAsync(cancellationToken);
session ??= await this.CreateSessionAsync(cancellationToken);
if (session is not CustomAgentSession typedSession)
{
@@ -69,7 +69,7 @@ namespace SampleApp
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentSession? session = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
// Create a session if the user didn't supply one.
session ??= await this.GetNewSessionAsync(cancellationToken);
session ??= await this.CreateSessionAsync(cancellationToken);
if (session is not CustomAgentSession typedSession)
{
@@ -33,7 +33,7 @@ AIAgent agent2 = await assistantClient.CreateAIAgentAsync(
instructions: JokerInstructions);
// You can invoke the agent like any other AIAgent.
AgentSession session = await agent1.GetNewSessionAsync();
AgentSession session = await agent1.CreateSessionAsync();
Console.WriteLine(await agent1.RunAsync("Tell me a joke about a pirate.", session));
// Cleanup for sample purposes.
@@ -10,7 +10,7 @@ using Microsoft.Extensions.AI;
var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY") ?? throw new InvalidOperationException("ANTHROPIC_API_KEY is not set.");
var model = Environment.GetEnvironmentVariable("ANTHROPIC_MODEL") ?? "claude-haiku-4-5";
AIAgent agent = new AnthropicClient(new ClientOptions { APIKey = apiKey })
AIAgent agent = new AnthropicClient(new ClientOptions { ApiKey = apiKey })
.AsAIAgent(model: model, instructions: "You are good at telling jokes.", name: "Joker");
// Invoke the agent and output the text result.
@@ -13,7 +13,7 @@ var model = Environment.GetEnvironmentVariable("ANTHROPIC_MODEL") ?? "claude-hai
var maxTokens = 4096;
var thinkingTokens = 2048;
var agent = new AnthropicClient(new ClientOptions { APIKey = apiKey })
var agent = new AnthropicClient(new ClientOptions { ApiKey = apiKey })
.AsAIAgent(
model: model,
clientFactory: (chatClient) => chatClient
@@ -22,15 +22,15 @@ const string AssistantName = "WeatherAssistant";
AITool tool = AIFunctionFactory.Create(GetWeather);
// Get anthropic client to create agents.
AIAgent agent = new AnthropicClient { APIKey = apiKey }
AIAgent agent = new AnthropicClient { ApiKey = apiKey }
.AsAIAgent(model: model, instructions: AssistantInstructions, name: AssistantName, tools: [tool]);
// Non-streaming agent interaction with function tools.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?", session));
// Streaming agent interaction with function tools.
session = await agent.GetNewSessionAsync();
session = await agent.CreateSessionAsync();
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("What is the weather like in Amsterdam?", session))
{
Console.WriteLine(update);
@@ -47,14 +47,14 @@ AIAgent agent = new AzureOpenAIClient(
});
// Start a new session for the agent conversation.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
// Run the agent with the session that stores conversation history in the vector store.
Console.WriteLine(await agent.RunAsync("I like jokes about Pirates. Tell me a joke about a pirate.", session));
// Start a second session. Since we configured the search scope to be across all sessions for the user,
// the agent should remember that the user likes pirate jokes.
AgentSession? session2 = await agent.GetNewSessionAsync();
AgentSession? session2 = await agent.CreateSessionAsync();
// Run the agent with the second session.
Console.WriteLine(await agent.RunAsync("Tell me a joke that I might like.", session2));
@@ -40,7 +40,7 @@ AIAgent agent = new AzureOpenAIClient(
: new Mem0Provider(mem0HttpClient, ctx.SerializedState, ctx.JsonSerializerOptions))
});
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
// Clear any existing memories for this scope to demonstrate fresh behavior.
Mem0Provider mem0Provider = session.GetService<Mem0Provider>()!;
@@ -60,5 +60,5 @@ AgentSession restoredSession = await agent.DeserializeSessionAsync(serializedSes
Console.WriteLine(await agent.RunAsync("Can you recap the personal details you remember?", restoredSession));
Console.WriteLine("\n>> Start a new session that shares the same Mem0 scope\n");
AgentSession newSession = await agent.GetNewSessionAsync();
AgentSession newSession = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("Summarize what you already know about me.", newSession));
@@ -37,7 +37,7 @@ AIAgent agent = chatClient.AsAIAgent(new ChatClientAgentOptions()
});
// Create a new session for the conversation.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(">> Use session with blank memory\n");
@@ -68,7 +68,7 @@ Console.WriteLine("\n>> Use new session with previously created memories\n");
// It is also possible to set the memories in a memory component on an individual session.
// This is useful if we want to start a new session, but have it share the same memories as a previous session.
var newSession = await agent.GetNewSessionAsync();
var newSession = await agent.CreateSessionAsync();
if (userInfo is not null && newSession.GetService<UserInfoMemory>() is UserInfoMemory newSessionMemory)
{
newSessionMemory.UserInfo = userInfo;
@@ -30,7 +30,7 @@ using JsonDocument createConversationResultAsJson = JsonDocument.Parse(createCon
string conversationId = createConversationResultAsJson.RootElement.GetProperty("id"u8)!.GetString()!;
// Create a session for the conversation - this enables conversation state management for subsequent turns
AgentSession session = await agent.GetNewSessionAsync(conversationId);
AgentSession session = await agent.CreateSessionAsync(conversationId);
Console.WriteLine("=== Multi-turn Conversation Demo ===\n");
@@ -33,7 +33,7 @@ The `AgentSession` works with `ChatClientAgentRunOptions` to link the agent to a
ChatClientAgentRunOptions agentRunOptions = new() { ChatOptions = new ChatOptions() { ConversationId = conversationId } };
// Create a session for the conversation
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
// First call links the session to the conversation
ChatCompletion firstResponse = await agent.RunAsync([firstMessage], session, agentRunOptions);
@@ -59,7 +59,7 @@ foreach (ClientResult result in getConversationItemsResults.GetRawPages())
1. **Create an OpenAI Client**: Initialize an `OpenAIClient` with your API key
2. **Create a Conversation**: Use `ConversationClient` to create a server-side conversation
3. **Create an Agent**: Initialize an `OpenAIResponseClientAgent` with the desired model and instructions
4. **Create a Session**: Call `agent.GetNewSessionAsync()` to create a new conversation session
4. **Create a Session**: Call `agent.CreateSessionAsync()` to create a new conversation session
5. **Link Session to Conversation**: Pass `ChatClientAgentRunOptions` with the `ConversationId` on the first call
6. **Send Messages**: Subsequent calls to `agent.RunAsync()` only need the session - context is maintained
7. **Cleanup**: Delete the conversation when done using `conversationClient.DeleteConversation()`
@@ -70,7 +70,7 @@ AIAgent agent = azureOpenAIClient
.WithAIContextProviderMessageRemoval()),
});
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(">> Asking about returns\n");
Console.WriteLine(await agent.RunAsync("Hi! I need help understanding the return policy.", session));
@@ -74,7 +74,7 @@ AIAgent agent = azureOpenAIClient
AIContextProviderFactory = (ctx, ct) => new ValueTask<AIContextProvider>(new TextSearchProvider(SearchAdapter, ctx.SerializedState, ctx.JsonSerializerOptions, textSearchOptions))
});
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(">> Asking about SK sessions\n");
Console.WriteLine(await agent.RunAsync("Hi! How do I create a thread/session in Semantic Kernel?", session));
@@ -32,7 +32,7 @@ AIAgent agent = new AzureOpenAIClient(
AIContextProviderFactory = (ctx, ct) => new ValueTask<AIContextProvider>(new TextSearchProvider(MockSearchAsync, ctx.SerializedState, ctx.JsonSerializerOptions, textSearchOptions))
});
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(">> Asking about returns\n");
Console.WriteLine(await agent.RunAsync("Hi! I need help understanding the return policy.", session));
@@ -43,7 +43,7 @@ AIAgent agent = await aiProjectClient
instructions: "You are a helpful support specialist for Contoso Outdoors. Answer questions using the provided context and cite the source document when available.",
tools: [fileSearchTool]);
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(">> Asking about returns\n");
Console.WriteLine(await agent.RunAsync("Hi! I need help understanding the return policy.", session));
@@ -17,12 +17,12 @@ AIAgent agent = new AzureOpenAIClient(
.AsAIAgent(instructions: "You are good at telling jokes.", name: "Joker");
// Invoke the agent with a multi-turn conversation, where the context is preserved in the session object.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session));
Console.WriteLine(await agent.RunAsync("Now add some emojis to the joke and tell it in the voice of a pirate's parrot.", session));
// Invoke the agent with a multi-turn conversation and streaming, where the context is preserved in the session object.
session = await agent.GetNewSessionAsync();
session = await agent.CreateSessionAsync();
await foreach (var update in agent.RunStreamingAsync("Tell me a joke about a pirate.", session))
{
Console.WriteLine(update);
@@ -30,7 +30,7 @@ AIAgent agent = new AzureOpenAIClient(
.AsAIAgent(instructions: "You are a helpful assistant", tools: [new ApprovalRequiredAIFunction(AIFunctionFactory.Create(GetWeather))]);
// Call the agent and check if there are any user input requests to handle.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
var response = await agent.RunAsync("What is the weather like in Amsterdam?", session);
var userInputRequests = response.UserInputRequests.ToList();
@@ -19,7 +19,7 @@ AIAgent agent = new AzureOpenAIClient(
.AsAIAgent(instructions: "You are good at telling jokes.", name: "Joker");
// Start a new session for the agent conversation.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
// Run the agent with a new session.
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session));
@@ -39,7 +39,7 @@ AIAgent agent = new AzureOpenAIClient(
});
// Start a new session for the agent conversation.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
// Run the agent with the session that stores chat history in the vector store.
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session));
@@ -49,7 +49,7 @@ internal sealed class SampleService(AIAgent agent, IHostApplicationLifetime appL
public async Task StartAsync(CancellationToken cancellationToken)
{
// Create a session that will be used for the entirety of the service lifetime so that the user can ask follow up questions.
this._session = await agent.GetNewSessionAsync(cancellationToken);
this._session = await agent.CreateSessionAsync(cancellationToken);
_ = this.RunAsync(appLifetime.ApplicationStopping);
}
@@ -22,7 +22,7 @@ ChatMessage message = new(ChatRole.User, [
new UriContent("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", "image/jpeg")
]);
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await foreach (var update in agent.RunStreamingAsync(message, session))
{
@@ -32,7 +32,7 @@ AIAgent agent = new AzureOpenAIClient(
// Enable background responses (only supported by {Azure}OpenAI Responses at this time).
AgentRunOptions options = new() { AllowBackgroundResponses = true };
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
// Start the initial run.
AgentResponse response = await agent.RunAsync("Write a very long novel about a team of astronauts exploring an uncharted galaxy.", session, options);
@@ -45,7 +45,7 @@ var middlewareEnabledAgent = originalAgent
.Use(GuardrailMiddleware, null)
.Build();
var session = await middlewareEnabledAgent.GetNewSessionAsync();
var session = await middlewareEnabledAgent.CreateSessionAsync();
Console.WriteLine("\n\n=== Example 1: Wording Guardrail ===");
var guardRailedResponse = await middlewareEnabledAgent.RunAsync("Tell me something harmful.");
@@ -27,7 +27,7 @@ AIAgent agent = new AzureOpenAIClient(
ChatHistoryProviderFactory = (ctx, ct) => new ValueTask<ChatHistoryProvider>(new InMemoryChatHistoryProvider(new MessageCountingChatReducer(2), ctx.SerializedState, ctx.JsonSerializerOptions))
});
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
// Invoke the agent and output the text result.
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session));
@@ -19,7 +19,7 @@ AIAgent agent = new AzureOpenAIClient(
// Enable background responses (only supported by OpenAI Responses at this time).
AgentRunOptions options = new() { AllowBackgroundResponses = true };
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
// Start the initial run.
AgentResponse response = await agent.RunAsync("Write a very long novel about otters in space.", session, options);
@@ -41,7 +41,7 @@ Console.WriteLine(response.Text);
// Reset options and session for streaming.
options = new() { AllowBackgroundResponses = true };
session = await agent.GetNewSessionAsync();
session = await agent.CreateSessionAsync();
AgentResponseUpdate? lastReceivedUpdate = null;
// Start streaming.
@@ -39,7 +39,7 @@ Console.WriteLine();
try
{
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
await foreach (var response in agent.RunStreamingAsync(Task, session))
{
@@ -58,7 +58,7 @@ AIAgent agent = new AzureOpenAIClient(
});
// Invoke the agent and output the text result.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("I need to pick up milk from the supermarket.", session) + "\n");
Console.WriteLine(await agent.RunAsync("I need to take Sally for soccer practice.", session) + "\n");
Console.WriteLine(await agent.RunAsync("I need to make a dentist appointment for Jimmy.", session) + "\n");
@@ -29,13 +29,13 @@ ProjectConversation conversation = await conversationsClient.CreateProjectConver
// Providing the conversation Id is not strictly necessary, but by not providing it no information will show up in the Foundry Project UI as conversations.
// Sessions that don't have a conversation Id will work based on the `PreviousResponseId`.
AgentSession session = await jokerAgent.GetNewSessionAsync(conversation.Id);
AgentSession session = await jokerAgent.CreateSessionAsync(conversation.Id);
Console.WriteLine(await jokerAgent.RunAsync("Tell me a joke about a pirate.", session));
Console.WriteLine(await jokerAgent.RunAsync("Now add some emojis to the joke and tell it in the voice of a pirate's parrot.", session));
// Invoke the agent with a multi-turn conversation and streaming, where the context is preserved in the session object.
session = await jokerAgent.GetNewSessionAsync(conversation.Id);
session = await jokerAgent.CreateSessionAsync(conversation.Id);
await foreach (AgentResponseUpdate update in jokerAgent.RunStreamingAsync("Tell me a joke about a pirate.", session))
{
Console.WriteLine(update);
@@ -54,6 +54,6 @@ The sample will:
When working with multi-turn conversations, there are two approaches:
- **With Conversation ID**: By passing a `conversation.Id` to `GetNewSessionAsync()`, the conversation will be visible in the Azure Foundry Project UI. This is useful for tracking and debugging conversations.
- **With Conversation ID**: By passing a `conversation.Id` to `CreateSessionAsync()`, the conversation will be visible in the Azure Foundry Project UI. This is useful for tracking and debugging conversations.
- **Without Conversation ID**: Sessions created without a conversation ID still work correctly, maintaining context via `PreviousResponseId`. However, these conversations may not appear in the Foundry UI.
@@ -37,11 +37,11 @@ var newAgent = await aiProjectClient.CreateAIAgentAsync(name: AssistantName, mod
var existingAgent = await aiProjectClient.GetAIAgentAsync(name: AssistantName, tools: [tool]);
// Non-streaming agent interaction with function tools.
AgentSession session = await existingAgent.GetNewSessionAsync();
AgentSession session = await existingAgent.CreateSessionAsync();
Console.WriteLine(await existingAgent.RunAsync("What is the weather like in Amsterdam?", session));
// Streaming agent interaction with function tools.
session = await existingAgent.GetNewSessionAsync();
session = await existingAgent.CreateSessionAsync();
await foreach (AgentResponseUpdate update in existingAgent.RunStreamingAsync("What is the weather like in Amsterdam?", session))
{
Console.WriteLine(update);
@@ -32,7 +32,7 @@ AIAgent agent = await aiProjectClient.CreateAIAgentAsync(name: AssistantName, mo
// Call the agent with approval-required function tools.
// The agent will request approval before invoking the function.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
AgentResponse response = await agent.RunAsync("What is the weather like in Amsterdam?", session);
// Check if there are any user input requests (approvals needed).
@@ -19,7 +19,7 @@ AIProjectClient aiProjectClient = new(new Uri(endpoint), new AzureCliCredential(
AIAgent agent = await aiProjectClient.CreateAIAgentAsync(name: JokerName, model: deploymentName, instructions: JokerInstructions);
// Start a new session for the agent conversation.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
// Run the agent with a new session.
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session));
@@ -38,11 +38,11 @@ AIAgent agent = (await aiProjectClient.CreateAIAgentAsync(name: JokerName, model
.Build();
// Invoke the agent and output the text result.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.", session));
// Invoke the agent with streaming support.
session = await agent.GetNewSessionAsync();
session = await agent.CreateSessionAsync();
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Tell me a joke about a pirate.", session))
{
Console.WriteLine(update);
@@ -54,7 +54,7 @@ internal sealed class SampleService(AIProjectClient client, AIAgent agent, IHost
public async Task StartAsync(CancellationToken cancellationToken)
{
// Create a session that will be used for the entirety of the service lifetime so that the user can ask follow up questions.
this._session = await agent.GetNewSessionAsync(cancellationToken);
this._session = await agent.CreateSessionAsync(cancellationToken);
_ = this.RunAsync(appLifetime.ApplicationStopping);
}
@@ -24,7 +24,7 @@ ChatMessage message = new(ChatRole.User, [
new DataContent(File.ReadAllBytes("assets/walkway.jpg"), "image/jpeg")
]);
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(message, session))
{
@@ -39,7 +39,7 @@ AIAgent agent = await aiProjectClient.CreateAIAgentAsync(
tools: [weatherAgent.AsAIFunction()]);
// Invoke the agent and output the text result.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?", session));
// Cleanup by agent name removes the agent versions created.
@@ -49,7 +49,7 @@ AIAgent middlewareEnabledAgent = originalAgent
.Use(GuardrailMiddleware, null)
.Build();
AgentSession session = await middlewareEnabledAgent.GetNewSessionAsync();
AgentSession session = await middlewareEnabledAgent.CreateSessionAsync();
Console.WriteLine("\n\n=== Example 1: Wording Guardrail ===");
AgentResponse guardRailedResponse = await middlewareEnabledAgent.RunAsync("Tell me something harmful.");
@@ -42,7 +42,7 @@ AIAgent agent = await aiProjectClient.CreateAIAgentAsync(
services: serviceProvider);
// Invoke the agent and output the text result.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("Tell me current time and weather in Seattle.", session));
// Cleanup by agent name removes the agent version created.
@@ -83,7 +83,7 @@ internal sealed class Program
AllowBackgroundResponses = true,
};
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
ChatMessage message = new(ChatRole.User, [
new TextContent("I need you to help me search for 'OpenAI news'. Please type 'OpenAI news' and submit the search. Once you see search results, the task is complete."),
@@ -42,7 +42,7 @@ AIAgent agent = await persistentAgentsClient.CreateAIAgentAsync(
});
// You can then invoke the agent like any other AIAgent.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("Please summarize the Azure AI Agent documentation related to MCP Tool calling?", session));
// Cleanup for sample purposes.
@@ -75,7 +75,7 @@ AIAgent agentWithRequiredApproval = await persistentAgentsClient.CreateAIAgentAs
});
// You can then invoke the agent like any other AIAgent.
var sessionWithRequiredApproval = await agentWithRequiredApproval.GetNewSessionAsync();
var sessionWithRequiredApproval = await agentWithRequiredApproval.CreateSessionAsync();
var response = await agentWithRequiredApproval.RunAsync("Please summarize the Azure AI Agent documentation related to MCP Tool calling?", sessionWithRequiredApproval);
var userInputRequests = response.UserInputRequests.ToList();
@@ -37,7 +37,7 @@ AIAgent agent = new AzureOpenAIClient(
tools: [mcpTool]);
// You can then invoke the agent like any other AIAgent.
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("Please summarize the Azure AI Agent documentation related to MCP Tool calling?", session));
// **** MCP Tool with Approval Required ****
@@ -64,7 +64,7 @@ AIAgent agentWithRequiredApproval = new AzureOpenAIClient(
tools: [mcpToolWithApproval]);
// You can then invoke the agent like any other AIAgent.
var sessionWithRequiredApproval = await agentWithRequiredApproval.GetNewSessionAsync();
var sessionWithRequiredApproval = await agentWithRequiredApproval.CreateSessionAsync();
var response = await agentWithRequiredApproval.RunAsync("Please summarize the Azure AI Agent documentation related to MCP Tool calling?", sessionWithRequiredApproval);
var userInputRequests = response.UserInputRequests.ToList();
@@ -136,7 +136,7 @@ internal sealed class SloganWriterExecutor : Executor
public async ValueTask<SloganResult> HandleAsync(string message, IWorkflowContext context, CancellationToken cancellationToken = default)
{
this._session ??= await this._agent.GetNewSessionAsync(cancellationToken);
this._session ??= await this._agent.CreateSessionAsync(cancellationToken);
var result = await this._agent.RunAsync(message, this._session, cancellationToken: cancellationToken);
@@ -209,7 +209,7 @@ internal sealed class FeedbackExecutor : Executor<SloganResult>
public override async ValueTask HandleAsync(SloganResult message, IWorkflowContext context, CancellationToken cancellationToken = default)
{
this._session ??= await this._agent.GetNewSessionAsync(cancellationToken);
this._session ??= await this._agent.CreateSessionAsync(cancellationToken);
var sloganMessage = $"""
Here is a slogan for the task '{message.Task}':
@@ -37,7 +37,7 @@ public static class Program
// Create the workflow and turn it into an agent
var workflow = WorkflowFactory.BuildWorkflow(chatClient);
var agent = workflow.AsAgent("workflow-agent", "Workflow Agent");
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
// Start an interactive loop to interact with the workflow as if it were an agent
while (true)
@@ -47,7 +47,7 @@ internal sealed class Program
AIAgent agent = aiProjectClient.AsAIAgent(agentVersion);
AgentSession session = await agent.GetNewSessionAsync();
AgentSession session = await agent.CreateSessionAsync();
ProjectConversation conversation =
await aiProjectClient
@@ -90,7 +90,7 @@ public static class Program
{
EnableSensitiveData = true // enable sensitive data at the agent level such as prompts and responses
};
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
// Start an interactive loop to interact with the workflow as if it were an agent
while (true)
@@ -16,7 +16,7 @@ IChatClient aws = new AmazonBedrockRuntimeClient(
.AsIChatClient("amazon.nova-pro-v1:0");
IChatClient anthropic = new Anthropic.AnthropicClient(
new() { APIKey = Environment.GetEnvironmentVariable("ANTHROPIC_APIKEY") })
new() { ApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_APIKEY") })
.AsIChatClient("claude-sonnet-4-20250514");
IChatClient openai = new OpenAI.OpenAIClient(
@@ -44,7 +44,7 @@ internal sealed class AFAgentApplication : AgentApplication
// Deserialize the conversation history into an AgentSession, or create a new one if none exists.
AgentSession agentSession = sessionElementStart.ValueKind is not JsonValueKind.Undefined and not JsonValueKind.Null
? await this._agent.DeserializeSessionAsync(sessionElementStart, JsonUtilities.DefaultOptions, cancellationToken)
: await this._agent.GetNewSessionAsync(cancellationToken);
: await this._agent.CreateSessionAsync(cancellationToken);
ChatMessage chatMessage = HandleUserInput(turnContext);
@@ -54,7 +54,7 @@ public sealed class A2AAgent : AIAgent
}
/// <inheritdoc/>
public sealed override ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default)
public sealed override ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default)
=> new(new A2AAgentSession());
/// <summary>
@@ -62,7 +62,7 @@ public sealed class A2AAgent : AIAgent
/// </summary>
/// <param name="contextId">The context id to continue.</param>
/// <returns>A value task representing the asynchronous operation. The task result contains a new <see cref="AgentSession"/> instance.</returns>
public ValueTask<AgentSession> GetNewSessionAsync(string contextId)
public ValueTask<AgentSession> CreateSessionAsync(string contextId)
=> new(new A2AAgentSession() { ContextId = contextId });
/// <inheritdoc/>
@@ -230,7 +230,7 @@ public sealed class A2AAgent : AIAgent
throw new InvalidOperationException("A session must be provided when AllowBackgroundResponses is enabled.");
}
session ??= await this.GetNewSessionAsync(cancellationToken).ConfigureAwait(false);
session ??= await this.CreateSessionAsync(cancellationToken).ConfigureAwait(false);
if (session is not A2AAgentSession typedSession)
{
@@ -123,7 +123,7 @@ public abstract class AIAgent
/// may be deferred until first use to optimize performance.
/// </para>
/// </remarks>
public abstract ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default);
public abstract ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Deserializes an agent session from its JSON serialized representation.
@@ -26,7 +26,7 @@ namespace Microsoft.Agents.AI;
/// <item><description>Chat history reduction, e.g. where messages needs to be summarized or truncated to reduce the size.</description></item>
/// </list>
/// An <see cref="AgentSession"/> is always constructed by an <see cref="AIAgent"/> so that the <see cref="AIAgent"/>
/// can attach any necessary behaviors to the <see cref="AgentSession"/>. See the <see cref="AIAgent.GetNewSessionAsync(System.Threading.CancellationToken)"/>
/// can attach any necessary behaviors to the <see cref="AgentSession"/>. See the <see cref="AIAgent.CreateSessionAsync(System.Threading.CancellationToken)"/>
/// and <see cref="AIAgent.DeserializeSessionAsync(JsonElement, JsonSerializerOptions?, System.Threading.CancellationToken)"/> methods for more information.
/// </para>
/// <para>
@@ -42,7 +42,7 @@ namespace Microsoft.Agents.AI;
/// </para>
/// </remarks>
/// <seealso cref="AIAgent"/>
/// <seealso cref="AIAgent.GetNewSessionAsync(System.Threading.CancellationToken)"/>
/// <seealso cref="AIAgent.CreateSessionAsync(System.Threading.CancellationToken)"/>
/// <seealso cref="AIAgent.DeserializeSessionAsync(JsonElement, JsonSerializerOptions?, System.Threading.CancellationToken)"/>
public abstract class AgentSession
{
@@ -74,7 +74,7 @@ public abstract class DelegatingAIAgent : AIAgent
}
/// <inheritdoc />
public override ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default) => this.InnerAgent.GetNewSessionAsync(cancellationToken);
public override ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default) => this.InnerAgent.CreateSessionAsync(cancellationToken);
/// <inheritdoc />
public override ValueTask<AgentSession> DeserializeSessionAsync(JsonElement serializedSession, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
@@ -42,7 +42,7 @@ public class CopilotStudioAgent : AIAgent
}
/// <inheritdoc/>
public sealed override ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default)
public sealed override ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default)
=> new(new CopilotStudioAgentSession());
/// <summary>
@@ -50,7 +50,7 @@ public class CopilotStudioAgent : AIAgent
/// </summary>
/// <param name="conversationId">The conversation id to continue.</param>
/// <returns>A new <see cref="AgentSession"/> instance.</returns>
public ValueTask<AgentSession> GetNewSessionAsync(string conversationId)
public ValueTask<AgentSession> CreateSessionAsync(string conversationId)
=> new(new CopilotStudioAgentSession() { ConversationId = conversationId });
/// <inheritdoc/>
@@ -68,7 +68,7 @@ public class CopilotStudioAgent : AIAgent
// Ensure that we have a valid session to work with.
// If the session ID is null, we need to start a new conversation and set the session ID accordingly.
session ??= await this.GetNewSessionAsync(cancellationToken).ConfigureAwait(false);
session ??= await this.CreateSessionAsync(cancellationToken).ConfigureAwait(false);
if (session is not CopilotStudioAgentSession typedSession)
{
throw new InvalidOperationException("The provided session is not compatible with the agent. Only sessions created by the agent can be used.");
@@ -107,7 +107,7 @@ public class CopilotStudioAgent : AIAgent
// Ensure that we have a valid session to work with.
// If the session ID is null, we need to start a new conversation and set the session ID accordingly.
session ??= await this.GetNewSessionAsync(cancellationToken).ConfigureAwait(false);
session ??= await this.CreateSessionAsync(cancellationToken).ConfigureAwait(false);
if (session is not CopilotStudioAgentSession typedSession)
{
throw new InvalidOperationException("The provided session is not compatible with the agent. Only sessions created by the agent can be used.");
@@ -67,7 +67,7 @@ internal class AgentEntity(IServiceProvider services, CancellationToken cancella
// Start the agent response stream
IAsyncEnumerable<AgentResponseUpdate> responseStream = agentWrapper.RunStreamingAsync(
this.State.Data.ConversationHistory.SelectMany(e => e.Messages).Select(m => m.ToChatMessage()),
await agentWrapper.GetNewSessionAsync(cancellationToken).ConfigureAwait(false),
await agentWrapper.CreateSessionAsync(cancellationToken).ConfigureAwait(false),
options: null,
this._cancellationToken);
@@ -34,7 +34,7 @@ public sealed class DurableAIAgent : AIAgent
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A value task that represents the asynchronous operation. The task result contains a new agent session.</returns>
public override ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default)
public override ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default)
{
AgentSessionId sessionId = this._context.NewAgentSessionId(this._agentName);
return ValueTask.FromResult<AgentSession>(new DurableAgentSession(sessionId));
@@ -76,12 +76,12 @@ public sealed class DurableAIAgent : AIAgent
throw new NotSupportedException("Cancellation is not supported for durable agents.");
}
session ??= await this.GetNewSessionAsync(cancellationToken).ConfigureAwait(false);
session ??= await this.CreateSessionAsync(cancellationToken).ConfigureAwait(false);
if (session is not DurableAgentSession durableSession)
{
throw new ArgumentException(
"The provided session is not valid for a durable agent. " +
"Create a new session using GetNewSessionAsync or provide a session previously created by this agent.",
"Create a new session using CreateSessionAsync or provide a session previously created by this agent.",
paramName: nameof(session));
}
@@ -18,7 +18,7 @@ internal class DurableAIAgentProxy(string name, IDurableAgentClient agentClient)
return ValueTask.FromResult<AgentSession>(DurableAgentSession.Deserialize(serializedSession, jsonSerializerOptions));
}
public override ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default)
public override ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default)
{
return ValueTask.FromResult<AgentSession>(new DurableAgentSession(AgentSessionId.WithRandomKey(this.Name!)));
}
@@ -29,12 +29,12 @@ internal class DurableAIAgentProxy(string name, IDurableAgentClient agentClient)
AgentRunOptions? options = null,
CancellationToken cancellationToken = default)
{
session ??= await this.GetNewSessionAsync(cancellationToken).ConfigureAwait(false);
session ??= await this.CreateSessionAsync(cancellationToken).ConfigureAwait(false);
if (session is not DurableAgentSession durableSession)
{
throw new ArgumentException(
"The provided session is not valid for a durable agent. " +
"Create a new session using GetNewSession or provide a session previously created by this agent.",
"Create a new session using CreateSessionAsync or provide a session previously created by this agent.",
paramName: nameof(session));
}
@@ -86,7 +86,7 @@ public sealed class GitHubCopilotAgent : AIAgent, IAsyncDisposable
}
/// <inheritdoc/>
public sealed override ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default)
public sealed override ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default)
=> new(new GitHubCopilotAgentSession());
/// <summary>
@@ -94,7 +94,7 @@ public sealed class GitHubCopilotAgent : AIAgent, IAsyncDisposable
/// </summary>
/// <param name="sessionId">The session id to continue.</param>
/// <returns>A new <see cref="AgentSession"/> instance.</returns>
public ValueTask<AgentSession> GetNewSessionAsync(string sessionId)
public ValueTask<AgentSession> CreateSessionAsync(string sessionId)
=> new(new GitHubCopilotAgentSession() { SessionId = sessionId });
/// <inheritdoc/>
@@ -122,7 +122,7 @@ public sealed class GitHubCopilotAgent : AIAgent, IAsyncDisposable
_ = Throw.IfNull(messages);
// Ensure we have a valid session
session ??= await this.GetNewSessionAsync(cancellationToken).ConfigureAwait(false);
session ??= await this.CreateSessionAsync(cancellationToken).ConfigureAwait(false);
if (session is not GitHubCopilotAgentSession typedSession)
{
throw new InvalidOperationException(
@@ -74,7 +74,7 @@ public static async Task<string> SpamDetectionOrchestration(
// Get the spam detection agent
DurableAIAgent spamDetectionAgent = context.GetAgent("SpamDetectionAgent");
AgentSession spamSession = await spamDetectionAgent.GetNewSessionAsync();
AgentSession spamSession = await spamDetectionAgent.CreateSessionAsync();
// Step 1: Check if the email is spam
AgentResponse<DetectionResult> spamDetectionResponse = await spamDetectionAgent.RunAsync<DetectionResult>(
@@ -97,7 +97,7 @@ public static async Task<string> SpamDetectionOrchestration(
{
// Generate and send response for legitimate email
DurableAIAgent emailAssistantAgent = context.GetAgent("EmailAssistantAgent");
AgentSession emailSession = await emailAssistantAgent.GetNewSessionAsync();
AgentSession emailSession = await emailAssistantAgent.CreateSessionAsync();
AgentResponse<EmailResponse> emailAssistantResponse = await emailAssistantAgent.RunAsync<EmailResponse>(
message:
@@ -45,7 +45,7 @@ public sealed class InMemoryAgentSessionStore : AgentSessionStore
return sessionContent switch
{
null => await agent.GetNewSessionAsync(cancellationToken).ConfigureAwait(false),
null => await agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false),
_ => await agent.DeserializeSessionAsync(sessionContent.Value, cancellationToken: cancellationToken).ConfigureAwait(false),
};
}
@@ -20,6 +20,6 @@ public sealed class NoopAgentSessionStore : AgentSessionStore
/// <inheritdoc/>
public override ValueTask<AgentSession> GetSessionAsync(AIAgent agent, string conversationId, CancellationToken cancellationToken = default)
{
return agent.GetNewSessionAsync(cancellationToken);
return agent.CreateSessionAsync(cancellationToken);
}
}
@@ -36,9 +36,9 @@ internal class PurviewAgent : AIAgent, IDisposable
}
/// <inheritdoc/>
public override ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default)
public override ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default)
{
return this._innerAgent.GetNewSessionAsync(cancellationToken);
return this._innerAgent.CreateSessionAsync(cancellationToken);
}
/// <inheritdoc/>
@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Agents.AI.Workflows.Declarative.PowerFx;
using Microsoft.Agents.ObjectModel;
@@ -83,7 +84,8 @@ internal static class ChatMessageExtensions
public static ChatMessage ToChatMessage(this RecordDataValue message) =>
new(message.GetRole(), [.. message.GetContent()])
{
AdditionalProperties = message.GetProperty<RecordDataValue>("metadata").ToMetadata()
MessageId = message.GetProperty<StringDataValue>(TypeSchema.Message.Fields.Id)?.Value,
AdditionalProperties = message.GetProperty<RecordDataValue>(TypeSchema.Message.Fields.Metadata).ToMetadata()
};
public static ChatMessage ToChatMessage(this StringDataValue message) => new(ChatRole.User, message.Value);
@@ -118,7 +120,7 @@ internal static class ChatMessageExtensions
public static ChatRole ToChatRole(this AgentMessageRole? role) => role?.ToChatRole() ?? ChatRole.User;
public static AIContent? ToContent(this AgentMessageContentType contentType, string? contentValue)
public static AIContent? ToContent(this AgentMessageContentType contentType, string? contentValue, string? mediaType = null)
{
if (string.IsNullOrEmpty(contentValue))
{
@@ -128,7 +130,7 @@ internal static class ChatMessageExtensions
return
contentType switch
{
AgentMessageContentType.ImageUrl => GetImageContent(contentValue),
AgentMessageContentType.ImageUrl => GetImageContent(contentValue, mediaType ?? InferMediaType(contentValue)),
AgentMessageContentType.ImageFile => new HostedFileContent(contentValue),
_ => new TextContent(contentValue)
};
@@ -159,14 +161,16 @@ internal static class ChatMessageExtensions
foreach (RecordDataValue contentItem in content.Values)
{
StringDataValue? contentValue = contentItem.GetProperty<StringDataValue>(TypeSchema.MessageContent.Fields.Value);
StringDataValue? mediaTypeValue = contentItem.GetProperty<StringDataValue>(TypeSchema.MessageContent.Fields.MediaType);
if (contentValue is null || string.IsNullOrWhiteSpace(contentValue.Value))
{
continue;
}
yield return
contentItem.GetProperty<StringDataValue>(TypeSchema.MessageContent.Fields.Type)?.Value switch
{
TypeSchema.MessageContent.ContentTypes.ImageUrl => GetImageContent(contentValue.Value),
TypeSchema.MessageContent.ContentTypes.ImageUrl => GetImageContent(contentValue.Value, mediaTypeValue?.Value ?? InferMediaType(contentValue.Value)),
TypeSchema.MessageContent.ContentTypes.ImageFile => new HostedFileContent(contentValue.Value),
_ => new TextContent(contentValue.Value)
};
@@ -174,10 +178,35 @@ internal static class ChatMessageExtensions
}
}
private static AIContent GetImageContent(string uriText) =>
private static string InferMediaType(string value)
{
// Base64 encoded content includes media type
if (value.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
{
int semicolonIndex = value.IndexOf(';');
if (semicolonIndex > 5)
{
return value.Substring(5, semicolonIndex - 5);
}
}
// URL based input only supports image
string fileExtension = Path.GetExtension(value);
return
fileExtension.ToUpperInvariant() switch
{
".JPG" or ".JPEG" => "image/jpeg",
".PNG" => "image/png",
".GIF" => "image/gif",
".WEBP" => "image/webp",
_ => "image/*"
};
}
private static AIContent GetImageContent(string uriText, string mediaType) =>
uriText.StartsWith("data:", StringComparison.OrdinalIgnoreCase) ?
new DataContent(uriText, "image/*") :
new UriContent(uriText, "image/*");
new DataContent(uriText, mediaType) :
new UriContent(uriText, mediaType);
private static TValue? GetProperty<TValue>(this RecordDataValue record, string name)
where TValue : DataValue
@@ -40,7 +40,7 @@ internal sealed class AddConversationMessageExecutor(AddConversationMessage mode
{
foreach (AddConversationMessageContent content in this.Model.Content)
{
AIContent? messageContent = content.Type.Value.ToContent(this.Engine.Format(content.Value));
AIContent? messageContent = content.Type.Value.ToContent(this.Engine.Format(content.Value), content.MediaType);
if (messageContent is not null)
{
yield return messageContent;
@@ -93,7 +93,7 @@ internal sealed class AIAgentHostExecutor : ChatProtocolExecutor
=> emitEvents ?? this._options.EmitAgentUpdateEvents ?? false;
private async ValueTask<AgentSession> EnsureSessionAsync(IWorkflowContext context, CancellationToken cancellationToken) =>
this._session ??= await this._agent.GetNewSessionAsync(cancellationToken).ConfigureAwait(false);
this._session ??= await this._agent.CreateSessionAsync(cancellationToken).ConfigureAwait(false);
private const string UserInputRequestStateKey = nameof(_userInputHandler);
private const string FunctionCallRequestStateKey = nameof(_functionCallHandler);
@@ -65,7 +65,7 @@ internal sealed class WorkflowHostAgent : AIAgent
protocol.ThrowIfNotChatProtocol(allowCatchAll: true);
}
public override ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default)
public override ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default)
=> new(new WorkflowSession(this._workflow, this.GenerateNewId(), this._executionEnvironment, this._checkpointManager, this._includeExceptionDetails, this._includeWorkflowOutputsInResponse));
public override ValueTask<AgentSession> DeserializeSessionAsync(JsonElement serializedSession, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)
@@ -73,7 +73,7 @@ internal sealed class WorkflowHostAgent : AIAgent
private async ValueTask<WorkflowSession> UpdateSessionAsync(IEnumerable<ChatMessage> messages, AgentSession? session = null, CancellationToken cancellationToken = default)
{
session ??= await this.GetNewSessionAsync(cancellationToken).ConfigureAwait(false);
session ??= await this.CreateSessionAsync(cancellationToken).ConfigureAwait(false);
if (session is not WorkflowSession workflowSession)
{
@@ -302,7 +302,7 @@ public sealed partial class ChatClientAgent : AIAgent
: this.ChatClient.GetService(serviceType, serviceKey));
/// <inheritdoc/>
public override async ValueTask<AgentSession> GetNewSessionAsync(CancellationToken cancellationToken = default)
public override async ValueTask<AgentSession> CreateSessionAsync(CancellationToken cancellationToken = default)
{
ChatHistoryProvider? chatHistoryProvider = this._agentOptions?.ChatHistoryProviderFactory is not null
? await this._agentOptions.ChatHistoryProviderFactory.Invoke(new() { SerializedState = default, JsonSerializerOptions = null }, cancellationToken).ConfigureAwait(false)
@@ -337,7 +337,7 @@ public sealed partial class ChatClientAgent : AIAgent
/// instances that support server-side conversation storage through their underlying <see cref="IChatClient"/>.
/// </para>
/// </remarks>
public async ValueTask<AgentSession> GetNewSessionAsync(string conversationId, CancellationToken cancellationToken = default)
public async ValueTask<AgentSession> CreateSessionAsync(string conversationId, CancellationToken cancellationToken = default)
{
AIContextProvider? contextProvider = this._agentOptions?.AIContextProviderFactory is not null
? await this._agentOptions.AIContextProviderFactory.Invoke(new() { SerializedState = default, JsonSerializerOptions = null }, cancellationToken).ConfigureAwait(false)
@@ -365,14 +365,14 @@ public sealed partial class ChatClientAgent : AIAgent
/// with a <see cref="ChatHistoryProvider"/> may not be compatible with these services.
/// </para>
/// <para>
/// Where a service requires server-side conversation storage, use <see cref="GetNewSessionAsync(string, CancellationToken)"/>.
/// Where a service requires server-side conversation storage, use <see cref="CreateSessionAsync(string, CancellationToken)"/>.
/// </para>
/// <para>
/// If the agent detects, during the first run, that the underlying AI service requires server-side conversation storage,
/// the session will throw an exception to indicate that it cannot continue using the provided <see cref="ChatHistoryProvider"/>.
/// </para>
/// </remarks>
public async ValueTask<AgentSession> GetNewSessionAsync(ChatHistoryProvider chatHistoryProvider, CancellationToken cancellationToken = default)
public async ValueTask<AgentSession> CreateSessionAsync(ChatHistoryProvider chatHistoryProvider, CancellationToken cancellationToken = default)
{
AIContextProvider? contextProvider = this._agentOptions?.AIContextProviderFactory is not null
? await this._agentOptions.AIContextProviderFactory.Invoke(new() { SerializedState = default, JsonSerializerOptions = null }, cancellationToken).ConfigureAwait(false)
@@ -689,7 +689,7 @@ public sealed partial class ChatClientAgent : AIAgent
throw new InvalidOperationException("A session must be provided when continuing a background response with a continuation token.");
}
session ??= await this.GetNewSessionAsync(cancellationToken).ConfigureAwait(false);
session ??= await this.CreateSessionAsync(cancellationToken).ConfigureAwait(false);
if (session is not ChatClientAgentSession typedSession)
{
throw new InvalidOperationException("The provided session is not compatible with the agent. Only sessions created by the agent can be used.");
@@ -22,7 +22,7 @@ public abstract class ChatClientAgentRunStreamingTests<TAgentFixture>(Func<TAgen
{
// Arrange
var agent = await this.Fixture.CreateChatClientAgentAsync(instructions: "Always respond with 'Computer says no', even if there was no user input.");
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var agentCleanup = new AgentCleanup(agent, this.Fixture);
await using var sessionCleanup = new SessionCleanup(session, this.Fixture);
@@ -53,7 +53,7 @@ public abstract class ChatClientAgentRunStreamingTests<TAgentFixture>(Func<TAgen
AIFunctionFactory.Create(MenuPlugin.GetSpecials),
AIFunctionFactory.Create(MenuPlugin.GetItemPrice)
]);
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
foreach (var questionAndAnswer in questionsAndAnswers)
{
@@ -21,7 +21,7 @@ public abstract class ChatClientAgentRunTests<TAgentFixture>(Func<TAgentFixture>
{
// Arrange
var agent = await this.Fixture.CreateChatClientAgentAsync(instructions: "ALWAYS RESPOND WITH 'Computer says no', even if there was no user input.");
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var agentCleanup = new AgentCleanup(agent, this.Fixture);
await using var sessionCleanup = new SessionCleanup(session, this.Fixture);
@@ -53,7 +53,7 @@ public abstract class ChatClientAgentRunTests<TAgentFixture>(Func<TAgentFixture>
AIFunctionFactory.Create(MenuPlugin.GetSpecials),
AIFunctionFactory.Create(MenuPlugin.GetItemPrice)
]);
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
foreach (var questionAndAnswer in questionsAndAnswers)
{
@@ -24,7 +24,7 @@ public abstract class RunStreamingTests<TAgentFixture>(Func<TAgentFixture> creat
{
// Arrange
var agent = this.Fixture.Agent;
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var cleanup = new SessionCleanup(session, this.Fixture);
// Act
@@ -36,7 +36,7 @@ public abstract class RunStreamingTests<TAgentFixture>(Func<TAgentFixture> creat
{
// Arrange
var agent = this.Fixture.Agent;
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var cleanup = new SessionCleanup(session, this.Fixture);
// Act
@@ -52,7 +52,7 @@ public abstract class RunStreamingTests<TAgentFixture>(Func<TAgentFixture> creat
{
// Arrange
var agent = this.Fixture.Agent;
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var cleanup = new SessionCleanup(session, this.Fixture);
// Act
@@ -68,7 +68,7 @@ public abstract class RunStreamingTests<TAgentFixture>(Func<TAgentFixture> creat
{
// Arrange
var agent = this.Fixture.Agent;
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var cleanup = new SessionCleanup(session, this.Fixture);
// Act
@@ -92,7 +92,7 @@ public abstract class RunStreamingTests<TAgentFixture>(Func<TAgentFixture> creat
const string Q1 = "What is the capital of France.";
const string Q2 = "And Austria?";
var agent = this.Fixture.Agent;
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var cleanup = new SessionCleanup(session, this.Fixture);
// Act
@@ -24,7 +24,7 @@ public abstract class RunTests<TAgentFixture>(Func<TAgentFixture> createAgentFix
{
// Arrange
var agent = this.Fixture.Agent;
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var cleanup = new SessionCleanup(session, this.Fixture);
// Act
@@ -39,7 +39,7 @@ public abstract class RunTests<TAgentFixture>(Func<TAgentFixture> createAgentFix
{
// Arrange
var agent = this.Fixture.Agent;
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var cleanup = new SessionCleanup(session, this.Fixture);
// Act
@@ -57,7 +57,7 @@ public abstract class RunTests<TAgentFixture>(Func<TAgentFixture> createAgentFix
{
// Arrange
var agent = this.Fixture.Agent;
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var cleanup = new SessionCleanup(session, this.Fixture);
// Act
@@ -74,7 +74,7 @@ public abstract class RunTests<TAgentFixture>(Func<TAgentFixture> createAgentFix
{
// Arrange
var agent = this.Fixture.Agent;
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var cleanup = new SessionCleanup(session, this.Fixture);
// Act
@@ -99,7 +99,7 @@ public abstract class RunTests<TAgentFixture>(Func<TAgentFixture> createAgentFix
const string Q1 = "What is the capital of France.";
const string Q2 = "And Austria?";
var agent = this.Fixture.Agent;
var session = await agent.GetNewSessionAsync();
var session = await agent.CreateSessionAsync();
await using var cleanup = new SessionCleanup(session, this.Fixture);
// Act

Some files were not shown because too many files have changed in this diff Show More