360 Secure SkillHub
360 安全技能中心

agentscope-gemini-usage-fix

该 Skill 说明 AgentScope 中 GeminiChatModel 的 cached_content_token_count 为 None 导致 ChatUsage 校验失败的问题,并提供运行时 monkey patch,将 cache_input_tokens 为 None 时设为 0,同时给出上游一行修复思路。

trend0522
trend0522
热度 7.65
最近更新 2026-10-03 09:56:38
分类:开发依赖:代码执行 / 第三方 API应用场景:调试排错 / API 集成

安装技能

复制下面的话术发给你的 Agent,它会通过 secure-skills 检索并安装该技能。

执行命令安装此 skill: npx secure-skills-cli add agentscope-gemini-usage-fix
Metadata
name
agentscope-gemini-usage-fix
description
Work around a Gemini usage normalization bug in AgentScope where cached_content_token_count=None causes Usage validation to fail. Use this whenever the user uses GeminiChatModel and sees ValidationError on cache_input_tokens.
version
0.1.0
metadata
{"openclaw":{"requires":{"env":["GOOGLE_API_KEY"],"bins":["python3"]},"primaryEnv":"GOOGLE_API_KEY","envVars":[{"name":"GOOGLE_API_KEY","required":true,"description":"Google Generative AI API key."}],"emoji":"🐞","homepage":"https://github.com/agentscope-ai/agentscope"}}

AgentScope Gemini Usage Fix

This skill documents a known bug and a runtime workaround for GeminiChatModel usage extraction.

Bug

GeminiChatModel._extract_usage uses getattr(..., "cached_content_token_count", 0), which returns None when the attribute exists but is None. ChatUsage validates cache_input_tokens as int, so None raises a pydantic ValidationError.

Workaround

Apply this patch before using Gemini models:

from agentscope.model._gemini._model import GeminiChatModel

_original = GeminiChatModel._extract_usage

def _patched_extract_usage(self, usage_metadata, start_datetime):
    if not usage_metadata:
        return None
    usage = _original(self, usage_metadata, start_datetime)
    if usage and getattr(usage, "cache_input_tokens", None) is None:
        usage.cache_input_tokens = 0
    return usage

GeminiChatModel._extract_usage = _patched_extract_usage

Upstream Fix

The upstream fix is a one-line change:

cache_input_tokens=getattr(
    usage_metadata,
    "cached_content_token_count",
    0,
) or 0,

Reference: https://github.com/agentscope-ai/agentscope/issues/3077