使用Vertex AI SDK(Gemini)时如何正确指定ResponseSchema?
问题分析与解决方案
错误原因
你遇到的Google.Protobuf.InvalidProtocolBufferException异常,核心原因是传入的ResponseSchema格式不符合要求。你当前使用的是Python风格的类型注解字符串,而Vertex AI的ResponseSchema要求的是符合OpenAPI 3.0规范的JSON结构,Protobuf解析器无法识别自定义的类型注解格式,因此抛出了无效wire type的错误。
正确实现步骤
1. 定义标准OpenAPI Schema JSON
首先需要将你的list[Comp]结构转换为符合OpenAPI规范的JSON Schema,示例如下:
{ "type": "array", "items": { "type": "object", "properties": { "rank": {"type": "integer"}, "score": {"type": "integer"}, "propertyId": {"type": "integer"}, "address": {"type": "string"}, "proximity": {"type": "string"}, "price": {"type": "string"}, "livingArea": {"type": "string"}, "lotSize": {"type": "string"}, "yearBuilt": {"type": "integer"}, "bedrooms": {"type": "integer"}, "bathrooms": {"type": "integer"}, "notes": {"type": "string"} }, "required": ["rank", "score", "propertyId", "address", "price", "bedrooms", "bathrooms"] } }
2. 修改C#代码中的ResponseSchema解析逻辑
将原来的Python风格字符串替换为上述标准JSON结构,修改后的GenerationConfig部分代码如下:
GenerationConfig = new GenerationConfig { CandidateCount = 1, Temperature = Temperature, MaxOutputTokens = args.MaxOutputTokens ?? MaxOutputTokens, TopP = TopP, Seed = Seed, ResponseMimeType = "application/json", // 必须与ResponseSchema配合使用 ResponseSchema = OpenApiSchema.Parser.ParseFrom( BinaryData.FromBytes( Encoding.UTF8.GetBytes(@" { ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""rank"": {""type"": ""integer""}, ""score"": {""type"": ""integer""}, ""propertyId"": {""type"": ""integer""}, ""address"": {""type"": ""string""}, ""proximity"": {""type"": ""string""}, ""price"": {""type"": ""string""}, ""livingArea"": {""type"": ""string""}, ""lotSize"": {""type"": ""string""}, ""yearBuilt"": {""type"": ""integer""}, ""bedrooms"": {""type"": ""integer""}, ""bathrooms"": {""type"": ""integer""}, ""notes"": {""type"": ""string""} }, ""required"": [""rank"", ""score"", ""propertyId"", ""address"", ""price"", ""bedrooms"", ""bathrooms""] } }") ) ) }
3. 额外注意事项
- 确保使用的
Google.Cloud.AIPlatform.V1SDK版本在1.13.0及以上,该版本才正式支持ResponseSchema特性。 ResponseMimeType必须设置为application/json,否则ResponseSchema不会生效。- 如果需要从外部传入Schema,确保传入的是标准JSON字符串,而非自定义类型注解。
内容的提问来源于stack exchange,提问作者Justin
相关产品推荐
相关产品推荐

