Spaces:
Running
Running
Download backend/app/api/ai_training.py from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 18.8 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/ai_training.py
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/backend/app/api/ai_training.py
-
curl -L -o ai_training.py https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/ai_training.py
18.8 kB
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from sqlmodel import select | |
| from sqlmodel.ext.asyncio.session import AsyncSession | |
| from pydantic import BaseModel | |
| from typing import List, Optional, Dict, Any | |
| from uuid import UUID | |
| from datetime import datetime | |
| from app.core.database import get_async_session | |
| from app.api.deps import get_current_user | |
| from app.models.user import User | |
| from app.models.ai_training import ( | |
| AIFeedback, | |
| AITrainingExample, | |
| AILearningRule, | |
| FeedbackType, | |
| TrainingStatus | |
| ) | |
| router = APIRouter(prefix="/ai-training", tags=["AI Training"]) | |
| # ============================================================================ | |
| # Schemas | |
| # ============================================================================ | |
| class FeedbackCreate(BaseModel): | |
| message_id: Optional[UUID] = None | |
| conversation_id: Optional[UUID] = None | |
| lead_id: Optional[UUID] = None | |
| feedback_type: str # "positive", "negative", "correction", "instruction" | |
| original_prompt: Optional[str] = None | |
| original_response: Optional[str] = None | |
| corrected_response: Optional[str] = None | |
| user_comment: Optional[str] = None | |
| rating: Optional[int] = None | |
| class TrainingExampleCreate(BaseModel): | |
| user_input: str | |
| ideal_response: str | |
| category: Optional[str] = None | |
| tags: Optional[str] = None | |
| scenario_description: Optional[str] = None | |
| weight: float = 1.0 | |
| class LearningRuleCreate(BaseModel): | |
| rule_name: str | |
| rule_description: str | |
| trigger_keywords: Optional[str] = None | |
| apply_to_category: Optional[str] = None | |
| instruction: str | |
| priority: int = 5 | |
| class FeedbackResponse(BaseModel): | |
| id: UUID | |
| tenant_id: UUID | |
| feedback_type: str | |
| original_response: Optional[str] | |
| corrected_response: Optional[str] | |
| user_comment: Optional[str] | |
| rating: Optional[int] | |
| status: str | |
| is_applied: bool | |
| created_at: datetime | |
| class TrainingExampleResponse(BaseModel): | |
| id: UUID | |
| tenant_id: UUID | |
| user_input: str | |
| ideal_response: str | |
| category: Optional[str] | |
| weight: float | |
| use_count: int | |
| success_rate: float | |
| status: str | |
| is_active: bool | |
| created_at: datetime | |
| class LearningRuleResponse(BaseModel): | |
| id: UUID | |
| tenant_id: UUID | |
| rule_name: str | |
| rule_description: str | |
| instruction: str | |
| priority: int | |
| times_triggered: int | |
| positive_outcomes: int | |
| negative_outcomes: int | |
| is_active: bool | |
| created_at: datetime | |
| # ============================================================================ | |
| # Feedback Endpoints | |
| # ============================================================================ | |
| async def create_feedback( | |
| request: FeedbackCreate, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Create feedback on AI response. | |
| This helps AI learn from corrections and improve over time. | |
| """ | |
| feedback = AIFeedback( | |
| tenant_id=current_user.tenant_id, | |
| conversation_id=request.conversation_id, | |
| message_id=request.message_id, | |
| lead_id=request.lead_id, | |
| feedback_type=FeedbackType(request.feedback_type), | |
| original_prompt=request.original_prompt, | |
| original_response=request.original_response, | |
| corrected_response=request.corrected_response, | |
| user_comment=request.user_comment, | |
| rating=request.rating, | |
| created_by_user_id=current_user.id | |
| ) | |
| session.add(feedback) | |
| await session.commit() | |
| await session.refresh(feedback) | |
| # Auto-convert correction to training example if provided | |
| if request.feedback_type == "correction" and request.corrected_response: | |
| training_example = AITrainingExample( | |
| tenant_id=current_user.tenant_id, | |
| user_input=request.original_prompt or "", | |
| ideal_response=request.corrected_response, | |
| source="feedback", | |
| source_feedback_id=feedback.id, | |
| weight=1.5, # Corrections are important | |
| created_by_user_id=current_user.id | |
| ) | |
| session.add(training_example) | |
| feedback.is_applied = True | |
| session.add(feedback) | |
| await session.commit() | |
| return FeedbackResponse( | |
| id=feedback.id, | |
| tenant_id=feedback.tenant_id, | |
| feedback_type=feedback.feedback_type.value, | |
| original_response=feedback.original_response, | |
| corrected_response=feedback.corrected_response, | |
| user_comment=feedback.user_comment, | |
| rating=feedback.rating, | |
| status=feedback.status.value, | |
| is_applied=feedback.is_applied, | |
| created_at=feedback.created_at | |
| ) | |
| async def list_feedback( | |
| skip: int = 0, | |
| limit: int = 50, | |
| feedback_type: Optional[str] = None, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """List all feedback for current tenant.""" | |
| stmt = select(AIFeedback).where( | |
| AIFeedback.tenant_id == current_user.tenant_id | |
| ) | |
| if feedback_type: | |
| stmt = stmt.where(AIFeedback.feedback_type == FeedbackType(feedback_type)) | |
| stmt = stmt.order_by(AIFeedback.created_at.desc()).offset(skip).limit(limit) | |
| result = await session.execute(stmt) | |
| feedbacks = result.scalars().all() | |
| return [ | |
| FeedbackResponse( | |
| id=f.id, | |
| tenant_id=f.tenant_id, | |
| feedback_type=f.feedback_type.value, | |
| original_response=f.original_response, | |
| corrected_response=f.corrected_response, | |
| user_comment=f.user_comment, | |
| rating=f.rating, | |
| status=f.status.value, | |
| is_applied=f.is_applied, | |
| created_at=f.created_at | |
| ) | |
| for f in feedbacks | |
| ] | |
| # ============================================================================ | |
| # Training Examples Endpoints | |
| # ============================================================================ | |
| async def create_training_example( | |
| request: TrainingExampleCreate, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Create a training example for few-shot learning. | |
| AI will use these examples to learn your preferred response style. | |
| """ | |
| example = AITrainingExample( | |
| tenant_id=current_user.tenant_id, | |
| user_input=request.user_input, | |
| ideal_response=request.ideal_response, | |
| category=request.category, | |
| tags=request.tags, | |
| scenario_description=request.scenario_description, | |
| weight=request.weight, | |
| source="manual", | |
| created_by_user_id=current_user.id | |
| ) | |
| session.add(example) | |
| await session.commit() | |
| await session.refresh(example) | |
| return TrainingExampleResponse( | |
| id=example.id, | |
| tenant_id=example.tenant_id, | |
| user_input=example.user_input, | |
| ideal_response=example.ideal_response, | |
| category=example.category, | |
| weight=example.weight, | |
| use_count=example.use_count, | |
| success_rate=example.success_rate, | |
| status=example.status.value, | |
| is_active=example.is_active, | |
| created_at=example.created_at | |
| ) | |
| async def list_training_examples( | |
| skip: int = 0, | |
| limit: int = 100, | |
| category: Optional[str] = None, | |
| only_active: bool = True, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """List training examples for current tenant.""" | |
| stmt = select(AITrainingExample).where( | |
| AITrainingExample.tenant_id == current_user.tenant_id | |
| ) | |
| if category: | |
| stmt = stmt.where(AITrainingExample.category == category) | |
| if only_active: | |
| stmt = stmt.where(AITrainingExample.is_active == True) | |
| stmt = stmt.order_by( | |
| AITrainingExample.weight.desc(), | |
| AITrainingExample.created_at.desc() | |
| ).offset(skip).limit(limit) | |
| result = await session.execute(stmt) | |
| examples = result.scalars().all() | |
| return [ | |
| TrainingExampleResponse( | |
| id=ex.id, | |
| tenant_id=ex.tenant_id, | |
| user_input=ex.user_input, | |
| ideal_response=ex.ideal_response, | |
| category=ex.category, | |
| weight=ex.weight, | |
| use_count=ex.use_count, | |
| success_rate=ex.success_rate, | |
| status=ex.status.value, | |
| is_active=ex.is_active, | |
| created_at=ex.created_at | |
| ) | |
| for ex in examples | |
| ] | |
| async def delete_training_example( | |
| example_id: UUID, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """Delete (deactivate) a training example.""" | |
| result = await session.execute( | |
| select(AITrainingExample).where( | |
| AITrainingExample.id == example_id, | |
| AITrainingExample.tenant_id == current_user.tenant_id | |
| ) | |
| ) | |
| example = result.scalar_one_or_none() | |
| if not example: | |
| raise HTTPException(status_code=404, detail="Training example not found") | |
| example.is_active = False | |
| example.updated_at = datetime.utcnow() | |
| session.add(example) | |
| await session.commit() | |
| return None | |
| # ============================================================================ | |
| # Learning Rules Endpoints | |
| # ============================================================================ | |
| async def create_learning_rule( | |
| request: LearningRuleCreate, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Create a learning rule for AI. | |
| Rules define specific behaviors AI should follow. | |
| """ | |
| rule = AILearningRule( | |
| tenant_id=current_user.tenant_id, | |
| rule_name=request.rule_name, | |
| rule_description=request.rule_description, | |
| trigger_keywords=request.trigger_keywords, | |
| apply_to_category=request.apply_to_category, | |
| instruction=request.instruction, | |
| priority=request.priority, | |
| source="manual", | |
| created_by_user_id=current_user.id | |
| ) | |
| session.add(rule) | |
| await session.commit() | |
| await session.refresh(rule) | |
| return LearningRuleResponse( | |
| id=rule.id, | |
| tenant_id=rule.tenant_id, | |
| rule_name=rule.rule_name, | |
| rule_description=rule.rule_description, | |
| instruction=rule.instruction, | |
| priority=rule.priority, | |
| times_triggered=rule.times_triggered, | |
| positive_outcomes=rule.positive_outcomes, | |
| negative_outcomes=rule.negative_outcomes, | |
| is_active=rule.is_active, | |
| created_at=rule.created_at | |
| ) | |
| async def list_learning_rules( | |
| only_active: bool = True, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """List learning rules for current tenant.""" | |
| stmt = select(AILearningRule).where( | |
| AILearningRule.tenant_id == current_user.tenant_id | |
| ) | |
| if only_active: | |
| stmt = stmt.where(AILearningRule.is_active == True) | |
| stmt = stmt.order_by( | |
| AILearningRule.priority.desc(), | |
| AILearningRule.created_at.desc() | |
| ) | |
| result = await session.execute(stmt) | |
| rules = result.scalars().all() | |
| return [ | |
| LearningRuleResponse( | |
| id=r.id, | |
| tenant_id=r.tenant_id, | |
| rule_name=r.rule_name, | |
| rule_description=r.rule_description, | |
| instruction=r.instruction, | |
| priority=r.priority, | |
| times_triggered=r.times_triggered, | |
| positive_outcomes=r.positive_outcomes, | |
| negative_outcomes=r.negative_outcomes, | |
| is_active=r.is_active, | |
| created_at=r.created_at | |
| ) | |
| for r in rules | |
| ] | |
| async def delete_learning_rule( | |
| rule_id: UUID, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """Delete (deactivate) a learning rule.""" | |
| result = await session.execute( | |
| select(AILearningRule).where( | |
| AILearningRule.id == rule_id, | |
| AILearningRule.tenant_id == current_user.tenant_id | |
| ) | |
| ) | |
| rule = result.scalar_one_or_none() | |
| if not rule: | |
| raise HTTPException(status_code=404, detail="Learning rule not found") | |
| rule.is_active = False | |
| rule.updated_at = datetime.utcnow() | |
| session.add(rule) | |
| await session.commit() | |
| return None | |
| # ============================================================================ | |
| # Quick Corrections (from Demo Chat) | |
| # ============================================================================ | |
| class QuickCorrectionRequest(BaseModel): | |
| """Simple correction from demo chat""" | |
| correction: str | |
| async def add_quick_correction( | |
| request: QuickCorrectionRequest, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Quickly add a correction/rule for AI from demo chat. | |
| Simplified endpoint - just the correction text. | |
| """ | |
| if not request.correction.strip(): | |
| raise HTTPException(status_code=400, detail="Correction text is required") | |
| # Create learning rule | |
| rule = AILearningRule( | |
| tenant_id=current_user.tenant_id, | |
| rule_name=f"Правка: {request.correction[:30]}...", | |
| rule_description=request.correction, | |
| trigger_keywords=None, | |
| apply_to_category=None, | |
| instruction=request.correction, | |
| priority=8, # High priority for user corrections | |
| source="demo_chat", | |
| created_by_user_id=current_user.id | |
| ) | |
| session.add(rule) | |
| await session.commit() | |
| await session.refresh(rule) | |
| return { | |
| "ok": True, | |
| "id": str(rule.id), | |
| "message": "Правка сохранена" | |
| } | |
| # ============================================================================ | |
| # Stats Endpoints | |
| # ============================================================================ | |
| async def get_training_stats( | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """Get AI training statistics for current tenant.""" | |
| # Count feedback | |
| feedback_result = await session.execute( | |
| select(AIFeedback).where(AIFeedback.tenant_id == current_user.tenant_id) | |
| ) | |
| total_feedback = len(feedback_result.scalars().all()) | |
| # Count training examples | |
| examples_result = await session.execute( | |
| select(AITrainingExample).where( | |
| AITrainingExample.tenant_id == current_user.tenant_id, | |
| AITrainingExample.is_active == True | |
| ) | |
| ) | |
| active_examples = len(examples_result.scalars().all()) | |
| # Count rules | |
| rules_result = await session.execute( | |
| select(AILearningRule).where( | |
| AILearningRule.tenant_id == current_user.tenant_id, | |
| AILearningRule.is_active == True | |
| ) | |
| ) | |
| active_rules = len(rules_result.scalars().all()) | |
| return { | |
| "total_feedback": total_feedback, | |
| "active_training_examples": active_examples, | |
| "active_learning_rules": active_rules, | |
| "training_status": "active" if (active_examples + active_rules) > 0 else "not_configured" | |
| } | |
| # ============================================================================ | |
| # Train from Chat Endpoint | |
| # ============================================================================ | |
| class TrainFromChatRequest(BaseModel): | |
| conversation_id: UUID | |
| lead_id: UUID | |
| async def train_from_chat( | |
| request: TrainFromChatRequest, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Create training examples from a conversation. | |
| Extracts user-AI message pairs and saves them as training examples. | |
| """ | |
| from app.models.lead import Conversation, Message | |
| # Get conversation | |
| conv_result = await session.execute( | |
| select(Conversation).where( | |
| Conversation.id == request.conversation_id, | |
| Conversation.tenant_id == current_user.tenant_id | |
| ) | |
| ) | |
| conversation = conv_result.scalar_one_or_none() | |
| if not conversation: | |
| raise HTTPException(status_code=404, detail="Conversation not found") | |
| # Get messages | |
| msg_result = await session.execute( | |
| select(Message).where( | |
| Message.conversation_id == request.conversation_id | |
| ).order_by(Message.created_at) | |
| ) | |
| messages = msg_result.scalars().all() | |
| if len(messages) < 2: | |
| raise HTTPException(status_code=400, detail="Not enough messages to create training example") | |
| # Create training examples from user-AI pairs | |
| examples_created = 0 | |
| # Build conversation segments (user message -> AI response) | |
| user_message = None | |
| for msg in messages: | |
| if msg.sender_type == 'user' or msg.sender_type == 'lead': | |
| user_message = msg.content | |
| elif msg.sender_type == 'ai' and user_message: | |
| # Create training example | |
| example = AITrainingExample( | |
| tenant_id=current_user.tenant_id, | |
| user_input=user_message, | |
| ideal_response=msg.content, | |
| category="conversation", | |
| scenario_description=f"Real conversation from lead chat", | |
| source="chat", | |
| weight=1.2, # Real conversations are valuable | |
| created_by_user_id=current_user.id | |
| ) | |
| session.add(example) | |
| examples_created += 1 | |
| user_message = None # Reset for next pair | |
| await session.commit() | |
| return { | |
| "ok": True, | |
| "message": f"Created {examples_created} training examples from chat", | |
| "examples_created": examples_created | |
| } | |