gemini.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import os
  2. from google import genai
  3. from google.genai import types
  4. import config
  5. class GeminiProcessor:
  6. def __init__(self, api_key: str = None):
  7. """
  8. 初始化Gemini客户端
  9. :param api_key: Gemini API密钥,如果为None则使用config中的密钥
  10. """
  11. self.api_key = api_key if api_key else config.GEMINI_API_KEY
  12. self.client = genai.Client(api_key=self.api_key)
  13. def process(self, content: str, system_prompt: str, model_name: str = "gemini-2.5-flash"):
  14. """
  15. 处理文本内容
  16. :param content: 要处理的文本内容
  17. :param system_prompt: 系统提示语
  18. :param model_name: 使用的模型名称,默认为gemini-2.5-flash
  19. :return: 处理后的文本结果
  20. """
  21. input_text = ({content})
  22. try:
  23. # 调用Gemini模型处理内容
  24. response = self.client.models.generate_content(
  25. model=model_name,
  26. config=types.GenerateContentConfig(
  27. system_instruction=system_prompt
  28. ),
  29. contents=input_text
  30. )
  31. return response.text
  32. except Exception as e:
  33. print(f"处理内容时出错: {e}")
  34. return None
  35. # 使用示例
  36. if __name__ == "__main__":
  37. processor = GeminiProcessor()
  38. result = processor.process(
  39. content="你好,请介绍一下你自己",
  40. system_prompt="你是一个有帮助的AI助手"
  41. )
  42. if result:
  43. print(result)
  44. print("\n处理完成")