| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- from pymongo import MongoClient
- from datetime import datetime
- MONGO_URI = "mongodb://arkapi:arkapi@dds-2zedd8d70bde6e541.mongodb.rds.aliyuncs.com:3717,dds-2zedd8d70bde6e542.mongodb.rds.aliyuncs.com:3717/arklogs"
- client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=5000)
- db = client["arklogs"]
- chat_logs = db["chat_logs"]
- # 带下划线的表示私有方法(Private)
- def _ensure_index():
- try:
- chat_logs.create_index([("username", 1), ("asked_at", -1)])
- except Exception:
- pass
- def save_chat_log(
- username: str,
- question: str,
- stream_mode: bool,
- raw_response: str = None,
- status: str = "success",
- error: str = None,
- ):
- """
- 保存聊天原始响应日志到 MongoDB
- Args:
- username: 提问人
- question: 提问的问题
- stream_mode: 回答方式(流式或非流式)
- raw_response: API 原始响应的 repr 字符串
- status: 响应状态 success | error
- error: 异常时的错误信息
- """
- try:
- _ensure_index()
- chat_logs.insert_one({
- "username": username,
- "question": question,
- "stream_mode": stream_mode,
- "raw_response": raw_response,
- "status": status,
- "error": error,
- "asked_at": datetime.now(),
- })
- except Exception as e:
- print(f"MongoDB 日志写入失败: {e}")
|