Skip to content

Commit

Permalink
.Net: Use C# 11/12 features throughout repo (#4387)
Browse files Browse the repository at this point in the history
~~Fixes #4295. For
now this is done using a package reference to the latest C# toolset.
Once we drop use of the .NET 6/7 SDKs in CI, this reference can be
removed.~~

The changes to upgrade projects to LangVersion 12 was done separately.
This PR now rolls out use of C# 12 features.
  • Loading branch information
stephentoub committed Apr 11, 2024
1 parent cbbaa59 commit 8d0662e
Show file tree
Hide file tree
Showing 299 changed files with 1,622 additions and 1,790 deletions.
5 changes: 0 additions & 5 deletions dotnet/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,6 @@
<!-- Symbols -->
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="8.0.0" />
<!-- Toolset -->
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.9.28" />
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers">
<PrivateAssets>all</PrivateAssets>
Expand Down
3 changes: 2 additions & 1 deletion dotnet/samples/CreateChatGptPlugin/.editorconfig
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
[*.cs]
dotnet_diagnostic.CA1016.severity = none
dotnet_diagnostic.CA1016.severity = none
dotnet_diagnostic.CA2007.severity = none
2 changes: 1 addition & 1 deletion dotnet/samples/CreateChatGptPlugin/Solution/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
await kernel.ImportPluginFromOpenApiAsync("MathPlugin", new Uri("http://localhost:7071/swagger.json")).ConfigureAwait(false);

// Create chat history
ChatHistory history = new();
ChatHistory history = [];

