Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ def execute(self, model_id, dialogue_number, history_chat_record, user_input, br
try:
r = chat_model.invoke(message_list)
classification_result = r.content.strip()

# 解析分类结果获取分支信息
matched_branch = self.parse_classification_result(classification_result, branch)

Expand All @@ -101,7 +100,7 @@ def execute(self, model_id, dialogue_number, history_chat_record, user_input, br
'history_message': history_message,
'user_input': user_input,
'branch_id': matched_branch['id'],
'reason': json.loads(r.content).get('reason'),
'reason': self.parse_result_reason(r.content),
'category': matched_branch.get('content', matched_branch['id'])
}, {}, _write_context=write_context)

Expand Down Expand Up @@ -191,7 +190,7 @@ def get_branch_by_id(category_id: int):

try:
result_json = json.loads(result)
classification_id = result_json.get('classificationId', 0) # 0 兜底
classification_id = result_json.get('classificationId')
# 如果是 0 ,返回其他分支
matched_branch = get_branch_by_id(classification_id)
if matched_branch:
Expand All @@ -210,6 +209,26 @@ def get_branch_by_id(category_id: int):
# 如果都解析失败,返回“other”
return other_branch or (normal_intents[0] if normal_intents else {'id': 'unknown', 'content': 'unknown'})

def parse_result_reason(self, result: str):
"""解析分类的原因"""
try:
result_json = json.loads(result)
return result_json.get('reason', '')
except Exception as e:
reason_patterns = [
r'"reason":\s*"([^"]*)"', # 标准格式
r'"reason":\s*"([^"]*)', # 缺少结束引号
r'"reason":\s*([^,}\n]*)', # 没有引号包围的内容
]
for pattern in reason_patterns:
match = re.search(pattern, result, re.DOTALL)
if match:
reason = match.group(1).strip()
# 清理可能的尾部字符
reason = re.sub(r'["\s]*$', '', reason)
return reason

return ''

def find_other_branch(self, branch: List[Dict]) -> Dict[str, Any] | None:
"""查找其他分支"""
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code has several issues and can be optimized:

Issues Found:

  1. Inconsistent Handling of JSON Parsing:

    • In parse_classification_result, there's inconsistent handling of parsing errors using json.loads. The error case should handle exceptions more robustly.
  2. Duplicate Code Block:

    • There's a duplicate block of code in execute that can be minimized by combining the two branches into a single condition.
  3. Parsing Reason for Classification Results:

    • The parse_result_reason function has multiple regular expression patterns to extract reasons from different formats, which is inefficient due to repeated regex searches on each parse attempt.
  4. Unused Variable matched_branch_id:

    • The variable matched_branch_id is not used within the function, so it can be removed for clarity.
  5. Return Values:

    • The return values seem ambiguous. For example, when no branch matches and normal intents are available, some functions default to 'unknown' instead of returning a structured dictionary like {'id': '', 'content': ''}.

Optimization Suggestions:

  1. Refactor and Simplify Logic for Classifying Result Reason:

    def parse_result_reason(self, result: str) -> str:
        """解析分类的结果原因"""
        try:
            result_json = json.loads(result)
            return result_json.get('reason', '')
        except Exception as e:
            match = re.search(
                '(?P<delim>["\s]*):(?=\s*\breason\b)(.*?)"reason"', result, re.DOTALL
            )
            if match:
                reason = match.group(1).strip()
                # Clean up possible tailing characters
                reason = re.sub(r'[,"\s]*$', '', reason)
                return reason
    
            return ''
  2. Combine Condition in Execute Method:

    matched_branch = self.find_matched_branch(history_message, user_input, branch)
    
    if not matched_branch or (not matched_branch['enabled'] and matched_branch != 'other'):
        matched_branch = {key: key for key in ('id', 'content')} if other_branch else normal_intents[0]

These changes will improve the consistency, readability, and efficiency of the code while addressing potential issues such as redundant code blocks and insufficient exception handling.

Expand Down
Loading