gemini.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. raise ValueError("未找到GEMINI_API_KEY环境变量")
  21. # 配置Gemini
  22. genai.configure(api_key=self.api_key)
  23. self.model = genai.GenerativeModel('gemini-2.5-flash')
  24. def process(self, content: Any, system_prompt: str) -> Dict[str, Any]:
  25. try:
  26. # 构建完整的提示词
  27. full_prompt = f"{system_prompt}\n\n内容:{json.dumps(content, ensure_ascii=False)}"
  28. # 调用 Gemini API
  29. response = self.model.generate_content(
  30. contents=content,
  31. config=types.GenerateContentConfig(
  32. system_instruction=system_prompt
  33. )
  34. )
  35. # 尝试解析 JSON 响应
  36. try:
  37. result = json.loads(response.text)
  38. return result
  39. except json.JSONDecodeError:
  40. # 如果不是 JSON 格式,返回原始文本
  41. return {"result": response.text, "raw_response": response.text}
  42. except Exception as e:
  43. return {"error": str(e), "content": content}
  44. def batch_process(self, contents: list, system_prompt: str) -> list:
  45. results = []
  46. for content in contents:
  47. result = self.process(content, system_prompt)
  48. results.append(result)
  49. return results