TL;DR: 本文档旨在为SRE团队提供Gemini API在自动化脚本中集成的详细指南。涵盖API密钥获取、Python SDK配置、文本生成与摘要、数据结构化等核心应用场景,旨在提升故障诊断与报告自动化水平。所有操作均基于Python 3.9+及google-generativeai库。
1. 前提条件与环境准备
在开始Gemini API的集成之前,请确保满足以下条件:
- Google Cloud Platform (GCP) 账户: 拥有有效的GCP账户并已启用相关计费。
- Gemini API访问权限: 确保您的GCP项目已开通Gemini API。关于Gemini怎么注册及启用,请参考官方文档。
- Python环境: Python 3.9或更高版本。
- 安装Python SDK:
pip install -q -U google-generativeai
预期输出:
Collecting google-generativeai
Downloading google_generativeai-0.6.0-py3-none-any.whl (272 kB)
...
Successfully installed google-generativeai-0.6.0 protobuf-4.25.3
Note: 推荐在虚拟环境中进行安装,以避免依赖冲突。
2. Gemini API密钥配置与初始化
访问Gemini API需要API密钥。本节将指导如何获取密钥并进行SDK初始化。
- 获取API密钥:
- 访问 Google AI Studio。
- 点击“Create API key in new project”或选择现有项目创建密钥。
- 复制生成的API密钥。
- 配置环境变量: 为安全起见,不应将API密钥硬编码到代码中。
export GOOGLE_API_KEY="YOUR_API_KEY"
Warning: 生产环境中,请使用Google Cloud Secret Manager或其他安全机制管理API密钥。
- SDK初始化:
import os
import google.generativeai as genai
API_KEY = os.getenv("GOOGLE_API_KEY")
if not API_KEY:
raise ValueError("GOOGLE_API_KEY environment variable not set.")
genai.configure(api_key=API_KEY)
print(f"Gemini SDK initialized successfully with API Key: {API_KEY[:5]}...")
预期输出:
Gemini SDK initialized successfully with API Key: AIzaS...
3. 自动化脚本中的Gemini API应用案例
本节将展示Google AI怎么用于SRE日常任务,例如日志摘要与故障报告生成。
- 日志分析与摘要:
假设我们有一个长日志文件,需要快速提取关键信息。
model = genai.GenerativeModel('gemini-pro')
log_content = """
[2024-06-24 10:01:05] INFO: Application started successfully.
[2024-06-24 10:01:10] WARNING: Database connection pool exhausted. Retrying...
[2024-06-24 10:01:15] ERROR: Service 'UserService' unresponsive. Timeout after 5s.
[2024-06-24 10:01:20] INFO: Health check passed for 'AuthService'.
[2024-06-24 10:01:25] ERROR: Disk usage on /var/log/ is at 95%. Critical.
"""
prompt = f"Summarize the following system log, highlighting any errors or warnings and suggesting immediate actions:\n\n{log_content}"
response = model.generate_content(prompt)
print("\n--- Log Summary ---")
print(response.text)
预期输出示例:
--- Log Summary ---
The application started successfully but immediately encountered a database connection pool exhaustion warning. The 'UserService' became unresponsive, timing out after 5 seconds. Additionally, disk usage on /var/log/ reached a critical level of 95%. Immediate actions should include investigating the database connection pool, checking the 'UserService' status, and addressing the high disk usage on /var/log/.
- 故障报告草稿生成:
基于结构化数据自动生成故障报告草稿,提升效率。
incident_data = {
"incident_id": "INC-20240625-001",
"service_affected": "PaymentGateway",
"severity": "Critical",
"start_time": "2024-06-25 14:30 UTC",
"end_time": "2024-06-25 15:15 UTC",
"root_cause_hypothesis": "High traffic overwhelmed database connections.",
"mitigation_steps": ["Increased DB connection pool size", "Scaled up PaymentGateway instances"]
}
prompt = f"Generate a concise incident report draft based on the following data:\n\nIncident ID: {incident_data['incident_id']}\nService Affected: {incident_data['service_affected']}\nSeverity: {incident_data['severity']}\nStart Time: {incident_data['start_time']}\nEnd Time: {incident_data['end_time']}\nRoot Cause Hypothesis: {incident_data['root_cause_hypothesis']}\nMitigation Steps: {', '.join(incident_data['mitigation_steps'])}"
response = model.generate_content(prompt)
print("\n--- Incident Report Draft ---")
print(response.text)
预期输出示例:
--- Incident Report Draft ---
Incident Report: INC-20240625-001
Service Affected: PaymentGateway
Severity: Critical
Duration: 2024-06-25 14:30 UTC - 2024-06-25 15:15 UTC
Summary:
A critical incident affecting the PaymentGateway service occurred between 14:30 and 15:15 UTC on June 25, 2024.
Root Cause Hypothesis:
The primary hypothesis for the incident is that high traffic volume led to an overwhelming of database connections.
Mitigation Steps:
Immediate mitigation involved increasing the database connection pool size and scaling up the PaymentGateway instances.
以上案例展示了Gemini API在SRE自动化中的基础应用。通过定制Prompt和结合其他工具,可以实现更复杂的自动化流程。