agno 图像结构化抽取实战:用 output_schema 将图片解析为带置信度的 Pydantic 对象 agno 图像结构化抽取实战用 output_schema 将图片解析为带置信度的 Pydantic 对象【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno图片 → 类型化 Pydantic 对象是 agnocookbook/data_labeling/_07_image_extraction数据标注体系中的核心能力之一。本指南以该模块三个经过真实测试的示例脚本为主线讲解如何用output_schema让多模态 Agent 从单张图片中抽取场景属性、OCR 文本字段与逐字段置信度并依据 TEST_LOG.md 中记录的实测结果给出可直接复制运行、可预期输出形态的完整方案。读完你将掌握三种图片结构化抽取模式并理解 agno 底层Image媒体封装、RunOutput返回结构与 schema 约束机制。一、模块定位图片结构化抽取是什么在 agno 的 data_labeling 标注体系中_07_image_extraction解决的任务是输入一张图片远程 URL输出一个结构完全由你定义的 Pydantic 对象。它与文本抽取共享同一套output_schema机制区别仅在于输入端多了多模态图片描述性属性主体、场景、光线、颜色、显著物体OCR 字段招牌、小票、产品标签上的文字结构化元数据可进入数据库、向量库或下游表单的字段级数据。模块自述的典型应用场景见 README.md商品照片自动编目颜色、风格、类型从照片小票、名片预填表单字段为媒体档案库生成可检索的元数据进一步可对接_09_image_extraction_to_vectordb/存入向量库。边界约定也很清晰如果只需要一个分类标签用_06_image_classification/如果需要像素级区域坐标用_08_image_bounding_boxes/。本模块专注整图 → 结构化描述。模块共三个示例脚本均已在 TEST_LOG 中实测通过脚本抽取任务输出模型实测耗时实测 tokenbasic.py场景属性Scenegemini-3.5-flash6.9s1249ocr_fields.py招牌文字SignReadinggemini-3.5-flash2.4s1246with_confidence.py带置信度的Scenegemini-3.5-flash3.3s1332二、基础模式场景属性抽取basic.py2.1 类型化 Schema 定义basic.py 用 PydanticBaseModel定义输出结构这是output_schema的输入形式from typing import List, Literal, Optional from pydantic import BaseModel, Field class Scene(BaseModel): subject: str Field(..., descriptionThe main subject of the image) setting: Literal[indoor, outdoor, studio, unknown] time_of_day: Optional[Literal[day, night, dawn_or_dusk]] None dominant_colors: List[str] Field( default_factorylist, descriptionTwo to four named colors ) notable_objects: List[str] Field( default_factorylist, descriptionUp to five named objects in the scene )几个值得注意的字段约束设计Literal[indoor, outdoor, studio, unknown]把枚举值写死在类型里模型只能从中取值天然规避自由文本的格式漂移Optional[...] None表达该字段可能无法判定配合指令要求模型在不确定时留空而不是强行编造List[str]配description说明数量范围两到四种颜色、最多五个物体通过Field描述把业务规则注入 schema 提示。2.2 Agent 指令与模型装配instructions \ Describe the image as a structured Scene. Be concrete and observational. If a field is not determinable from the image, leave it null or empty. agent Agent( modelgoogle:gemini-3.5-flash, instructionsinstructions, output_schemaScene, )指令与 schema 是互补的schema 约束能填什么指令约束怎么填要具体、可观察、不可判定就留空。2.3 运行与实测结果if __name__ __main__: url https://agno-public.s3.amazonaws.com/images/krakow_mariacki.jpg run: RunOutput agent.run(Extract the scene attributes., images[Image(urlurl)]) pprint({url: url, result: run.content})针对克拉科夫圣玛利亚教堂照片TEST_LOG 记录的实际输出为Scene( subjectSt. Marys Basilica viewed through the arches of the Cloth Hall in Kraków, settingoutdoor, time_of_daydawn_or_dusk, dominant_colors[blue, yellow, beige], notable_objects[..., Sukiennice (Cloth Hall) arches, Adam Mickiewicz Monument] )注意subject是完整带上下文的描述句透过纺织会馆拱门看到的圣玛利亚教堂notable_objects多达五个并识别出地标级物体。该次运行耗时 6.9s、总消耗 1249 tokens。run.content返回的即是被反序列化后的ScenePydantic 实例可直接取字段落入下游结构。三、OCR 模式从文字密集型图片抽取字段ocr_fields.pyocr_fields.py 演示读图上的字把招牌、菜单、小票、名片上的可见文字映射进类型化 schema。class SignReading(BaseModel): primary_text: Optional[str] Field( None, descriptionThe main word or phrase shown on the sign ) secondary_text: List[str] Field( default_factorylist, descriptionAny additional words shown, in reading order, ) color_scheme: Optional[str] Field( None, descriptionDominant colors used on the sign, comma separated ) instructions \ Read the text on the sign in the image. Return what is literally written - do not translate, expand, or paraphrase. If the sign is partly obscured, include what is legible and leave the rest null. 关键指令约束是原样转录不翻译、不扩写、不改写——这正是 OCR 抽取与看图说话的本质区别。对 agno 官方 intro 图形agono-intro.png的实测结果primary_textWhat is Agno secondary_text 八个条目按阅读顺序从 Introduction 到 Level 5: Agentic Workflows with state and determinism. color_schemeBlack, White, Redsecondary_text数组的排列顺序直接对应图片中的阅读顺序验证了description中 in reading order 的约束确实生效。该次运行耗时 2.4s、1246 tokens是三个用例中吞吐最快的。四、进阶模式逐字段置信度with_confidence.pywith_confidence.py 解决真实标注中最头疼的问题低分辨率、运动模糊、部分遮挡导致的不确定字段。它的做法是把标量/列表字段各包一层置信度包装器Confidence Literal[high, medium, low] class ConfidentStr(BaseModel): value: Optional[str] None confidence: Confidence class ConfidentList(BaseModel): values: List[str] Field(default_factorylist) confidence: Confidence class Scene(BaseModel): subject: ConfidentStr setting: ConfidentStr time_of_day: ConfidentStr dominant_colors: ConfidentList notable_objects: ConfidentList指令明确规定了置信度语义让模型有据可依- high - clearly determinable from the image - medium - inferred but well-supported - low - guessed or partially obscured并强调宁可保守看不到的字段把value置为 null、置信度标 low。对挪威峡湾风景图gstatic 官方画廊样例图的实测结果五个字段全部填充且confidencehigh例如subject.value A deep fjord valley with a river flowing between steep, green mountains dominant_colors.values [blue, green, grey, brown] notable_objects.values [fjord, mountains, rocky peak, valley, river]TEST_LOG 特别注明嵌套包装器被正确反序列化为对应的 Pydantic 模型——即run.content中subject是一个ConfidentStr实例而非裸 dict。该次运行耗时 3.3s、1332 tokens。这一模式的价值在于下游可编排置信度为 low/medium 的字段转入人工复核队列high 字段直接入库形成机器预标注 人工兜底的半自动数据标注流水线。五、源码级原理output_schema、Image 与 RunOutput 是如何协作的三个示例都只用了四行核心 API但背后是 agno 完整的结构化输出管线结合 libs/agno 源码可以看清其机制。5.1 output_schemaPydantic 模型或 JSON Schema dictoutput_schema定义在 Agent接受两种形态PydanticBaseModel类型或符合 provider 预期的 JSON Schema dict。同参数下还有两个配套开关parse_response: bool True为 True 时模型返回会被转换为output_schema类型的实例否则返回 JSON 字符串structured_outputs/use_json_mode决定是否走模型原生强制结构化输出。从 agent/_messages.py 的实现可以看到只有当模型不原生支持结构化输出supports_native_structured_outputs/supports_json_schema_outputs且未启用 JSON mode 时agono 才会把 JSON 输出提示注入系统消息——也就是说对支持原生结构化输出的模型schema 约束是走模型 API 的强约束通道完成的而非纯提示词工程。5.2 Image统一的多模态输入封装Image类agno/media/media.py是 agno 对所有图片用法的统一抽象核心内容字段三选一由 model_validator 校验且标准化为 bytes字段用途url远程图片地址示例脚本采用的方式filepath本地文件路径content原始图片字节此外还支持detaillow/medium/high/auto对应 OpenAI vision 的清晰度规格、format/mime_type元数据、alt_text等。示例中agent.run(..., images[Image(urlurl)])传入的就是这个统一对象。5.3 RunOutput标准化的返回封装run()的返回类型是RunOutputagno/run/agent.py它把一次运行的所有信息打包content解析后的 schema 实例、content_type、run_id/session_id、model/model_provider、metrics含 token 统计、messages、reasoning_steps等。示例中pprint({url: url, result: run.content})打印的正是content字段——TEST_LOG 中记录的耗时与 token 数据即来自该次运行的metrics。5.4 数据标注流水线的位置TEST_LOG 中记录的全部是真实运行结果测试时间 2026-07-18环境为 agno 2.7.4 gemini-3.5-flashtoken 与耗时数据可直接作为后续标注任务预算与模型选型的参考基准。若要把抽取结果送入检索链路可衔接_09_image_extraction_to_vectordb/完成图片 → 结构化元数据 → 向量库的完整闭环。六、运行指南三个脚本均需GOOGLE_API_KEY环境变量默认使用google:gemini-3.5-flash模型。按模块 README 提供的命令执行python cookbook/data_labeling/_07_image_extraction/basic.py python cookbook/data_labeling/_07_image_extraction/with_confidence.py python cookbook/data_labeling/_07_image_extraction/ocr_fields.py示例中的图片 URL 均可按需替换为自有图片也支持Image(filepath...)本地路径三个脚本共用同一套Agentoutput_schema骨架改 schema 与指令即可迁移到任意图片标注任务。七、选型小结需求选用模式参考脚本整图 → 主题/场景/颜色/物体等描述属性基础Sceneschemabasic.py招牌/小票/名片上的文字原样转录SignReading 不译不改写指令ocr_fields.py低质量输入、需标记不确定字段供人工复核ConfidentStr/ConfidentList嵌套包装with_confidence.py只需分类标签改用图片分类模块_06_image_classification/需要像素区域坐标改用边界框模块_08_image_bounding_boxes/三条实测路径表明只要 schema 定义得当、指令约束明确agno 就能稳定产出可直接反序列化为 Pydantic 实例的结构化抽取结果且Optional 置信度机制让不知道也能被诚实表达——这正是它适合进入真实数据标注流水线的关键。【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考