semantic-kernel icon indicating copy to clipboard operation
semantic-kernel copied to clipboard

.Net upon upgrading to 1.5 function calling fails

Open joslat opened this issue 2 years ago • 13 comments

Describe the bug A clear and concise description of what the bug is.

To Reproduce Steps to reproduce the behavior: With packages Microsoft.SemanticKernel & Microsoft.SemanticKernel.Connectors.OpenAI 1.0 up to 1.4 with the following code there is no issue. Upon upgrading to 1.5 I get the exception:

Unhandled exception. System.NotSupportedException: Runtime type 'Microsoft.SemanticKernel.Connectors.OpenAI.OpenAIChatMessageContent' is not supported by polymorphic type 'Microsoft.SemanticKernel.KernelContent'. Path: $.
 ---> System.NotSupportedException: Runtime type 'Microsoft.SemanticKernel.Connectors.OpenAI.OpenAIChatMessageContent' is not supported by polymorphic type 'Microsoft.SemanticKernel.KernelContent'.
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException_RuntimeTypeNotSupported(Type baseType, Type runtimeType)
   at System.Text.Json.Serialization.Metadata.PolymorphicTypeResolver.TryGetDerivedJsonTypeInfo(Type runtimeType, JsonTypeInfo& jsonTypeInfo, Object& typeDiscriminator)
   at System.Text.Json.Serialization.JsonConverter.ResolvePolymorphicConverter(Object value, JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException(WriteStack& state, NotSupportedException ex)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.Serialize(Utf8JsonWriter writer, T& rootValue, Object rootValueBoxed)
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.SerializeAsObject(Utf8JsonWriter writer, Object rootValue)
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.Serialize(Utf8JsonWriter writer, T& rootValue, Object rootValueBoxed)
   at System.Text.Json.JsonSerializer.WriteString[TValue](TValue& value, JsonTypeInfo`1 jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)
   at Microsoft.SemanticKernel.Connectors.OpenAI.ClientCore.GetChatMessageContentsAsync(ChatHistory chat, PromptExecutionSettings executionSettings, Kernel kernel, CancellationToken cancellationToken)
   at Microsoft.SemanticKernel.ChatCompletion.ChatCompletionServiceExtensions.GetChatMessageContentAsync(IChatCompletionService chatCompletionService, String prompt, PromptExecutionSettings executionSettings, Kernel kernel, CancellationToken cancellationToken)
   at Microsoft.SemanticKernel.KernelFunctionFromPrompt.InvokeCoreAsync(Kernel kernel, KernelArguments arguments, CancellationToken cancellationToken)
   at Microsoft.SemanticKernel.KernelFunction.InvokeAsync(Kernel kernel, KernelArguments arguments, CancellationToken cancellationToken)
   at _04_03e.FunctionCalling.Execute() in C:\git\joslat\semantic-kernel-in-action-1-fundamentals-3836112\src\04_03e\FunctionCalling.cs:line 53
   at Program.<Main>$(String[] args) in C:\git\joslat\semantic-kernel-in-action-1-fundamentals-3836112\src\04_03e\Program.cs:line 6
   at Program.<Main>(String[] args)

The code used is:

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.OpenAI;
namespace _04_03e;

public class FunctionCalling
{
  public static async Task Execute()
  {
    var modelDeploymentName = "Gpt4v32k";
    var azureOpenAIEndpoint = Environment.GetEnvironmentVariable("AZUREOPENAI_ENDPOINT");
    var azureOpenAIApiKey = Environment.GetEnvironmentVariable("AZUREOPENAI_APIKEY");

    var builder = Kernel.CreateBuilder();
    builder.Services.AddAzureOpenAIChatCompletion(
        modelDeploymentName,
        azureOpenAIEndpoint,
        azureOpenAIApiKey,
        modelId: "gpt-4-32k"
    );
    var kernel = builder.Build();

    KernelFunction kernelFunctionRespondAsTony =
        KernelFunctionFactory.CreateFromPrompt(
            "Respond to the user question as if you were Tony Stark, Iron man. Respond to it as you were him, showing your personality",
            functionName: "RespondAsTony",
            description: "Responds to a question as the superhero Tony Stark, Iron Man.");

    KernelPlugin superheroOpinionsPlugin =
        KernelPluginFactory.CreateFromFunctions(
            "SuperHeroTalk",
            "Responds to questions or statements as superheros do.",
            new[] {
                    kernelFunctionRespondAsTony
                  });
    kernel.Plugins.Add(superheroOpinionsPlugin);

    string userPrompt = "I just woke up and found myself in the middle of nowhere, " +
        "What would Tony Stark do in my place?";

    OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
    {
      ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
    };

    var result = await kernel.InvokePromptAsync(
        userPrompt,
        new(openAIPromptExecutionSettings));

    Console.WriteLine($"Result: {result}");
    Console.ReadLine();
  }
}

Please note that the code is copyrighted by LinkedIn Learning

Expected behavior A clear and concise description of what you expected to happen. I get function calling to work and a response.

joslat avatar Mar 01 '24 16:03 joslat

There's also the issue happening when executing FunctionCallingStepwisePlanner while serializing an OpenAIChatMessageContent: https://github.com/microsoft/semantic-kernel/blob/c78ebfbd1d58c7ea5ed981d0b9fbacc289137966/dotnet/src/Planners/Planners.OpenAI/Stepwise/FunctionCallingStepwisePlanner.cs#L137

I believe it's connected to this PR => https://github.com/microsoft/semantic-kernel/pull/5131, specifically in this section: https://github.com/microsoft/semantic-kernel/blob/c78ebfbd1d58c7ea5ed981d0b9fbacc289137966/dotnet/src/SemanticKernel.Abstractions/Contents/KernelContent.cs#L11-L18 as it appears that the OpenAIChatMessageContent type is not being properly supported.

LuisM000 avatar Mar 02 '24 12:03 LuisM000

There's also the issue happening when executing FunctionCallingStepwisePlanner while serializing an OpenAIChatMessageContent:

https://github.com/microsoft/semantic-kernel/blob/c78ebfbd1d58c7ea5ed981d0b9fbacc289137966/dotnet/src/Planners/Planners.OpenAI/Stepwise/FunctionCallingStepwisePlanner.cs#L137

I believe it's connected to this PR => #5131, specifically in this section:

https://github.com/microsoft/semantic-kernel/blob/c78ebfbd1d58c7ea5ed981d0b9fbacc289137966/dotnet/src/SemanticKernel.Abstractions/Contents/KernelContent.cs#L11-L18

as it appears that the OpenAIChatMessageContent type is not being properly supported.

HI @LuisM000, thanks for reporting the issue. Could you please provide code snippet that reproduces the issue?

SergeyMenshykh avatar Mar 04 '24 14:03 SergeyMenshykh

There's also the issue happening when executing FunctionCallingStepwisePlanner while serializing an OpenAIChatMessageContent: https://github.com/microsoft/semantic-kernel/blob/c78ebfbd1d58c7ea5ed981d0b9fbacc289137966/dotnet/src/Planners/Planners.OpenAI/Stepwise/FunctionCallingStepwisePlanner.cs#L137

I believe it's connected to this PR => #5131, specifically in this section: https://github.com/microsoft/semantic-kernel/blob/c78ebfbd1d58c7ea5ed981d0b9fbacc289137966/dotnet/src/SemanticKernel.Abstractions/Contents/KernelContent.cs#L11-L18

as it appears that the OpenAIChatMessageContent type is not being properly supported.

HI @LuisM000, thanks for reporting the issue. Could you please provide code snippet that reproduces the issue?

Hi @SergeyMenshykh, thanks for addressing the issue. Sure, here's the code snippet:

[Fact]
public async Task RunAsync()
{
    Kernel kernel = Kernel.CreateBuilder()
        .AddAzureOpenAIChatCompletion("gpt-35-turbo-16k",
            TestConfiguration.AzureOpenAI.Endpoint,
            TestConfiguration.AzureOpenAI.ApiKey
        )
        .Build();

    KernelFunction kernelFunctionGetSuperheroes = KernelFunctionFactory.CreateFromPrompt(
        "Returns a list of superheroes. Only return Tony Stark and Hulk.",
        functionName: "GetSuperheroes",
        description: "Get a list of available superheroes.");

    KernelPlugin superheroesPlugin =
        KernelPluginFactory.CreateFromFunctions(
            "SuperHeroList",
            "Get superheroes",
            new[]
            {
                kernelFunctionGetSuperheroes
            });

    kernel.Plugins.Add(superheroesPlugin);

    FunctionCallingStepwisePlannerOptions options = new FunctionCallingStepwisePlannerOptions
    {
        MaxIterations = 15,
        MaxTokens = 4000,
    };

    FunctionCallingStepwisePlanner planner = new FunctionCallingStepwisePlanner(options);

    string userPrompt = "Provide me a list of superheroes";

    var result = await planner.ExecuteAsync(kernel, userPrompt);
}

If you set a breakpoint at: https://github.com/microsoft/semantic-kernel/blob/c78ebfbd1d58c7ea5ed981d0b9fbacc289137966/dotnet/src/Planners/Planners.OpenAI/Stepwise/FunctionCallingStepwisePlanner.cs#L141 You'll see that the exception occurs during serialization. Thanks!

LuisM000 avatar Mar 04 '24 15:03 LuisM000

I' am having the same issue with nuget package version 1.5. I have some kernel functions wrapped in a plugin and an Handlebars planner. The errors continues to be triggered during the step of the generated plan.

immagine

zimeo99 avatar Mar 04 '24 15:03 zimeo99

I' am having the same issue with nuget package version 1.5 and 1.4 works well.

PS H:\workspace\gpt\sharpchat\sktest> dotnet run
Unhandled exception. Microsoft.SemanticKernel.HttpOperationException: Service request failed.
Status: 500 (Internal Server Error)

Content:
500 Internal Server Error
[json.exception.type_error.302] type must be string, but is array

Headers:
Access-Control-Allow-Origin: REDACTED
Keep-Alive: REDACTED
Server: llama.cpp
Content-Length: 91
Content-Type: text/plain; charset=utf-8

 ---> Azure.RequestFailedException: Service request failed.
Status: 500 (Internal Server Error)

Content:
500 Internal Server Error
[json.exception.type_error.302] type must be string, but is array

Headers:
Access-Control-Allow-Origin: REDACTED
Keep-Alive: REDACTED
Server: llama.cpp
Content-Length: 91
Content-Type: text/plain; charset=utf-8

   at Azure.Core.HttpPipelineExtensions.ProcessMessageAsync(HttpPipeline pipeline, HttpMessage message, RequestContext requestContext, CancellationToken cancellationToken)
   at Azure.AI.OpenAI.OpenAIClient.GetChatCompletionsAsync(ChatCompletionsOptions chatCompletionsOptions, CancellationToken cancellationToken)
   at Microsoft.SemanticKernel.Connectors.OpenAI.ClientCore.RunRequestAsync[T](Func`1 request)
   --- End of inner exception stack trace ---
   at Microsoft.SemanticKernel.Connectors.OpenAI.ClientCore.RunRequestAsync[T](Func`1 request)
   at Microsoft.SemanticKernel.Connectors.OpenAI.ClientCore.GetChatMessageContentsAsync(ChatHistory chat, PromptExecutionSettings executionSettings, Kernel kernel, CancellationToken cancellationToken)
   at Microsoft.SemanticKernel.ChatCompletion.ChatCompletionServiceExtensions.GetChatMessageContentAsync(IChatCompletionService chatCompletionService, String prompt, PromptExecutionSettings executionSettings, Kernel kernel, CancellationToken cancellationToken)
   at Microsoft.SemanticKernel.KernelFunctionFromPrompt.InvokeCoreAsync(Kernel kernel, KernelArguments arguments, CancellationToken cancellationToken)
   at Microsoft.SemanticKernel.KernelFunction.InvokeAsync(Kernel kernel, KernelArguments arguments, CancellationToken cancellationToken)
   at Program.<Main>$(String[] args) in H:\workspace\gpt\sharpchat\sktest\Program.cs:line 27
   at Program.<Main>(String[] args)

sangyuxiaowu avatar Mar 04 '24 15:03 sangyuxiaowu

I' am having the same issue with nuget package version 1.5. I have some kernel functions wrapped in a plugin and an Handlebars planner. The errors continues to be triggered during the step of the generated plan.

immagine

Hi @zimeo99, thanks for reporting the issue. A code snippet would be very helpful to repro the issue for the Handlebars planner.

SergeyMenshykh avatar Mar 04 '24 19:03 SergeyMenshykh

And @zimeo99 the code snippets must have superheroes on it ;) - just joking but... it's fun to see the "theme" being followe ;)

joslat avatar Mar 04 '24 19:03 joslat

I' am having the same issue with nuget package version 1.5. I have some kernel functions wrapped in a plugin and an Handlebars planner. The errors continues to be triggered during the step of the generated plan. immagine

Hi @zimeo99, thanks for reporting the issue. A code snippet would be very helpful to repro the issue for the Handlebars planner.

Hey @zimeo99, it would also be helpful to see what one of your plans looks like

teresaqhoang avatar Mar 04 '24 20:03 teresaqhoang

I also get the error since version 1.5.0. I tried it on version 1.6.3 but it doesn't work. It happens when I try to use a semantic function without further ado. I'll leave a screenshot of the code in case it helps.

image

image

blinchi avatar Mar 20 '24 08:03 blinchi

I also get the error since version 1.5.0. I tried it on version 1.6.3 but it doesn't work. It happens when I try to use a semantic function without further ado. I'll leave a screenshot of the code in case it helps.

image

image

HI @blinchi, which line in the code throws the exception? Could you please provide a simple example code snippet (unit test/console app) that we can easily copy and run to reproduce the issue on our side?

SergeyMenshykh avatar Mar 20 '24 11:03 SergeyMenshykh

Hello @SergeyMenshykh .Yes, I'll send you a console application that showcases the issue. It happens at line 23 of the example I'm providing you. Maybe I'm doing something incorrectly, but it doesn't happen with version 1.4.0

sk-invoketest.zip

blinchi avatar Mar 20 '24 12:03 blinchi

Hello @SergeyMenshykh .Yes, I'll send you a console application that showcases the issue. It happens at line 23 of the example I'm providing you. Maybe I'm doing something incorrectly, but it doesn't happen with version 1.4.0

sk-invoketest.zip

Hi @blinchi, thanks for the console app. It allowed us to reproduce the issue. The problem you see is related to the logging of function results, and it does not impact the function execution flow. We are working on a fix, which will be available in one of the upcoming SK versions.

SergeyMenshykh avatar Mar 21 '24 14:03 SergeyMenshykh

i have same issue in 1.5 1.6 My function will return a C# code comment in XML format that will raise the issue at this point . I inject the function into the kernel and ask Ai to call it at its own discretion image Additionally, can I specify the AI return format in YAML, e.g. Json, XML

Here is My Code

using (StreamReader reader = new(Assembly.GetExecutingAssembly().GetManifestResourceStream("CSharpCodeMethodComment.yaml")!)) { KernelFunction function = this._SK_Kernel.CreateFunctionFromPromptYaml(reader.ReadToEnd()); this._SK_Kernel.ImportPluginFromFunctions(function.Name, new KernelFunction[] { function } ); } OpenAIPromptExecutionSettings Settings= new() { Temperature = 0.7f }; Settings.ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions; ChatHistory ch = new ChatHistory(); aoiare.Add(new ChatMessageContent(AuthorRole.User, content: @" Write with code public static async Task RegenerateCodeComment(this SolutionVisitor visitor, ASTNode node, OAIP ai, Boolean relationship, Boolean usecurrentcomment, String additionalinfo, CancellationToken cancellationToken) { ........ } other code ..... ")); ChatMessageContent re_action = await AzureOpenAiInstance.GetChatMessageContentAsync(ch, Settings, kernel:_SK_Kernel).ConfigureAwait(false);

In YAML image

I have set response_format = Text

strikene avatar Apr 17 '24 08:04 strikene