Spaces:
Sleeping
Sleeping
File size: 18,777 Bytes
cd61bf7 1f1df4a cd61bf7 f0e1c07 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 | 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
# ============================================================================
@router.post("/feedback", response_model=FeedbackResponse, status_code=status.HTTP_201_CREATED)
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
)
@router.get("/feedback", response_model=List[FeedbackResponse])
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
# ============================================================================
@router.post("/examples", response_model=TrainingExampleResponse, status_code=status.HTTP_201_CREATED)
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
)
@router.get("/examples", response_model=List[TrainingExampleResponse])
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
]
@router.delete("/examples/{example_id}", status_code=status.HTTP_204_NO_CONTENT)
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
# ============================================================================
@router.post("/rules", response_model=LearningRuleResponse, status_code=status.HTTP_201_CREATED)
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
)
@router.get("/rules", response_model=List[LearningRuleResponse])
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
]
@router.delete("/rules/{rule_id}", status_code=status.HTTP_204_NO_CONTENT)
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
@router.post("/corrections/quick", status_code=status.HTTP_201_CREATED)
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
# ============================================================================
@router.get("/stats")
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
@router.post("/from-chat", status_code=status.HTTP_201_CREATED)
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
}
|