You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用chat-bison模型时Google.Protobuf.JsonFormatter格式化PredictResponse失败

问题排查与解决方案:Google.Cloud.AIPlatform.V1调用chat-bison模型时JsonFormatter格式化失败

根因分析

  • 异常System.InvalidOperationException: 'Value message must contain a value for the oneof.'由Protobuf的JsonFormatter抛出,核心原因是oneof类型字段未被赋值:Protobuf规范要求oneof字段必须有且仅有一个选项被设置,否则序列化时触发该异常。
  • chat-bison模型返回的PredictResponse中存在未赋值的oneof字段,而text-bison的响应结构无此问题,因此仅chat-bison调用触发错误。
  • 推测触发场景:Vertex AI的chat-bison模型近期更新了响应结构,当前使用的v2.19.0版本Google.Cloud.AIPlatform.V1库未适配该变化,导致解析后的Protobuf对象存在不符合规范的oneof字段。

解决方案

方案1:升级SDK库版本

优先尝试升级Google.Cloud.AIPlatform.V1到最新稳定版,官方可能已修复该兼容性问题:

# NuGet包管理器命令
Install-Package Google.Cloud.AIPlatform.V1 -Version [最新版本号]

方案2:使用宽松序列化配置

修改JsonFormatter的初始化设置,允许忽略未赋值的oneof字段:

var formatterSettings = new JsonFormatter.Settings
{
    IgnoreUnknownFields = true,
    FormatDefaultValues = false,
    PreserveProtoFieldNames = true
};
var formatter = new JsonFormatter(formatterSettings);

try
{
    string json = formatter.Format(response);
}
catch (InvalidOperationException)
{
    // 降级处理:手动提取核心响应字段构建JSON
    var responsePayload = new
    {
        Predictions = response.Predictions.Select(p => p.ToString()),
        Metadata = response.Metadata.ToDictionary(kv => kv.Key, kv => kv.Value.ToString())
    };
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(responsePayload);
}

方案3:直接解析预测结果字段

chat-bison的核心响应内容存储在PredictResponse.Predictions集合中,可直接遍历并序列化该集合:

// 解析每个Prediction的结构化字段
var predictions = response.Predictions
    .Select(pred =>
    {
        var resultDict = new Dictionary<string, object>();
        foreach (var field in pred.Fields)
        {
            // 根据字段类型转换值(示例为字符串,可按需扩展)
            resultDict[field.Key] = field.Value.KindCase switch
            {
                Google.Protobuf.WellKnownTypes.Value.KindOneofCase.StringValue => field.Value.StringValue,
                Google.Protobuf.WellKnownTypes.Value.KindOneofCase.StructValue => Newtonsoft.Json.JsonConvert.SerializeObject(field.Value.StructValue),
                _ => field.Value.ToString()
            };
        }
        return resultDict;
    })
    .ToList();

// 序列化最终结果
string json = Newtonsoft.Json.JsonConvert.SerializeObject(new { Predictions = predictions });

方案4:使用Google.Protobuf.Json序列化器

通过Google官方提供的Google.Protobuf.Json包实现兼容序列化:

// 先安装依赖包
// Install-Package Google.Protobuf.Json

string json = Google.Protobuf.Json.JsonFormatter.Default.Format(response);

内容的提问来源于stack exchange,提问作者Юрій Ізьо

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:43:19