mongo.py 1.4 KB

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