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

在Gemini API响应Schema中使用字典触发ValueError的问题问询

解决Gemini结构化输出Schema中dict类型导致的additionalProperties报错问题

问题背景

当使用TypedDict定义包含dict类型的Schema用于Gemini结构化输出时,调用generate_content_async会抛出ValueError: Unknown field for Schema: additionalProperties错误。即使替换为typing.Dict问题依旧,移除字典类型虽能避免报错但无法满足动态键值对的业务需求。

出错的Schema定义示例:

from typing_extensions import TypedDict

class LeagueStandings(TypedDict):
  teams: dict[str, int]

class LeaguesSchema(TypedDict):
  leagues: dict[str, LeagueStandings]

原因分析

Gemini的结构化输出Schema解析器不支持JSON Schema中的additionalProperties字段,但TypedDict在自动转换为JSON Schema时,会将dict[str, T]类型映射为包含additionalProperties的对象结构,从而触发报错。

解决方案

放弃使用TypedDict自动生成Schema,改为手动构建符合Gemini要求的JSON Schema,用patternProperties替代additionalProperties来定义动态键值对。

示例代码

import google.generativeai as genai

# 手动定义符合Gemini要求的JSON Schema
leagues_schema = {
    "type": "object",
    "required": ["leagues"],
    "properties": {
        "leagues": {
            "type": "object",
            "patternProperties": {
                # 匹配任意非空字符串作为联赛名称键
                "^.+$": {
                    "type": "object",
                    "required": ["teams"],
                    "properties": {
                        "teams": {
                            "type": "object",
                            "patternProperties": {
                                # 匹配任意非空字符串作为球队名称键,值为整数类型(如积分)
                                "^.+$": {"type": "integer"}
                            }
                        }
                    }
                }
            }
        }
    }
}

async def generate_league_standings():
    model = genai.GenerativeModel(model_name="gemini-1.5-pro")
    response = await model.generate_content_async(
        prompt="生成各大足球联赛的球队积分排名,输出JSON格式",
        generation_config=genai.GenerationConfig(
            response_mime_type="application/json",
            response_schema=leagues_schema
        )
    )
    # 解析并输出响应结果
    print(response.text)

补充说明

  • patternProperties用于定义匹配特定模式的键对应的结构,这里用^.+$匹配任意非空字符串键,适配动态的联赛和球队名称需求
  • 若需要更严格的键格式验证,可修改patternProperties中的正则表达式(比如限定联赛名称为英文、数字组合等)
  • 确保使用的Gemini SDK为最新版本,避免因版本兼容问题导致其他Schema解析错误

内容的提问来源于stack exchange,提问作者Guy McLean

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:13:18