Files
semantic-kernel/dotnet/samples/KernelSyntaxExamples/Example05_InlineFunctionDefinition.cs
T
01afd3f128 .Net: Update KernelSyntaxExamples env variables (#1832)
### Description
Updating KernelSyntaxExamples to use the same environment variable keys
as the Integration tests. This is a step toward making these tests
simpler to run, and even running them as automation in CI tests.

This is a first pass -- more cleanup to be done.

### Contribution Checklist
<!-- Before submitting this PR, please make sure: -->
- [X] The code builds clean without any errors or warnings
- [X] The PR follows SK Contribution Guidelines
(https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md)
- [X] The code follows the .NET coding conventions
(https://learn.microsoft.com/dotnet/csharp/fundamentals/coding-style/coding-conventions)
verified with `dotnet format`
- [X] All unit tests pass, and I have added new tests where possible
- [X] I didn't break anyone 😄

---------

Co-authored-by: name <email>
Co-authored-by: Dmytro Struk <[email protected]>
2023-07-17 17:36:06 +00:00

65 lines
2.1 KiB
C#

// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Threading.Tasks;
using Microsoft.SemanticKernel;
using RepoUtils;
// ReSharper disable once InconsistentNaming
public static class Example05_InlineFunctionDefinition
{
public static async Task RunAsync()
{
Console.WriteLine("======== Inline Function Definition ========");
string openAIModelId = TestConfiguration.OpenAI.ModelId;
string openAIApiKey = TestConfiguration.OpenAI.ApiKey;
if (openAIModelId == null || openAIApiKey == null)
{
Console.WriteLine("OpenAI credentials not found. Skipping example.");
return;
}
/*
* Example: normally you would place prompt templates in a folder to separate
* C# code from natural language code, but you can also define a semantic
* function inline if you like.
*/
IKernel kernel = new KernelBuilder()
.WithLogger(ConsoleLogger.Log)
.WithOpenAITextCompletionService(
modelId: openAIModelId,
apiKey: openAIApiKey)
.Build();
// Function defined using few-shot design pattern
const string FunctionDefinition = @"
Generate a creative reason or excuse for the given event.
Be creative and be funny. Let your imagination run wild.
Event: I am running late.
Excuse: I was being held ransom by giraffe gangsters.
Event: I haven't been to the gym for a year
Excuse: I've been too busy training my pet dragon.
Event: {{$input}}
";
var excuseFunction = kernel.CreateSemanticFunction(FunctionDefinition, maxTokens: 100, temperature: 0.4, topP: 1);
var result = await excuseFunction.InvokeAsync("I missed the F1 final race");
Console.WriteLine(result);
result = await excuseFunction.InvokeAsync("sorry I forgot your birthday");
Console.WriteLine(result);
var fixedFunction = kernel.CreateSemanticFunction($"Translate this date {DateTimeOffset.Now:f} to French format", maxTokens: 100);
result = await fixedFunction.InvokeAsync();
Console.WriteLine(result);
}
}