Backend (FastAPI + SQLAlchemy + Claude API + RAG): - Config management with Pydantic v2 - Database engine with connection pooling and SQL injection prevention - AI engine with Claude API integration (support custom base URL) - RAG engine with ChromaDB and sentence-transformers - Requirement analysis service - Config generation service - Executor engine with SQL validation - REST API endpoints: /analyze, /generate, /execute Frontend (Vue 3 + Element Plus + Pinia): - Complete 3-step workflow: analyze → generate → execute - Step indicator with progress visualization - Analysis result display with field table - SQL preview with monospace font - Execute confirmation dialog with safety warning - Execution result display - State management with Pinia - API service integration Security: - SQL injection prevention with parameterized queries - Dangerous SQL operation blocking - Database password URL encoding - Transaction auto-rollback - Pydantic config validation Features: - Natural language requirement analysis - Automated SQL configuration generation - Safe execution with human review - LAN access support - Custom Claude API endpoint support Documentation: - README with quick start guide - Quick start guide - LAN access configuration - Dependency fixes guide - Claude API configuration - Git operation guide - Implementation report Dependencies fixed: - numpy<2.0.0 for chromadb compatibility - sentence-transformers==2.7.0 for huggingface_hub compatibility Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
135 lines
4.5 KiB
Python
135 lines
4.5 KiB
Python
"""Config Generation Service.
|
|
|
|
This module provides the ConfigService class for generating ERP platform
|
|
configuration SQL based on structured requirements.
|
|
"""
|
|
|
|
from typing import Dict, Any
|
|
|
|
from loguru import logger
|
|
|
|
from app.core.ai_engine import ClaudeEngine
|
|
from app.core.rag_engine import RAGEngine
|
|
from app.core.prompts import SYSTEM_PROMPT, GENERATE_PROMPT_TEMPLATE
|
|
from app.core.db_engine import DatabaseEngine
|
|
|
|
|
|
class ConfigService:
|
|
"""Service for generating ERP platform configuration.
|
|
|
|
This service uses Claude AI with RAG knowledge retrieval to generate
|
|
SQL configuration statements based on structured requirements.
|
|
"""
|
|
|
|
def __init__(self) -> None:
|
|
"""Initialize config service with required engines."""
|
|
self.ai_engine = ClaudeEngine()
|
|
self.rag_engine = RAGEngine()
|
|
self.db_engine = DatabaseEngine()
|
|
logger.info("ConfigService initialized")
|
|
|
|
async def generate(
|
|
self,
|
|
requirements: Dict[str, Any],
|
|
session_id: str
|
|
) -> Dict[str, Any]:
|
|
"""Generate configuration SQL based on requirements.
|
|
|
|
Args:
|
|
requirements: Structured requirement specification
|
|
session_id: Session ID for tracking
|
|
|
|
Returns:
|
|
Configuration plan with SQL statements
|
|
|
|
Raises:
|
|
ValueError: If requirements are invalid
|
|
Exception: If generation fails
|
|
"""
|
|
if not requirements:
|
|
raise ValueError("Requirements cannot be empty")
|
|
|
|
function_name = requirements.get("功能名称", "Unknown")
|
|
logger.info(f"[{session_id}] Starting config generation for: {function_name}")
|
|
|
|
try:
|
|
# Step 1: Retrieve platform rules for form type
|
|
form_type = requirements.get("窗体类型", "0")
|
|
logger.debug(f"[{session_id}] Retrieving platform rules for form type: {form_type}")
|
|
platform_rules = self._get_platform_rules(form_type)
|
|
logger.info(f"[{session_id}] Retrieved platform rules")
|
|
|
|
# Step 2: Retrieve similar cases
|
|
logger.debug(f"[{session_id}] Retrieving similar cases")
|
|
similar_cases = self._get_similar_cases(function_name)
|
|
logger.info(f"[{session_id}] Retrieved similar cases")
|
|
|
|
# Step 3: Build prompt
|
|
prompt = GENERATE_PROMPT_TEMPLATE.format(
|
|
requirements=str(requirements),
|
|
platform_rules=platform_rules,
|
|
similar_cases=similar_cases
|
|
)
|
|
|
|
messages = [
|
|
{"role": "user", "content": SYSTEM_PROMPT},
|
|
{"role": "assistant", "content": "我已了解,请提供需求信息。"},
|
|
{"role": "user", "content": prompt}
|
|
]
|
|
|
|
# Step 4: Call Claude API
|
|
logger.debug(f"[{session_id}] Calling Claude API for config generation")
|
|
response = await self.ai_engine.call_claude(messages, temperature=0.5)
|
|
|
|
# Step 5: Parse JSON response
|
|
result = self.ai_engine.parse_json_response(response)
|
|
|
|
logger.success(f"[{session_id}] Config generation completed")
|
|
return result
|
|
|
|
except Exception as e:
|
|
logger.error(f"[{session_id}] Config generation failed: {e}")
|
|
raise
|
|
|
|
def _get_platform_rules(self, form_type: str) -> str:
|
|
"""Retrieve platform configuration rules for specific form type.
|
|
|
|
Args:
|
|
form_type: Form type code
|
|
|
|
Returns:
|
|
Platform rules text
|
|
"""
|
|
try:
|
|
results = self.rag_engine.search(
|
|
f"窗体类型{form_type}配置规则",
|
|
top_k=2
|
|
)
|
|
if not results:
|
|
return "未找到相关配置规则"
|
|
|
|
return "\n\n".join([r["content"] for r in results])
|
|
|
|
except Exception as e:
|
|
logger.warning(f"Failed to retrieve platform rules: {e}")
|
|
return "无法获取平台配置规则"
|
|
|
|
def _get_similar_cases(self, keywords: str) -> str:
|
|
"""Retrieve similar configuration cases from knowledge base.
|
|
|
|
Args:
|
|
keywords: Search keywords
|
|
|
|
Returns:
|
|
Similar cases text
|
|
"""
|
|
try:
|
|
results = self.rag_engine.search(keywords, top_k=2)
|
|
if not results:
|
|
return "未找到相似案例"
|
|
|
|
return "\n\n".join([r["content"] for r in results])
|
|
|
|
except Exception as e:
|
|
logger.warning(f"Failed to retrieve similar cases: {e}")
|
|
return "无法获取相似案例" |