// Get chat completion service
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
Expand Down
2 changes: 1 addition & 1 deletion dotnet/samples/DocumentationExamples/BaseTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public abstract class BaseTest
{
protected ITestOutputHelper Output { get; }

protected List<string> SimulatedInputText = new();
protected List<string> SimulatedInputText = [];
protected int SimulatedInputTextIndex = 0;

protected BaseTest(ITestOutputHelper output)
Expand Down
9 changes: 4 additions & 5 deletions dotnet/samples/DocumentationExamples/ConfiguringPrompts.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// Copyright (c) Microsoft. All rights reserved.

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.SemanticKernel;
Expand Down Expand Up @@ -50,11 +49,11 @@ public async Task RunAsync()
User: {{$request}}
Assistant: ",
TemplateFormat = "semantic-kernel",
InputVariables = new List<InputVariable>()
{
InputVariables =
[
new() { Name = "history", Description = "The history of the conversation.", IsRequired = false, Default = "" },
new() { Name = "request", Description = "The user's request.", IsRequired = true }
},
],
ExecutionSettings =
{
{
Expand Down Expand Up @@ -88,7 +87,7 @@ public async Task RunAsync()
// </FunctionFromPrompt>

// Create chat history and choices
ChatHistory history = new();
ChatHistory history = [];

// Start the chat loop
Write("User > ");
Expand Down
2 changes: 1 addition & 1 deletion dotnet/samples/DocumentationExamples/CreatingFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public async Task RunAsync()
// </RunningNativeFunction>

// Create chat history
ChatHistory history = new();
ChatHistory history = [];

// <Chat>

Expand Down
20 changes: 9 additions & 11 deletions dotnet/samples/DocumentationExamples/FunctionsWithinPrompts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,24 +41,22 @@ public async Task RunAsync()
Kernel kernel = builder.Build();
// </KernelCreation>

List<string> choices = new() { "ContinueConversation", "EndConversation" };
List<string> choices = ["ContinueConversation", "EndConversation"];

// Create few-shot examples
List<ChatHistory> fewShotExamples = new()
{
new ChatHistory()
{
List<ChatHistory> fewShotExamples =
[
[
new ChatMessageContent(AuthorRole.User, "Can you send a very quick approval to the marketing team?"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "ContinueConversation")
},
new ChatHistory()
{
],
[
new ChatMessageContent(AuthorRole.User, "Can you send the full update to the marketing team?"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "EndConversation")
}
};
]
];

// Create handlebars template for intent
// <IntentFunction>
Expand Down Expand Up @@ -97,7 +95,7 @@ public async Task RunAsync()

// <Chat>
// Create chat history
ChatHistory history = new();
ChatHistory history = [];

// Start the chat loop
while (true)
Expand Down
2 changes: 1 addition & 1 deletion dotnet/samples/DocumentationExamples/Planner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public async Task RunAsync()
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();

// Create chat history
ChatHistory history = new();
ChatHistory history = [];

// Start the conversation
Write("User > ");
Expand Down
20 changes: 9 additions & 11 deletions dotnet/samples/DocumentationExamples/SerializingPrompts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,25 @@ await reader.ReadToEndAsync(),
);

// Create choices
List<string> choices = new() { "ContinueConversation", "EndConversation" };
List<string> choices = ["ContinueConversation", "EndConversation"];

// Create few-shot examples
List<ChatHistory> fewShotExamples = new()
{
new ChatHistory()
{
List<ChatHistory> fewShotExamples =
[
[
new ChatMessageContent(AuthorRole.User, "Can you send a very quick approval to the marketing team?"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "ContinueConversation")
},
new ChatHistory()
{
],
[
new ChatMessageContent(AuthorRole.User, "Can you send the full update to the marketing team?"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "EndConversation")
}
};
]
];

// Create chat history
ChatHistory history = new();
ChatHistory history = [];

// Start the chat loop
Write("User > ");
Expand Down
14 changes: 6 additions & 8 deletions dotnet/samples/DocumentationExamples/Templates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,21 @@ public async Task RunAsync()
Assistant: ");

// Create choices
List<string> choices = new() { "ContinueConversation", "EndConversation" };
List<string> choices = ["ContinueConversation", "EndConversation"];

// Create few-shot examples
List<ChatHistory> fewShotExamples =
[
new ChatHistory()
{
[
new ChatMessageContent(AuthorRole.User, "Can you send a very quick approval to the marketing team?"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "ContinueConversation")
},
new ChatHistory()
{
],
[
new ChatMessageContent(AuthorRole.User, "Thanks, I'm done for now"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "EndConversation")
}
]
];

// Create handlebars template for intent
Expand Down Expand Up @@ -89,7 +87,7 @@ public async Task RunAsync()
new HandlebarsPromptTemplateFactory()
);

ChatHistory history = new();
ChatHistory history = [];

// Start the chat loop
while (true)
Expand Down
2 changes: 1 addition & 1 deletion dotnet/samples/HomeAutomation/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ internal static async Task Main(string[] args)
builder.Services.AddKeyedTransient<Kernel>("HomeAutomationKernel", (sp, key) =>
{
// Create a collection of plugins that the kernel will use
KernelPluginCollection pluginCollection = new();
KernelPluginCollection pluginCollection = [];
pluginCollection.AddFromObject(sp.GetRequiredService<MyTimePlugin>());
pluginCollection.AddFromObject(sp.GetRequiredService<MyAlarmPlugin>());
pluginCollection.AddFromObject(sp.GetRequiredKeyedService<MyLightPlugin>("OfficeLight"), "OfficeLight");
Expand Down
6 changes: 3 additions & 3 deletions dotnet/samples/KernelSyntaxExamples/Example16_CustomLLM.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,10 @@ public async IAsyncEnumerable<StreamingTextContent> GetStreamingTextContentsAsyn

public Task<IReadOnlyList<TextContent>> GetTextContentsAsync(string prompt, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default)
{
return Task.FromResult<IReadOnlyList<TextContent>>(new List<TextContent>
{
return Task.FromResult<IReadOnlyList<TextContent>>(
[
new(LLMResultText)
});
]);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public async Task RunInferenceApiEmbeddingAsync()
var embeddingGenerator = kernel.GetRequiredService<ITextEmbeddingGenerationService>();

// Generate embeddings for each chunk.
var embeddings = await embeddingGenerator.GenerateEmbeddingsAsync(new[] { "John: Hello, how are you?\nRoger: Hey, I'm Roger!" });
var embeddings = await embeddingGenerator.GenerateEmbeddingsAsync(["John: Hello, how are you?\nRoger: Hey, I'm Roger!"]);

this.WriteLine($"Generated {embeddings.Count} embeddings for the provided text");
}
Expand Down
14 changes: 8 additions & 6 deletions dotnet/samples/KernelSyntaxExamples/Example21_OpenAIPlugins.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,14 @@ public async Task CallKlarnaAsync()

var plugin = await kernel.ImportPluginFromOpenAIAsync("Klarna", new Uri("https://www.klarna.com/.well-known/ai-plugin.json"));

var arguments = new KernelArguments();
arguments["q"] = "Laptop"; // Category or product that needs to be searched for.
arguments["size"] = "3"; // Number of products to return
arguments["budget"] = "200"; // Maximum price of the matching product in local currency
arguments["countryCode"] = "US";// ISO 3166 country code with 2 characters based on the user location.
// Currently, only US, GB, DE, SE and DK are supported.
var arguments = new KernelArguments
{
["q"] = "Laptop", // Category or product that needs to be searched for.
["size"] = "3", // Number of products to return
["budget"] = "200", // Maximum price of the matching product in local currency
["countryCode"] = "US" // ISO 3166 country code with 2 characters based on the user location.
};
// Currently, only US, GB, DE, SE and DK are supported.

var functionResult = await kernel.InvokeAsync(plugin["productsUsingGET"], arguments);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,11 @@ private async Task AddSecretToAzureKeyVaultAsync(Kernel kernel, KernelPlugin plu
private static async Task GetSecretFromAzureKeyVaultWithRetryAsync(Kernel kernel, KernelPlugin plugin)
{
// Add arguments for required parameters, arguments for optional ones can be skipped.
var arguments = new KernelArguments();
arguments["secret-name"] = SecretName;
arguments["api-version"] = "7.0";
var arguments = new KernelArguments
{
["secret-name"] = SecretName,
["api-version"] = "7.0"
};

// Run
var functionResult = await kernel.InvokeAsync(plugin["GetSecret"], arguments);
Expand Down Expand Up @@ -139,8 +141,8 @@ internal sealed class OpenAIAuthenticationProvider
/// <param name="credentials">A dictionary containing credentials for each authentication scheme.</param>
public OpenAIAuthenticationProvider(Dictionary<string, Dictionary<string, string>>? oAuthValues = null, Dictionary<string, string>? credentials = null)
{
this._oAuthValues = oAuthValues ?? new();
this._credentials = credentials ?? new();
this._oAuthValues = oAuthValues ?? [];
this._credentials = credentials ?? [];
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,13 @@ public async Task RunAsync()
);
}

var arguments = new KernelArguments();

// GetIssue Function
// Set Properties for the Get Issue operation in the openAPI.swagger.json
// Make sure the issue exists in your Jira instance or it will return a 404
arguments["issueKey"] = "TEST-1";
var arguments = new KernelArguments
{
// GetIssue Function
// Set Properties for the Get Issue operation in the openAPI.swagger.json
// Make sure the issue exists in your Jira instance or it will return a 404
["issueKey"] = "TEST-1"
};

// Run operation via the semantic kernel
var result = await kernel.InvokeAsync(jiraFunctions["GetIssue"], arguments);
Expand All @@ -102,7 +103,7 @@ public async Task RunAsync()

// AddComment Function
arguments["issueKey"] = "TEST-2";
arguments[RestApiOperation.PayloadArgumentName] = "{\"body\": \"Here is a rad comment\"}";
arguments[RestApiOperation.PayloadArgumentName] = """{"body": "Here is a rad comment"}""";

// Run operation via the semantic kernel
result = await kernel.InvokeAsync(jiraFunctions["AddComment"], arguments);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public async Task RunAsync()
{
var store = new ReadOnlyMemoryStore(s_jsonVectorEntries);

var embedding = new ReadOnlyMemory<float>(new float[] { 22, 4, 6 });
var embedding = new ReadOnlyMemory<float>([22, 4, 6]);

WriteLine("Reading data from custom read-only memory store");
var memoryRecord = await store.GetAsync("collection", "key3");
Expand Down Expand Up @@ -136,7 +136,7 @@ public IAsyncEnumerable<string> GetCollectionsAsync(CancellationToken cancellati
throw new Exception($"Embedding vector size {embedding.Length} does not match expected size of {this._vectorSize}");
}

List<(MemoryRecord Record, double Score)> embeddings = new();
List<(MemoryRecord Record, double Score)> embeddings = [];

foreach (var item in this._memoryRecords)
{
Expand Down
8 changes: 5 additions & 3 deletions dotnet/samples/KernelSyntaxExamples/Example35_GrpcPlugins.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ public async Task RunAsync()
var plugin = kernel.ImportPluginFromGrpcFile("<path-to-.proto-file>", "<plugin-name>");

// Add arguments for required parameters, arguments for optional ones can be skipped.
var arguments = new KernelArguments();
arguments["address"] = "<gRPC-server-address>";
arguments["payload"] = "<gRPC-request-message-as-json>";
var arguments = new KernelArguments
{
["address"] = "<gRPC-server-address>",
["payload"] = "<gRPC-request-message-as-json>"
};

// Run
var result = await kernel.InvokeAsync(plugin["<operation-name>"], arguments);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,10 @@ public async Task StreamingIdentityAsync(bool withName)
private static ChatHistory CreateHistory(bool withName)
{
return
new ChatHistory()
{
[
new ChatMessageContent(AuthorRole.System, "Write one paragraph in response to the user that rhymes") { AuthorName = withName ? "Echo" : null },
new ChatMessageContent(AuthorRole.User, "Why is AI awesome") { AuthorName = withName ? "Ralph" : null },
};
];
}

private void ValidateMessages(ChatHistory chatHistory, bool expectName)
Expand Down
12 changes: 3 additions & 9 deletions dotnet/samples/KernelSyntaxExamples/Example40_DIContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,10 @@ public async Task RunAsync()
/// <summary>
/// Class that uses/references Kernel.
/// </summary>
private sealed class KernelClient
private sealed class KernelClient(Kernel kernel, ILoggerFactory loggerFactory)
{
private readonly Kernel _kernel;
private readonly ILogger _logger;

public KernelClient(Kernel kernel, ILoggerFactory loggerFactory)
{
this._kernel = kernel;
this._logger = loggerFactory.CreateLogger(nameof(KernelClient));
}
private readonly Kernel _kernel = kernel;
private readonly ILogger _logger = loggerFactory.CreateLogger(nameof(KernelClient));

public async Task SummarizeAsync(string ask)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public DeepDevTokenCounter()

public int Count(string input)
{
var tokens = this._tokenizer.Encode(input, new HashSet<string>());
var tokens = this._tokenizer.Encode(input, []);
return tokens.Count;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@ public async Task RunAsync()
modelId: modelId);
Kernel kernel = builder.Build();

var arguments = new KernelArguments();
arguments["word2"] = " Potter";
var arguments = new KernelArguments
{
["word2"] = " Potter"
};

// Load native plugin into the kernel function collection, sharing its functions with prompt templates
// Functions loaded here are available as "text.*"
Expand Down
Loading

0 comments on commit 8d0662e

Please sign in to comment.