mongo.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from pymongo import MongoClient
  2. from datetime import datetime
  3. MONGO_URI = (
  4. "mongodb://dds-2zedd8d70bde6e541.mongodb.rds.aliyuncs.com:3717,"
  5. "dds-2zedd8d70bde6e542.mongodb.rds.aliyuncs.com:3717"
  6. )
  7. client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=5000)
  8. db = client["arklogs"]
  9. chat_logs = db["chat_logs"]
  10. # 带下划线的表示私有方法(Private)
  11. def _ensure_index():
  12. try:
  13. chat_logs.create_index([("username", 1), ("asked_at", -1)])
  14. except Exception:
  15. pass
  16. def save_chat_log(
  17. username: str,
  18. question: str,
  19. stream_mode: bool,
  20. raw_response: str = None,
  21. status: str = "success",
  22. error: str = None,
  23. ):
  24. """
  25. 保存聊天原始响应日志到 MongoDB
  26. Args:
  27. username: 提问人
  28. question: 提问的问题
  29. stream_mode: 回答方式(流式或非流式)
  30. raw_response: API 原始响应的 repr 字符串
  31. status: 响应状态 success | error
  32. error: 异常时的错误信息
  33. """
  34. try:
  35. _ensure_index()
  36. chat_logs.insert_one({
  37. "username": username,
  38. "question": question,
  39. "stream_mode": stream_mode,
  40. "raw_response": raw_response,
  41. "status": status,
  42. "error": error,
  43. "asked_at": datetime.now(),
  44. })
  45. except Exception as e:
  46. print(f"MongoDB 日志写入失败: {e}")