Gemini结构化输出
生成 JSON
在文本提示中提供架构
在模型上配置架构是生成 JSON 的推荐方法,因为它会限制模型输出 JSON。
如需将模型限制为生成 JSON,请配置 responseSchema。然后,模型将以 JSON 格式的输出回答任何问题。
示例:
生成枚举值
示例:
import enum
class Instrument(enum.Enum):
PERCUSSION = "Percussion"
STRING = "String"
WOODWIND = "Woodwind"
BRASS = "Brass"
KEYBOARD = "Keyboard"
client = genai.Client(api_key="GEMINI_API_KEY")
response = client.models.generate_content(
model='gemini-2.5-flash',
contents='What type of instrument is an oboe?',
config={
'response_mime_type': 'text/x.enum',
'response_schema': Instrument,
},
)
print(response.text)
# Woodwind
修改于 2025-06-24 02:28:56