OpenAI-DotNet: Subsequent function tool calling serialization failure when streaming

Bug Report

Overview

If the first request uses streaming and then the message is passed to another chat completion call (regardless if it is normal or streaming), the API will return the following error:

code: BadRequest | Response body: {
  "error": {
    "message": "{'location': 'San Diego', 'unit': 'celsius'} is not of type 'string' - 'messages.2.tool_calls.0.function.arguments'",
    "type": "invalid_request_error",
    "param": null,
    "code": null
  }
}

Changing the arguments property in the Functions class to string seems to resolve the error:

        [JsonInclude]
        [JsonPropertyName("arguments")]
        public string Arguments
        {
            get
            {
                if (arguments == null &&
                    !string.IsNullOrWhiteSpace(argumentsString))
                {
                    arguments = JsonNode.Parse(argumentsString);
                }

                return arguments?.ToString();
            }
            private set => arguments = value;
        }

To Reproduce

Steps to reproduce the behavior:

            var messages = new List<Message>
            {
                new Message(Role.System, "You are a helpful weather assistant."),
                new Message(Role.User, "What's the weather like today in San Diego?"),
            };

            var tools = new List<Tool>
            {
                new Function(
                    nameof(WeatherService.GetCurrentWeather),
                    "Get the current weather in a given location",
                    new JsonObject
                    {
                        ["type"] = "object",
                        ["properties"] = new JsonObject
                        {
                            ["location"] = new JsonObject
                            {
                                ["type"] = "string",
                                ["description"] = "The city and state, e.g. San Francisco, CA"
                            },
                            ["unit"] = new JsonObject
                            {
                                ["type"] = "string",
                                ["enum"] = new JsonArray { "celsius", "fahrenheit" }
                            }
                        }
                    })
            };

            var chatRequest = new ChatRequest(messages, tools: tools, toolChoice: "auto");
            var response = await OpenAIClient.ChatEndpoint.StreamCompletionAsync(chatRequest, _ =>
            {
            });

            messages.Add(response.FirstChoice.Message);

            var usedTool = response.FirstChoice.Message.ToolCalls[0];

            var functionArgs = JsonSerializer.Deserialize<WeatherArgs>(usedTool.Function.Arguments.ToString());
            var functionResult = WeatherService.GetCurrentWeather(functionArgs);
            messages.Add(new Message(usedTool, functionResult));

            var locationMessage = new Message(Role.User, "I'm in Glasgow, Scotland");
            messages.Add(locationMessage);
            chatRequest = new ChatRequest(messages, tools: tools,
                toolChoice: "auto");

            response = await OpenAIClient.ChatEndpoint.StreamCompletionAsync(chatRequest, _ =>
            {
            });

Expected behavior

A success response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 1
  • Comments: 19 (19 by maintainers)

Commits related to this issue

Most upvoted comments

@StephenHodgson To illustrate:

Changing

                if (arguments == null &&
                    !string.IsNullOrWhiteSpace(argumentsString))
                {
                    arguments = JsonNode.Parse(argumentsString);
                }

to

                if (arguments == null &&
                    !string.IsNullOrWhiteSpace(argumentsString))
                {
                    arguments = JsonValue.Create(argumentsString);
                }

fixes the issue.

I suspect this would also break the non streaming tool function calling as well.

Only if the first call is streaming. If it’s GetCompletionAsync, it will succeed.

Yep!

I already cover the case for streaming tool function calls. Take a look at the unit test and check what might be different in your example.

The difference is here: https://github.com/RageAgainstThePixel/OpenAI-DotNet/blob/main/OpenAI-DotNet-Tests/TestFixture_03_Chat.cs#L552-L555

It doesn’t seem like you do a request after adding the message with the tool in it. Therefore the error won’t appear.

Adding this to the end will cause the test to fail:

            chatRequest = new ChatRequest(messages, tools: tools, toolChoice: "auto");
            
            response = await OpenAIClient.ChatEndpoint.StreamCompletionAsync(chatRequest, partialResponse =>
            {
                Assert.IsNotNull(partialResponse);
                Assert.NotNull(partialResponse.Choices);
                Assert.NotZero(partialResponse.Choices.Count);
            });