成本估算与健康监控:Google Colab 教程

本教程面向有编程基础的开发者,深入讲解如何为 Gemini API 应用构建可观测性层。通过实现 GeminiObservability 类,开发者可以提取令牌使用元数据、计算实时美元成本,并执行健康检查。教程涵盖环境配置、核心原理、架构设计、代码分析、实践步骤、常见错误排查及生产优化,帮助开发者有效监控成本与 API 健康状况,实现成本优化与系统稳定性。

技术背景

随着 AI 应用规模化,API 调用成本成为关键考量。Gemini API 按令牌计费,不同模型定价差异大,且存在配额限制。缺乏可观测性会导致成本失控、性能瓶颈难以定位。本教程旨在提供一套轻量级、可复用的监控方案,使开发者能够实时追踪成本、验证 API 可用性,从而优化资源分配、预防配额超限,并支持成本预算管理。

核心原理

核心原理基于 Gemini API 响应中的 usage_metadata 字段,该字段包含 prompt_token_count(输入令牌数)、candidates_token_count(输出令牌数)和 total_token_count(总令牌数)。通过将令牌数除以 1,000,000 并乘以每百万令牌的单价(输入和输出价格不同),即可估算单次调用的美元成本。健康检查通过发送最小请求(如 'ping')并设置 max_output_tokens=1 来验证 API 可用性,捕获 APIError 以识别配额问题。

架构分析

系统由 GeminiObservability 类构成,包含三个核心方法:estimate_cost 负责成本计算,check_health 负责健康检查,get_usage_summary 整合信息。类内部维护一个价格字典,映射模型名称到输入/输出单价。设计上,该类与客户端解耦,便于集成到任何应用。数据流为:API 调用 -> 响应中的 usage_metadata -> 传入 estimate_cost 或 get_usage_summary -> 输出成本或摘要。关键设计决策包括:价格字典可配置,便于更新;健康检查使用最小化请求以降低开销;错误处理区分 APIError 和通用异常。

完整实战教程

##### 版权所有 2025 Google LLC.

#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

使用 Gemini 进行成本估算与健康监控

<a target="_blank" href="https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/Cost_Estimation_And_Health_Monitoring.ipynb">

</a>

概述

成本可观测性是扩展 Gemini API 应用的关键。如果不跟踪令牌使用量和成本,就无法优化支出或识别高成本操作。

本笔记本演示了如何为 Gemini API 应用构建可观测性层。您将学习如何:

  1. 从 API 响应中提取令牌使用元数据
  2. 根据模型定价计算实时美元成本
  3. 执行健康检查以验证 API 可用性和配额

学完本笔记本后,您将拥有一个可复用的类,可以将其集成到任何 Gemini API 应用中,以监控成本和健康状况。

环境设置

首先,安装 Gemini API Python 库。

%pip install -U -q "google-genai>=1.0.0"

获取 API 密钥

在使用 Gemini API 之前,您必须先获取一个 API 密钥。如果您还没有,可以在 Google AI Studio 中一键创建密钥。

<a class="button button-primary" href="https://aistudio.google.com/app/apikey" target="_blank" rel="noopener noreferrer">获取 API 密钥</a>

在 Colab 中,将密钥添加到左侧面板的“🔑”下的密钥管理器中,并将其命名为 GEMINI_API_KEY。

from google import genai
from google.genai import types, errors
from typing import Dict
import os

try:
    from google.colab import userdata
    api_key = userdata.get('GEMINI_API_KEY')
except ImportError:
    api_key = os.environ.get('GEMINI_API_KEY')

client = genai.Client(api_key=api_key)
print("✅ API key configured successfully!")

成本估算器类

GeminiObservability 类提供了一种简单的方法来跟踪成本并监控 Gemini API 使用状况。它会自动处理不同模型的不同定价。

# @title
class GeminiObservability:
    """A class to monitor costs and health of Gemini API usage."""

    def __init__(self, client):
        """
        Initialize the observability class.

        Args:
            client: The genai.Client instance
        """
        self.client = client
        # Prices per 1 million tokens (Example 2026 rates)
        # Update these prices based on current pricing at https://ai.google.dev/pricing
        self.prices = {
            "gemini-3.6-flash": {"input": 1.50, "output": 7.50},
            "gemini-3.5-flash-lite": {"input": 0.30, "output": 2.50},
            "gemini-3.1-pro-preview": {"input": 2.00, "output": 12.00},
            "gemini-2.5-flash": {"input": 0.075, "output": 0.30},
            "gemini-2.5-pro": {"input": 3.50, "output": 10.50},
        }

    def estimate_cost(self, usage_metadata: types.UsageMetadata, model_name: str) -> float:
        """
        Calculate the cost in USD based on token usage.

        Args:
            usage_metadata: The usage_metadata object from a Gemini API response
            model_name: The name of the model used (e.g., "gemini-3.6-flash")

        Returns:
            The estimated cost in USD
        """
        if model_name not in self.prices:
            print(f"Warning: No pricing data for model {model_name}. Returning 0.0")
            return 0.0

        # Calculate input cost (prompt tokens)
        input_cost = (
            usage_metadata.prompt_token_count / 1_000_000
        ) * self.prices[model_name]["input"]

        # Calculate output cost (response tokens)
        output_cost = (
            usage_metadata.candidates_token_count / 1_000_000
        ) * self.prices[model_name]["output"]

        return input_cost + output_cost

    def check_health(self, model_name: str = "gemini-3.6-flash") -> bool:
        """
        Perform a simple health check by making a minimal API call.

        Args:
            model_name: The model to test (default: "gemini-3.6-flash")

        Returns:
            True if the API is healthy, False otherwise
        """
        try:
            response = self.client.models.generate_content(
                model=model_name,
                contents="ping",
                config=types.GenerateContentConfig(max_output_tokens=1)
            )
            return True
        except errors.APIError as e:
            print(f"Health Check Failed: Quota limit reached. {e}")
            return False
        except Exception as e:
            print(f"Health Check Failed: {e}")
            return False

    def get_usage_summary(self, usage_metadata: types.UsageMetadata, model_name: str) -> Dict:
        """
        Get a summary of token usage and cost.

        Args:
            usage_metadata: The usage_metadata object from a Gemini API response
            model_name: The name of the model used

        Returns:
            A dictionary with usage details and cost
        """
        cost = self.estimate_cost(usage_metadata, model_name)
        return {
            "model": model_name,
            "input_tokens": usage_metadata.prompt_token_count,
            "output_tokens": usage_metadata.candidates_token_count,
            "total_tokens": usage_metadata.total_token_count,
            "estimated_cost_usd": round(cost, 6)
        }

