111/agents/code_explainer.py
2026-01-08 21:48:24 +08:00

65 lines
2.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from services.ai_service import ai_service
from models.schemas import CodeExplanation
from typing import List, Optional
class CodeExplainer:
"""代码解释智能体"""
def __init__(self):
self.service = ai_service
def explain(self, code: str, language: str, depth: str = "detailed") -> CodeExplanation:
"""解释代码"""
explanation_text = self.service.generate_explanation(code, language, depth)
return CodeExplanation(
explanation=explanation_text,
line_by_line=self._parse_line_explanations(explanation_text),
key_concepts=self._extract_concepts(explanation_text),
suggestions=self._extract_suggestions(explanation_text)
)
def _parse_line_explanations(self, explanation: str) -> List[dict]:
"""解析逐行解释"""
lines = explanation.split('\n')
parsed = []
current_item = {}
for line in lines:
if line.strip().startswith(('', 'Line', '')):
if current_item:
parsed.append(current_item)
current_item = {"line": line}
elif current_item:
current_item["explanation"] = current_item.get("explanation", "") + line + "\n"
if current_item:
parsed.append(current_item)
return parsed if parsed else None
def _extract_concepts(self, explanation: str) -> List[str]:
"""提取关键概念"""
import re
patterns = [
r'关键概念[:]\s*(.+?)(?:\n|$)',
r'概念[:]\s*(.+?)(?:\n|$)',
r'(?:concept|term|关键字)[s]*[:]\s*(.+?)(?:\n|$)'
]
concepts = []
for pattern in patterns:
matches = re.findall(pattern, explanation, re.IGNORECASE)
concepts.extend(matches)
return concepts if concepts else None
def _extract_suggestions(self, explanation: str) -> List[str]:
"""提取建议"""
import re
pattern = r'(?:建议|tips?|提示|最佳实践)[:]\s*(.+?)(?:\n|$)'
matches = re.findall(pattern, explanation, re.IGNORECASE)
return matches if matches else None
code_explainer = CodeExplainer()