首页 新闻 会员 周边

如何让 Semantic Kernel 中 json 序列化时不对中文进行编码

0
悬赏园豆:30 [已解决问题] 解决于 2024-02-18 17:30

Semantic Kernel 在 json 序列化时默认会对中文进行编码,比如下面的 json

{"content":"\u8BF7\u5F00\u706F","role":"user"}

请问如何设置为不编码?

dudu的主页 dudu | 高人七级 | 园豆:30948
提问于:2024-02-18 12:02
< >
分享
最佳答案
0

通过 Semantic Kernel 的源码 ClientCore.cs#L299 追踪到在 GetChatMessageContentsAsync 中调用了 Azure.AI.OpenAI.OpenAIClientGetChatCompletionsAsync 方法,在这个方法中调用 ChatCompletionsToRequestContent 方法进行 json 序列化:

RequestContent content = chatCompletionsOptions.ToRequestContent();

注:ChatCompletions 的实现代码是自动生成的

ToRequestContent 方法中通过 Utf8JsonRequestContentWriteObjectValue 方法进行序列化

internal virtual RequestContent ToRequestContent()
{
    var content = new Utf8JsonRequestContent();
    content.JsonWriter.WriteObjectValue(this);
    return content;
}

上面代码中的 JsonWriter 是在 Utf8JsonRequestContent 的构造函数中初始化的

public Utf8JsonRequestContent()
{ 
    JsonWriter = new Utf8JsonWriter(_stream);
}

这里的 Utf8JsonWriter 就是 System.Text.Json.Utf8JsonWriter

public sealed partial class Utf8JsonWriter : IDisposable, IAsyncDisposable
{
    public Utf8JsonWriter(IBufferWriter<byte> bufferWriter, JsonWriterOptions options = default)
    {
        // ...
    }
}

由于 Utf8JsonRequestContent 创建 Utf8JsonWriter 实例时没有给 options 参数传值,所以,没有办法通过设置 JsonWriterOptions 实现 json 序列化时不对中文进行编码。

dudu | 高人七级 |园豆:30948 | 2024-02-18 17:28
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册