coze_client.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # coze_client.py
  2. import requests
  3. import json
  4. import logging
  5. class CozeClient:
  6. """
  7. 封装Coze API的聊天完成操作。
  8. """
  9. def __init__(self, api_key: str):
  10. self.api_key = api_key
  11. self.api_url = "https://api.coze.com/v1/chat/completions" # Coze API 聊天完成端点
  12. def send_message(self, bot_id: str, prompt_template: str, input_data: str) -> str | None:
  13. """
  14. 向Coze机器人发送消息并获取回复。
  15. Args:
  16. bot_id (str): Coze 机器人的 Bot ID。
  17. prompt_template (str): Coze API的提示模板字符串,需要包含 '{input_data}' 占位符。
  18. input_data (str): 实际要填充到模板中的输入数据。
  19. Returns:
  20. str | None: Coze的回复内容,如果失败则返回 None。
  21. Raises:
  22. Exception: 如果Coze API调用失败或返回非预期格式。
  23. """
  24. headers = {
  25. "Authorization": f"Bearer {self.api_key}",
  26. "Content-Type": "application/json",
  27. "Accept": "application/json"
  28. }
  29. # 填充提示模板
  30. user_message_content = prompt_template.format(input_data=input_data)
  31. payload = {
  32. "model": bot_id, # 在Coze API中,bot_id 通常作为 model 参数传入
  33. "messages": [
  34. {"role": "user", "content": user_message_content}
  35. ],
  36. "stream": False # 非流式响应
  37. }
  38. try:
  39. logging.info(f"正在调用 Coze Bot '{bot_id}' (输入内容前50字: '{user_message_content[:50]}...')")
  40. response = requests.post(self.api_url, headers=headers, json=payload, timeout=60)
  41. response.raise_for_status() # 检查HTTP响应状态码
  42. result = response.json()
  43. # 检查Coze响应结构,提取内容
  44. if result.get("choices") and result["choices"][0].get("message") and result["choices"][0]["message"].get("content"):
  45. coze_output_content = result["choices"][0]["message"]["content"]
  46. logging.info(f"Coze API 调用成功,返回内容长度: {len(coze_output_content)}")
  47. return coze_output_content
  48. else:
  49. logging.warning(f"Coze API 未返回有效内容。原始响应: {json.dumps(result, ensure_ascii=False, indent=2)}")
  50. raise Exception(f"Coze API returned no valid content: {result}")
  51. except requests.exceptions.RequestException as e:
  52. logging.error(f"请求Coze API发生网络错误: {e}")
  53. raise Exception(f"Coze API Request Failed: {e}")
  54. except (IndexError, KeyError) as e:
  55. logging.error(f"Coze API 响应格式错误: {e}. 原始响应: {json.dumps(result, ensure_ascii=False, indent=2) if 'result' in locals() else 'N/A'}")
  56. raise Exception(f"Coze API Response Format Error: {e}")
  57. except Exception as e:
  58. logging.error(f"处理Coze API响应失败: {e}")
  59. raise Exception(f"Coze API Response Handling Failed: {e}")
  60. # 可以在这里添加一些简单的测试代码,但通常在main.py中进行集成测试
  61. if __name__ == '__main__':
  62. # 仅作示例,请勿在生产环境直接硬编码敏感信息
  63. # 配置日志,用于独立测试
  64. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  65. print("--- Coze客户端独立测试 (请确保替换YOUR_...) ---")
  66. TEST_COZE_API_KEY = "YOUR_COZE_API_KEY"
  67. TEST_COZE_BOT_ID = "YOUR_COZE_BOT_ID"
  68. TEST_PROMPT_TEMPLATE = "请用一句话总结以下内容: {input_data}"
  69. TEST_INPUT_TEXT = "Python是一种高级编程语言,由Guido van Rossum创建,并于1991年首次发布。它以其清晰的语法和广泛的库而闻名,适用于Web开发、数据分析、人工智能等多个领域。"
  70. if "YOUR_" in TEST_COZE_API_KEY:
  71. logging.warning("请替换 coze_client.py 中的 YOUR_ 占位符为您的实际Coze API信息以运行测试。")
  72. else:
  73. try:
  74. coze_client = CozeClient(TEST_COZE_API_KEY)
  75. coze_output = coze_client.send_message(
  76. TEST_COZE_BOT_ID,
  77. TEST_PROMPT_TEMPLATE,
  78. TEST_INPUT_TEXT
  79. )
  80. if coze_output:
  81. print(f"\nCoze API 成功响应:\n{coze_output}")
  82. else:
  83. print("\nCoze API 未返回有效内容。")
  84. except Exception as e:
  85. logging.error(f"Coze客户端独立测试失败: {e}")
  86. print("--- Coze客户端独立测试结束 ---")