MCPcopy Create free account
hub / github.com/dataease/SQLBot / get_chat_log_history

Function get_chat_log_history

backend/apps/chat/curd/chat.py:547–664  ·  view source on GitHub ↗

获取ChatRecord的详细历史记录 Args: session: 数据库会话 chat_record_id: ChatRecord的ID current_user: 当前用户 without_steps Returns: ChatLogHistory: 包含历史步骤和时间信息的对象

(session: SessionDep, chat_record_id: int, current_user: CurrentUser,
                         without_steps: bool = False)

Source from the content-addressed store, hash-verified

545
546
547def get_chat_log_history(session: SessionDep, chat_record_id: int, current_user: CurrentUser,
548 without_steps: bool = False) -> ChatLogHistory:
549 """
550 获取ChatRecord的详细历史记录
551
552 Args:
553 session: 数据库会话
554 chat_record_id: ChatRecord的ID
555 current_user: 当前用户
556 without_steps
557
558 Returns:
559 ChatLogHistory: 包含历史步骤和时间信息的对象
560 """
561 # 1. 首先验证ChatRecord存在且属于当前用户
562 chat_record = session.get(ChatRecord, chat_record_id)
563 if not chat_record:
564 raise Exception(f"ChatRecord with id {chat_record_id} not found")
565
566 if chat_record.create_by != current_user.id:
567 raise Exception(f"ChatRecord with id {chat_record_id} not owned by the current user")
568
569 # 2. 查询与该ChatRecord相关的所有ChatLog记录
570 chat_logs = session.query(ChatLog).filter(
571 ChatLog.pid == chat_record_id,
572 ChatLog.operate != OperationEnum.GENERATE_RECOMMENDED_QUESTIONS
573 ).order_by(ChatLog.start_time).all()
574
575 # 3. 计算总的时间和token信息
576 total_tokens = 0
577 steps = []
578
579 for log in chat_logs:
580 # 计算单条记录的token消耗
581 log_tokens = 0
582 if log.token_usage is not None:
583 if isinstance(log.token_usage, dict):
584 if log.token_usage and "total_tokens" in log.token_usage:
585 token_value = log.token_usage["total_tokens"]
586 if isinstance(token_value, (int, float)):
587 log_tokens = int(token_value)
588 elif isinstance(log.token_usage, (int, float)):
589 log_tokens = log.token_usage
590
591 # 累加到总token消耗
592 total_tokens += log_tokens
593
594 if not without_steps:
595 # 计算单条记录的耗时
596 duration = None
597 if log.start_time and log.finish_time:
598 try:
599 time_diff = log.finish_time - log.start_time
600 duration = round(time_diff.total_seconds(), 2)
601 except Exception:
602 duration = None
603
604 # 获取操作类型的枚举名称

Callers 1

innerFunction · 0.90

Calls 5

ChatLogHistoryItemClass · 0.90
ChatLogHistoryClass · 0.90
getMethod · 0.65
filterMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected