Files
erp-ass/backend/app/api/analyze.py
dazhuang acd73431ae feat: implement ERP AI Assistant Phase 1
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>
2026-03-21 14:23:20 +00:00

113 lines
3.6 KiB
Python

"""Analyze API endpoint for requirement analysis.
This module provides the /analyze endpoint for analyzing user requirements.
"""
import uuid
from typing import Dict
from fastapi import APIRouter, HTTPException, status
from loguru import logger
from app.models.request import AnalyzeRequest
from app.models.response import AnalyzeResponse, ErrorResponse
from app.services.requirement_service import RequirementService
# Create router
router = APIRouter()
@router.post(
"/analyze",
response_model=AnalyzeResponse,
responses={
400: {"model": ErrorResponse, "description": "Invalid request"},
500: {"model": ErrorResponse, "description": "Internal server error"}
},
summary="Analyze user requirement",
description="Analyze natural language or structured requirement and return structured specification"
)
async def analyze_requirement(request: AnalyzeRequest) -> AnalyzeResponse:
"""Analyze user requirement and return structured specification.
This endpoint accepts either natural language or structured input,
processes it through Claude AI with RAG knowledge retrieval, and
returns a structured requirement specification.
Args:
request: AnalyzeRequest containing input_type, content, and optional session_id
Returns:
AnalyzeResponse with session_id, status, and structured data
Raises:
HTTPException: 400 for invalid input, 500 for processing errors
"""
# Generate session ID if not provided
session_id = request.session_id or str(uuid.uuid4())
try:
# Validate input type
if request.input_type not in ["natural_language", "structured"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={
"code": "INVALID_INPUT_TYPE",
"message": "input_type must be 'natural_language' or 'structured'",
"session_id": session_id
}
)
# Validate content
if not request.content or not request.content.strip():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={
"code": "EMPTY_CONTENT",
"message": "content cannot be empty",
"session_id": session_id
}
)
logger.info(f"[{session_id}] Processing analyze request: {request.content[:50]}...")
# Create service and analyze
service = RequirementService()
result = await service.analyze(
user_input=request.content,
session_id=session_id
)
logger.success(f"[{session_id}] Analysis completed successfully")
return AnalyzeResponse(
session_id=session_id,
status="success",
data=result
)
except HTTPException:
# Re-raise HTTP exceptions
raise
except ValueError as e:
logger.error(f"[{session_id}] Validation error: {e}")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={
"code": "VALIDATION_ERROR",
"message": str(e),
"session_id": session_id
}
)
except Exception as e:
logger.error(f"[{session_id}] Analysis failed: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={
"code": "ANALYSIS_FAILED",
"message": f"Failed to analyze requirement: {str(e)}",
"session_id": session_id
}
)