Enum.ipynb:Python枚举类型详解与实战指南
技术背景
在大语言模型(LLM)应用中,模型输出往往是非结构化的自由文本,这给下游程序解析和业务逻辑集成带来巨大挑战。例如,当需要模型从预定义类别中选择答案时,自由文本可能产生拼写变体、同义词或无关内容,导致程序崩溃或数据不一致。枚举(Enum)提供了一种强约束机制,将模型输出限制在预定义的值集合内,确保输出的合法性和一致性。Gemini API通过response_format参数支持枚举模式,适用于分类、标签、状态机等场景。其主要限制是枚举值必须预先定义,无法处理动态或开放集合,且模型可能因过度约束而降低灵活性。
核心原理
枚举约束的核心原理是在模型解码阶段,通过response_format中的schema定义允许的输出值集合,模型在生成每个token时只会从该集合中选择,从而保证最终输出严格匹配枚举值。在Gemini API的Interactions API中,response_format接受一个包含type、mime_type和schema的对象。当schema指定为{"type": "string", "enum": [...]}时,模型输出被限制为枚举值之一。若mime_type为application/json,输出会被包装为JSON字符串(如"Percussion"),便于程序解析。枚举也可嵌套在更复杂的JSON Schema中,如对象属性或数组元素,实现结构化输出。数据流为:用户输入(文本/图像)→ Gemini模型 → 受约束的解码 → 输出JSON字符串 → 程序解析。
架构分析
本教程的架构设计围绕Gemini API的Interactions API展开,核心组件包括:genai.Client(API客户端)、client.interactions.create(交互创建接口)、response_format(输出约束配置)以及Python枚举类(定义合法值)。设计决策包括:使用枚举类集中管理合法值,避免硬编码字符串;通过schema参数传递枚举值列表,实现声明式约束;利用typing.TypedDict定义复杂对象结构,与枚举组合使用。这种设计将业务逻辑(枚举定义)与API调用解耦,便于维护和扩展。可修改点包括:枚举值可动态生成,response_format可配置为不同MIME类型,模型ID可切换。
完整实战教程
##### 版权所有 2026 Google LLC.
# @title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Gemini API:枚举快速入门
<a target="_blank" href="https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Enum.ipynb">
</a>
Gemini API 允许您提供模式来定义函数参数(用于函数调用),或将其输出限制为 JSON 或使用枚举。本教程提供了一些使用枚举的示例。
注意: 本笔记本使用 Interactions API,这是与 Gemini 模型交互的最新方式。正在寻找 generateContent 版本?请查看 归档分支。
安装依赖
%pip install -U -q "google-genai>=2.9.0" # 2.9.0 for Interactions API
配置你的 API 密钥
要运行以下单元格,你的 API 密钥必须存储在名为 GEMINI_API_KEY 的 Colab Secret 中。如果你还没有 API 密钥,或者不确定如何创建 Colab Secret,请参阅 身份验证 获取详细指南。
from google import genai
from google.colab import userdata
GEMINI_API_KEY = userdata.get('GEMINI_API_KEY')
client = genai.Client(api_key=GEMINI_API_KEY)
选择您想在本指南中使用的模型:
MODEL_ID = "gemini-3.7-flash" # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite", "gemini-2.5-pro"] {"allow-input":true, isTemplate: true}
枚举
在最简单的情况下,如果你需要模型从一系列选项中选择一个,可以使用枚举类来定义模式。让它识别这个乐器:
!curl -O https://storage.googleapis.com/generativeai-downloads/images/instrument.jpg
import base64
from IPython.display import Image, display
display(Image(filename='instrument.jpg'))
with open('instrument.jpg', 'rb') as f:
instrument_data = base64.b64encode(f.read()).decode('utf-8')
响应应为以下选项之一:
import enum
class InstrumentClass(enum.Enum):
PERCUSSION = "Percussion"
STRING = "String"
WOODWIND = "Woodwind"
BRASS = "Brass"
KEYBOARD = "Keyboard"
在 Interactions API 中,将枚举类作为 schema 传入 response_format,并指定 application/json MIME 类型:
interaction = client.interactions.create(
model=MODEL_ID,
input=[
{"type": "image", "data": instrument_data, "mime_type": "image/jpeg"},
{"type": "text", "text": "what is the category of this instrument?"},
],
response_format={
"type": "text",
"mime_type": "application/json",
"schema": {
"type": "string",
"enum": [e.value for e in InstrumentClass],
},
},
)
print(interaction.steps[-1].content[0].text)
你也可以在 application/json mime_type 中使用枚举。在这个简单的情况下,响应将被包装在一个 JSON 字符串中:
interaction = client.interactions.create(
model=MODEL_ID,
input=[
{"type": "image", "data": instrument_data, "mime_type": "image/jpeg"},
{"type": "text", "text": "what category of instrument is this?"},
],
response_format={
"type": "text",
"mime_type": "application/json",
"schema": {
"type": "string",
"enum": [e.value for e in InstrumentClass],
},
},
)
print(interaction.steps[-1].content[0].text)
除了简单的多项选择问题之外,枚举类型还可以在JSON或函数调用的架构中的任何地方使用。例如,要求它列出一系列食谱标题,并使用Grade枚举为每个标题赋予一个受欢迎程度等级:
import typing_extensions as typing
class Grade(enum.Enum):
A_PLUS = 'a+'
A = 'a'
B = 'b'
C = 'c'
D = 'd'
F = 'f'
class Recipe(typing.TypedDict):
recipe_name: str
grade: Grade
在这个例子中,你想要一个 Recipe 对象的列表,所以将 list[Recipe] 作为 schema 传递给 response_format:
result = client.interactions.create(
model=MODEL_ID,
input="List about 10 cookie recipes, grade them based on popularity",
response_format={
"type": "text",
"mime_type": "application/json",
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"recipe_name": {"type": "string"},
"grade": {
"type": "string",
"enum": [e.value for e in Grade],
},
},
"required": ["recipe_name", "grade"],
},
},
},
)
import json
response = json.loads(result.steps[-1].content[0].text)
print(json.dumps(response, indent=4))
后续步骤
有用的 API 参考:
查看 结构化输出 文档或 GenerationConfig API 参考以了解更多详情。
相关示例
* 在 文本摘要 示例中使用了受限输出,为模型提供一种格式来总结故事(类型、角色等)。
* 目标检测 示例使用 JSON 受限输出来统一检测输出。
继续探索 Gemini API
枚举并不是限制模型输出的唯一方式,您还可以使用 JSON 模式。 函数调用 和 代码执行 是增强模型的其他方式,可以让模型使用您自己的函数,或者让它编写并运行这些函数。
常见问题
常见错误及排查方法:1. API密钥未配置或无效,导致认证失败——检查GEMINI_API_KEY是否正确设置,参考身份验证指南。2. 枚举值不匹配,模型输出不在枚举内——确保枚举值字符串与预期完全一致,注意大小写和空格。3. JSON解析错误——检查mime_type是否为application/json,输出可能被包装为JSON字符串,需用json.loads解析。4. 模型不支持枚举约束——确认使用的模型版本支持Interactions API和结构化输出,如gemini-3.7-flash。5. 网络或配额问题——检查网络连接和API配额。生产环境优化:使用缓存减少重复调用,设置超时和重试机制,监控API使用量,对枚举值进行版本管理。
企业应用扩展
枚举约束可扩展至更复杂的场景:1. 在函数调用中,枚举用于限制参数值,确保函数接收合法输入。2. 结合JSON模式,构建嵌套枚举对象,如多字段分类。3. 动态枚举:根据用户输入或上下文动态生成枚举值,但需注意模型解码的实时性。4. 与其他约束组合:如正则表达式、长度限制等,实现更精细的输出控制。5. 生产级应用:将枚举定义与业务逻辑分离,使用配置管理工具维护枚举值,便于跨团队协作。此外,可探索Gemini API的其他功能,如代码执行、多模态输入,与枚举结合构建更强大的AI应用。
总结
本教程面向有编程基础的开发者,深入讲解如何在Gemini API中利用Python枚举类型(enum.Enum)约束模型输出,实现结构化、可预测的AI响应。通过乐器分类、食谱评级等实战案例,展示枚举在JSON模式和函数调用中的应用,并涵盖环境配置、代码解析、常见错误排查及生产环境优化建议,帮助开发者掌握AI工程中的输出控制技术。
- --
内容来源与验证
- 内容等级:PREMIUM_A
- 质量等级:A
- 难度:中级
- 验证等级:V1
- 原文作者:
- 原文日期:
- 来源许可:Apache-2.0
- 来源版本:
7b1c745f47b2ece2783b768ed2a9856cda2c4d64 - 查看原文
站内还有更多完整实战教程
加入会员,解锁全部教程、完整代码与持续更新内容。
加入会员