Skip to content

Commit

Permalink
.Net Removing special "input" argument (#4156)
Browse files Browse the repository at this point in the history
### Motivation and Context

Resolves #3887 

Before:
```csharp
var result = await kernel.InvokeAsync(excuseFunction, new("I missed the F1 final race"));
```

After:
```csharp
var result = await kernel.InvokeAsync(excuseFunction, new() { ["input"] = "I missed the F1 final race" });
```
  • Loading branch information
RogerBarreto committed Dec 12, 2023
1 parent 398c814 commit da2dfda
Show file tree
Hide file tree
Showing 31 changed files with 119 additions and 162 deletions.
3 changes: 2 additions & 1 deletion dotnet/samples/KernelSyntaxExamples/Example03_Arguments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ public static async Task RunAsync()
Kernel kernel = new();
var textPlugin = kernel.ImportPluginFromType<StaticTextPlugin>();

var arguments = new KernelArguments("Today is: ")
var arguments = new KernelArguments()
{
["input"] = "Today is: ",
["day"] = DateTimeOffset.Now.ToString("dddd", CultureInfo.CurrentCulture)
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ Be creative and be funny. Let your imagination run wild.

var excuseFunction = kernel.CreateFunctionFromPrompt(promptTemplate, new OpenAIPromptExecutionSettings() { MaxTokens = 100, Temperature = 0.4, TopP = 1 });

var result = await kernel.InvokeAsync(excuseFunction, new("I missed the F1 final race"));
var result = await kernel.InvokeAsync(excuseFunction, new() { ["input"] = "I missed the F1 final race" });
Console.WriteLine(result.GetValue<string>());

result = await kernel.InvokeAsync(excuseFunction, new("sorry I forgot your birthday"));
result = await kernel.InvokeAsync(excuseFunction, new() { ["input"] = "sorry I forgot your birthday" });
Console.WriteLine(result.GetValue<string>());

var fixedFunction = kernel.CreateFunctionFromPrompt($"Translate this date {DateTimeOffset.Now:f} to French format", new OpenAIPromptExecutionSettings() { MaxTokens = 100 });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ private static async Task Example1Async(Kernel kernel, string searchPluginName)
// Run
var question = "What's the largest building in the world?";
var function = kernel.Plugins[searchPluginName]["search"];
var result = await kernel.InvokeAsync(function, new(question));
var result = await kernel.InvokeAsync(function, new() { ["input"] = question });

Console.WriteLine(question);
Console.WriteLine($"----{searchPluginName}----");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public async Task<string> Type03Async()
[KernelFunction]
public async Task<string> Type04Async(Kernel kernel)
{
var summary = await kernel.InvokeAsync(kernel.Plugins["SummarizePlugin"]["Summarize"], new("blah blah blah"));
var summary = await kernel.InvokeAsync(kernel.Plugins["SummarizePlugin"]["Summarize"], new() { ["input"] = "blah blah blah" });
Console.WriteLine($"Running function type 4 [{summary}]");
return "";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static async Task RunAsync()

// Run
var ask = "What's the tallest building in Europe?";
var result = await kernel.InvokeAsync(bing["BingSearchUrl"], new(ask));
var result = await kernel.InvokeAsync(bing["BingSearchUrl"], new() { ["input"] = ask });

Console.WriteLine(ask + "\n");
Console.WriteLine(result.GetValue<string>());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ private static async Task ConversationSummaryPluginAsync()
KernelPlugin conversationSummaryPlugin = kernel.ImportPluginFromType<ConversationSummaryPlugin>();

FunctionResult summary = await kernel.InvokeAsync(
conversationSummaryPlugin["SummarizeConversation"], new(ChatTranscript));
conversationSummaryPlugin["SummarizeConversation"], new() { ["input"] = ChatTranscript });

Console.WriteLine("Generated Summary:");
Console.WriteLine(summary.GetValue<string>());
Expand All @@ -146,7 +146,7 @@ private static async Task GetConversationActionItemsAsync()
KernelPlugin conversationSummary = kernel.ImportPluginFromType<ConversationSummaryPlugin>();

FunctionResult summary = await kernel.InvokeAsync(
conversationSummary["GetConversationActionItems"], new(ChatTranscript));
conversationSummary["GetConversationActionItems"], new() { ["input"] = ChatTranscript });

Console.WriteLine("Generated Action Items:");
Console.WriteLine(summary.GetValue<string>());
Expand All @@ -160,7 +160,7 @@ private static async Task GetConversationTopicsAsync()
KernelPlugin conversationSummary = kernel.ImportPluginFromType<ConversationSummaryPlugin>();

FunctionResult summary = await kernel.InvokeAsync(
conversationSummary["GetConversationTopics"], new(ChatTranscript));
conversationSummary["GetConversationTopics"], new() { ["input"] = ChatTranscript });

