Skip to content

Serialization in ChatClientHelper #170

@rwhitworth127

Description

@rwhitworth127

Spent some time troubleshooting an issue today when ChatClient with SemanticKernel. I have several Functions in csharp that return objects instead of strings. When performing a chat completion, Anthropic would run these tools and not actually see the function results.
It appears to be because the ChatClientHelper calls .ToString() when adding ToolResultContent to a message, meaning only the class name and not the json results are being passed to anthropic.

in this section:

case Microsoft.Extensions.AI.FunctionResultContent frc:
    currentMessage.Content.Add(new ToolResultContent()
    {
        ToolUseId = frc.CallId,
        Content = new List<ContentBase>() { new TextContent () { Text = frc.Result?.ToString() ?? string.Empty } },
        IsError = frc.Exception is not null,
    });
    break;

we could consider changing

Text = frc.Result?.ToString() ?? string.Empty

to

Text = frc.Result switch
{
    string s => s,
    null => string.Empty,
    _ => JsonSerializer.Serialize(frc.Result)
}

For now, I have created a workaround in my code by overriding my ToString() method on the result class I have created for each Function.

I haven't tried to test this yet recommendation on the sdk itself, if I get time I could pull it down, test the change, and do a PR. Just posting here in case I am way off base and missing something.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions