mcpField
I
invoking-gemini

invoking-gemini

github.com/oaustegardAgent 工作流15744 次安装1 天前更新
代码仓库

关于 invoking-gemini

用于将任务委派给 Google Gemini 模型的技能,面向需要文本、多模态或结构化输出的工作流。它提供 Python 客户端函数,涵盖图像、语音、并行调用和 Pydantic 结构化输出。

主要功能

  1. 01生成图像并设置输出路径
  2. 02生成语音并设计或查询声音
  3. 03文本与多模态模型调用
  4. 04按 Pydantic 模型生成结构化输出
  5. 05并行处理多个提示词

适用场景

  1. 01制作插图、博客页眉或图表
  2. 02生成旁白或双人对话语音
  3. 03将图像或视频内容转为结构化分析
  4. 04批量处理简单文本任务

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/oaustegard/claude-skills --skill invoking-gemini

安装后在 Claude Code 中输入/invoking-gemini确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

CHANGELOG.md
README.md
references/
advanced.md
examples.md
models.md
scripts/
gemini_client.py

详细介绍

调用 Gemini

当 Google 的 Gemini 模型比 Claude 更有优势时,将任务委托给它们。

何时使用 Gemini

图像生成:

  • 博客页眉图片、插图、图表
  • 风格引导的图像创作(孔版印刷、编辑插画等)
  • 在图像中渲染文字

语音(TTS):

  • 旁白、配音、朗读,并为每行指定风格
  • 根据文字描述设计的自定义语音
  • 双人对话

结构化输出:

  • JSON Schema 验证,并保证属性顺序
  • 符合 Pydantic 模型
  • 严格遵循 Schema(枚举值、必填字段)

成本优化:

  • 并行批处理(Gemini 3 Flash 轻量高效)
  • 大批量简单任务

多模态任务:

  • 输出 JSON 的图像分析
  • 视频处理
  • 带结构的音频转录

设置

uv pip install requests pydantic

凭据 — 选项 A(推荐):Cloudflare AI Gateway

从 /mnt/project/proxy.env 加载 CF_ACCOUNT_ID、CF_GATEWAY_ID、CF_API_TOKEN。 请求通过 Cloudflare AI Gateway 路由,绕过 IP 封锁。Google API 密钥通过 BYOK 存储在 Gateway 中。

凭据 — 选项 B:直接使用 Google API

如果没有 proxy.env,则回退到直接访问:GOOGLE_API_KEY.txt 或 API_CREDENTIALS.json。

图像生成

使用 Gemini 原生图像模型生成图像。这是创作插图、博客页眉图片、图表和视觉内容的主要方式。

快速开始
import sys
sys.path.append('/mnt/skills/user/invoking-gemini/scripts')
from gemini_client import generate_image

# One call — returns {"path": "...", "caption": "..."} or None
result = generate_image("A watercolor painting of a mountain lake at sunset")
print(result["path"])  # /mnt/user-data/outputs/gemini_image_1740000000.png
函数签名
generate_image(
    prompt: str,                    # The image description
    output_path: str = None,        # Auto-generates if omitted
    model: str = "nano-banana-2",   # Default: fast. Use "image-pro" for quality
    temperature: float = 0.7,       # 0.5-0.7 for diagrams, 0.7-0.8 for illustrations
) -> dict | None
# Returns: {"path": "/mnt/user-data/outputs/gemini_image_*.png", "caption": str|None}
# Returns None on failure
模型选择
别名模型最适合每张图像的成本
"nano-banana-2" 或 "image"gemini-3.1-flash-image-preview快速迭代、草稿$0.067
"image-pro" 或 "nano-banana-pro"gemini-3-pro-image-preview已发布内容、文字渲染$0.134
完整的博客页眉示例
import sys
sys.path.append('/mnt/skills/user/invoking-gemini/scripts')
from gemini_client import generate_image

# 1. Compose prompt with style prefix + subject
style_prefix = (
    "Style: Risograph-inspired editorial illustration. "
    "Visible halftone dot texture and slight color misregistration between layers. "
    "Limited ink palette: deep indigo, warm coral, and sage green on off-white paper. "
    "Layered transparency where colors overlap creates rich secondary tones. "
    "Modern and professional — the aesthetic of an indie design studio, not a fantasy novel. "
    "Generous whitespace. No photorealism, no glow effects, no cyberpunk. No text or labels."
)
subject = "A raven perched on a stack of books, observing a network graph"
prompt = f"{style_prefix}\n\nSubject: {subject}. Wide landscape format, suitable as a blog header."

# 2. Generate (use image-pro for published content)
result = generate_image(prompt, model="image-pro", temperature=0.75)

if result:
    print(f"Saved: {result['path']}")
    # 3. Present to user
    # present_files([result["path"]])
提示词模式
  • 风格前缀 + 主体:先添加风格描述,再描述主体
  • 明确指定风格:使用“受孔版印刷启发的编辑插画”,而不是“一张好看的图片”
  • 包含构图要求:使用“宽幅横向格式”/“居中、高对比度”
  • 文字渲染:使用“海报上用粗体红字写着‘SALE’”(搭配 image-pro 效果良好)
  • 负向约束:使用“不要照片级写实效果,不要发光效果”以避免默认效果
自定义输出路径
result = generate_image(
    "A logo for a coffee shop called 'Bean There'",
    output_path="/mnt/user-data/outputs/coffee_logo.png"
)

语音生成(TTS)

Gemini 3.8 Flash TTS 和 Flash-Lite TTS 于 2026-09-23 正式发布。输出格式为 WAV, 24 kHz 单声道 16 位,并带有 SynthID 水印。

from gemini_client import generate_speech, design_voice, list_voices

r = generate_speech("Odin kept two ravens. <short pause> Huginn was thought.",
                    output_path="/tmp/line.wav", voice="Algenib",
                    style="quiet and dry, unhurried")
# {'path': '/tmp/line.wav', 'seconds': 4.2, 'audio_tokens': 135} or None

v = design_voice("A low, dry, quietly amused male voice with a faint rasp. "
                 "Soft southern British accent.", "narrator", gender="male",
                 language_code="en-GB")      # {'id': 'voice_...', 'sample_path': ...}
generate_speech("...", voice=v["id"])

lows = list_voices(gender="male", pitch="low")   # library of 2,089 prebuilt voices
  • **语音:**30 种录音室语音(Charon、Kore、Algenib“沙哑”, Enceladus“气声”,……),以及 2,059 种带有类似 en-gb-storyteller-4 ID 的 Persona 语音。list_voices() 会返回每种语音的口音、音高、性别和 描述;accent 筛选器需要完全匹配的字符串(“Winchester English”),因此应根据返回字段筛选口音。
  • **风格:**传入 style=(一种 speech_metadata 注释)。不要在 文本前加上“Style: ...”——3.8 模型会把此前缀读出来,而且 systemInstruction 会被拒绝。行内事件写在文本中:<laugh>、 <sigh>、<breath>、<short pause>;大写字母表示重读。
  • 设计的语音会被存储(有效期为 1 年,每个项目最多 200 个)。描述也会设定基础表达方式:“thoughtful pauses”这样的描述会产生 1–1.8 秒的行中停顿,无法通过任何逐行风格设置消除。
  • **模型可能会改动文字。**在一段 29 行的旁白中,出现过“Hmm, I get things wrong”,以及用“tell them”替换“tell him”的情况。任何带字幕或固定脚本的内容都需要进行 ASR 检查(faster-whisper medium.en)并重录。
  • **成本:**每秒语音约需 32 个音频 token;截至 2026-12-31,3.8 Flash TTS 的价格为 $9/M(Lite 为 $6/M),因此每分钟约 $0.02。
  • 不支持语音复刻(通过 30 秒样本和录制的同意片段进行克隆),且在 EEA、UK、Switzerland、India、Illinois 和 Texas 不可用。

基本文本用法

import sys
sys.path.append('/mnt/skills/user/invoking-gemini/scripts')
from gemini_client import invoke_gemini

response = invoke_gemini(
    prompt="Explain quantum computing in 3 bullet points",
    model="flash",  # gemini-3.8-flash (default)
)
print(response)

结构化输出

使用 Pydantic 模型确保符合 JSON Schema:

from gemini_client import invoke_with_structured_output
from pydantic import BaseModel, Field

class BookAnalysis(BaseModel):
    title: str
    genre: str = Field(description="Primary genre")
    key_themes: list[str] = Field(max_length=5)
    rating: int = Field(ge=1, le=5)

result = invoke_with_structured_output(
    prompt="Analyze the book '1984' by George Orwell",
    pydantic_model=BookAnalysis
)
print(result.title)  # "1984"

支持嵌套模型。 Gemini 的 responseSchema 会拒绝 $ref/$defs,而 pydantic 会为每个嵌套模型生成这些字段,因此客户端会在发送前将其内联:

class Finding(BaseModel):
    claim: str
    confidence: Literal["high", "medium", "low"]
    note: str | None = None

class Analysis(BaseModel):
    findings: list[Finding]     # nested — inlined for you
    gaps: list[str]

