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-python
ADK(Agent Development Kit)的static_instruction特性允许把types.Content对象直接作为 Agent 的静态指令,而不仅限于纯文本。本文基于 static_non_text_content 示例,完整讲解如何在静态指令中混合文本、inline_data(图片)与file_data(文档):包括 .env 凭据配置、四种运行方式、默认测试提示词,以及 ADK 底层如何为非文本部分自动生成引用 ID(inline_data_0、file_data_1)并把真实数据搬到 user contents 中,读完即可复现一个"自带图表与论文参考材料"的多模态 Agent。
示例定位:静态指令里的非文本内容
static_non_text_content示例位于 contributing/samples/multimodal/static_non_text_content/,共 3 个文件:
- agent.py:定义带有混合内容静态指令的 Agent;
- main.py:可运行脚本,支持交互式、单提示词与默认测试提示词三种模式;
- __init__.py:按 ADK 约定完成包初始化。
示例演示的核心能力包括:
- 静态指令中混合内容:单条
static_instruction同时包含文本、图片和文件引用; - 引用 ID 自动生成:非文本 part 会被自动赋予
inline_data_0、file_data_1之类的引用 ID; - Gemini 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 黄色像素 PNG(
SAMPLE_IMAGE_DATA,代码中以 Base64 内嵌),以inline_data形式携带,mime_type="image/png",display_name="sample_chart.png"; - 一段说明文本"这是一个展示颜色数据的示例图表"。
Gemini Developer API 额外包含:
- 一份"Contributing Guide"文档(代码中的
SAMPLE_DOCUMENT,包含最佳实践与贡献指南),运行时通过genai.Client().files.upload(...)上传到 Gemini Files API,再以file_data+file_uri=uploaded_file.uri的形式引用。示例会先client.files.list()检查同名文件是否存在,存在则复用,避免重复上传;上传使用临时文件,结束后清理。Gemini API 会自动在 48 小时后清理上传的文件。
Vertex AI 额外包含:
- GCS URI 文件:
gs://cloud-samples-data/generative-ai/pdf/2507.06261.pdf(Gemini 1.5 技术报告,display_name="Gemini Research Paper"); - HTTPS URL 文件:
https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf(另一篇研究论文,display_name="Gemini Research Paper (HTTPS)"),用于对比两种文件访问方式,验证模型能否跨文档对比并选择性引用。
API 变体通过 variant_utils 中的get_google_llm_variant()判定,返回GoogleLLMVariant.VERTEX_AI或其他值,示例据此选择不同的file_dataparts 和指令文本。
最终root_agent的定义(agent.py):
root_agent = Agent( name="static_non_text_content_demo_agent", description=( "Demonstrates static instructions with non-text content (inline_data" " and file_data features)" ), static_instruction=create_static_instruction_with_file_upload(), instruction=( "Please analyze the user's question and provide helpful insights." " Reference the materials provided in your static instructions when" " relevant." ), )这里同时设置了static_instruction(types.Content)和instruction(动态指令字符串),两者的落点不同,下文源码分析会展开。
环境配置:.env 文件
在contributing/samples项目根目录创建.env文件(main.py 依赖agent.py顶部的load_dotenv()自动加载):
# Choose Model Backend: 0 -> ML Dev, 1 -> Vertex GOOGLE_GENAI_USE_ENTERPRISE=1 # ML Dev backend config GOOGLE_API_KEY=your_google_api_key_here # Vertex backend config GOOGLE_CLOUD_PROJECT=your_project_id GOOGLE_CLOUD_LOCATION=us-central1GOOGLE_GENAI_USE_ENTERPRISE=1切换到 Vertex AI 后端(0 或不设为 Gemini Developer API);- ML Dev 后端使用
GOOGLE_API_KEY; - Vertex 后端使用
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 → 创建InMemoryRunner(app_name="static_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_data),Vertex 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 instruction;
- inline_data part:生成引用文本
[Reference to inline binary data: inline_data_{n} ('display_name', type: mime_type)]替换进 system instruction,同时构造一条role="user"的 content,包含Referenced inline data: inline_data_{n}文本 + 原始inline_datapart; - file_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/ 展示了静态指令 + 缓存的分析用法,可作为延伸阅读。
关键代码走读:构造混合 parts
agent.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_data(1x1 黄色像素 PNG) types.Part( inline_data=types.Blob( data=SAMPLE_IMAGE_DATA, mime_type="image/png", display_name="sample_chart.png", ) ), types.Part.from_text( text=f"This is a sample chart showing color data.{additional_text}"), ] parts.extend(file_data_parts) # Files API 上传件 或 GCS/HTTPS 文件 parts.append(types.Part.from_text(text=instruction_text)) static_instruction_content = types.Content(parts=parts)要点:
display_name/mime_type不是装饰字段——它们会被append_instructions写进系统指令里的引用文本(见上文引用格式),模型正是靠这些描述识别"第几个引用对应什么材料";file_data的mime_type按实际格式填写(PDF 用application/pdf,Markdown 用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.py);- system_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),仅供参考