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,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<NoWarn>$(NoWarn);SKEXP0001</NoWarn>
<UserSecretsId>5ee045b0-aea3-4f08-8d31-32d1a6f8fed0</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.Extensions.Http" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Connectors\Connectors.OpenAI\Connectors.OpenAI.csproj" />
<ProjectReference Include="..\..\..\src\Plugins\Plugins.Core\Plugins.Core.csproj" />
<ProjectReference Include="..\..\..\src\SemanticKernel.Abstractions\SemanticKernel.Abstractions.csproj" />
<ProjectReference Include="..\..\..\src\SemanticKernel.Core\SemanticKernel.Core.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,113 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Text;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.Plugins.Core.CodeInterpreter;
#pragma warning disable SKEXP0050 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
var configuration = new ConfigurationBuilder()
.AddUserSecrets<Program>()
.AddEnvironmentVariables()
.Build();
var apiKey = configuration["OpenAI:ApiKey"];
var modelId = configuration["OpenAI:ChatModelId"];
var endpoint = configuration["AzureContainerAppSessionPool:Endpoint"];
// Cached token for the Azure Container Apps service
string? cachedToken = null;
// Logger for program scope
ILogger logger = NullLogger.Instance;
ArgumentNullException.ThrowIfNull(apiKey);
ArgumentNullException.ThrowIfNull(modelId);
ArgumentNullException.ThrowIfNull(endpoint);
/// <summary>
/// Acquire a token for the Azure Container Apps service
/// </summary>
async Task<string> TokenProvider(CancellationToken cancellationToken)
{
if (cachedToken is null)
{
string resource = "https://acasessions.io/.default";
var credential = new InteractiveBrowserCredential();
// Attempt to get the token
var accessToken = await credential.GetTokenAsync(new Azure.Core.TokenRequestContext([resource]), cancellationToken).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Access token obtained successfully");
}
cachedToken = accessToken.Token;
}
return cachedToken;
}
var settings = new SessionsPythonSettings(
sessionId: Guid.NewGuid().ToString(),
endpoint: new Uri(endpoint));
// Uncomment the following lines to enable file upload operations (disabled by default for security)
// settings.EnableDangerousFileUploads = true;
// settings.AllowedUploadDirectories = new[] { @"C:\allowed\upload\directory" };
// settings.AllowedDownloadDirectories = new[] { @"C:\allowed\download\directory" };
Console.WriteLine("=== Code Interpreter With Azure Container Apps Plugin Demo ===\n");
Console.WriteLine("Start your conversation with the assistant. Type enter or an empty message to quit.");
var builder =
Kernel.CreateBuilder()
.AddOpenAIChatCompletion(modelId, apiKey);
// Change the log level to Trace to see more detailed logs
builder.Services.AddLogging(loggingBuilder => loggingBuilder.AddConsole().SetMinimumLevel(LogLevel.Information));
builder.Services.AddHttpClient();
builder.Services.AddSingleton((sp)
=> new SessionsPythonPlugin(
settings,
sp.GetRequiredService<IHttpClientFactory>(),
TokenProvider,
sp.GetRequiredService<ILoggerFactory>()));
var kernel = builder.Build();
logger = kernel.GetRequiredService<ILoggerFactory>().CreateLogger<Program>();
kernel.Plugins.AddFromObject(kernel.GetRequiredService<SessionsPythonPlugin>());
var chatCompletion = kernel.GetRequiredService<IChatCompletionService>();
var chatHistory = new ChatHistory();
StringBuilder fullAssistantContent = new();
while (true)
{
Console.Write("\nUser: ");
var input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input)) { break; }
chatHistory.AddUserMessage(input);
Console.WriteLine("Assistant: ");
fullAssistantContent.Clear();
await foreach (var content in chatCompletion.GetStreamingChatMessageContentsAsync(
chatHistory,
new OpenAIPromptExecutionSettings { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() },
kernel)
.ConfigureAwait(false))
{
Console.Write(content.Content);
fullAssistantContent.Append(content.Content);
}
chatHistory.AddAssistantMessage(fullAssistantContent.ToString());
}
@@ -0,0 +1,59 @@
# Semantic Kernel - Code Interpreter Plugin with Azure Container Apps
This example demonstrates how to do AI Code Interpretetion using a Plugin with Azure Container Apps to execute python code in a container.
## Create and Configure Azure Container App Session Pool
1. Create a new Container App Session Pool using the Azure CLI or Azure Portal.
2. Specify "Python code interpreter" as the pool type.
3. Add the following roles to the user that will be used to access the session pool:
- The `Azure ContainerApps Session Executor` role to be able to create and manage sessions.
- The `Container Apps SessionPools Contributor` role to be able to work with files.
## Configuring Secrets
The example require credentials to access OpenAI and Azure Container Apps (ACA)
If you have set up those credentials as secrets within Secret Manager or through environment variables for other samples from the solution in which this project is found, they will be re-used.
### To set your secrets with Secret Manager:
```
dotnet user-secrets init
dotnet user-secrets set "OpenAI:ApiKey" "..."
dotnet user-secrets set "OpenAI:ChatModelId" "gpt-3.5-turbo" # or any other function callable model.
dotnet user-secrets set "AzureContainerAppSessionPool:Endpoint" " .. endpoint .. "
```
### To set your secrets with environment variables
Use these names:
```
# OpenAI
OpenAI__ApiKey
OpenAI__ChatModelId
# Azure Container Apps
AzureContainerAppSessionPool__Endpoint
```
### Usage Example
User: Upload the file c:\temp\code-interpreter\test-file.txt
Assistant: The file test-file.txt has been successfully uploaded.
User: How many files I have uploaded ?
Assistant: You have uploaded 1 file.
User: Show me the contents of this file
Assistant: The contents of the file "test-file.txt" are as follows:
```text
the contents of the file
```