mirror of
http://hblu.top:3000/st2411020106/111.git
synced 2026-01-27 22:43:24 +08:00
88 lines
2.5 KiB
Python
88 lines
2.5 KiB
Python
from openai import OpenAI
|
|
from config import config
|
|
from typing import Optional
|
|
|
|
class AIService:
|
|
def __init__(self):
|
|
api_key = config.SILICONFLOW_API_KEY or config.OPENAI_API_KEY
|
|
base_url = config.SILICONFLOW_BASE_URL
|
|
|
|
if not api_key:
|
|
raise ValueError("请设置 SILICONFLOW_API_KEY 或 OPENAI_API_KEY 环境变量")
|
|
|
|
self.client = OpenAI(
|
|
api_key=api_key,
|
|
base_url=base_url
|
|
)
|
|
self.model = config.SILICONFLOW_MODEL
|
|
|
|
def generate_explanation(self, code: str, language: str, depth: str) -> str:
|
|
"""生成代码解释"""
|
|
depth_instruction = config.EXPLANATION_DEPTH.get(depth, config.EXPLANATION_DEPTH["detailed"])
|
|
|
|
prompt = f"""
|
|
请作为一位耐心的编程导师,解释以下{language}代码。
|
|
|
|
解释要求:{depth_instruction}
|
|
|
|
代码:
|
|
```{language}
|
|
{code}
|
|
```
|
|
|
|
请提供:
|
|
1. 代码整体功能的概述
|
|
2. 逐行或分段的详细解释
|
|
3. 关键概念和语法的说明
|
|
4. 相关的最佳实践建议
|
|
"""
|
|
|
|
response = self.client.chat.completions.create(
|
|
model=self.model,
|
|
messages=[{"role": "user", "content": prompt}],
|
|
temperature=0.7
|
|
)
|
|
|
|
return response.choices[0].message.content
|
|
|
|
def generate_fix(self, code: str, language: str, error_description: Optional[str] = None) -> dict:
|
|
"""生成代码修复建议"""
|
|
prompt = f"""
|
|
请作为一位经验丰富的开发者,分析并修复以下{language}代码中的问题。
|
|
|
|
{('错误描述: ' + error_description) if error_description else ''}
|
|
|
|
代码:
|
|
```{language}
|
|
{code}
|
|
```
|
|
|
|
请提供:
|
|
1. 发现的问题列表
|
|
2. 修复后的完整代码
|
|
3. 每个修复的详细说明
|
|
4. 相关的最佳实践建议
|
|
"""
|
|
|
|
response = self.client.chat.completions.create(
|
|
model=self.model,
|
|
messages=[{"role": "user", "content": prompt}],
|
|
temperature=0.5
|
|
)
|
|
|
|
content = response.choices[0].message.content
|
|
|
|
return {
|
|
"analysis": content,
|
|
"fixed_code": self._extract_code_from_response(content)
|
|
}
|
|
|
|
def _extract_code_from_response(self, response: str) -> str:
|
|
"""从AI响应中提取代码块"""
|
|
import re
|
|
pattern = r'```[\w]*\n([\s\S]*?)```'
|
|
matches = re.findall(pattern, response)
|
|
return matches[0] if matches else ""
|
|
|
|
ai_service = AIService()
|