gemini.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 简单的 Gemini 处理器
  5. 用于满足导入需求,实际功能可以根据需要扩展
  6. """
  7. import os
  8. import json
  9. from typing import Any, Dict, Optional
  10. from dotenv import load_dotenv
  11. import google.generativeai as genai
  12. class GeminiProcessor:
  13. """Gemini API 处理器"""
  14. def __init__(self):
  15. # 加载环境变量
  16. load_dotenv()
  17. # 获取API密钥,支持多密钥配置
  18. self.api_key = os.getenv('GEMINI_API_KEY')
  19. if not self.api_key:
  20. # 如果没有基础密钥,尝试使用第一个多密钥
  21. self.api_key = os.getenv('GEMINI_API_KEY_1')
  22. if not self.api_key:
  23. raise ValueError("未找到GEMINI_API_KEY或GEMINI_API_KEY_1环境变量")
  24. # 延迟配置Gemini,在真正使用时再设置
  25. self._configured = False
  26. def _ensure_configured(self):
  27. """确保Gemini已配置"""
  28. if not self._configured:
  29. genai.configure(api_key=self.api_key)
  30. self._configured = True
  31. def process(self, content: Any, system_prompt: str) -> Dict[str, Any]:
  32. try:
  33. # 确保Gemini已配置
  34. self._ensure_configured()
  35. # 处理输入内容格式
  36. if isinstance(content, dict):
  37. # 将字典转换为JSON字符串
  38. formatted_content = json.dumps(content, ensure_ascii=False)
  39. else:
  40. formatted_content = content
  41. # 创建带有 system_instruction 的模型实例
  42. model_with_system = genai.GenerativeModel(
  43. 'gemini-2.5-flash',
  44. system_instruction=system_prompt
  45. )
  46. # 调用 Gemini API
  47. response = model_with_system.generate_content(
  48. contents=formatted_content
  49. )
  50. # 尝试解析 JSON 响应
  51. return response.text
  52. except Exception as e:
  53. print(f"Gemini API 调用失败: {e}")
  54. return {"error": str(e), "content": content}
  55. def batch_process(self, contents: list, system_prompt: str) -> list:
  56. results = []
  57. for content in contents:
  58. result = self.process(content, system_prompt)
  59. results.append(result)
  60. return results