gemini.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. """
  26. 处理内容结构化
  27. Args:
  28. content: 要处理的内容
  29. system_prompt: 系统提示词
  30. Returns:
  31. 处理结果
  32. """
  33. try:
  34. # 构建完整的提示词
  35. full_prompt = f"{system_prompt}\n\n内容:{json.dumps(content, ensure_ascii=False)}"
  36. # 调用 Gemini API
  37. response = self.model.generate_content(full_prompt)
  38. # 尝试解析 JSON 响应
  39. try:
  40. result = json.loads(response.text)
  41. return result
  42. except json.JSONDecodeError:
  43. # 如果不是 JSON 格式,返回原始文本
  44. return {"result": response.text, "raw_response": response.text}
  45. except Exception as e:
  46. return {"error": str(e), "content": content}