使用示例

现在你可以看到可观测性类的实际应用了。首先,创建该类的一个实例。

# Create an instance of the observability class
observability = GeminiObservability(client)
MODEL_ID = "gemini-3.7-flash"  # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite", "gemini-2.5-pro"] {"allow-input": true, "isTemplate": true}
# Check if the API is healthy
is_healthy = observability.check_health(MODEL_ID)
print(f"API Health Status: {'✅ Healthy' if is_healthy else '❌ Unhealthy'}")

成本估算示例

进行一次简单的 API 调用并跟踪成本。

# Make a simple API call
response = client.models.generate_content(
    model=MODEL_ID,
    contents="Explain quantum computing in one sentence."
)

# Get usage metadata from the response
usage_metadata = response.usage_metadata

# Calculate and display the cost
summary = observability.get_usage_summary(usage_metadata, MODEL_ID)
print("Usage Summary:")
for key, value in summary.items():
    print(f"  {key}: {value}")

跟踪多个请求

你可以跨多个 API 调用跟踪成本,以监控总支出。

# Example: Track costs across multiple requests
total_cost = 0.0
queries = [
    "What is machine learning?",
    "Explain neural networks briefly.",
    "What is the difference between AI and ML?"
]

print("Tracking costs for multiple queries:\n")
for i, query in enumerate(queries, 1):
    response = client.models.generate_content(
        model=MODEL_ID,
        contents=query
    )
    usage_metadata = response.usage_metadata
    cost = observability.estimate_cost(usage_metadata, MODEL_ID)
    total_cost += cost

    total_tokens = usage_metadata.total_token_count
    print(f"Query {i}: {query[:50]}...")
    print(f"  Tokens: {total_tokens} | Cost: ${cost:.6f}\n")

print(f"Total cost for all queries: ${total_cost:.6f}")

后续步骤

现在你已经拥有了一个可用的成本估算和健康监控系统,你可以:

  1. 集成到你的应用中:将 GeminiObservability 类添加到你的生产代码中,以实时跟踪成本。
  2. 设置警报:监控总成本,并在支出超过阈值时设置警报。
  3. 优化使用:使用令牌计数来识别昂贵的操作并优化你的提示。
  4. 更新定价:保持定价字典与 Google AI 定价 的最新费率同步。

有关 Gemini API 的更多信息,请查看 快速入门 和其他 示例。

常见问题

常见错误:1) 模型名称不在价格字典中,导致成本返回 0.0,应检查拼写或更新字典。2) API 密钥未正确配置,导致认证失败,需确保密钥已设置且环境变量或 Colab 密钥管理器正确。3) 配额超限,健康检查返回 False,需等待配额重置或申请提高配额。4) 令牌计数为 None,可能因响应异常,需检查 API 调用是否成功。排查方法:打印 usage_metadata 对象,确认字段存在;使用 try-except 捕获异常并输出详细信息;检查网络连接和 API 端点。

企业应用扩展

生产环境优化:1) 将价格字典外部化到配置文件或数据库,便于动态更新。2) 实现异步批量监控,减少开销。3) 集成日志系统(如 Cloud Logging)记录每次调用的成本和健康状态。4) 设置成本阈值警报,通过 Cloud Monitoring 或自定义 webhook 通知。5) 使用缓存减少重复调用,降低成本。6) 定期审查模型选择,根据成本效益调整模型。7) 扩展健康检查,增加延迟和错误率指标。

总结

本教程面向有编程基础的开发者,深入讲解如何为 Gemini API 应用构建可观测性层。通过实现 GeminiObservability 类,开发者可以提取令牌使用元数据、计算实时美元成本,并执行健康检查。教程涵盖环境配置、核心原理、架构设计、代码分析、实践步骤、常见错误排查及生产优化,帮助开发者有效监控成本与 API 健康状况,实现成本优化与系统稳定性。

内容来源与验证

继续系统学习

站内还有更多完整实战教程

加入会员,解锁全部教程、完整代码与持续更新内容。

加入会员
查看全部API 与工程实践教程