adk-python:用 static_instruction 在系统指令中内嵌图片与文件(static_non_text_content 示例深度解析)

adk-python:用 static_instruction 在系统指令中内嵌图片与文件(static_non_text_content 示例深度解析) adk-python用 static_instruction 在系统指令中内嵌图片与文件static_non_text_content 示例深度解析【免费下载链接】adk-pythonAn open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.项目地址: https://gitcode.com/GitHub_Trending/ad/adk-pythonADKAgent Development Kit的static_instruction特性允许把types.Content对象直接作为 Agent 的静态指令而不仅限于纯文本。本文基于 static_non_text_content 示例完整讲解如何在静态指令中混合文本、inline_data图片与file_data文档包括 .env 凭据配置、四种运行方式、默认测试提示词以及 ADK 底层如何为非文本部分自动生成引用 IDinline_data_0、file_data_1并把真实数据搬到 user contents 中读完即可复现一个自带图表与论文参考材料的多模态 Agent。示例定位静态指令里的非文本内容static_non_text_content示例位于 contributing/samples/multimodal/static_non_text_content/共 3 个文件agent.py定义带有混合内容静态指令的 Agentmain.py可运行脚本支持交互式、单提示词与默认测试提示词三种模式__init__.py按 ADK 约定完成包初始化。示例演示的核心能力包括静态指令中混合内容单条static_instruction同时包含文本、图片和文件引用引用 ID 自动生成非文本 part 会被自动赋予inline_data_0、file_data_1之类的引用 IDGemini Files API 集成上传文档到 Gemini Files API 并通过file_data引用API 变体差异化行为Gemini Developer API 与 Vertex AI 走不同的文件接入路径GCS 文件引用Vertex AI 下同时演示 GCS URI 与 HTTPS URL 两种访问方式。静态指令里放了什么内容agent.py 中由create_static_instruction_with_file_upload()构造types.Content其 parts 组合如下所有 API 变体共同包含一段文本指令说明 Agent 是分析和解读图片、文档的 AI 助手一张 1x1 黄色像素 PNGSAMPLE_IMAGE_DATA代码中以 Base64 内嵌以inline_data形式携带mime_typeimage/pngdisplay_namesample_chart.png一段说明文本这是一个展示颜色数据的示例图表。Gemini Developer API 额外包含一份Contributing Guide文档代码中的SAMPLE_DOCUMENT包含最佳实践与贡献指南运行时通过genai.Client().files.upload(...)上传到 Gemini Files API再以file_datafile_uriuploaded_file.uri的形式引用。示例会先client.files.list()检查同名文件是否存在存在则复用避免重复上传上传使用临时文件结束后清理。Gemini API 会自动在 48 小时后清理上传的文件。Vertex AI 额外包含GCS URI 文件gs://cloud-samples-data/generative-ai/pdf/2507.06261.pdfGemini 1.5 技术报告display_nameGemini Research PaperHTTPS URL 文件https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf另一篇研究论文display_nameGemini Research Paper (HTTPS)用于对比两种文件访问方式验证模型能否跨文档对比并选择性引用。API 变体通过 variant_utils 中的get_google_llm_variant()判定返回GoogleLLMVariant.VERTEX_AI或其他值示例据此选择不同的file_dataparts 和指令文本。最终root_agent的定义agent.pyroot_agent Agent( namestatic_non_text_content_demo_agent, description( Demonstrates static instructions with non-text content (inline_data and file_data features) ), static_instructioncreate_static_instruction_with_file_upload(), instruction( Please analyze the users question and provide helpful insights. Reference the materials provided in your static instructions when relevant. ), )这里同时设置了static_instructiontypes.Content和instruction动态指令字符串两者的落点不同下文源码分析会展开。环境配置.env 文件在contributing/samples项目根目录创建.env文件main.py 依赖agent.py顶部的load_dotenv()自动加载# Choose Model Backend: 0 - ML Dev, 1 - Vertex GOOGLE_GENAI_USE_ENTERPRISE1 # ML Dev backend config GOOGLE_API_KEYyour_google_api_key_here # Vertex backend config GOOGLE_CLOUD_PROJECTyour_project_id GOOGLE_CLOUD_LOCATIONus-central1GOOGLE_GENAI_USE_ENTERPRISE1切换到 Vertex AI 后端0 或不设为 Gemini Developer APIML Dev 后端使用GOOGLE_API_KEYVertex 后端使用GOOGLE_CLOUD_PROJECT与GOOGLE_CLOUD_LOCATION示例默认us-central1。运行方式以下命令均需先cd contributing/samples。默认测试提示词推荐不带--prompt时自动执行python -m static_non_text_content.mainADK 内置交互式模式adk run static_non_text_content单条提示词python -m static_non_text_content.main --prompt What reference materials do you have access to?带调试日志观察内部处理细节python -m static_non_text_content.main --debug --prompt What is the Gemini research paper about?main.py 中的main()流程解析参数--prompt/--debug→ 打印 Agent 名称、模型、描述并统计静态指令中 text / inline image / file reference 各多少个 part → 创建InMemoryRunnerapp_namestatic_non_text_content_demo→ 按--prompt走single_prompt_mode或run_default_test_prompts。call_agent_async()通过runner.run_async()流式消费事件拼接event.author ! user的文本作为最终响应。默认测试提示词清单不指定--prompt时main.py 按 API 变体组装提示词所有变体前 3 条What reference materials do you have access to?Can you describe the sample chart that was provided to you?How do the inline image and file references in your instructions help you answer questions?Gemini Developer API 追加第 4 条What does the contributing guide document say about best practices?Vertex AI 追加第 4–5 条What is the Gemma research paper about and what are its key contributions?Can you compare the research papers you have access to? Are they related or different?因此 Gemini Developer API 共 4 条验证inline_data Files APIfile_dataVertex AI 共 5 条验证inline_data GCS URIfile_data HTTPS URLfile_data。每条提示词之间以InMemoryRunner的同一 session 连续对话ValueError、ConnectionError、TimeoutError会被捕获打印而非中断。工作原理引用 ID 的生成与内容迁移README 描述的 4 步处理流程可以在 ADK 源码中找到对应实现。入口_build_instructions。src/google/adk/flows/llm_flows/instructions.py 中的请求处理器_InstructionsLlmRequestProcessor在每轮 LLM 请求构建时若agent.static_instruction存在先经google.genai的_transformers.t_content()将ContentUnion规范化为types.Content再调用llm_request.append_instructions(static_content)若同时存在instruction当没有static_instruction时instruction注入 system_instruction当有static_instruction时instruction被包成带标签的 user content 追加到contents从而与静态前缀分离这是上下文缓存优化的关键静态前缀保持稳定。核心LlmRequest.append_instructions对非文本 part 的处理。src/google/adk/models/llm_request.py 中当传入参数是types.Content时逐 part 处理non_text_count计数器对inline_data与file_data统一计数text part原文追加到 system instructioninline_data part生成引用文本[Reference to inline binary data: inline_data_{n} (display_name, type: mime_type)]替换进 system instruction同时构造一条roleuser的 content包含Referenced inline data: inline_data_{n}文本 原始inline_datapartfile_data part生成[Reference to file data: file_data_{n} (display_name, URI: ..., type: mime_type)]同样把原始file_datapart 搬进 user content。处理完的文本部分以\n\n连接后拼接到config.system_instruction模型 API 要求 system_instruction 必须是字符串而 user contents 直接extend到llm_request.contents并置位_has_static_instruction标记。这解释了示例中模型既看到描述性引用、又拿到真实内容的行为系统指令里是带引用 ID 的占位文本真正的二进制数据/文件 URI 位于用户内容中模型可以按引用 ID 关联两者。缓存友好性。从 LlmRequest 的类注释 与 LlmAgent 字段说明 可以看到设计意图static_instruction被单独追踪、总是置于contents前缀位置_static_instruction_prefix_end_index保证后续动态指令、工具触发的动态指令插入在其后而非之前使前缀在会话内保持稳定——这正是 prompt/context caching 可以命中的前提。源码同时明确仅设置static_instruction不会自动开启缓存需要额外配置缓存策略。与上下文缓存的配合示例。同仓库 contributing/samples/context_management/cache_analysis/ 展示了静态指令 缓存的分析用法可作为延伸阅读。关键代码走读构造混合 partsagent.py 中 parts 的组装顺序值得注意parts [ types.Part.from_text(text( You are an AI assistant that analyzes images and documents. You have access to the following reference materials:)), # 示例图片inline_data1x1 黄色像素 PNG types.Part( inline_datatypes.Blob( dataSAMPLE_IMAGE_DATA, mime_typeimage/png, display_namesample_chart.png, ) ), types.Part.from_text( textfThis is a sample chart showing color data.{additional_text}), ] parts.extend(file_data_parts) # Files API 上传件 或 GCS/HTTPS 文件 parts.append(types.Part.from_text(textinstruction_text)) static_instruction_content types.Content(partsparts)要点display_name/mime_type不是装饰字段——它们会被append_instructions写进系统指令里的引用文本见上文引用格式模型正是靠这些描述识别第几个引用对应什么材料file_data的mime_type按实际格式填写PDF 用application/pdfMarkdown 用text/markdown文件 part 放在说明文本之后、指令文本之前保持材料在前、行为规则在后的指令结构。实践建议与限制同一文档双通道验证Vertex AI 变体同时挂载 GCS URI 与 HTTPS URL 两个file_data是对同一类文件、不同接入方式行为一致性的直接验证手法可迁移到你自己的 GCS 文件集成测试Files API 复用逻辑示例先files.list()按display_name查重再上传避免重复会话堆积文件但 Gemini API 侧文件 48 小时后自动清理长期参考材料建议改用 Vertex AI GCS 引用instruction与static_instruction的分工static_instruction承载稳定不变的多模态参考材料可缓存前缀instruction承载每轮可动态变化的行为指令二者同时存在时后者会以 user content 形式落在静态前缀之后instructions.pysystem_instruction 类型限制append_instructions只支持向字符串类型的config.system_instruction追加遇到其他类型会打 warning 并跳过自定义 LlmRequest 配置时需注意运行前提本示例需要google-genai客户端可用的凭据API Key 或 Vertex 项目配置Vertex 路径下模型需具备访问gs://cloud-samples-data中公开示例 PDF 的权限该 bucket 为 Google 公开样例数据。小结static_non_text_content示例用最小化的代码闭环演示了 ADK 静态指令的多模态形态agent.py用types.Content拼装文本 inline_data图片 file_data文档运行时按 API 变体切换 Files API 上传与 GCS/HTTPS 文件引用ADK 在请求构建阶段llm_request.py把非文本 part 替换为带引用 ID 的系统指令占位文本并将真实数据以 user content 形式随请求下发同时在请求结构层面保证静态前缀稳定以支持上下文缓存。配合本文给出的 .env 配置、四种运行命令与默认测试提示词清单可以直接在本地复现并验证该特性。【免费下载链接】adk-pythonAn open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.项目地址: https://gitcode.com/GitHub_Trending/ad/adk-python创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考