chore: import upstream snapshot with attribution
CodeQL / Analyze (csharp) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:21:23 +08:00
commit b957a53def
5423 changed files with 863745 additions and 0 deletions
@@ -0,0 +1,143 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Agents.OpenAI;
using Microsoft.SemanticKernel.ChatCompletion;
namespace GettingStarted.OpenAIResponseAgents;
/// <summary>
/// This example demonstrates using <see cref="OpenAIResponseAgent"/>.
/// </summary>
public class Step01_OpenAIResponseAgent(ITestOutputHelper output) : BaseResponsesAgentTest(output)
{
[Fact]
public async Task UseOpenAIResponseAgentAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
Name = "ResponseAgent",
Instructions = "Answer all queries in English and French.",
};
// Invoke the agent and output the response
var responseItems = agent.InvokeAsync("What is the capital of France?");
await foreach (ChatMessageContent responseItem in responseItems)
{
WriteAgentChatMessage(responseItem);
}
}
[Fact]
public async Task UseOpenAIResponseAgentStreamingAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
Name = "ResponseAgent",
Instructions = "Answer all queries in English and French.",
};
// Invoke the agent and output the response
var responseItems = agent.InvokeStreamingAsync("What is the capital of France?");
await WriteAgentStreamMessageAsync(responseItems);
}
[Fact]
public async Task UseOpenAIResponseAgentWithThreadedConversationAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
Name = "ResponseAgent",
Instructions = "Answer all queries in the users preferred language.",
};
string[] messages =
[
"My name is Bob and my preferred language is French.",
"What is the capital of France?",
"What is the capital of Spain?",
"What is the capital of Italy?"
];
// Initial thread can be null as it will be automatically created
AgentThread? agentThread = null;
// Invoke the agent and output the response
foreach (string message in messages)
{
Console.Write($"Agent Thread Id: {agentThread?.Id}");
var responseItems = agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, message), agentThread);
await foreach (AgentResponseItem<ChatMessageContent> responseItem in responseItems)
{
// Update the thread so the previous response id is used
agentThread = responseItem.Thread;
WriteAgentChatMessage(responseItem.Message);
}
}
}
[Fact]
public async Task UseOpenAIResponseAgentWithThreadedConversationStreamingAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
Name = "ResponseAgent",
Instructions = "Answer all queries in the users preferred language.",
};
string[] messages =
[
"My name is Bob and my preferred language is French.",
"What is the capital of France?",
"What is the capital of Spain?",
"What is the capital of Italy?"
];
// Initial thread can be null as it will be automatically created
AgentThread? agentThread = null;
// Invoke the agent and output the response
foreach (string message in messages)
{
Console.Write($"Agent Thread Id: {agentThread?.Id}");
var responseItems = agent.InvokeStreamingAsync(new ChatMessageContent(AuthorRole.User, message), agentThread);
// Update the thread so the previous response id is used
agentThread = await WriteAgentStreamMessageAsync(responseItems);
}
}
[Fact]
public async Task UseOpenAIResponseAgentWithImageContentAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
Name = "ResponseAgent",
Instructions = "Provide a detailed description including the weather conditions.",
};
ICollection<ChatMessageContent> messages =
[
new ChatMessageContent(
AuthorRole.User,
items: [
new TextContent("What is in this image?"),
new ImageContent(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"))
]
),
];
// Invoke the agent and output the response
var responseItems = agent.InvokeAsync(messages);
await foreach (ChatMessageContent responseItem in responseItems)
{
WriteAgentChatMessage(responseItem);
}
}
}
@@ -0,0 +1,233 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Agents.OpenAI;
using Microsoft.SemanticKernel.ChatCompletion;
namespace GettingStarted.OpenAIResponseAgents;
/// <summary>
/// This example demonstrates how to manage conversation state during a model interaction using <see cref="OpenAIResponseAgent"/>.
/// OpenAI provides a few ways to manage conversation state, which is important for preserving information across multiple messages or turns in a conversation.
/// See: https://platform.openai.com/docs/guides/conversation-state?api-mode=responses for more information.
/// </summary>
public class Step02_OpenAIResponseAgent_ConversationState(ITestOutputHelper output) : BaseResponsesAgentTest(output)
{
[Fact]
public async Task ManuallyConstructPastConversationAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
StoreEnabled = false,
};
ICollection<ChatMessageContent> messages =
[
new ChatMessageContent(AuthorRole.User, "knock knock."),
new ChatMessageContent(AuthorRole.Assistant, "Who's there?"),
new ChatMessageContent(AuthorRole.User, "Orange.")
];
foreach (ChatMessageContent message in messages)
{
WriteAgentChatMessage(message);
}
// Invoke the agent and output the response
var responseItems = agent.InvokeAsync(messages);
await foreach (ChatMessageContent responseItem in responseItems)
{
WriteAgentChatMessage(responseItem);
}
}
[Fact]
public async Task ManuallyConstructPastConversationStreamingAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
StoreEnabled = false,
};
ICollection<ChatMessageContent> messages =
[
new ChatMessageContent(AuthorRole.User, "knock knock."),
new ChatMessageContent(AuthorRole.Assistant, "Who's there?"),
new ChatMessageContent(AuthorRole.User, "Orange.")
];
foreach (ChatMessageContent message in messages)
{
WriteAgentChatMessage(message);
}
// Invoke the agent and output the response
var responseItems = agent.InvokeStreamingAsync(messages);
Console.Write("\n# assistant: ");
await foreach (StreamingChatMessageContent responseItem in responseItems)
{
Console.Write(responseItem.Content);
}
}
[Fact]
public async Task ManageConversationStateWithResponseIdAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
StoreEnabled = false,
};
string[] messages =
[
"Tell me a joke?",
"Explain why this is funny?",
];
// Invoke the agent and output the response
AgentThread? agentThread = null;
foreach (string message in messages)
{
var userMessage = new ChatMessageContent(AuthorRole.User, message);
WriteAgentChatMessage(userMessage);
var responseItems = agent.InvokeAsync(userMessage, agentThread);
await foreach (AgentResponseItem<ChatMessageContent> responseItem in responseItems)
{
agentThread = responseItem.Thread;
WriteAgentChatMessage(responseItem.Message);
}
}
}
[Fact]
public async Task ManageConversationStateWithResponseIdStreamingAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
StoreEnabled = false,
};
string[] messages =
[
"Tell me a joke?",
"Explain why this is funny?",
];
// Invoke the agent and output the response
AgentThread? agentThread = null;
foreach (string message in messages)
{
var userMessage = new ChatMessageContent(AuthorRole.User, message);
WriteAgentChatMessage(userMessage);
Console.Write("\n# assistant: ");
var responseItems = agent.InvokeStreamingAsync(userMessage, agentThread);
await foreach (AgentResponseItem<StreamingChatMessageContent> responseItem in responseItems)
{
agentThread = responseItem.Thread;
Console.Write(responseItem.Message.Content);
}
}
}
[Fact]
public async Task StoreConversationStateAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
StoreEnabled = true,
};
string[] messages =
[
"Tell me a joke?",
"Explain why this is funny.",
];
// Invoke the agent and output the response
AgentThread? agentThread = null;
foreach (string message in messages)
{
var userMessage = new ChatMessageContent(AuthorRole.User, message);
WriteAgentChatMessage(userMessage);
var responseItems = agent.InvokeAsync(userMessage, agentThread);
await foreach (AgentResponseItem<ChatMessageContent> responseItem in responseItems)
{
agentThread = responseItem.Thread;
WriteAgentChatMessage(responseItem.Message);
}
}
// Display the contents in the latest thread
if (agentThread is not null)
{
this.Output.WriteLine("\n\nResponse Thread Messages\n");
var responseAgentThread = agentThread as OpenAIResponseAgentThread;
var threadMessages = responseAgentThread?.GetMessagesAsync();
if (threadMessages is not null)
{
await foreach (var threadMessage in threadMessages)
{
WriteAgentChatMessage(threadMessage);
}
}
await agentThread.DeleteAsync();
}
}
[Fact]
public async Task StoreConversationStateWithStreamingAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
StoreEnabled = true,
};
string[] messages =
[
"Tell me a joke?",
"Explain why this is funny.",
];
// Invoke the agent and output the response
AgentThread? agentThread = null;
foreach (string message in messages)
{
var userMessage = new ChatMessageContent(AuthorRole.User, message);
WriteAgentChatMessage(userMessage);
Console.Write("\n# assistant: ");
var responseItems = agent.InvokeStreamingAsync(userMessage, agentThread);
await foreach (AgentResponseItem<StreamingChatMessageContent> responseItem in responseItems)
{
agentThread = responseItem.Thread;
Console.Write(responseItem.Message.Content);
}
}
// Display the contents in the latest thread
if (agentThread is not null)
{
this.Output.WriteLine("\n\nResponse Thread Messages\n");
var responseAgentThread = agentThread as OpenAIResponseAgentThread;
var threadMessages = responseAgentThread?.GetMessagesAsync();
if (threadMessages is not null)
{
await foreach (var threadMessage in threadMessages)
{
WriteAgentChatMessage(threadMessage);
}
}
await agentThread.DeleteAsync();
}
}
}
@@ -0,0 +1,106 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents.OpenAI;
using OpenAI.Responses;
using Plugins;
namespace GettingStarted.OpenAIResponseAgents;
/// <summary>
/// This example demonstrates using <see cref="OpenAIResponseAgent"/>.
/// </summary>
public class Step03_OpenAIResponseAgent_ReasoningModel(ITestOutputHelper output) : BaseResponsesAgentTest(output, "o4-mini")
{
[Fact]
public async Task UseOpenAIResponseAgentWithAReasoningModelAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
Name = "ResponseAgent",
Instructions = "Answer all queries with a detailed response.",
};
// Invoke the agent and output the response
var responseItems = agent.InvokeAsync("Which of the last four Olympic host cities has the highest average temperature?");
await foreach (ChatMessageContent responseItem in responseItems)
{
WriteAgentChatMessage(responseItem);
}
}
[Fact]
public async Task UseOpenAIResponseAgentWithAReasoningModelAndSummariesAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId);
// ResponseCreationOptions allows you to specify tools for the agent.
OpenAIResponseAgentInvokeOptions invokeOptions = new()
{
ResponseCreationOptions = new()
{
ReasoningOptions = new()
{
ReasoningEffortLevel = ResponseReasoningEffortLevel.High,
// This parameter cannot be used due to a known issue in the OpenAI .NET SDK.
// https://github.com/openai/openai-dotnet/issues/457
// ReasoningSummaryVerbosity = ResponseReasoningSummaryVerbosity.Detailed,
},
},
};
// Invoke the agent and output the response
var responseItems = agent.InvokeAsync(
"""
Instructions:
- Given the React component below, change it so that nonfiction books have red
text.
- Return only the code in your reply
- Do not include any additional formatting, such as markdown code blocks
- For formatting, use four space tabs, and do not allow any lines of code to
exceed 80 columns
const books = [
{ title: 'Dune', category: 'fiction', id: 1 },
{ title: 'Frankenstein', category: 'fiction', id: 2 },
{ title: 'Moneyball', category: 'nonfiction', id: 3 },
];
export default function BookList() {
const listItems = books.map(book =>
<li>
{book.title}
</li>
);
return (
<ul>{listItems}</ul>
);
}
""", options: invokeOptions);
await foreach (ChatMessageContent responseItem in responseItems)
{
WriteAgentChatMessage(responseItem);
}
}
[Fact]
public async Task UseOpenAIResponseAgentWithAReasoningModelAndToolsAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
Name = "ResponseAgent",
Instructions = "Answer all queries with a detailed response.",
};
// Create a plugin that defines the tools to be used by the agent.
KernelPlugin plugin = KernelPluginFactory.CreateFromType<MenuPlugin>();
agent.Kernel.Plugins.Add(plugin);
// Invoke the agent and output the response
var responseItems = agent.InvokeAsync("What is the best value healthy meal?");
await foreach (ChatMessageContent responseItem in responseItems)
{
WriteAgentChatMessage(responseItem);
}
}
}
@@ -0,0 +1,168 @@
// Copyright (c) Microsoft. All rights reserved.
using System.ClientModel;
using System.ClientModel.Primitives;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents.OpenAI;
using Microsoft.SemanticKernel.ChatCompletion;
using OpenAI.Files;
using OpenAI.Responses;
using OpenAI.VectorStores;
using Plugins;
using Resources;
namespace GettingStarted.OpenAIResponseAgents;
/// <summary>
/// This example demonstrates how to use tools during a model interaction using <see cref="OpenAIResponseAgent"/>.
/// </summary>
public class Step04_OpenAIResponseAgent_Tools(ITestOutputHelper output) : BaseResponsesAgentTest(output)
{
[Fact]
public async Task InvokeAgentWithFunctionToolsAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
StoreEnabled = false,
};
// Create a plugin that defines the tools to be used by the agent.
KernelPlugin plugin = KernelPluginFactory.CreateFromType<MenuPlugin>();
agent.Kernel.Plugins.Add(plugin);
ICollection<ChatMessageContent> messages =
[
new ChatMessageContent(AuthorRole.User, "What is the special soup and its price?"),
new ChatMessageContent(AuthorRole.User, "What is the special drink and its price?"),
];
foreach (ChatMessageContent message in messages)
{
WriteAgentChatMessage(message);
}
// Invoke the agent and output the response
var responseItems = agent.InvokeAsync(messages);
await foreach (ChatMessageContent responseItem in responseItems)
{
WriteAgentChatMessage(responseItem);
}
}
[Fact]
public async Task InvokeAgentWithWebSearchAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
StoreEnabled = false,
};
// ResponseCreationOptions allows you to specify tools for the agent.
CreateResponseOptions creationOptions = new();
creationOptions.Tools.Add(ResponseTool.CreateWebSearchTool());
OpenAIResponseAgentInvokeOptions invokeOptions = new()
{
ResponseCreationOptions = creationOptions,
};
// Invoke the agent and output the response
var responseItems = agent.InvokeAsync("What was a positive news story from today?", options: invokeOptions);
await foreach (ChatMessageContent responseItem in responseItems)
{
WriteAgentChatMessage(responseItem);
}
}
[Fact]
public async Task InvokeAgentWithFileSearchAsync()
{
// Upload a file to the OpenAI File API
await using Stream stream = EmbeddedResource.ReadStream("employees.pdf")!;
OpenAIFile file = await this.FileClient.UploadFileAsync(stream, filename: "employees.pdf", purpose: FileUploadPurpose.UserData);
// Create a vector store for the file
ClientResult<VectorStore> createStoreOp = await this.VectorStoreClient.CreateVectorStoreAsync(
new VectorStoreCreationOptions()
{
FileIds = { file.Id },
});
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
StoreEnabled = false,
};
// ResponseCreationOptions allows you to specify tools for the agent.
CreateResponseOptions creationOptions = new();
creationOptions.Tools.Add(ResponseTool.CreateFileSearchTool([createStoreOp.Value.Id], null));
OpenAIResponseAgentInvokeOptions invokeOptions = new()
{
ResponseCreationOptions = creationOptions,
};
// Invoke the agent and output the response
ICollection<ChatMessageContent> messages =
[
new ChatMessageContent(AuthorRole.User, "Who is the youngest employee?"),
new ChatMessageContent(AuthorRole.User, "Who works in sales?"),
new ChatMessageContent(AuthorRole.User, "I have a customer request, who can help me?"),
];
foreach (ChatMessageContent message in messages)
{
WriteAgentChatMessage(message);
}
// Invoke the agent and output the response
var responseItems = agent.InvokeAsync(messages, options: invokeOptions);
await foreach (ChatMessageContent responseItem in responseItems)
{
WriteAgentChatMessage(responseItem);
}
// Clean up resources
RequestOptions noThrowOptions = new() { ErrorOptions = ClientErrorBehaviors.NoThrow };
this.FileClient.DeleteFile(file.Id, noThrowOptions);
this.VectorStoreClient.DeleteVectorStore(createStoreOp.Value.Id, noThrowOptions);
}
[Fact]
public async Task InvokeAgentWithMultipleToolsAsync()
{
// Define the agent
OpenAIResponseAgent agent = new(this.Client, this.ModelId)
{
StoreEnabled = false,
};
// Create a plugin that defines the tools to be used by the agent.
KernelPlugin plugin = KernelPluginFactory.CreateFromType<MenuPlugin>();
agent.Kernel.Plugins.Add(plugin);
ICollection<ChatMessageContent> messages =
[
new ChatMessageContent(AuthorRole.User, "What is the special soup and its price?"),
new ChatMessageContent(AuthorRole.User, "What is the special drink and its price?"),
];
foreach (ChatMessageContent message in messages)
{
WriteAgentChatMessage(message);
}
// ResponseCreationOptions allows you to specify tools for the agent.
CreateResponseOptions creationOptions = new();
creationOptions.Tools.Add(ResponseTool.CreateWebSearchTool());
OpenAIResponseAgentInvokeOptions invokeOptions = new()
{
ResponseCreationOptions = creationOptions,
};
// Invoke the agent and output the response
var responseItems = agent.InvokeAsync(messages, options: invokeOptions);
await foreach (ChatMessageContent responseItem in responseItems)
{
WriteAgentChatMessage(responseItem);
}
}
}