为输出预留充足预算。 思考令牌会计入 max_output_tokens(默认值为 32768)。预算太低会导致 JSON 在对象中途被截断,进而引发 pydantic 解析错误,而不是长度错误——客户端现在会检测 finishReason=MAX_TOKENS,并明确说明原因。

并行调用

from gemini_client import invoke_parallel

results = invoke_parallel(
    prompts=["Summarize Hamlet", "Summarize Macbeth", "Summarize Othello"],
    model="lite",  # gemini-3.5-flash-lite — cheap/fast tier for batch
)

可用模型

当前最前沿的 Flash 是 gemini-3.8-flash(GA 2026-09-02),也是默认模型和 flash 别名。Google 在六周内发布了三个 Flash 世代:3.6(2026-07-21)、3.7(2026-08-13)和 3.8(2026-09-02)。每个版本都可以通过固定别名调用(flash-3.7、flash-3.6、flash-3.5、flash-3),且都没有停用日期。早期文档中的 gemini-3.1-flash-lite-preview 已不可用(于 2026-05-25 停用)。

Pro 档位不在路由范围内。按当前价格,gemini-3.1-pro-preview 的输入成本是 3.8 Flash 的 2.7 倍,输出成本是 3.2 倍;在此处重要的编码和 Agent 基准测试中,其表现也不如 3.5+ Flash 系列。请勿将其作为目标模型;pro 别名现在会解析为 gemini-3.8-flash,而“最高推理能力”指的是在 Flash 上设置 thinking_level='high'。

文本 / 推理模型
模型别名输入/1M输出/1M上下文备注
gemini-3.8-flashflash$0.75 → $1.50$3.75 → $7.50输入 1M / 输出 64K默认。 2026-09-02 GA。当前最前沿的 Flash。与 3.7 相比:Terminal-Bench 2.1 为 90.8% vs 81.6%,SWE-Bench Pro 为 61.6% vs 60.4%,SWE-Atlas 为 51.9% vs 48.0%,HLE 持平(45.4% vs 45.7%)。Google 表示它在更高 effort 下会“更加努力地工作”,因此预计每项任务会使用更多思考 token。thinking_level 仅支持 low/medium/high——minimal 会返回 HTTP 400,客户端会将其降级为 low。默认的 medium 在回复一个词时用了 79 个思考 token(2026-09-03 实测);对于非推理任务,请传入 low。
gemini-3.7-flashflash-3.7$0.75 → $1.50$3.75 → $7.501M / 64K2026-08-13 GA。DeepSWE v1.1 为 65.3%,而 3.6 为 49.0%;Terminal-Bench 2.1 为 85.8%。与 3.8 有相同的 minimal 限制。Google 仍将其“完全支持用于效率优先的工作负载”。
gemini-3.6-flashflash-3.6$0.75 → $1.50$3.75 → $7.501M / 64K2026-07-21 GA。输出 token 比 3.5 Flash 少约 17%。最后一个接受 thinking_level='minimal' 的 Flash(2026-09-03 已验证)。
gemini-3.5-flashflash-3.5$1.50$9.001M2026-05-19 GA。Google 的模型列表现在将其标记为“legacy”。接受 minimal。输出成本高于 3.6–3.8。
gemini-3-flash-previewflash-3$0.30$2.501M较早的 Flash 预览版,为保持向后兼容而保留。Google 列出的迁移目标为 gemini-3.6-flash;尚无停用日期。
gemini-3.1-pro-preview—$2.00(≤200K)/ $4.00$12.00 / $18.001M已于 2026-09-03 停止路由。 性价比不如 3.6+ Flash;在大多数编码 / Agent 任务基准测试中,3.5 Flash 已经胜过它。为固定版本的代码保留可调用的 ID。pro 现在解析为 gemini-3.8-flash。3.5 Pro 于 2026-05-19 的 I/O 大会上宣布将在 6 月推出,截至 2026-09-03 仍未出现在 API 中;在任何别名指向它之前,也要对其进行相同的价格 / 质量测试。
gemini-3.5-flash-litelite$0.30$2.501M低价 / 批量档。 2026-07-21 GA。速度最快的 3.5 级模型(每秒输出 350 个 token);在 SWE-Bench Pro 和 OSWorld-Verified 上胜过 gemini-3-flash。
gemini-2.5-flashstable-flash$0.30$2.501M已弃用——2025 年代的版本,不要路由到此处。
gemini-2.5-flash-lite—$0.10$0.401M已弃用——价格更低,但属于 2025 年代的版本。lite 现在解析为 gemini-3.5-flash-lite。
gemini-2.5-prostable-pro$1.25(≤200K)/ $2.50$10.00 / $20.001M已弃用——2025 年代的版本,不要路由到此处。