Console.WriteLine("Generated Topics:");
Console.WriteLine(summary.GetValue<string>());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,9 @@ private static async Task RunWithStoreAsync(IMemoryStore memoryStore, Cancellati

// Save a memory with the Kernel
Console.WriteLine("Saving memory with key 'info5': \"My family is from New York\"");
await kernel.InvokeAsync(memoryPlugin["Save"], new("My family is from New York")
await kernel.InvokeAsync(memoryPlugin["Save"], new()
{
[TextMemoryPlugin.InputParam] = "My family is from New York",
[TextMemoryPlugin.CollectionParam] = MemoryCollectionName,
[TextMemoryPlugin.KeyParam] = "info5",
}, cancellationToken);
Expand Down Expand Up @@ -242,8 +243,9 @@ private static async Task RunWithStoreAsync(IMemoryStore memoryStore, Cancellati
Console.WriteLine("== PART 3b: Recall (similarity search) with Kernel and TextMemoryPlugin 'Recall' function ==");
Console.WriteLine("Ask: where do I live?");

result = await kernel.InvokeAsync(memoryPlugin["Recall"], new("Ask: where do I live?")
result = await kernel.InvokeAsync(memoryPlugin["Recall"], new()
{
[TextMemoryPlugin.InputParam] = "Ask: where do I live?",
[TextMemoryPlugin.CollectionParam] = MemoryCollectionName,
[TextMemoryPlugin.LimitParam] = "2",
[TextMemoryPlugin.RelevanceParam] = "0.79",
Expand Down Expand Up @@ -289,8 +291,9 @@ END FACTS

var aboutMeOracle = kernel.CreateFunctionFromPrompt(RecallFunctionDefinition, new OpenAIPromptExecutionSettings() { MaxTokens = 100 });

result = await kernel.InvokeAsync(aboutMeOracle, new("Do I live in the same town where I grew up?")
result = await kernel.InvokeAsync(aboutMeOracle, new()
{
[TextMemoryPlugin.InputParam] = "Do I live in the same town where I grew up?",
[TextMemoryPlugin.CollectionParam] = MemoryCollectionName,
[TextMemoryPlugin.LimitParam] = "2",
[TextMemoryPlugin.RelevanceParam] = "0.79",
Expand Down
2 changes: 1 addition & 1 deletion dotnet/samples/KernelSyntaxExamples/Example16_CustomLLM.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ private static async Task CustomTextGenerationWithSKFunctionAsync()

const string Input = "Why AI is awesome";
Console.WriteLine($"Function input: {Input}\n");
var result = await paragraphWritingFunction.InvokeAsync(kernel, new(Input));
var result = await paragraphWritingFunction.InvokeAsync(kernel, new() { ["input"] = Input });

Console.WriteLine(result);
}
Expand Down
4 changes: 2 additions & 2 deletions dotnet/samples/KernelSyntaxExamples/Example20_HuggingFace.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ private static async Task RunInferenceApiExampleAsync()

var questionAnswerFunction = kernel.CreateFunctionFromPrompt("Question: {{$input}}; Answer:");

var result = await kernel.InvokeAsync(questionAnswerFunction, new("What is New York?"));
var result = await kernel.InvokeAsync(questionAnswerFunction, new() { ["input"] = "What is New York?" });

Console.WriteLine(result.GetValue<string>());
}
Expand Down Expand Up @@ -66,7 +66,7 @@ private static async Task RunLlamaExampleAsync()

var questionAnswerFunction = kernel.CreateFunctionFromPrompt("Question: {{$input}}; Answer:");

var result = await kernel.InvokeAsync(questionAnswerFunction, new("What is New York?"));
var result = await kernel.InvokeAsync(questionAnswerFunction, new() { ["input"] = "What is New York?" });

Console.WriteLine(result.GetValue<string>());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public static async Task RunAsync()
var func = kernel.CreateFunctionFromPrompt(
"List the two planets closest to '{{$input}}', excluding moons, using bullet points.");

var result = await func.InvokeAsync(kernel, new("Jupiter"));
var result = await func.InvokeAsync(kernel, new() { ["input"] = "Jupiter" });
Console.WriteLine(result.GetValue<string>());

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public async Task SummarizeAsync(string ask)

var summarizePlugin = this._kernel.ImportPluginFromPromptDirectory(Path.Combine(folder, "SummarizePlugin"));

var result = await this._kernel.InvokeAsync(summarizePlugin["Summarize"], new(ask));
var result = await this._kernel.InvokeAsync(summarizePlugin["Summarize"], new() { ["input"] = ask });

this._logger.LogWarning("Result - {0}", result.GetValue<string>());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public static async Task RunAsync()
KernelFunction myFunction = kernel.CreateFunctionFromPrompt(FunctionDefinition);

// Invoke function through kernel
FunctionResult result = await kernel.InvokeAsync(myFunction, new("travel"));
FunctionResult result = await kernel.InvokeAsync(myFunction, new() { ["input"] = "travel" });

// Display results
Console.WriteLine(result.GetValue<string>());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ public static async Task GroundednessCheckingAsync()
her a beggar. My father came to her aid and two years later they married.
";

KernelArguments variables = new(summaryText)
KernelArguments variables = new()
{
["input"] = summaryText,
["topic"] = "people and places",
["example_entities"] = "John, Jane, mother, brother, Paris, Rome"
};
Expand Down
2 changes: 1 addition & 1 deletion dotnet/samples/KernelSyntaxExamples/Example52_ApimAuth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public static async Task RunAsync()
// Run
var result = await kernel.InvokeAsync(
kernel.Plugins["FunPlugin"]["Excuses"],
new("I have no homework")
new() { ["input"] = "I have no homework" }
);
Console.WriteLine(result.GetValue<string>());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ private static async Task ExampleWithKernelAsync()
var function = kernel.CreateFunctionFromPrompt("Question: {{$input}}");

// First question without previous context based on uploaded content.
var response = await kernel.InvokeAsync(function, new(ask));
var response = await kernel.InvokeAsync(function, new() { ["input"] = ask });

// Output
// Ask: How did Emily and David meet?
Expand All @@ -100,7 +100,7 @@ private static async Task ExampleWithKernelAsync()

// Second question based on uploaded content.
ask = "What are Emily and David studying?";
response = await kernel.InvokeAsync(function, new(ask));
response = await kernel.InvokeAsync(function, new() { ["input"] = ask });

// Output
// Ask: What are Emily and David studying?
Expand Down
4 changes: 2 additions & 2 deletions dotnet/samples/KernelSyntaxExamples/Example57_KernelHooks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ void MyPostExecutionHandler(object? sender, FunctionInvokedEventArgs e)

// Invoke prompt to trigger execution hooks.
const string Input = "I missed the F1 final race";
var result = await kernel.InvokeAsync(excuseFunction, new(Input));
var result = await kernel.InvokeAsync(excuseFunction, new() { ["input"] = Input });
Console.WriteLine($"Function Result: {result}");
}

Expand Down Expand Up @@ -136,7 +136,7 @@ void MyRenderedHandler(object? sender, PromptRenderedEventArgs e)

// Invoke prompt to trigger prompt rendering hooks.
const string Input = "I missed the F1 final race";
var result = await kernel.InvokeAsync(excuseFunction, new(Input));
var result = await kernel.InvokeAsync(excuseFunction, new() { ["input"] = Input });
Console.WriteLine($"Function Result: {result.GetValue<string>()}");
}

Expand Down
2 changes: 1 addition & 1 deletion dotnet/samples/KernelSyntaxExamples/Example70_Assistant.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ private static async Task RunAsFunctionAsync()
try
{
// Invoke assistant plugin function.
KernelArguments arguments = new("Practice makes perfect.");
KernelArguments arguments = new() { ["input"] = "Practice makes perfect." };

var kernel = new Kernel();
var result = await kernel.InvokeAsync(assistant.AsPlugin().Single(), arguments);
Expand Down
2 changes: 1 addition & 1 deletion dotnet/samples/NCalcPlugins/LanguageCalculatorPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public async Task<string> CalculateAsync(

try
{
var result = await kernel.InvokeAsync(this._mathTranslator, new(input)).ConfigureAwait(false);
var result = await kernel.InvokeAsync(this._mathTranslator, new() { ["input"] = input }).ConfigureAwait(false);
answer = result?.GetValue<string>() ?? string.Empty;
}
catch (Exception ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public HandlebarsPromptTemplateTests()
{
this._factory = new(TestConsoleLogger.LoggerFactory);
this._kernel = new();
this._arguments = new(Guid.NewGuid().ToString("X"));
this._arguments = new() { ["input"] = Guid.NewGuid().ToString("X") };
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ namespace SemanticKernel.IntegrationTests.Connectors.OpenAI;

public sealed class OpenAICompletionTests : IDisposable
{
private const string InputParameterName = "input";
private readonly IKernelBuilder _kernelBuilder;
private readonly IConfigurationRoot _configuration;

Expand Down Expand Up @@ -63,7 +64,7 @@ public async Task OpenAITestAsync(string prompt, string expectedAnswerContains)
IReadOnlyKernelPluginCollection plugins = TestHelpers.ImportSamplePlugins(target, "ChatPlugin");

// Act
FunctionResult actual = await target.InvokeAsync(plugins["ChatPlugin"]["Chat"], new(prompt));
FunctionResult actual = await target.InvokeAsync(plugins["ChatPlugin"]["Chat"], new() { [InputParameterName] = prompt });

// Assert
Assert.Contains(expectedAnswerContains, actual.GetValue<string>(), StringComparison.OrdinalIgnoreCase);
Expand All @@ -84,7 +85,7 @@ public async Task OpenAIChatAsTextTestAsync(string prompt, string expectedAnswer
IReadOnlyKernelPluginCollection plugins = TestHelpers.ImportSamplePlugins(target, "ChatPlugin");

// Act
FunctionResult actual = await target.InvokeAsync(plugins["ChatPlugin"]["Chat"], new(prompt));
FunctionResult actual = await target.InvokeAsync(plugins["ChatPlugin"]["Chat"], new() { [InputParameterName] = prompt });

// Assert
Assert.Contains(expectedAnswerContains, actual.GetValue<string>(), StringComparison.OrdinalIgnoreCase);
Expand All @@ -104,7 +105,7 @@ public async Task CanUseOpenAiChatForTextGenerationAsync()
"List the two planets after '{{$input}}', excluding moons, using bullet points.",
new OpenAIPromptExecutionSettings());

var result = await func.InvokeAsync(target, new("Jupiter"));
var result = await func.InvokeAsync(target, new() { [InputParameterName] = "Jupiter" });

Assert.NotNull(result);
Assert.Contains("Saturn", result.GetValue<string>(), StringComparison.InvariantCultureIgnoreCase);
Expand Down Expand Up @@ -135,7 +136,7 @@ public async Task AzureOpenAIStreamingTestAsync(bool useChatModel, string prompt

StringBuilder fullResult = new();
// Act
await foreach (var content in target.InvokeStreamingAsync<StreamingKernelContent>(plugins["ChatPlugin"]["Chat"], new(prompt)))
await foreach (var content in target.InvokeStreamingAsync<StreamingKernelContent>(plugins["ChatPlugin"]["Chat"], new() { [InputParameterName] = prompt }))
{
fullResult.Append(content);
};
Expand Down Expand Up @@ -167,7 +168,7 @@ public async Task AzureOpenAITestAsync(bool useChatModel, string prompt, string
IReadOnlyKernelPluginCollection plugins = TestHelpers.ImportSamplePlugins(target, "ChatPlugin");

// Act
FunctionResult actual = await target.InvokeAsync(plugins["ChatPlugin"]["Chat"], new(prompt));
FunctionResult actual = await target.InvokeAsync(plugins["ChatPlugin"]["Chat"], new() { [InputParameterName] = prompt });

// Assert
Assert.Contains(expectedAnswerContains, actual.GetValue<string>(), StringComparison.OrdinalIgnoreCase);
Expand Down Expand Up @@ -200,7 +201,7 @@ public async Task OpenAIHttpRetryPolicyTestAsync(string prompt, string expectedO
IReadOnlyKernelPluginCollection plugins = TestHelpers.ImportSamplePlugins(target, "SummarizePlugin");

// Act
await Assert.ThrowsAsync<HttpOperationException>(() => target.InvokeAsync(plugins["SummarizePlugin"]["Summarize"], new(prompt)));
await Assert.ThrowsAsync<HttpOperationException>(() => target.InvokeAsync(plugins["SummarizePlugin"]["Summarize"], new() { [InputParameterName] = prompt }));

// Assert
Assert.Contains(expectedOutput, this._testOutputHelper.GetLogs(), StringComparison.OrdinalIgnoreCase);
Expand Down Expand Up @@ -238,7 +239,7 @@ public async Task AzureOpenAIHttpRetryPolicyTestAsync(string prompt, string expe
IReadOnlyKernelPluginCollection plugins = TestHelpers.ImportSamplePlugins(target, "SummarizePlugin");

// Act
await Assert.ThrowsAsync<HttpOperationException>(() => target.InvokeAsync(plugins["SummarizePlugin"]["Summarize"], new(prompt)));
await Assert.ThrowsAsync<HttpOperationException>(() => target.InvokeAsync(plugins["SummarizePlugin"]["Summarize"], new() { [InputParameterName] = prompt }));

// Assert
Assert.Contains(expectedOutput, this._testOutputHelper.GetLogs(), StringComparison.OrdinalIgnoreCase);
Expand Down Expand Up @@ -301,7 +302,7 @@ public async Task OpenAIHttpInvalidKeyShouldReturnErrorDetailAsync()
IReadOnlyKernelPluginCollection plugins = TestHelpers.ImportSamplePlugins(target, "SummarizePlugin");

// Act and Assert
var ex = await Assert.ThrowsAsync<HttpOperationException>(() => target.InvokeAsync(plugins["SummarizePlugin"]["Summarize"], new("Any")));
var ex = await Assert.ThrowsAsync<HttpOperationException>(() => target.InvokeAsync(plugins["SummarizePlugin"]["Summarize"], new() { [InputParameterName] = "Any" }));

Assert.Equal(HttpStatusCode.Unauthorized, ((HttpOperationException)ex).StatusCode);
}
Expand All @@ -326,7 +327,7 @@ public async Task AzureOpenAIHttpInvalidKeyShouldReturnErrorDetailAsync()
IReadOnlyKernelPluginCollection plugins = TestHelpers.ImportSamplePlugins(target, "SummarizePlugin");

// Act and Assert
var ex = await Assert.ThrowsAsync<HttpOperationException>(() => target.InvokeAsync(plugins["SummarizePlugin"]["Summarize"], new("Any")));
var ex = await Assert.ThrowsAsync<HttpOperationException>(() => target.InvokeAsync(plugins["SummarizePlugin"]["Summarize"], new() { [InputParameterName] = "Any" }));

Assert.Equal(HttpStatusCode.Unauthorized, ((HttpOperationException)ex).StatusCode);
}
Expand All @@ -352,7 +353,7 @@ public async Task AzureOpenAIHttpExceededMaxTokensShouldReturnErrorDetailAsync()

// Act
// Assert
await Assert.ThrowsAsync<HttpOperationException>(() => plugins["SummarizePlugin"]["Summarize"].InvokeAsync(target, new(string.Join('.', Enumerable.Range(1, 40000)))));
await Assert.ThrowsAsync<HttpOperationException>(() => plugins["SummarizePlugin"]["Summarize"].InvokeAsync(target, new() { [InputParameterName] = string.Join('.', Enumerable.Range(1, 40000)) }));
}

[Theory(Skip = "This test is for manual verification.")]
Expand All @@ -378,7 +379,7 @@ public async Task CompletionWithDifferentLineEndingsAsync(string lineEnding, AIS
IReadOnlyKernelPluginCollection plugins = TestHelpers.ImportSamplePlugins(target, "ChatPlugin");

// Act
FunctionResult actual = await target.InvokeAsync(plugins["ChatPlugin"]["Chat"], new(prompt));
FunctionResult actual = await target.InvokeAsync(plugins["ChatPlugin"]["Chat"], new() { [InputParameterName] = prompt });

// Assert
Assert.Contains(ExpectedAnswerContains, actual.GetValue<string>(), StringComparison.OrdinalIgnoreCase);
Expand Down
Loading

0 comments on commit da2dfda

Please sign in to comment.