ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

使用 instructor + Gemini 处理多模态音频:三种实战模式与源码级原理

2026/9/15 16:39:54 拓冰建站 浏览量
使用 instructor + Gemini 处理多模态音频:三种实战模式与源码级原理 使用 instructor Gemini 处理多模态音频三种实战模式与源码级原理【免费下载链接】instructorstructured outputs for llms项目地址: https://gitcode.com/GitHub_Trending/in/instructor本指南基于 instructor 官方示例 multi_modal_gemini.md讲解如何将instructor与google-generativeai结合对音频类多模态数据完成结构化抽取摘要、转写、说话人识别等。读完你将掌握三种音频输入方式整文件消息、内联音频片段、混合内容列表的完整写法、Mode.JSON的选择依据、20MB 内联大小限制的规避策略以及 instructor 底层多模态内容管线的实现原理。为什么音频场景必须使用Mode.JSON文档第一个脚注即点明了核心约束必须将 mode 设置为instructor.Mode.JSON它取代了已弃用的GEMINI_JSON因为 Tool Calling 无法与多模态输入协同工作。在 instructor/v2/core/mode.py 中Mode枚举为不同 Provider 定义了请求格式化策略tool_modes()返回所有基于工具调用的模式集合json_modes()返回所有基于 JSON 的模式集合。对于 Gemini 系历史上存在GEMINI_JSON、GEMINI_TOOLS等模式而现在这些旧模式已被统一收编进DEPRECATED_TO_CORE映射表见 instructor/v2/core/mode.py会触发DeprecationWarning。因此在新代码中直接使用import instructor client instructor.from_provider( google/gemini-2.5-flash, modeinstructor.Mode.JSON, # 取代已弃用的 GEMINI_JSON )from_provider接受形如provider/model-name的模型字符串并支持async_client、cache、mode等参数见 instructor/v2/auto_client.py。音频转录任务不需要函数调用机制JSON 模式直接要求模型输出符合 Pydantic 模型的 JSON 结构配合多模态输入完全没有障碍。环境准备与示例素材本示例使用的录音是 1961 年 1 月 30 日约翰·肯尼迪总统的国情咨文演讲摘自 Google Generative AI cookbook 的 Audio 示例。完整流程分两步准备素材下载 mp3 文件到本地sample.mp3可选用pydub将音频裁剪为前 60 秒片段便于快速测试与减少请求体。import requests from pydub import AudioSegment # 下载音频文件 url https://storage.googleapis.com/generativeai-downloads/data/State_of_the_Union_Address_30_January_1961.mp3 response requests.get(url) with open(sample.mp3, wb) as file: file.write(response.content) # 裁剪为前 60 秒 sound AudioSegment.from_mp3(sample.mp3) sound sound[:60000] sound.export(sample.mp3, formatmp3)依赖提示pydub负责音频解码与裁剪AudioSegment.from_mp3/export需要预先安装pip install pydub。方式一整文件作为普通消息Normal Message最直接的用法将完整音频文件通过genai.upload_file上传然后把返回的文件对象像普通用户消息一样传入client.create。这也是官方推荐的文件上传方式——音频、视频这类大体积媒体都应走 File API 而非内联字节。import instructor import google.generativeai as genai from pydantic import BaseModel client instructor.from_provider( google/gemini-2.5-flash, modeinstructor.Mode.JSON, # Tool Calling 不支持多模态输入必须用 JSON 模式 ) mp3_file genai.upload_file(./sample.mp3) # 若已上传可用 genai.get_file 获取 class Description(BaseModel): description: str resp client.create( response_modelDescription, messages[ { role: user, content: Summarize whats happening in this audio file and who the main speaker is, }, { role: user, content: mp3_file, # 文件对象可像普通消息一样传入 }, ], ) print(resp) description The main speaker is President John F. Kennedy, giving his State of the Union address to a joint session of Congress. He is speaking in the House of Representatives in Washington, D.C. on January 30th, 1961. He is thanking the members of Congress for their knowledge and inspiration. 三个关键点模式Mode.JSON是前提原因上文已述。上传/取回genai.upload_file上传本地文件如果文件已经上传过可以用genai.get_file直接拿回文件对象避免重复上传。消息结构mp3_file一个genai.types.File对象直接作为content传入instructor 会在底层将它正确组装进 Gemini 的contents。方式二内联音频片段Inline Audio Segment第二种方式是把音频片段转成字节以内联对象形式放入消息的content字典。此时需要pydub完成读取与裁剪再把data字段填充为音频字节流。import instructor from pydantic import BaseModel from pydub import AudioSegment client instructor.from_provider( google/gemini-2.5-flash, modeinstructor.Mode.JSON, # Tool Calling 不支持多模态输入必须用 JSON 模式 ) sound AudioSegment.from_mp3(sample.mp3) # 用 AudioSegment 加载音频 sound sound[:60000] class Transcription(BaseModel): summary: str exact_transcription: str resp client.create( response_modelTranscription, messages[ { role: user, content: Please transcribe this recording, }, { role: user, content: { mime_type: audio/mp3, data: sound.export().read(), # 音频字节流填入 data 字段 }, }, ], ) print(resp) summaryPresident addresses the joint session of Congress, reflecting on his first time taking the oath of federal office and the knowledge and inspiration gained. exact_transcriptionThe Presidents state of the union address to a joint session of the Congress from the rostrum of the House of Representatives, Washington D.C. January 30th 1961 Speaker, Mr Vice President members of the Congress It is a pleasure to return from whence I came You are among my oldest friends in Washington And this house is my oldest home It was here it was here more than 14 years ago that I first took the oath of federal office It was here for 14 years that I gained both knowledge and inspiration from members of both 这里content是一个字典mime_type声明音频格式audio/mp3data填入sound.export().read()返回的原始字节。instructor 会将该 dict 原样透传给底层生成式 AI 客户端由 Gemini 端负责解析内联字节。内联方式的最大文件大小限制当音频以内联字节提交时API 存在 20MB20971520 字节的请求体上限。超出后会抛出如下错误google.api_core.exceptions.InvalidArgument: 400 Request payload size exceeds the limit: 20971520 bytes. Please upload your files with the File API instead.f genai.upload_file(path); m.generate_content([tell me about this file:, f])遇到该错误时的处理策略很明确改用方式一File API 上传即f genai.upload_file(path)后再传给模型。对于视频文件文档同样建议使用genai.upload_file而非内联方式。值得说明的是instructor 仓库内部的远程媒体抓取也设置了类似的字节上限图片MAX_IMAGE_BYTES 20MB、音频MAX_AUDIO_BYTES 25MB、PDFMAX_PDF_BYTES 50MB见 instructor/v2/core/remote.py。这是 instructor 在自动下载 URL 媒体时自己的安全约束与 Gemini 端的内联限制相互独立。方式三混合内容列表Lists of Content第三种方式是 Google Generative AI 文档支持的列表形式将文本消息与文件对象放进同一个content列表instructor 会按顺序把它们作为一条用户消息发送。列表中可以自由混入普通字符串与genai文件对象非常灵活。import instructor import google.generativeai as genai from pydantic import BaseModel client instructor.from_provider( google/gemini-2.5-flash, modeinstructor.Mode.JSON, # Tool Calling 不支持多模态输入必须用 JSON 模式 ) mp3_file genai.upload_file(./sample.mp3) # 也可用 genai.get_file 取回已上传文件 class Description(BaseModel): description: str content [ Summarize whats happening in this audio file and who the main speaker is, mp3_file, # 文本与文件对象可混在同一个列表里 ] resp client.create( response_modelDescription, messages[ { role: user, content: content, } ], ) print(resp) description President John F. Kennedy delivers his State of the Union address to the Congress on January 30, 1961. The speech was delivered at the rostrum of the House of Representatives in Washington, D.C. 这种写法适合需要指令 素材同时送达的场景例如先听这段音频再判断说话人情绪——指令与音频在同一个列表中顺序排列模型按序消费。三种方式对比与选型建议方式素材形态适用场景注意事项方式一Normal Messagegenai.upload_file返回的文件对象大体积音频/视频、需要复用已上传文件走 File API无 20MB 内联限制文件已上传可用genai.get_file取回方式二Inline Segment{mime_type: ..., data: 字节流}字典小片段、需要pydub先裁剪处理请求体上限 20971520 字节超限须退回方式一需要安装pydub方式三Lists of Content文本与文件对象混合的列表一条消息同时携带指令与多个素材列表内可自由混入字符串与文件对象三种方式的共同前提都是modeinstructor.Mode.JSON且都需要response_modelPydantic 模型来约束输出结构。源码级原理instructor 的多模态内容管线以上三种写法看似是把文件/字节丢进 messages实际上 instructor 在底层有一套完整的多模态内容转换管线位于 instructor/v2/core/multimodal.py并针对 Google GenAI 有专门的编码器 instructor/v2/providers/genai/multimodal.py。1. 请求入口从 messages 到 contentsGemini 的 API 输入是contents而非 OpenAI 风格的messages。在 instructor/v2/providers/genai/handlers.py 中handler 会调用gemini_utils.convert_to_genai_messages把messages转成 GenAI 类型再交给extract_genai_multimodal_content处理多模态内容最后写入kwargs[contents]并移除messages键。2. 类型识别File 对象直接透传extract_multimodal_contentinstructor/v2/providers/genai/multimodal.py逐条遍历 contents如果内容本身就是types.File即方式一/方式三中genai.upload_file的返回值直接原样透传——这正是整文件上传方式零成本工作的原因如果内容是types.Content则遍历其parts对每个 part 的文本执行autodetect_media自动探测若文本其实是图片、音频或 PDF 的来源URL、路径、base64 等就转换为对应的媒体对象并调用to_genai()编码否则保留原文。3. 内联字节编码Part.from_bytesAudio.to_genaiinstructor/v2/providers/genai/multimodal.py实现非常简洁def audio_to_genai(audio: Any) - Any: types _types() return types.Part.from_bytes( database64.b64decode(audio.data), mime_typeaudio.media_type, )即把 base64 编码的音频数据解码回字节连同mime_type一起包装成types.Part.from_bytes。这与方式二中手工构造{mime_type: audio/mp3, data: ...}字典是同一思路——一个是用户手工构造 dict一个是 instructor 用Audio模型统一封装。4. 通用媒体模型Image / Audio / PDF在 instructor/v2/core/multimodal.py 中Audio是一个 Pydantic 模型字段为sourceURL/路径、database64 编码字节、media_typeMIME 类型。它提供了多种构造入口Audio.from_url抓取公网 URL 并校验 MIME 类型Audio.from_path读取本地文件并做 MIME 归一化如 Windows 上audio/vnd.dlna.adts会归一化为audio/aacAudio.from_gs_url处理gs://Google Cloud Storage 地址Audio.autodetect自动判断来源类型。同样的模式也适用于Image与PDF含支持 Anthropic 提示缓存的ImageWithCacheControl/PDFWithCacheControl音频只是其中的一种媒体类型。跨 Provider 时统一通过to_openai/to_anthropic/to_genai等方法将媒体对象转换成各家 API 的格式。5. 安全边界公网媒体抓取当 instructor 需要从 URL 自动下载媒体时会走 instructor/v2/core/remote.py 中带安全约束的抓取逻辑只允许 http/https 公网地址、拒绝内网/私网 IP、限制重定向次数MAX_REDIRECTS 5与下载字节上限并关闭环境代理trust_env False避免媒体 URL 意外携带凭据。这保证了即使素材来自不可信 URL也不会触发 SSRF 类风险。更多相关资源方式一与方式三所用genai.upload_file/genai.get_file的完整说明可参考 docs/integrations/genai.md多模态输入在 instructor 中的通用抽象Image / Audio / PDF 自动探测见 docs/concepts/multimodal.md旧模式如GEMINI_JSON向新模式迁移的说明见 docs/concepts/mode-migration.md更多实战配方图片表格抽取、发票识别、幻灯片转文本等见 docs/examples/index.md 的 Multi-Modal Examples 章节底层多模态管线与 GenAI 编码器的确定性测试见 tests/v2/test_genai_handlers_deterministic.py。小结通过本文你可以快速上手三类音频多模态用法整文件上传适合大文件与复用、内联片段适合小片段与预处理、混合内容列表适合指令素材同发。核心要诀是牢记Mode.JSON与 20MB 内联上限更进一步instructor 的Image/Audio/PDF统一模型与autodetect_media自动探测机制让你可以把同一套多模态处理逻辑平滑迁移到图片、PDF 甚至不同 Provider 之间。【免费下载链接】instructorstructured outputs for llms项目地址: https://gitcode.com/GitHub_Trending/in/instructor创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考