$0.75 → $1.50 表示入门定价:Google 的定价页面(2026-09-03 获取)显示,3.6、3.7 和 3.8 Flash 的输入 / 输出价格在 2026-12-31 前为 $0.75 / $3.75,自 2027-01-01 起为 $1.50 / $7.50。上下文缓存价格为 $0.075 → $0.15; Batch 的价格是标准价格的一半。输出价格包含思考 token。

图像模型
模型别名输入/1M每张图像
gemini-3.1-flash-image-previewimage、nano-banana-2$0.25$0.067
gemini-3-pro-image-previewimage-pro、nano-banana-pro$2.00$0.134
语音模型
模型别名输入/1M输出/1M(音频)备注
gemini-3.8-flash-ttstts$0.50 → $1.00$9.00 → $18.002026-09-23 GA。富有表现力,支持 130 种语言和 2 位说话者。使用 generate_speech(),不要使用 invoke_gemini()。
gemini-3.8-flash-lite-ttstts-lite$0.50 → $1.00$6.00 → $12.002026-09-23 GA。适用于批量处理 / 朗读,支持 101 种语言。取代 gemini-3.1-flash-tts-preview($1 / $20)。

语音别名位于 SPEECH_ALIASES 中,而非 MODEL_ALIASES 中,因此文本调用永远不会解析到音频模型。

详情请参阅 references/models.md。

思考预算(Gemini 3.x)

Gemini 3.x 模型会在回复前进行推理。该参数于 2026 年更改:整数型 thinking_budget 已移除;请改用字符串型 thinking_level ∈ {minimal、low、medium、high}。3.5–3.8 Flash 的默认值为 medium。对于转录、分类和提取任务,请传入 thinking_level='minimal',否则模型会悄悄将输出 token 用于推理(表现为:响应为空,且 finishReason=MAX_TOKENS)。

3.7 和 3.8 Flash 不接受 minimal,会返回 HTTP 400(Thinking level MINIMAL is not supported for this model);low 是它们支持的最低级别。客户端会在这两个模型上将 minimal 降级为 low,并向 stderr 打印提示,因此现有调用方仍可正常工作。在 3.8 上的测量结果(2026-09-03):单词回复使用 low 时消耗了 0 个思考 token,默认的 medium 则消耗了 79 个。在 3.7 上,low 仍消耗了 45–88 个;使用 low 调用 max_output_tokens=50 时触发了 MAX_TOKENS 并返回 None,因此请为该模型设置充足的输出预算。如果任务需要完全不进行思考的处理,请固定使用 flash-3.6 或 lite,它们仍接受 minimal。

response = invoke_gemini(
    prompt="Transcribe this image.",
    model="flash",
    image_path="/tmp/screenshot.png",
    max_output_tokens=4000,
    thinking_level="minimal",  # don't burn output budget on reasoning
)

错误处理

response = invoke_gemini(prompt="...", model="flash")
if response is None:
    print("API call failed — check credentials")

result = generate_image("...")
if result is None:
    print("Image generation failed — check credentials or try again")

常见问题:缺少 API 密钥 → 请参阅设置。速率限制 → 自动重试并采用退避策略。网络错误 → 返回 None。

高级功能

自定义生成配置
response = invoke_gemini(
    prompt="Write a haiku",
    model="flash",                  # gemini-3.8-flash
    temperature=0.9,
    max_output_tokens=200,
    top_p=0.95,
    thinking_level="low",           # haiku is short; modest reasoning is fine
)
多模态输入
from pydantic import BaseModel
from gemini_client import invoke_with_structured_output

class ImageDescription(BaseModel):
    objects: list[str]
    scene: str
    colors: list[str]

result = invoke_with_structured_output(
    prompt="Describe this image",
    pydantic_model=ImageDescription,
    image_path="/mnt/user-data/uploads/photo.jpg"
)

更多模式请参阅 references/advanced.md。

故障排除

“未配置凭据”: 创建 /mnt/project/proxy.env 并填入 CF 凭据,或添加 GOOGLE_API_KEY.txt。

CF Gateway 401/403: 确认 CF_API_TOKEN 具有 AI Gateway 权限。如果未使用 BYOK,请将 GOOGLE_API_KEY 添加到 proxy.env。

导入错误: uv pip install requests pydantic

图像生成返回 None: 检查凭据。如果问题仍然存在,请尝试 model="nano-banana-2"(比 image-pro 更可靠)。检查错误输出中是否存在内容政策拦截。

评论

支持 Markdown