diff --git a/CLAUDE.md b/CLAUDE.md index cdd7f8812..ad625e643 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code when working with code in this reposi ## Project Overview -Kaapi is an AI platform built with FastAPI and PostgreSQL, containerized with Docker. It provides AI capabilities including OpenAI assistants, fine-tuning, document processing, and collection management. +Kaapi is an AI platform built with FastAPI and PostgreSQL, containerized with Docker. It provides AI capabilities including LLM calls, evaluations, document and collection management, and OpenAI assistants. ## Key Commands @@ -55,7 +55,6 @@ The backend follows a layered architecture located in `backend/app/`: - Database connection and session management - Security (JWT, password hashing, API keys) - Cloud storage (`cloud/storage.py`) - - Fine-tuning utilities (`finetune/`) - Langfuse observability integration (`langfuse/`) - Exception handlers and middleware diff --git a/backend/app/alembic/versions/097_drop_fine_tuning_and_model_evaluation_tables.py b/backend/app/alembic/versions/097_drop_fine_tuning_and_model_evaluation_tables.py new file mode 100644 index 000000000..20a98c57e --- /dev/null +++ b/backend/app/alembic/versions/097_drop_fine_tuning_and_model_evaluation_tables.py @@ -0,0 +1,283 @@ +"""drop fine_tuning and model_evaluation + +Revision ID: 097 +Revises: 096 +Create Date: 2026-12-04 00:00:00.000000 + +The Fine-tuning and Model evaluation modules were removed, so nothing reads or +writes these tables any more. Rows are lost on upgrade; downgrade restores the schema +as it stood at 096 (empty tables) so older code can boot, not the data. + +model_evaluation references fine_tuning, so it is dropped first and recreated last. +""" + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import postgresql + +revision = "097" +down_revision = "096" +branch_labels = None +depends_on = None + + +def upgrade(): + op.drop_table("model_evaluation") + op.drop_table("fine_tuning") + op.execute("DROP TYPE IF EXISTS modelevaluationstatus") + op.execute("DROP TYPE IF EXISTS finetuningstatus") + + +def downgrade(): + lifecycle_status = ("pending", "running", "completed", "failed") + finetuning_status = postgresql.ENUM(*lifecycle_status, name="finetuningstatus") + modelevaluation_status = postgresql.ENUM( + *lifecycle_status, name="modelevaluationstatus" + ) + + op.create_table( + "fine_tuning", + sa.Column( + "base_model", + sa.String(), + nullable=False, + comment="Base model used for fine-tuning", + ), + sa.Column( + "split_ratio", + sa.Float(), + nullable=False, + comment="Train/test split ratio for the dataset", + ), + sa.Column( + "document_id", + sa.Uuid(), + nullable=False, + comment="Reference to the training document", + ), + sa.Column( + "training_file_id", + sa.String(), + nullable=True, + comment="OpenAI training file identifier", + ), + sa.Column( + "system_prompt", + sa.Text(), + nullable=False, + comment="System prompt used during fine-tuning", + ), + sa.Column( + "id", + sa.Integer(), + nullable=False, + comment="Unique identifier for the fine-tuning job", + ), + sa.Column( + "provider_job_id", + sa.String(), + nullable=True, + comment="Fine-tuning job ID returned by the provider", + ), + sa.Column( + "status", + finetuning_status, + server_default="pending", + nullable=False, + comment="Current status of the fine-tuning job", + ), + sa.Column( + "fine_tuned_model", + sa.String(), + nullable=True, + comment="Name of the resulting fine-tuned model", + ), + sa.Column( + "train_data_s3_object", + sa.String(), + nullable=True, + comment="S3 URL of the training data", + ), + sa.Column( + "test_data_s3_object", + sa.String(), + nullable=True, + comment="S3 URL of the testing data", + ), + sa.Column( + "error_message", + sa.String(), + nullable=True, + comment="Error message if the job failed", + ), + sa.Column( + "project_id", + sa.Integer(), + nullable=False, + comment="Reference to the project", + ), + sa.Column( + "organization_id", + sa.Integer(), + nullable=False, + comment="Reference to the organization", + ), + sa.Column( + "inserted_at", + sa.DateTime(), + nullable=False, + comment="Timestamp when the job was created", + ), + sa.Column( + "updated_at", + sa.DateTime(), + nullable=False, + comment="Timestamp when the job was last updated", + ), + sa.Column( + "deleted_at", + sa.DateTime(), + nullable=True, + comment="Timestamp when the job was deleted", + ), + sa.ForeignKeyConstraint(["document_id"], ["document.id"], ondelete="CASCADE"), + sa.ForeignKeyConstraint( + ["organization_id"], ["organization.id"], ondelete="CASCADE" + ), + sa.ForeignKeyConstraint(["project_id"], ["project.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index("ix_fine_tuning_project_id", "fine_tuning", ["project_id"]) + op.create_index( + "ix_fine_tuning_document_project", "fine_tuning", ["document_id", "project_id"] + ) + + op.create_table( + "model_evaluation", + sa.Column( + "fine_tuning_id", + sa.Integer(), + nullable=False, + comment="Reference to the fine-tuning job", + ), + sa.Column( + "id", + sa.Integer(), + nullable=False, + comment="Unique identifier for the model evaluation", + ), + sa.Column( + "document_id", + sa.Uuid(), + nullable=False, + comment="Reference to the evaluation document", + ), + sa.Column( + "fine_tuned_model", + sa.String(), + nullable=False, + comment="Name of the fine-tuned model being evaluated", + ), + sa.Column( + "test_data_s3_object", + sa.String(), + nullable=False, + comment="S3 URI of the testing data", + ), + sa.Column( + "base_model", + sa.String(), + nullable=False, + comment="Base model used for fine-tuning", + ), + sa.Column( + "split_ratio", + sa.Float(), + nullable=False, + comment="Train/test split ratio used", + ), + sa.Column( + "system_prompt", + sa.Text(), + nullable=False, + comment="System prompt used during evaluation", + ), + sa.Column( + "score", + sa.JSON(), + nullable=True, + comment="Evaluation scores per metric (e.g., MCC)", + ), + sa.Column( + "prediction_data_s3_object", + sa.String(), + nullable=True, + comment="S3 URL where the prediction data is stored", + ), + sa.Column( + "status", + modelevaluation_status, + server_default="pending", + nullable=False, + comment="Current status of the evaluation", + ), + sa.Column( + "error_message", + sa.String(), + nullable=True, + comment="Error message if evaluation failed", + ), + sa.Column( + "project_id", + sa.Integer(), + nullable=False, + comment="Reference to the project", + ), + sa.Column( + "organization_id", + sa.Integer(), + nullable=False, + comment="Reference to the organization", + ), + sa.Column( + "inserted_at", + sa.DateTime(), + nullable=False, + comment="Timestamp when the evaluation was created", + ), + sa.Column( + "updated_at", + sa.DateTime(), + nullable=False, + comment="Timestamp when the evaluation was last updated", + ), + sa.Column( + "deleted_at", + sa.DateTime(), + nullable=True, + comment="Timestamp when the evaluation was deleted", + ), + sa.ForeignKeyConstraint(["document_id"], ["document.id"], ondelete="CASCADE"), + sa.ForeignKeyConstraint( + ["fine_tuning_id"], ["fine_tuning.id"], ondelete="CASCADE" + ), + sa.ForeignKeyConstraint( + ["organization_id"], ["organization.id"], ondelete="CASCADE" + ), + sa.ForeignKeyConstraint(["project_id"], ["project.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index( + "ix_model_evaluation_project_id", "model_evaluation", ["project_id"] + ) + op.create_index( + "ix_model_evaluation_fine_tuning_project", + "model_evaluation", + ["fine_tuning_id", "project_id"], + ) + op.create_index( + "ix_model_evaluation_document_project_updated_at", + "model_evaluation", + ["document_id", "project_id", sa.text("updated_at DESC")], + postgresql_where=sa.text("deleted_at IS NULL"), + ) diff --git a/backend/app/api/docs/documents/permanent_delete.md b/backend/app/api/docs/documents/permanent_delete.md index 45463d403..317ef9dc8 100644 --- a/backend/app/api/docs/documents/permanent_delete.md +++ b/backend/app/api/docs/documents/permanent_delete.md @@ -1,8 +1,7 @@ Permanently delete a document. The file is removed from cloud storage (e.g., S3) and the database record is deleted. This cannot be undone. Records -that depend on the document, such as its transformed documents, fine-tuning jobs and model -evaluations, are deleted along with it. +that depend on the document, such as its transformed documents, are deleted along with it. Works on both active and soft-deleted documents. Collections and knowledge bases that contain this document are not touched. diff --git a/backend/app/api/docs/fine_tuning/create.md b/backend/app/api/docs/fine_tuning/create.md deleted file mode 100644 index 52b5f0346..000000000 --- a/backend/app/api/docs/fine_tuning/create.md +++ /dev/null @@ -1,25 +0,0 @@ -Initiate fine-tuning of an OpenAI model using a CSV dataset. The CSV must include: - -- A column named `query`, `question`, or `message` containing user inputs or messages. -- A column named `label` indicating whether a given message is a genuine query or not (e.g., casual conversation or small talk). - -The `split_ratio` form field is a comma-separated string that determines how your data is divided between training and testing. For example, `"0.5"` means 50% training and 50% testing. You can provide multiple ratios—for instance, `"0.7,0.9"`. This will trigger multiple fine-tuning jobs, one for each ratio. You would also need to specify a `base_model` that you want to fine-tune. - -The `system_prompt` form field allows you to define an initial instruction or context-setting message that will be included in the training data. This message helps the model learn how it is expected to behave when responding to user inputs. It is prepended as the first message in each training example during fine-tuning. - -The system handles the fine-tuning process by interacting with OpenAI's APIs under the hood. These include: - -- [Openai File create to upload your training and testing files](https://platform.openai.com/docs/api-reference/files/create) - -- [Openai Fine Tuning Job create to initiate each fine-tuning job](https://platform.openai.com/docs/api-reference/fine_tuning/create) - -If successful, the response will include a message along with a list of fine-tuning jobs that were initiated. Each job object includes: - -```json -{ - "id": "the internal ID of the fine-tuning job", - "document_id": "the ID of the document used for fine-tuning", - "split_ratio": "the data split used for that job", - "status": "the initial status of the job (usually 'pending')" -} -``` diff --git a/backend/app/api/docs/fine_tuning/retrieve.md b/backend/app/api/docs/fine_tuning/retrieve.md deleted file mode 100644 index 95710eaf5..000000000 --- a/backend/app/api/docs/fine_tuning/retrieve.md +++ /dev/null @@ -1,7 +0,0 @@ -Refreshes the status of a fine-tuning job by retrieving the latest information from OpenAI. -If there are any changes in status, fine-tuned model, or error message, the local job record is updated accordingly. -Returns the latest state of the job. - -When a job is completed and updated in the database, model evaluation for that fine-tuned model will start automatically. - -OpenAI's job status is retrieved using their [Fine-tuning Job Retrieve API](https://platform.openai.com/docs/api-reference/fine_tuning/retrieve). diff --git a/backend/app/api/docs/model_evaluation/evaluate.md b/backend/app/api/docs/model_evaluation/evaluate.md deleted file mode 100644 index d4c276cec..000000000 --- a/backend/app/api/docs/model_evaluation/evaluate.md +++ /dev/null @@ -1,3 +0,0 @@ -Start evaluations for one or more fine-tuned models. - -For each fine-tuning job ID provided, this endpoint fetches the fine-tuned model and test data, then queues a background task that runs predictions on the test set and computes evaluation scores (Matthews correlation coefficient). Returns created or active evaluation records. diff --git a/backend/app/api/docs/model_evaluation/examples.py b/backend/app/api/docs/model_evaluation/examples.py deleted file mode 100644 index 50152291e..000000000 --- a/backend/app/api/docs/model_evaluation/examples.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Request-body examples for the Model Evaluation routes. - - -""" - -from app.api.openapi_docs import Examples - -MODEL_EVALUATION_CREATE_EXAMPLES: Examples = { - "basic": ("Evaluate fine-tuned models", {"fine_tuning_ids": [7, 8]}), -} diff --git a/backend/app/api/docs/model_evaluation/get_top_model.md b/backend/app/api/docs/model_evaluation/get_top_model.md deleted file mode 100644 index 5b24e6988..000000000 --- a/backend/app/api/docs/model_evaluation/get_top_model.md +++ /dev/null @@ -1,3 +0,0 @@ -Get the top-performing model for a specific document. - -Returns the best model trained on the given document, ranked by Matthews correlation coefficient (MCC) across all evaluations. Includes prediction data file URL if available. diff --git a/backend/app/api/docs/model_evaluation/list_by_document.md b/backend/app/api/docs/model_evaluation/list_by_document.md deleted file mode 100644 index 2325d6a4e..000000000 --- a/backend/app/api/docs/model_evaluation/list_by_document.md +++ /dev/null @@ -1,3 +0,0 @@ -Get all model evaluations for a specific document. - -Returns list of all evaluation records for models trained on the given document within the current project, including prediction data file URLs. diff --git a/backend/app/api/docs/openapi_config.py b/backend/app/api/docs/openapi_config.py index 4d33f84a0..1a3b3c210 100644 --- a/backend/app/api/docs/openapi_config.py +++ b/backend/app/api/docs/openapi_config.py @@ -77,13 +77,6 @@ "config and poll or receive the result by webhook, and check whether a " "submission duplicates an entry in a corpus." ), - "Fine Tuning": ( - "Start OpenAI fine-tuning jobs from a labelled CSV dataset and refresh " - "their status." - ), - "Model Evaluation": ( - "Evaluate fine-tuned models for a document and find the best-performing one." - ), "Assistants": ( "[**Deprecated**] OpenAI Assistant creation and management. This " "feature will be removed in a future version." @@ -165,8 +158,6 @@ "TTS Evaluation", "Assessment", "Assessment (Experimental)", - "Fine Tuning", - "Model Evaluation", "Assistants", "Threads", ], diff --git a/backend/app/api/docs/organization/delete.md b/backend/app/api/docs/organization/delete.md index 7b20f9437..a63f32cea 100644 --- a/backend/app/api/docs/organization/delete.md +++ b/backend/app/api/docs/organization/delete.md @@ -7,6 +7,6 @@ Supports two delete modes, selected by an optional request body: ``` - **`hard_delete: false` (default)** — *Soft delete.* The organization is marked **inactive** and all of its projects are deactivated as well. No data is removed, so the organization can be reactivated later. It simply stops appearing in listings and can no longer be used. Omitting the body entirely also performs a soft delete. -- **`hard_delete: true`** — *Permanent delete.* The organization and everything owned by it — projects, collections, documents, credentials, assistants, fine-tunings, and user-project mappings — are permanently removed. **This cannot be undone.** +- **`hard_delete: true`** — *Permanent delete.* The organization and everything owned by it — projects, collections, documents, credentials, assistants, and user-project mappings — are permanently removed. **This cannot be undone.** In both modes, user **accounts are never deleted** (a user may belong to other organizations). Any user left without an active project afterwards is marked **inactive** and can no longer log in until they are added to an active project again. diff --git a/backend/app/api/docs/projects/delete.md b/backend/app/api/docs/projects/delete.md index 2df363532..5d8fded15 100644 --- a/backend/app/api/docs/projects/delete.md +++ b/backend/app/api/docs/projects/delete.md @@ -7,6 +7,6 @@ Supports two delete modes, selected by an optional request body: ``` - **`hard_delete: false` (default)** — *Soft delete.* The project is marked **inactive**. No data is removed, so the project can be reactivated later. It simply stops appearing in listings and can no longer be used. Omitting the body entirely also performs a soft delete. -- **`hard_delete: true`** — *Permanent delete.* The project and everything owned by it — collections, documents, credentials, assistants, fine-tunings, and user-project mappings — are permanently removed. **This cannot be undone.** +- **`hard_delete: true`** — *Permanent delete.* The project and everything owned by it — collections, documents, credentials, assistants, and user-project mappings — are permanently removed. **This cannot be undone.** In both modes, user **accounts are never deleted** (a user may belong to other projects). Any user left without an active project afterwards is marked **inactive** and can no longer log in until they are added to an active project again. diff --git a/backend/app/api/main.py b/backend/app/api/main.py index 0062448dc..75ddad991 100644 --- a/backend/app/api/main.py +++ b/backend/app/api/main.py @@ -15,7 +15,6 @@ documents, evaluations, features, - fine_tuning, guardrails, languages, llm, @@ -23,7 +22,6 @@ llm_sts, login, model_config, - model_evaluation, onboarding, organization, project, @@ -58,7 +56,6 @@ api_router.include_router(duplicate_detection.router) api_router.include_router(evaluations.router) api_router.include_router(features.router) -api_router.include_router(fine_tuning.router) api_router.include_router(languages.router) api_router.include_router(llm.router) api_router.include_router(llm_chain.router) @@ -66,7 +63,6 @@ api_router.include_router(llm_sts.router) api_router.include_router(login.router) api_router.include_router(model_config.router) -api_router.include_router(model_evaluation.router) api_router.include_router(onboarding.router) api_router.include_router(organization.router) api_router.include_router(project.router) diff --git a/backend/app/api/routes/fine_tuning.py b/backend/app/api/routes/fine_tuning.py deleted file mode 100644 index 69f8951df..000000000 --- a/backend/app/api/routes/fine_tuning.py +++ /dev/null @@ -1,446 +0,0 @@ -from typing import Optional -import logging -import time -from uuid import UUID, uuid4 -from pathlib import Path - -import openai -from sqlmodel import Session -from fastapi import ( - APIRouter, - HTTPException, - BackgroundTasks, - File, - Form, - UploadFile, - Depends, -) - -from app.models import ( - FineTuningJobCreate, - FineTuningJobPublic, - FineTuningUpdate, - FineTuningStatus, - Document, - ModelEvaluationBase, - ModelEvaluationStatus, -) -from app.core.cloud import get_cloud_storage -from app.crud.document.document import DocumentCrud -from app.utils import ( - get_openai_client, - handle_openai_error, - mask_string, - load_description, - APIResponse, -) -from app.crud import ( - create_fine_tuning_job, - fetch_by_id, - update_finetune_job, - fetch_by_document_id, - create_model_evaluation, - fetch_active_model_evals, -) -from app.core.db import engine -from app.api.deps import AuthContextDep, SessionDep -from app.api.permissions import Permission, require_permission -from app.core.finetune.preprocessing import DataPreprocessor -from app.api.routes.model_evaluation import run_model_evaluation - -logger = logging.getLogger(__name__) - -router = APIRouter(prefix="/fine_tuning", tags=["Fine Tuning"]) - - -OPENAI_TO_INTERNAL_STATUS = { - "validating_files": FineTuningStatus.running, - "queued": FineTuningStatus.running, - "running": FineTuningStatus.running, - "succeeded": FineTuningStatus.completed, - "failed": FineTuningStatus.failed, - "cancelled": FineTuningStatus.cancelled, -} - - -def process_fine_tuning_job( - job_id: int, - ratio: float, - current_user: AuthContextDep, - request: FineTuningJobCreate, -): - start_time = time.time() - project_id = current_user.project_.id - fine_tune = None - - logger.info( - f"[process_fine_tuning_job]Starting fine-tuning job processing | job_id={job_id}, project_id={project_id}|" - ) - with Session(engine) as session: - try: - fine_tune = fetch_by_id(session, job_id, project_id) - - client = get_openai_client( - session, current_user.organization_.id, project_id - ) - storage = get_cloud_storage( - session=session, project_id=current_user.project_.id - ) - document_crud = DocumentCrud(session, current_user.project_.id) - document = document_crud.read_one(request.document_id) - preprocessor = DataPreprocessor( - document, storage, ratio, request.system_prompt - ) - result = preprocessor.process() - train_data_temp_filepath = result["train_jsonl_temp_filepath"] - train_data_s3_object = result["train_csv_s3_object"] - test_data_s3_object = result["test_csv_s3_object"] - - try: - with open(train_data_temp_filepath, "rb") as train_f: - uploaded_train = client.files.create( - file=train_f, purpose="fine-tune" - ) - logger.info( - f"[process_fine_tuning_job] File uploaded to OpenAI successfully | " - f"job_id={job_id}, project_id={project_id}|" - ) - except openai.OpenAIError as e: - error_msg = handle_openai_error(e) - logger.error( - f"[process_fine_tuning_job] Failed to upload to OpenAI: {error_msg} | " - f"job_id={job_id}, project_id={project_id}|" - ) - update_finetune_job( - session=session, - job=fine_tune, - update=FineTuningUpdate( - status=FineTuningStatus.failed, - error_message="Error while uploading file to openai : " - + error_msg, - ), - ) - return - finally: - preprocessor.cleanup() - - training_file_id = uploaded_train.id - - try: - job = client.fine_tuning.jobs.create( - training_file=training_file_id, model=request.base_model - ) - logger.info( - f"[process_fine_tuning_job] OpenAI fine-tuning job created | " - f"provider_job_id={mask_string(job.id)}, job_id={job_id}, project_id={project_id}|" - ) - except openai.OpenAIError as e: - error_msg = handle_openai_error(e) - logger.error( - f"[process_fine_tuning_job] Failed to create OpenAI fine-tuning job: {error_msg} | " - f"job_id={job_id}, project_id={project_id}|" - ) - update_finetune_job( - session=session, - job=fine_tune, - update=FineTuningUpdate( - status=FineTuningStatus.failed, - error_message="Error while creating an openai fine tuning job : " - + error_msg, - ), - ) - return - - update_finetune_job( - session=session, - job=fine_tune, - update=FineTuningUpdate( - training_file_id=training_file_id, - train_data_s3_object=train_data_s3_object, - test_data_s3_object=test_data_s3_object, - split_ratio=ratio, - provider_job_id=job.id, - status=FineTuningStatus.running, - ), - ) - - end_time = time.time() - duration = end_time - start_time - - logger.info( - f"[process_fine_tuning_job] Fine-tuning job processed successfully | " - f"time_taken={duration:.2f}s, job_id={job_id}, project_id={project_id}|" - ) - - except Exception as e: - error_msg = str(e) - logger.error( - f"[process_fine_tuning_job] Background job failure: {e} | " - f"job_id={job_id}, project_id={project_id}|" - ) - update_finetune_job( - session=session, - job=fine_tune, - update=FineTuningUpdate( - status=FineTuningStatus.failed, - error_message="Error while processing the background job : " - + error_msg, - ), - ) - - -@router.post( - "/fine_tune", - description=load_description("fine_tuning/create.md"), - response_model=APIResponse, - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -async def fine_tune_from_CSV( - session: SessionDep, - current_user: AuthContextDep, - background_tasks: BackgroundTasks, - file: UploadFile = File(..., description="CSV file to use for fine-tuning"), - base_model: str = Form(...), - split_ratio: str = Form(...), - system_prompt: str = Form(...), -): - # Parse split ratios - try: - split_ratios = [float(r.strip()) for r in split_ratio.split(",")] - except ValueError as e: - raise HTTPException(status_code=400, detail=f"Invalid split_ratio format: {e}") - - # Validate file is CSV - if not file.filename.lower().endswith(".csv") and file.content_type != "text/csv": - raise HTTPException(status_code=400, detail="File must be a CSV file") - - get_openai_client( # Used here only to validate the user's OpenAI key; - # the actual client is re-initialized separately inside the background task - session, - current_user.organization_.id, - current_user.project_.id, - ) - - # Upload the file to storage and create document - # ToDo: create a helper function and then use it rather than doing things in router - storage = get_cloud_storage(session=session, project_id=current_user.project_.id) - document_id = uuid4() - object_store_url = storage.put(file, Path(str(document_id))) - - # Create document in database - document_crud = DocumentCrud(session, current_user.project_.id) - document = Document( - id=document_id, - fname=file.filename, - object_store_url=str(object_store_url), - ) - created_document = document_crud.update(document) - - # Create FineTuningJobCreate request object - request = FineTuningJobCreate( - document_id=created_document.id, - base_model=base_model, - split_ratio=split_ratios, - system_prompt=system_prompt.strip(), - ) - - results = [] - - for ratio in split_ratios: - job, created = create_fine_tuning_job( - session=session, - request=request, - split_ratio=ratio, - organization_id=current_user.organization_.id, - project_id=current_user.project_.id, - ) - results.append((job, created)) - - if created: - background_tasks.add_task( - process_fine_tuning_job, job.id, ratio, current_user, request - ) - - if not results: - logger.error( - f"[fine_tune_from_CSV]All fine-tuning job creations failed for document_id={request.document_id}, project_id={current_user.project_.id}" - ) - raise HTTPException( - status_code=500, detail="Failed to create or fetch any fine-tuning jobs." - ) - - job_infos = [ - { - "id": job.id, - "document_id": job.document_id, - "split_ratio": job.split_ratio, - "status": job.status, - } - for job, _ in results - ] - - created_count = sum(c for _, c in results) - total = len(results) - message = ( - "Fine-tuning job(s) started." - if created_count == total - else "Active fine-tuning job(s) already exists." - if created_count == 0 - else f"Started {created_count} job(s); {total - created_count} active fine-tuning job(s) already exists." - ) - - return APIResponse.success_response({"message": message, "jobs": job_infos}) - - -@router.get( - "/{fine_tuning_id}/refresh", - description=load_description("fine_tuning/retrieve.md"), - response_model=APIResponse[FineTuningJobPublic], - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def refresh_fine_tune_status( - fine_tuning_id: int, - background_tasks: BackgroundTasks, - session: SessionDep, - current_user: AuthContextDep, -): - project_id = current_user.project_.id - job = fetch_by_id(session, fine_tuning_id, project_id) - client = get_openai_client(session, current_user.organization_.id, project_id) - storage = get_cloud_storage(session=session, project_id=current_user.project_.id) - - if job.provider_job_id is not None: - try: - openai_job = client.fine_tuning.jobs.retrieve(job.provider_job_id) - except openai.OpenAIError as e: - error_msg = handle_openai_error(e) - logger.error( - f"[Retrieve_fine_tune_status] Failed to retrieve OpenAI job | " - f"provider_job_id={mask_string(job.provider_job_id)}, " - f"error={error_msg}, fine_tuning_id={fine_tuning_id}, project_id={project_id}" - ) - raise HTTPException( - status_code=502, detail=f"OpenAI API error: {error_msg}" - ) - - mapped_status: Optional[str] = OPENAI_TO_INTERNAL_STATUS.get( - getattr(openai_job, "status", None) - ) - - openai_error = getattr(openai_job, "error", None) - openai_error_msg = ( - getattr(openai_error, "message", None) if openai_error else None - ) - - update_payload = FineTuningUpdate( - status=mapped_status or job.status, - fine_tuned_model=getattr(openai_job, "fine_tuned_model", None), - error_message=openai_error_msg, - ) - - # Check if status is changing from running to completed - is_newly_completed = ( - job.status == FineTuningStatus.running - and update_payload.status == FineTuningStatus.completed - ) - - if ( - job.status != update_payload.status - or job.fine_tuned_model != update_payload.fine_tuned_model - or job.error_message != update_payload.error_message - ): - job = update_finetune_job(session=session, job=job, update=update_payload) - - # If the job just completed, automatically trigger evaluation - if is_newly_completed: - logger.info( - f"[refresh_fine_tune_status] Fine-tuning job completed, triggering evaluation | " - f"fine_tuning_id={fine_tuning_id}, project_id={project_id}" - ) - - # Check if there's already an active evaluation for this job - active_evaluations = fetch_active_model_evals( - session, fine_tuning_id, project_id - ) - - if not active_evaluations: - # Create a new evaluation - model_eval = create_model_evaluation( - session=session, - request=ModelEvaluationBase(fine_tuning_id=fine_tuning_id), - project_id=project_id, - organization_id=current_user.organization_.id, - status=ModelEvaluationStatus.pending, - ) - - # Queue the evaluation task - background_tasks.add_task( - run_model_evaluation, model_eval.id, current_user - ) - - logger.info( - f"[refresh_fine_tune_status] Created and queued evaluation | " - f"eval_id={model_eval.id}, fine_tuning_id={fine_tuning_id}, project_id={project_id}" - ) - else: - logger.info( - f"[refresh_fine_tune_status] Skipping evaluation creation - active evaluation exists | " - f"fine_tuning_id={fine_tuning_id}, project_id={project_id}" - ) - - job = job.model_copy( - update={ - "train_data_file_url": storage.get_signed_url(job.train_data_s3_object) - if job.train_data_s3_object - else None, - "test_data_file_url": storage.get_signed_url(job.test_data_s3_object) - if job.test_data_s3_object - else None, - } - ) - - return APIResponse.success_response(job) - - -@router.get( - "/{document_id}", - description="Retrieves all fine-tuning jobs associated with the given document ID for the current project", - response_model=APIResponse[list[FineTuningJobPublic]], - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def retrieve_jobs_by_document( - document_id: UUID, session: SessionDep, current_user: AuthContextDep -): - storage = get_cloud_storage(session=session, project_id=current_user.project_.id) - project_id = current_user.project_.id - jobs = fetch_by_document_id(session, document_id, project_id) - if not jobs: - logger.warning( - f"[retrive_job_by_document]No fine-tuning jobs found for document_id={document_id}, project_id={project_id}" - ) - raise HTTPException( - status_code=404, - detail="No fine-tuning jobs found for the given document ID", - ) - updated_jobs = [] - for job in jobs: - train_url = ( - storage.get_signed_url(job.train_data_s3_object) - if job.train_data_s3_object - else None - ) - test_url = ( - storage.get_signed_url(job.test_data_s3_object) - if job.test_data_s3_object - else None - ) - - updated_job = job.model_copy( - update={ - "train_data_file_url": train_url, - "test_data_file_url": test_url, - } - ) - updated_jobs.append(updated_job) - - return APIResponse.success_response(updated_jobs) diff --git a/backend/app/api/routes/model_evaluation.py b/backend/app/api/routes/model_evaluation.py deleted file mode 100644 index 40ed0d173..000000000 --- a/backend/app/api/routes/model_evaluation.py +++ /dev/null @@ -1,261 +0,0 @@ -import logging -import time -from uuid import UUID - -from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends -from sqlmodel import Session - -from app.crud import ( - fetch_by_id, - create_model_evaluation, - fetch_active_model_evals, - fetch_eval_by_doc_id, - update_model_eval, - fetch_top_model_by_doc_id, -) -from app.models import ( - ModelEvaluationBase, - ModelEvaluationCreate, - ModelEvaluationStatus, - ModelEvaluationUpdate, - ModelEvaluationPublic, -) -from app.core.db import engine -from app.core.cloud import get_cloud_storage -from app.core.finetune.evaluation import ModelEvaluator -from app.utils import get_openai_client, APIResponse, load_description -from app.api.deps import AuthContextDep, SessionDep -from app.api.docs.model_evaluation.examples import MODEL_EVALUATION_CREATE_EXAMPLES -from app.api.openapi_docs import request_examples -from app.api.permissions import Permission, require_permission - - -logger = logging.getLogger(__name__) - -router = APIRouter(prefix="/model_evaluation", tags=["Model Evaluation"]) - - -def attach_prediction_file_url(model_obj, storage): - """ - Given a model-like object and a storage client, - attach a signed prediction data file URL (if available). - """ - s3_key = getattr(model_obj, "prediction_data_s3_object", None) - prediction_data_file_url = storage.get_signed_url(s3_key) if s3_key else None - - return model_obj.model_copy( - update={"prediction_data_file_url": prediction_data_file_url} - ) - - -def run_model_evaluation( - eval_id: int, - current_user: AuthContextDep, -): - start_time = time.time() - logger.info( - f"[run_model_evaluation] Starting | eval_id={eval_id}, project_id={current_user.project_.id}" - ) - - with Session(engine) as db: - client = get_openai_client( - db, current_user.organization_.id, current_user.project_.id - ) - storage = get_cloud_storage(session=db, project_id=current_user.project_.id) - - try: - model_eval = update_model_eval( - session=db, - eval_id=eval_id, - project_id=current_user.project_.id, - update=ModelEvaluationUpdate(status=ModelEvaluationStatus.running), - ) - - evaluator = ModelEvaluator( - fine_tuned_model=model_eval.fine_tuned_model, - test_data_s3_object=model_eval.test_data_s3_object, - system_prompt=model_eval.system_prompt, - client=client, - storage=storage, - ) - result = evaluator.run() - - update_model_eval( - session=db, - eval_id=eval_id, - project_id=current_user.project_.id, - update=ModelEvaluationUpdate( - score=result["evaluation_score"], - prediction_data_s3_object=result["prediction_data_s3_object"], - status=ModelEvaluationStatus.completed, - ), - ) - - elapsed = time.time() - start_time - logger.info( - f"[run_model_evaluation] Completed | eval_id={eval_id}, project_id={current_user.project_.id}, elapsed={elapsed:.2f}s" - ) - - except Exception as e: - error_msg = str(e) - logger.error( - f"[run_model_evaluation] Failed | eval_id={eval_id}, project_id={current_user.project_.id}: {e}" - ) - db.rollback() - update_model_eval( - session=db, - eval_id=eval_id, - project_id=current_user.project_.id, - update=ModelEvaluationUpdate( - status=ModelEvaluationStatus.failed, - error_message="failed during background job processing:" - + error_msg, - ), - ) - - -@router.post( - "/evaluate_models", - response_model=APIResponse, - description=load_description("model_evaluation/evaluate.md"), - openapi_extra=request_examples(MODEL_EVALUATION_CREATE_EXAMPLES), - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def evaluate_models( - request: ModelEvaluationCreate, - background_tasks: BackgroundTasks, - session: SessionDep, - current_user: AuthContextDep, -): - """ - Start evaluations for one or more fine-tuning jobs. - - Request:{ fine_tuning_ids: list[int] } (one or many). - - Process: - For each ID, it fetches the fine-tuned model and its testing file from fine tuning table, - then queues a background task that runs predictions on the test set - and computes evaluation scores. - - Response: - APIResponse with the created/active evaluation records and a success message. - """ - client = get_openai_client( - session, current_user.organization_.id, current_user.project_.id - ) # keeping this here for checking if the user's validated OpenAI key is present or not, - # even though the client will be initialized separately inside the background task - - if not request.fine_tuning_ids: - logger.warning( - f"[evaluate_model] No fine tuning IDs provided | project_id:{current_user.project_.id}" - ) - raise HTTPException(status_code=400, detail="No fine-tuned job IDs provided") - - evaluations: list[ModelEvaluationPublic] = [] - - for job_id in request.fine_tuning_ids: - fine_tuning_job = fetch_by_id(session, job_id, current_user.project_.id) - active_evaluations = fetch_active_model_evals( - session, job_id, current_user.project_.id - ) - - if active_evaluations: - logger.info( - f"[evaluate_model] Skipping creation for {job_id}. Active evaluation exists, project_id:{current_user.project_.id}" - ) - evaluations.extend( - ModelEvaluationPublic.model_validate(ev) for ev in active_evaluations - ) - continue - - model_eval = create_model_evaluation( - session=session, - request=ModelEvaluationBase(fine_tuning_id=fine_tuning_job.id), - project_id=current_user.project_.id, - organization_id=current_user.organization_.id, - status=ModelEvaluationStatus.pending, - ) - - evaluations.append(ModelEvaluationPublic.model_validate(model_eval)) - - logger.info( - f"[evaluate_model] Created evaluation for fine_tuning_id {job_id} with eval ID={model_eval.id}, project_id:{current_user.project_.id}" - ) - - background_tasks.add_task(run_model_evaluation, model_eval.id, current_user) - - response_data = [ - { - "id": ev.id, - "fine_tuning_id": ev.fine_tuning_id, - "fine_tuned_model": getattr(ev, "fine_tuned_model", None), - "document_id": getattr(ev, "document_id", None), - "status": ev.status, - } - for ev in evaluations - ] - - return APIResponse.success_response( - {"message": "Model evaluation(s) started successfully", "data": response_data} - ) - - -@router.get( - "/{document_id}/top_model", - response_model=APIResponse[ModelEvaluationPublic], - response_model_exclude_none=True, - description=load_description("model_evaluation/get_top_model.md"), - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def get_top_model_by_doc_id( - document_id: UUID, - session: SessionDep, - current_user: AuthContextDep, -): - """ - Return the top model trained on the given document_id, ranked by - Matthews correlation coefficient (MCC) across all evaluations. - """ - logger.info( - f"[get_top_model_by_doc_id] Fetching top model for document_id={document_id}, " - f"project_id={current_user.project_.id}" - ) - - top_model = fetch_top_model_by_doc_id( - session, document_id, current_user.project_.id - ) - storage = get_cloud_storage(session=session, project_id=current_user.project_.id) - - top_model = attach_prediction_file_url(top_model, storage) - - return APIResponse.success_response(top_model) - - -@router.get( - "/{document_id}", - response_model=APIResponse[list[ModelEvaluationPublic]], - response_model_exclude_none=True, - description=load_description("model_evaluation/list_by_document.md"), - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def get_evaluations_by_doc_id( - document_id: UUID, - session: SessionDep, - current_user: AuthContextDep, -): - """ - Return all model evaluations for the given document_id within the current project. - """ - logger.info( - f"[get_evaluations_by_doc_id] Fetching evaluations for document_id={document_id}, " - f"project_id={current_user.project_.id}" - ) - - evaluations = fetch_eval_by_doc_id(session, document_id, current_user.project_.id) - storage = get_cloud_storage(session=session, project_id=current_user.project_.id) - - updated_evaluations = [ - attach_prediction_file_url(ev, storage) for ev in evaluations - ] - - return APIResponse.success_response(updated_evaluations) diff --git a/backend/app/core/finetune/evaluation.py b/backend/app/core/finetune/evaluation.py deleted file mode 100644 index 09ad38938..000000000 --- a/backend/app/core/finetune/evaluation.py +++ /dev/null @@ -1,263 +0,0 @@ -import difflib -import logging -import time -import uuid -from typing import Set - -import openai -import pandas as pd -from openai import OpenAI -from sklearn.metrics import matthews_corrcoef - -from app.core.cloud import AmazonCloudStorage -from app.core.finetune.preprocessing import DataPreprocessor -from app.utils import handle_openai_error - -logger = logging.getLogger(__name__) - - -class ModelEvaluator: - max_latency = 90 - retries = 3 - normalization_cutoff = 0.7 - - def __init__( - self, - fine_tuned_model: str, - test_data_s3_object: str, - storage: AmazonCloudStorage, - system_prompt: str, - client: OpenAI, - ): - self.fine_tuned_model = fine_tuned_model - self.test_data_s3_object = test_data_s3_object - self.storage = storage - self.system_instruction = system_prompt - self.client = client - - self.allowed_labels: Set[str] = set() - self.y_true: list[str] = [] - self.prompts: list[str] = [] - - logger.info(f"ModelEvaluator initialized with model: {fine_tuned_model}") - - def load_labels_and_prompts(self) -> None: - """ - Load prompts (X) and labels (y) from an S3-hosted CSV via storage.stream. - Expects: - - one of: 'query' | 'question' | 'message' - - 'label' - """ - logger.info( - f"[ModelEvaluator.load_labels_and_prompts] Loading CSV from: " - f"{self.test_data_s3_object}" - ) - file_obj = self.storage.stream(self.test_data_s3_object) - try: - df = pd.read_csv(file_obj) - df.columns = [c.strip().lower() for c in df.columns] - - possible_query_columns = ["query", "question", "message"] - query_col = next( - (c for c in possible_query_columns if c in df.columns), None - ) - label_col = "label" if "label" in df.columns else None - - if not query_col or not label_col: - logger.warning( - "[ModelEvaluator.load_labels_and_prompts] CSV must " - "contain a 'label' column and one of: " - f"{possible_query_columns}" - ) - raise ValueError( - f"CSV must contain a 'label' column and one of: " - f"{possible_query_columns}" - ) - - prompts = df[query_col].astype(str).tolist() - labels = df[label_col].astype(str).str.strip().str.lower().tolist() - - self.prompts = prompts - self.y_true = labels - self.allowed_labels = set(labels) - - self.query_col = query_col - self.label_col = label_col - - logger.info( - "[ModelEvaluator.load_labels_and_prompts] " - f"Loaded {len(self.prompts)} prompts and " - f"{len(self.y_true)} labels; " - f"query_col={query_col}, label_col={label_col}, " - f"allowed_labels={self.allowed_labels}" - ) - except Exception as e: - logger.error( - f"[ModelEvaluator.load_labels_and_prompts] " - f"Failed to load/parse test CSV: {e}", - exc_info=True, - ) - raise - finally: - file_obj.close() - - def normalize_prediction(self, text: str) -> str: - logger.debug(f"[normalize_prediction] Normalizing prediction: {text}") - t = (text or "").strip().lower() - - if t in self.allowed_labels: - return t - - closest = difflib.get_close_matches( - t, self.allowed_labels, n=1, cutoff=self.normalization_cutoff - ) - if closest: - return closest[0] - - logger.warning( - f"[normalize_prediction] No close match found for '{t}'. " - f"Using default label '{next(iter(self.allowed_labels))}'." - ) - return next(iter(self.allowed_labels)) - - def generate_predictions(self) -> tuple[list[str], str]: - logger.info( - f"[generate_predictions] Generating predictions for " - f"{len(self.prompts)} prompts." - ) - start_preds = time.time() - predictions = [] - total_prompts = len(self.prompts) - - for idx, prompt in enumerate(self.prompts, 1): - attempt = 0 - while attempt < self.retries: - start_time = time.time() - logger.info( - f"[generate_predictions] Processing prompt " - f"{idx}/{total_prompts} " - f"(Attempt {attempt + 1}/{self.retries})" - ) - - try: - response = self.client.responses.create( - model=self.fine_tuned_model, - instructions=self.system_instruction, - input=prompt, - ) - - elapsed_time = time.time() - start_time - if elapsed_time > self.max_latency: - logger.warning( - f"[generate_predictions] Timeout exceeded for " - f"prompt {idx}/{total_prompts}. Retrying..." - ) - continue - - raw = response.output_text or "" - prediction = self.normalize_prediction(raw) - predictions.append(prediction) - break - - except openai.OpenAIError as e: - error_msg = handle_openai_error(e) - logger.error( - f"[generate_predictions] OpenAI API error at prompt " - f"{idx}/{total_prompts}: {error_msg}" - ) - attempt += 1 - if attempt == self.retries: - predictions.append("openai_error") - logger.error( - f"[generate_predictions] Maximum retries reached " - f"for prompt {idx}/{total_prompts}. " - f"Appending 'openai_error'." - ) - else: - logger.info( - f"[generate_predictions] Retrying prompt " - f"{idx}/{total_prompts} after OpenAI error " - f"({attempt}/{self.retries})." - ) - - total_elapsed = time.time() - start_preds - logger.info( - f"[generate_predictions] Finished {total_prompts} prompts in " - f"{total_elapsed:.2f}s | Generated {len(predictions)} " - f"predictions." - ) - - prediction_data = pd.DataFrame( - { - "prompt": self.prompts, - "true_label": self.y_true, - "prediction": predictions, - } - ) - - unique_id = uuid.uuid4().hex - filename = f"predictions_{self.fine_tuned_model}_{unique_id}.csv" - prediction_data_s3_object = DataPreprocessor.upload_csv_to_s3( - self.storage, prediction_data, filename - ) - self.prediction_data_s3_object = prediction_data_s3_object - - logger.info( - f"[generate_predictions] Predictions CSV uploaded to S3 | " - f"url={prediction_data_s3_object}" - ) - - return predictions, prediction_data_s3_object - - def evaluate(self) -> dict: - """Evaluate using the predictions CSV previously uploaded to S3.""" - if not getattr(self, "prediction_data_s3_object", None): - raise RuntimeError( - "[evaluate] predictions_s3_object not set. " - "Call generate_predictions() first." - ) - - logger.info( - f"[evaluate] Streaming predictions CSV from: " - f"{self.prediction_data_s3_object}" - ) - prediction_obj = self.storage.stream(self.prediction_data_s3_object) - try: - df = pd.read_csv(prediction_obj) - finally: - prediction_obj.close() - - if "true_label" not in df.columns or "prediction" not in df.columns: - raise ValueError( - "[evaluate] prediction data CSV must contain 'true_label' " - "and 'prediction' columns." - ) - - y_true = df["true_label"].astype(str).str.strip().str.lower().tolist() - y_pred = df["prediction"].astype(str).str.strip().str.lower().tolist() - - try: - mcc_score = round(matthews_corrcoef(y_true, y_pred), 4) - logger.info(f"[evaluate] Computed MCC={mcc_score}") - return {"mcc_score": mcc_score} - except Exception as e: - logger.error(f"[evaluate] Evaluation failed: {e}", exc_info=True) - raise - - def run(self) -> dict: - """Run the full evaluation process. - - Load data, generate predictions, and evaluate results. - """ - try: - self.load_labels_and_prompts() - predictions, prediction_data_s3_object = self.generate_predictions() - evaluation_results = self.evaluate() - logger.info("[evaluate] Model evaluation completed successfully.") - return { - "evaluation_score": evaluation_results, - "prediction_data_s3_object": prediction_data_s3_object, - } - except Exception as e: - logger.error(f"[evaluate] Error in running ModelEvaluator: {str(e)}") - raise diff --git a/backend/app/core/finetune/preprocessing.py b/backend/app/core/finetune/preprocessing.py deleted file mode 100644 index ff080c50c..000000000 --- a/backend/app/core/finetune/preprocessing.py +++ /dev/null @@ -1,157 +0,0 @@ -import os -import json -import uuid -import tempfile -import logging -import io - -from pathlib import Path -from fastapi import UploadFile -from starlette.datastructures import Headers -import pandas as pd -from sklearn.model_selection import train_test_split - -logger = logging.getLogger(__name__) - - -class DataPreprocessor: - RANDOM_STATE = 42 - - def __init__(self, document, storage, split_ratio: float, system_message: str): - self.document = document - self.storage = storage - self.split_ratio = split_ratio - self.query_col = None - self.label_col = None - self.generated_files = [] - - self.system_message = {"role": "system", "content": system_message.strip()} - - @staticmethod - def upload_csv_to_s3(storage, df, filename: str) -> str: - """ - Uploads a DataFrame as CSV to S3 using the provided storage instance. - """ - logger.info( - f"[upload_csv_to_s3] Preparing to upload '{filename}' to s3 | rows={len(df)}, cols={len(df.columns)}" - ) - - buf = io.BytesIO(df.to_csv(index=False).encode("utf-8")) - buf.seek(0) - - headers = Headers({"content-type": "text/csv"}) - upload = UploadFile( - filename=filename, - file=buf, - headers=headers, - ) - - try: - dest = storage.put(upload, file_path=Path("datasets") / filename) - logger.info( - f"[upload_csv_to_s3] Upload successful | filename='{filename}', s3_object='{dest}'" - ) - return str(dest) - except Exception as err: - logger.error( - f"[upload_csv_to_s3] Upload failed | filename='{filename}', error='{err}'", - exc_info=True, - ) - raise - - def _save_to_jsonl(self, data, filename): - temp_dir = tempfile.gettempdir() - file_path = os.path.join(temp_dir, filename) - with open(file_path, "w", encoding="utf-8") as f: - for record in data: - json.dump(record, f, ensure_ascii=False) - f.write("\n") - self.generated_files.append(file_path) - return file_path - - def cleanup(self): - for path in self.generated_files: - if os.path.exists(path): - os.remove(path) - self.generated_files = [] - - def _modify_data_format(self, data): - modified_data = [] - for record in data: - user_message = {"role": "user", "content": record[self.query_col]} - assistant_message = {"role": "assistant", "content": record[self.label_col]} - modified_record = { - "messages": [self.system_message, user_message, assistant_message] - } - modified_data.append(modified_record) - return modified_data - - def _load_dataframe(self): - logger.info(f"Loading CSV from: {self.document.object_store_url}") - f_obj = self.storage.stream(self.document.object_store_url) - try: - f_obj.name = self.document.fname - df = pd.read_csv(f_obj) - df.columns = [col.strip().lower() for col in df.columns] - - possible_query_columns = ["query", "question", "message"] - self.query_col = next( - (col for col in possible_query_columns if col in df.columns), None - ) - self.label_col = "label" if "label" in df.columns else None - - if not self.query_col or not self.label_col: - logger.warning( - f"[DataPreprocessor] Dataset does not contain a 'label' column and one of: {possible_query_columns}" - ) - raise ValueError( - f"CSV must contain a 'label' column and one of: {possible_query_columns}" - ) - - logger.info( - f"[DataPreprocessor] Identified columns - query_col={self.query_col}, label_col={self.label_col}" - ) - return df - finally: - f_obj.close() - - def process(self): - logger.info("Starting data preprocessing") - df = self._load_dataframe() - - train_data, test_data = train_test_split( - df, - test_size=1 - self.split_ratio, - stratify=df[self.label_col], - random_state=self.RANDOM_STATE, - ) - - logger.info( - f"[DataPreprocessor] Data split complete: train_size={len(train_data)}, test_size={len(test_data)}" - ) - - train_dict = train_data.to_dict(orient="records") - train_jsonl = self._modify_data_format(train_dict) - - unique_id = uuid.uuid4().hex - train_percentage = int(self.split_ratio * 100) # train % - test_percentage = ( - 100 - train_percentage - ) # remaining % for test (since we used 1 - ratio earlier for test size) - - train_csv_name = f"train_split_{train_percentage}_{unique_id}.csv" - test_csv_name = f"test_split_{test_percentage}_{unique_id}.csv" - train_jsonl_name = f"train_data_{train_percentage}_{unique_id}.jsonl" - - train_csv_object = self.upload_csv_to_s3( - self.storage, train_data, train_csv_name - ) - test_csv_object = self.upload_csv_to_s3(self.storage, test_data, test_csv_name) - - train_jsonl_path = self._save_to_jsonl(train_jsonl, train_jsonl_name) - - return { - "train_csv_s3_object": train_csv_object, - "test_csv_s3_object": test_csv_object, - "train_jsonl_temp_filepath": train_jsonl_path, - } diff --git a/backend/app/crud/__init__.py b/backend/app/crud/__init__.py index 2d12199cc..1752b99dd 100644 --- a/backend/app/crud/__init__.py +++ b/backend/app/crud/__init__.py @@ -50,24 +50,6 @@ delete_assistant, ) -from .fine_tuning import ( - create_fine_tuning_job, - fetch_by_id, - fetch_by_provider_job_id, - fetch_by_document_id, - update_finetune_job, - fetch_active_jobs_by_document_id, -) - -from .model_evaluation import ( - create_model_evaluation, - fetch_active_model_evals, - fetch_by_eval_id, - fetch_eval_by_doc_id, - fetch_top_model_by_doc_id, - update_model_eval, -) - from .onboarding import onboard_project from .user_project import ( diff --git a/backend/app/crud/fine_tuning.py b/backend/app/crud/fine_tuning.py deleted file mode 100644 index 369520a81..000000000 --- a/backend/app/crud/fine_tuning.py +++ /dev/null @@ -1,182 +0,0 @@ -from uuid import UUID -import logging -from typing import Optional - -from sqlmodel import Session, select -from fastapi import HTTPException - -from app.core.util import now -from app.models import ( - FineTuning, - FineTuningJobCreate, - FineTuningUpdate, - FineTuningStatus, -) -from app.crud import DocumentCrud - -logger = logging.getLogger(__name__) - - -def create_fine_tuning_job( - session: Session, - request: FineTuningJobCreate, - split_ratio: float, - status: FineTuningStatus = FineTuningStatus.pending, - project_id: int = None, - organization_id: int = None, -) -> tuple[FineTuning, bool]: - active_jobs = fetch_active_jobs_by_document_id( - session=session, - document_id=request.document_id, - project_id=project_id, - split_ratio=split_ratio, - base_model=request.base_model, - ) - if active_jobs: - existing = active_jobs[0] - logger.info( - f"[Create_fine_tuning_job]Active fine-tune job exists; returning it. document_id={request.document_id}, split_ratio={split_ratio}, base_model={request.base_model}, project_id={project_id}" - ) - return existing, False - - document_crud = DocumentCrud( - session, project_id - ) # to check if the given document is present in the document table or not - document = document_crud.read_one(request.document_id) - - fine_tune_data = request.model_dump(exclude_unset=True) - base_data = { - **fine_tune_data, - "split_ratio": split_ratio, - "project_id": project_id, - "organization_id": organization_id, - "status": status, - } - - fine_tune = FineTuning(**base_data) - fine_tune.updated_at = now() - - session.add(fine_tune) - session.commit() - session.refresh(fine_tune) - - logger.info( - f"[Create_fine_tuning_job]Created new fine-tuning job ID={fine_tune.id}, project_id={project_id}" - ) - return fine_tune, True - - -def fetch_by_provider_job_id( - session: Session, provider_job_id: str, project_id: int -) -> FineTuning: - job = session.exec( - select(FineTuning).where( - FineTuning.provider_job_id == provider_job_id, - FineTuning.project_id == project_id, - ) - ).one_or_none() - - if job is None: - logger.warning( - f"Fine-tune job not found for openai_job_id={provider_job_id}, project_id={project_id}" - ) - raise HTTPException(status_code=404, detail="OpenAI fine tuning ID not found") - - return job - - -def fetch_by_id(session: Session, job_id: int, project_id: int) -> FineTuning: - job = session.exec( - select(FineTuning).where( - FineTuning.id == job_id, FineTuning.project_id == project_id - ) - ).one_or_none() - - if job is None: - logger.warning( - f"[fetch_by_id]Fine-tune job not found: job_id={job_id}, project_id={project_id}" - ) - raise HTTPException(status_code=404, detail="Job not found") - - logger.info( - f"[fetch_by_id]Fetched fine-tune job ID={job.id}, project_id={project_id}" - ) - return job - - -def fetch_by_document_id( - session: Session, - document_id: UUID, - project_id: int, - split_ratio: float = None, - base_model: Optional[str] = None, -) -> list[FineTuning]: - query = select(FineTuning).where( - FineTuning.document_id == document_id, FineTuning.project_id == project_id - ) - - if split_ratio is not None: - query = query.where(FineTuning.split_ratio == split_ratio) - if base_model is not None: - query = query.where(FineTuning.base_model == base_model) - - jobs = session.exec(query).all() - logger.info( - f"[fetch_by_document_id]Found {len(jobs)} fine-tune jobs for document_id={document_id}, project_id={project_id}" - ) - return jobs - - -def fetch_active_jobs_by_document_id( - session: Session, - document_id: UUID, - project_id: int, - split_ratio: Optional[float] = None, - base_model: Optional[str] = None, - exclude_job_id: Optional[int] = None, -) -> list["FineTuning"]: - """ - Return all ACTIVE jobs for the given document & project. - Active = status != failed AND not soft-deleted. - """ - stmt = ( - select(FineTuning) - .where( - FineTuning.document_id == document_id, - FineTuning.project_id == project_id, - FineTuning.deleted_at.is_(None), - FineTuning.status != FineTuningStatus.failed, - ) - .order_by(FineTuning.inserted_at.desc()) - ) - - if split_ratio is not None: - stmt = stmt.where(FineTuning.split_ratio == split_ratio) - - if base_model is not None: - stmt = stmt.where(FineTuning.base_model == base_model) - - if exclude_job_id is not None: - stmt = stmt.where(FineTuning.id != exclude_job_id) - - return session.exec(stmt).all() - - -def update_finetune_job( - session: Session, - job: FineTuning, - update: FineTuningUpdate, -) -> FineTuning: - for key, value in update.model_dump(exclude_unset=True).items(): - setattr(job, key, value) - - job.updated_at = now() - - session.add(job) - session.commit() - session.refresh(job) - - logger.info( - f"[update_finetune_job]Updated fine-tune job ID={job.id}, project_id={job.project_id}" - ) - return job diff --git a/backend/app/crud/model_evaluation.py b/backend/app/crud/model_evaluation.py deleted file mode 100644 index f5d7b0e2d..000000000 --- a/backend/app/crud/model_evaluation.py +++ /dev/null @@ -1,185 +0,0 @@ -import logging -from uuid import UUID - -from fastapi import HTTPException -from sqlalchemy import Float, cast -from sqlmodel import Session, select - -from app.crud import fetch_by_id -from app.models import ( - ModelEvaluation, - ModelEvaluationStatus, - ModelEvaluationBase, - ModelEvaluationUpdate, -) -from app.core.util import now - - -logger = logging.getLogger(__name__) - - -def create_model_evaluation( - session: Session, - request: ModelEvaluationBase, - project_id: int, - organization_id: int, - status: ModelEvaluationStatus = ModelEvaluationStatus.pending, -) -> ModelEvaluation: - fine_tuning_job = fetch_by_id(session, request.fine_tuning_id, project_id) - - if fine_tuning_job.fine_tuned_model and fine_tuning_job.test_data_s3_object is None: - logger.warning( - f"[create_model_evaluation] No fine tuned model or test data found for the given fine tuning ID | fine_tuning_id={request.fine_tuning_id}, project_id={project_id}" - ) - raise HTTPException(404, "Fine tuned model not found") - - base_data = { - "fine_tuning_id": request.fine_tuning_id, - "system_prompt": fine_tuning_job.system_prompt, - "base_model": fine_tuning_job.base_model, - "split_ratio": fine_tuning_job.split_ratio, - "fine_tuned_model": fine_tuning_job.fine_tuned_model, - "document_id": fine_tuning_job.document_id, - "test_data_s3_object": fine_tuning_job.test_data_s3_object, - "project_id": project_id, - "organization_id": organization_id, - "status": status, - } - - model_eval = ModelEvaluation(**base_data) - model_eval.updated_at = now() - - session.add(model_eval) - session.commit() - session.refresh(model_eval) - - logger.info( - f"[Create_fine_tuning_job]Created new model evaluation from fine tuning job ID={fine_tuning_job.id}, project_id={project_id}" - ) - return model_eval - - -def fetch_by_eval_id( - session: Session, eval_id: int, project_id: int -) -> ModelEvaluation: - model_eval = session.exec( - select(ModelEvaluation).where( - ModelEvaluation.id == eval_id, ModelEvaluation.project_id == project_id - ) - ).one_or_none() - - if model_eval is None: - raise HTTPException(status_code=404, detail="Model evaluation not found") - - logger.info( - f"[fetch_by_id]Fetched model evaluation for eval ID={model_eval.id}, project_id={project_id}" - ) - return model_eval - - -def fetch_eval_by_doc_id( - session: Session, - document_id: UUID, - project_id: int, -) -> list[ModelEvaluation]: - query = ( - select(ModelEvaluation) - .where( - ModelEvaluation.document_id == document_id, - ModelEvaluation.project_id == project_id, - ) - .order_by(ModelEvaluation.updated_at.desc()) - ) - - model_evals = session.exec(query).all() - - if not model_evals: - raise HTTPException(status_code=404, detail="Model evaluation not found") - - logger.info( - f"[fetch_eval_by_doc_id]Found {len(model_evals)} model evaluation(s) for document_id={document_id}, " - f"project_id={project_id}" - ) - - return model_evals - - -def fetch_top_model_by_doc_id( - session: Session, document_id: UUID, project_id: int -) -> ModelEvaluation: - mcc_expr = cast(ModelEvaluation.score["mcc_score"].astext, Float) - - stmt = ( - select(ModelEvaluation) - .where( - ModelEvaluation.document_id == document_id, - ModelEvaluation.project_id == project_id, - ModelEvaluation.deleted_at.is_(None), - ModelEvaluation.score.is_not(None), - mcc_expr.is_not(None), - ) - .order_by(mcc_expr.desc()) - .limit(1) - ) - - top_model = session.exec(stmt).first() - - if not top_model: - logger.warning( - f"[fetch_top_model_by_doc_id]No model evaluation found with populated score for document_id={document_id}, project_id={project_id}" - ) - raise HTTPException(status_code=404, detail="No top model found") - - logger.info( - f"[fetch_top_model_by_doc_id]Found top model evaluation for document_id={document_id}, " - f"project_id={project_id}, sorted by MCC" - ) - - return top_model - - -def fetch_active_model_evals( - session: Session, - fine_tuning_id: int, - project_id: int, -) -> list["ModelEvaluation"]: - """ - Return all ACTIVE model evaluations for the given document & project. - Active = status != failed AND not soft-deleted. - """ - stmt = ( - select(ModelEvaluation) - .where( - ModelEvaluation.fine_tuning_id == fine_tuning_id, - ModelEvaluation.project_id == project_id, - ModelEvaluation.deleted_at.is_(None), - ModelEvaluation.status != "failed", - ) - .order_by(ModelEvaluation.inserted_at.desc()) - ) - - return session.exec(stmt).all() - - -def update_model_eval( - session: Session, eval_id: int, project_id: int, update: ModelEvaluationUpdate -) -> ModelEvaluation: - model_eval = fetch_by_eval_id(session, eval_id, project_id) - - logger.info( - f"[update_model_eval] Updating model evaluation ID={model_eval.id} with status={update.status}" - ) - - for key, value in update.model_dump(exclude_unset=True).items(): - setattr(model_eval, key, value) - - model_eval.updated_at = now() - - session.add(model_eval) - session.commit() - session.refresh(model_eval) - - logger.info( - f"[update_model_eval] Successfully updated model evaluation ID={model_eval.id}" - ) - return model_eval diff --git a/backend/app/crud/organization.py b/backend/app/crud/organization.py index 5254e1d5a..0c1756ef2 100644 --- a/backend/app/crud/organization.py +++ b/backend/app/crud/organization.py @@ -118,7 +118,7 @@ def hard_delete_organization( ) -> list[int]: """ Permanently delete an organization and everything owned by it — projects, - collections, documents, credentials, assistants, fine-tunings, + collections, documents, credentials, assistants, and user-project mappings all cascade away. This cannot be undone. User *accounts* are still never deleted (a user may belong to other orgs): diff --git a/backend/app/crud/project.py b/backend/app/crud/project.py index 76edf9fc3..e5269594b 100644 --- a/backend/app/crud/project.py +++ b/backend/app/crud/project.py @@ -163,7 +163,7 @@ def soft_delete_project(*, session: Session, project: Project) -> list[int]: def hard_delete_project(*, session: Session, project: Project) -> list[int]: """ Permanently delete a project and everything owned by it — collections, - documents, credentials, assistants, fine-tunings, and + documents, credentials, assistants, and user-project mappings all cascade away. This cannot be undone. User *accounts* are still never deleted (a user may belong to other diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 9766412aa..01b91f759 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -142,14 +142,6 @@ FeatureFlagUpdate, ) from .file import AudioUploadResponse, File, FilePublic, FileType -from .fine_tuning import ( - FineTuning, - FineTuningJobBase, - FineTuningJobCreate, - FineTuningJobPublic, - FineTuningStatus, - FineTuningUpdate, -) from .job import Job, JobStatus, JobType, JobUpdate from .language import ( Language, @@ -179,14 +171,6 @@ ModelConfigPublic, ModelConfigUpdate, ) -from .model_evaluation import ( - ModelEvaluation, - ModelEvaluationBase, - ModelEvaluationCreate, - ModelEvaluationPublic, - ModelEvaluationStatus, - ModelEvaluationUpdate, -) from .notification import ( Notification, NotificationEntityType, diff --git a/backend/app/models/fine_tuning.py b/backend/app/models/fine_tuning.py deleted file mode 100644 index fa46d4084..000000000 --- a/backend/app/models/fine_tuning.py +++ /dev/null @@ -1,181 +0,0 @@ -from datetime import datetime -from enum import Enum -from uuid import UUID - -from pydantic import field_validator -from sqlalchemy import Column, Text -from sqlmodel import Field, Relationship, SQLModel - -from app.core.util import now -from app.models.project import Project - - -class FineTuningStatus(str, Enum): - pending = "pending" - running = "running" - completed = "completed" - failed = "failed" - cancelled = "cancelled" - - -class FineTuningJobBase(SQLModel): - base_model: str = Field(nullable=False, description="Base model for fine-tuning") - split_ratio: float = Field(nullable=False) - document_id: UUID = Field(foreign_key="document.id", nullable=False) - training_file_id: str | None = Field(default=None) - system_prompt: str = Field(sa_column=Column(Text, nullable=False)) - - -class FineTuningJobCreate(SQLModel): - document_id: UUID - base_model: str - split_ratio: list[float] - system_prompt: str - - @field_validator("split_ratio") - @classmethod - def check_ratios(cls, v): - if not v: - raise ValueError("split_ratio cannot be empty") - for ratio in v: - if not (0 < ratio < 1): - raise ValueError( - f"Invalid split_ratio: {ratio}. Must be between 0 and 1." - ) - return v - - @field_validator("system_prompt") - @classmethod - def check_prompt(cls, v): - if not v.strip(): - raise ValueError("system_prompt must be a non-empty string") - return v.strip() - - -class FineTuning(FineTuningJobBase, table=True): - """Database model for tracking fine-tuning jobs.""" - - __tablename__ = "fine_tuning" - - id: int = Field( - primary_key=True, - sa_column_kwargs={"comment": "Unique identifier for the fine-tuning job"}, - ) - base_model: str = Field( - nullable=False, - description="Base model for fine-tuning", - sa_column_kwargs={"comment": "Base model used for fine-tuning"}, - ) - split_ratio: float = Field( - nullable=False, - sa_column_kwargs={"comment": "Train/test split ratio for the dataset"}, - ) - training_file_id: str | None = Field( - default=None, - sa_column_kwargs={"comment": "OpenAI training file identifier"}, - ) - system_prompt: str = Field( - sa_column=Column( - Text, nullable=False, comment="System prompt used during fine-tuning" - ) - ) - provider_job_id: str | None = Field( - default=None, - description="Fine tuning Job ID returned by OpenAI", - sa_column_kwargs={"comment": "Fine-tuning job ID returned by the provider"}, - ) - status: FineTuningStatus = Field( - default=FineTuningStatus.pending, - description="Fine tuning status", - sa_column_kwargs={"comment": "Current status of the fine-tuning job"}, - ) - fine_tuned_model: str | None = Field( - default=None, - description="Final fine tuned model name from OpenAI", - sa_column_kwargs={"comment": "Name of the resulting fine-tuned model"}, - ) - train_data_s3_object: str | None = Field( - default=None, - description="S3 URL of the training data stored in S3", - sa_column_kwargs={"comment": "S3 URL of the training data"}, - ) - test_data_s3_object: str | None = Field( - default=None, - description="S3 URL of the testing data stored in S3", - sa_column_kwargs={"comment": "S3 URL of the testing data"}, - ) - error_message: str | None = Field( - default=None, - description="Error message for when something failed", - sa_column_kwargs={"comment": "Error message if the job failed"}, - ) - # Foreign keys - document_id: UUID = Field( - foreign_key="document.id", - nullable=False, - ondelete="CASCADE", - sa_column_kwargs={"comment": "Reference to the training document"}, - ) - project_id: int = Field( - foreign_key="project.id", - nullable=False, - ondelete="CASCADE", - sa_column_kwargs={"comment": "Reference to the project"}, - ) - organization_id: int = Field( - foreign_key="organization.id", - nullable=False, - ondelete="CASCADE", - sa_column_kwargs={"comment": "Reference to the organization"}, - ) - - # Timestamps - inserted_at: datetime = Field( - default_factory=now, - nullable=False, - sa_column_kwargs={"comment": "Timestamp when the job was created"}, - ) - updated_at: datetime = Field( - default_factory=now, - nullable=False, - sa_column_kwargs={"comment": "Timestamp when the job was last updated"}, - ) - deleted_at: datetime | None = Field( - default=None, - nullable=True, - sa_column_kwargs={"comment": "Timestamp when the job was deleted"}, - ) - - # Relationships - project: Project = Relationship(back_populates="fine_tuning") - model_evaluation: "ModelEvaluation" = Relationship(back_populates="fine_tuning") - - -class FineTuningUpdate(SQLModel): - training_file_id: str | None = None - train_data_s3_object: str | None = None - test_data_s3_object: str | None = None - split_ratio: float | None = None - provider_job_id: str | None = None - fine_tuned_model: str | None = None - status: str | None = None - error_message: str | None = None - - -class FineTuningJobPublic(SQLModel): - """Public response model with job status and metadata.""" - - id: int - split_ratio: float - base_model: str - document_id: UUID - provider_job_id: str | None = None - train_data_file_url: str | None = None - test_data_file_url: str | None = None - status: str - error_message: str | None = None - fine_tuned_model: str | None = None - training_file_id: str | None = None - - inserted_at: datetime - updated_at: datetime diff --git a/backend/app/models/model_evaluation.py b/backend/app/models/model_evaluation.py deleted file mode 100644 index 6879eb6c7..000000000 --- a/backend/app/models/model_evaluation.py +++ /dev/null @@ -1,160 +0,0 @@ -from datetime import datetime -from enum import Enum -from uuid import UUID - -from pydantic import field_validator -from sqlalchemy import Column, Text -from sqlalchemy.dialects.postgresql import JSON -from sqlmodel import Field, Relationship, SQLModel - -from app.core.util import now -from app.models.project import Project - - -class ModelEvaluationStatus(str, Enum): - pending = "pending" - running = "running" - completed = "completed" - failed = "failed" - - -class ModelEvaluationBase(SQLModel): - fine_tuning_id: int = Field( - foreign_key="fine_tuning.id", - nullable=False, - ondelete="CASCADE", - ) - - -class ModelEvaluationCreate(SQLModel): - fine_tuning_ids: list[int] - - @field_validator("fine_tuning_ids") - @classmethod - def dedupe_ids(cls, v: list[int]) -> list[int]: - return list(dict.fromkeys(v)) - - -class ModelEvaluation(ModelEvaluationBase, table=True): - """Database model for keeping a record of model evaluation.""" - - __tablename__ = "model_evaluation" - - id: int = Field( - primary_key=True, - sa_column_kwargs={"comment": "Unique identifier for the model evaluation"}, - ) - fine_tuned_model: str = Field( - description="Fine-tuned model name from OpenAI", - sa_column_kwargs={"comment": "Name of the fine-tuned model being evaluated"}, - ) - test_data_s3_object: str = Field( - description="S3 URI of the testing data stored in S3", - sa_column_kwargs={"comment": "S3 URI of the testing data"}, - ) - base_model: str = Field( - nullable=False, - description="Base model used for fine-tuning", - sa_column_kwargs={"comment": "Base model used for fine-tuning"}, - ) - split_ratio: float = Field( - nullable=False, - description="The ratio the dataset was divided in", - sa_column_kwargs={"comment": "Train/test split ratio used"}, - ) - system_prompt: str = Field( - description="System prompt used during evaluation", - sa_column=Column( - Text, nullable=False, comment="System prompt used during evaluation" - ), - ) - score: dict[str, float] | None = Field( - description="Evaluation scores per metric (e.g., {'mcc': 0.85})", - sa_column=Column( - JSON, nullable=True, comment="Evaluation scores per metric (e.g., MCC)" - ), - ) - prediction_data_s3_object: str | None = Field( - default=None, - description="S3 URL where the prediction data generated by the fine-tuned model is stored", - sa_column_kwargs={"comment": "S3 URL where the prediction data is stored"}, - ) - status: ModelEvaluationStatus = Field( - default=ModelEvaluationStatus.pending, - description="Current status of the evaluation", - sa_column_kwargs={"comment": "Current status of the evaluation"}, - ) - error_message: str | None = Field( - default=None, - description="Error message if evaluation failed", - sa_column_kwargs={"comment": "Error message if evaluation failed"}, - ) - # Foreign keys - fine_tuning_id: int = Field( - foreign_key="fine_tuning.id", - nullable=False, - ondelete="CASCADE", - sa_column_kwargs={"comment": "Reference to the fine-tuning job"}, - ) - document_id: UUID = Field( - foreign_key="document.id", - nullable=False, - ondelete="CASCADE", - sa_column_kwargs={"comment": "Reference to the evaluation document"}, - ) - project_id: int = Field( - foreign_key="project.id", - nullable=False, - ondelete="CASCADE", - sa_column_kwargs={"comment": "Reference to the project"}, - ) - organization_id: int = Field( - foreign_key="organization.id", - nullable=False, - ondelete="CASCADE", - sa_column_kwargs={"comment": "Reference to the organization"}, - ) - - # Timestamps - inserted_at: datetime = Field( - default_factory=now, - nullable=False, - sa_column_kwargs={"comment": "Timestamp when the evaluation was created"}, - ) - updated_at: datetime = Field( - default_factory=now, - nullable=False, - sa_column_kwargs={"comment": "Timestamp when the evaluation was last updated"}, - ) - deleted_at: datetime | None = Field( - default=None, - nullable=True, - sa_column_kwargs={"comment": "Timestamp when the evaluation was deleted"}, - ) - - # Relationships - project: Project = Relationship() - fine_tuning: "FineTuning" = Relationship(back_populates="model_evaluation") - - -class ModelEvaluationUpdate(SQLModel): - score: dict[str, float] | None = None - status: ModelEvaluationStatus | None = None - error_message: str | None = None - prediction_data_s3_object: str | None = None - - -class ModelEvaluationPublic(ModelEvaluationBase): - """Public response model for evaluation result.""" - - id: int - document_id: UUID - fine_tuned_model: str - split_ratio: float - base_model: str - prediction_data_file_url: str | None = None - score: dict[str, float] | None = None - status: ModelEvaluationStatus - - inserted_at: datetime - updated_at: datetime diff --git a/backend/app/models/project.py b/backend/app/models/project.py index 65652e21b..6b0000ea2 100644 --- a/backend/app/models/project.py +++ b/backend/app/models/project.py @@ -13,7 +13,6 @@ from .assistants import Assistant from .collection import Collection from .credentials import Credential - from .fine_tuning import FineTuning from .organization import Organization @@ -122,9 +121,6 @@ class Project(ProjectBase, table=True): collections: list["Collection"] = Relationship( back_populates="project", cascade_delete=True ) - fine_tuning: list["FineTuning"] = Relationship( - back_populates="project", cascade_delete=True - ) # Properties to return via API diff --git a/backend/app/tests/api/routes/test_fine_tuning.py b/backend/app/tests/api/routes/test_fine_tuning.py deleted file mode 100644 index 5654ce4f3..000000000 --- a/backend/app/tests/api/routes/test_fine_tuning.py +++ /dev/null @@ -1,457 +0,0 @@ -import io -from typing import Any -from unittest.mock import patch, MagicMock - -import pytest -from moto import mock_aws -from sqlmodel import Session -from fastapi.testclient import TestClient -import boto3 - -from app.tests.utils.test_data import create_test_fine_tuning_jobs -from app.tests.utils.utils import get_document -from app.models import ( - FineTuning, - FineTuningStatus, - ModelEvaluation, - ModelEvaluationStatus, -) -from app.core.config import settings - - -def create_file_mock(file_type): - counter = {"train": 0, "test": 0} - - def _side_effect(file=None, purpose=None): - if purpose == "fine-tune": - if "train" in file.name: - counter["train"] += 1 - return MagicMock(id=f"file_{counter['train']}") - elif "test" in file.name: - counter["test"] += 1 - return MagicMock(id=f"file_{counter['test']}") - - return _side_effect - - -@pytest.mark.usefixtures("client", "db", "user_api_key_header") -class TestCreateFineTuningJobAPI: - @mock_aws - def test_finetune_from_csv_multiple_split_ratio( - self, - client: TestClient, - db: Session, - user_api_key_header: dict[str, str], - ) -> None: - # Setup S3 bucket for moto - s3 = boto3.client("s3", region_name=settings.AWS_DEFAULT_REGION) - bucket_name = settings.AWS_S3_BUCKET_PREFIX - if settings.AWS_DEFAULT_REGION == "us-east-1": - s3.create_bucket(Bucket=bucket_name) - else: - s3.create_bucket( - Bucket=bucket_name, - CreateBucketConfiguration={ - "LocationConstraint": settings.AWS_DEFAULT_REGION - }, - ) - - # Create a test CSV file content - csv_content = "prompt,label\ntest1,label1\ntest2,label2\ntest3,label3" - - # Setup test files for preprocessing - for path in ["/tmp/train.jsonl", "/tmp/test.jsonl"]: - with open(path, "w") as f: - f.write('{"prompt": "test", "completion": "label"}') - - with patch( - "app.api.routes.fine_tuning.get_cloud_storage" - ) as mock_get_cloud_storage: - with patch( - "app.api.routes.fine_tuning.get_openai_client" - ) as mock_get_openai_client: - with patch( - "app.api.routes.fine_tuning.process_fine_tuning_job" - ) as mock_process_job: - mock_storage = MagicMock() - mock_storage.put.return_value = ( - f"s3://{settings.AWS_S3_BUCKET_PREFIX}/test.csv" - ) - mock_get_cloud_storage.return_value = mock_storage - - mock_openai = MagicMock() - mock_get_openai_client.return_value = mock_openai - - csv_file = io.BytesIO(csv_content.encode()) - response = client.post( - "/api/v1/fine_tuning/fine_tune", - files={"file": ("test.csv", csv_file, "text/csv")}, - data={ - "base_model": "gpt-4", - "split_ratio": "0.5,0.7,0.9", - "system_prompt": "you are a model able to classify", - }, - headers=user_api_key_header, - ) - - assert response.status_code == 200 - json_data = response.json() - assert json_data["success"] is True - assert json_data["data"]["message"] == "Fine-tuning job(s) started." - assert json_data["metadata"] is None - assert "jobs" in json_data["data"] - assert len(json_data["data"]["jobs"]) == 3 - - # Verify that the background task was called for each split ratio - assert mock_process_job.call_count == 3 - - jobs = db.query(FineTuning).all() - assert len(jobs) == 3 - - for job in jobs: - db.refresh(job) - assert ( - job.status == "pending" - ) # Since background processing is mocked, status remains pending - assert job.split_ratio in [0.5, 0.7, 0.9] - - -@pytest.mark.usefixtures("client", "db", "user_api_key_header") -@patch("app.api.routes.fine_tuning.get_openai_client") -class TestRetriveFineTuningJobAPI: - def test_retrieve_fine_tuning_job( - self, - mock_get_openai_client: Any, - client: TestClient, - db: Session, - user_api_key_header: dict[str, str], - ) -> None: - jobs, _ = create_test_fine_tuning_jobs(db, [0.3]) - job = jobs[0] - job.provider_job_id = "ftjob-mock_job_123" - db.flush() - - mock_openai_job = MagicMock( - status="succeeded", - fine_tuned_model="ft:gpt-4:custom-model", - error=None, - ) - - mock_openai = MagicMock() - mock_openai.fine_tuning.jobs.retrieve.return_value = mock_openai_job - mock_get_openai_client.return_value = mock_openai - - response = client.get( - f"/api/v1/fine_tuning/{job.id}/refresh", headers=user_api_key_header - ) - - assert response.status_code == 200 - json_data = response.json() - - assert json_data["data"]["status"] == "completed" - assert json_data["data"]["fine_tuned_model"] == "ft:gpt-4:custom-model" - assert json_data["data"]["id"] == job.id - - def test_retrieve_fine_tuning_job_failed( - self, - mock_get_openai_client: Any, - client: TestClient, - db: Session, - user_api_key_header: dict[str, str], - ) -> None: - jobs, _ = create_test_fine_tuning_jobs(db, [0.3]) - job = jobs[0] - job.provider_job_id = "ftjob-mock_job_123" - db.flush() - - mock_openai_job = MagicMock( - status="failed", - fine_tuned_model=None, - error=MagicMock(message="Invalid file format for openai fine tuning"), - ) - - mock_openai = MagicMock() - mock_openai.fine_tuning.jobs.retrieve.return_value = mock_openai_job - mock_get_openai_client.return_value = mock_openai - - response = client.get( - f"/api/v1/fine_tuning/{job.id}/refresh", headers=user_api_key_header - ) - - assert response.status_code == 200 - json_data = response.json() - assert json_data["data"]["status"] == "failed" - assert ( - json_data["data"]["error_message"] - == "Invalid file format for openai fine tuning" - ) - assert json_data["data"]["id"] == job.id - - -@pytest.mark.usefixtures("client", "db", "user_api_key_header") -class TestFetchJob: - def test_fetch_jobs_document( - self, client: TestClient, db: Session, user_api_key_header: dict[str, str] - ) -> None: - jobs, _ = create_test_fine_tuning_jobs(db, [0.3, 0.4]) - document = get_document(db, "dalgo_sample.json") - - response = client.get( - f"/api/v1/fine_tuning/{document.id}", headers=user_api_key_header - ) - assert response.status_code == 200 - json_data = response.json() - - assert json_data["success"] is True - assert json_data["metadata"] is None - assert len(json_data["data"]) == 2 - - job_ratios = sorted([job["split_ratio"] for job in json_data["data"]]) - assert job_ratios == sorted([0.3, 0.4]) - - for job in json_data["data"]: - assert job["document_id"] == str(document.id) - assert job["status"] == "pending" - - -@pytest.mark.usefixtures("client", "db", "user_api_key_header") -@patch("app.api.routes.fine_tuning.get_openai_client") -@patch("app.api.routes.fine_tuning.get_cloud_storage") -@patch("app.api.routes.fine_tuning.run_model_evaluation") -class TestAutoEvaluationTrigger: - """Test cases for automatic evaluation triggering when fine-tuning completes.""" - - def test_successful_auto_evaluation_trigger( - self, - mock_run_model_evaluation: Any, - mock_get_cloud_storage: Any, - mock_get_openai_client: Any, - client: TestClient, - db: Session, - user_api_key_header: dict[str, str], - ) -> None: - """Test that evaluation is automatically triggered when job status changes from running to completed.""" - jobs, _ = create_test_fine_tuning_jobs(db, [0.7]) - job = jobs[0] - job.status = FineTuningStatus.running - job.provider_job_id = "ftjob-mock_job_123" - # Add required fields for model evaluation - job.test_data_s3_object = f"{settings.AWS_S3_BUCKET_PREFIX}/test-data.csv" - job.system_prompt = "You are a helpful assistant" - db.add(job) - db.commit() - db.refresh(job) - - mock_storage = MagicMock() - mock_storage.get_signed_url.return_value = ( - "https://test.s3.amazonaws.com/signed-url" - ) - mock_get_cloud_storage.return_value = mock_storage - - mock_openai_job = MagicMock( - status="succeeded", - fine_tuned_model="ft:gpt-4:custom-model:12345", - error=None, - ) - mock_openai = MagicMock() - mock_openai.fine_tuning.jobs.retrieve.return_value = mock_openai_job - mock_get_openai_client.return_value = mock_openai - - response = client.get( - f"/api/v1/fine_tuning/{job.id}/refresh", headers=user_api_key_header - ) - - assert response.status_code == 200 - json_data = response.json() - assert json_data["data"]["status"] == "completed" - assert json_data["data"]["fine_tuned_model"] == "ft:gpt-4:custom-model:12345" - - mock_run_model_evaluation.assert_called_once() - call_args = mock_run_model_evaluation.call_args[0] - eval_id = call_args[0] - - model_eval = ( - db.query(ModelEvaluation).filter(ModelEvaluation.id == eval_id).first() - ) - assert model_eval is not None - assert model_eval.fine_tuning_id == job.id - assert model_eval.status == ModelEvaluationStatus.pending - - def test_skip_evaluation_when_already_exists( - self, - mock_run_model_evaluation: Any, - mock_get_cloud_storage: Any, - mock_get_openai_client: Any, - client: TestClient, - db: Session, - user_api_key_header: dict[str, str], - ) -> None: - """Test that evaluation is skipped when an active evaluation already exists.""" - jobs, _ = create_test_fine_tuning_jobs(db, [0.7]) - job = jobs[0] - job.status = FineTuningStatus.running - job.provider_job_id = "ftjob-mock_job_123" - job.test_data_s3_object = f"{settings.AWS_S3_BUCKET_PREFIX}/test-data.csv" - job.system_prompt = "You are a helpful assistant" - db.add(job) - db.commit() - - existing_eval = ModelEvaluation( - fine_tuning_id=job.id, - status=ModelEvaluationStatus.pending, - project_id=job.project_id, - organization_id=job.organization_id, - document_id=job.document_id, - fine_tuned_model="ft:gpt-4:test-model:123", - test_data_s3_object=f"{settings.AWS_S3_BUCKET_PREFIX}/test-data.csv", - base_model="gpt-4", - split_ratio=0.7, - system_prompt="You are a helpful assistant", - ) - db.add(existing_eval) - db.commit() - - mock_storage = MagicMock() - mock_storage.get_signed_url.return_value = ( - "https://test.s3.amazonaws.com/signed-url" - ) - mock_get_cloud_storage.return_value = mock_storage - - mock_openai_job = MagicMock( - status="succeeded", - fine_tuned_model="ft:gpt-4:custom-model:12345", - error=None, - ) - mock_openai = MagicMock() - mock_openai.fine_tuning.jobs.retrieve.return_value = mock_openai_job - mock_get_openai_client.return_value = mock_openai - - response = client.get( - f"/api/v1/fine_tuning/{job.id}/refresh", headers=user_api_key_header - ) - - assert response.status_code == 200 - json_data = response.json() - assert json_data["data"]["status"] == "completed" - - mock_run_model_evaluation.assert_not_called() - - evaluations = ( - db.query(ModelEvaluation) - .filter(ModelEvaluation.fine_tuning_id == job.id) - .all() - ) - assert len(evaluations) == 1 - assert evaluations[0].id == existing_eval.id - - def test_evaluation_not_triggered_for_non_completion_status_changes( - self, - mock_run_model_evaluation: Any, - mock_get_cloud_storage: Any, - mock_get_openai_client: Any, - client: TestClient, - db: Session, - user_api_key_header: dict[str, str], - ) -> None: - """Test that evaluation is not triggered for status changes other than to completed.""" - # Test Case 1: pending to running - jobs, _ = create_test_fine_tuning_jobs(db, [0.7]) - job = jobs[0] - job.status = FineTuningStatus.pending - job.provider_job_id = "ftjob-mock_job_123" - db.add(job) - db.commit() - - # Mock cloud storage - mock_storage = MagicMock() - mock_storage.get_signed_url.return_value = ( - "https://test.s3.amazonaws.com/signed-url" - ) - mock_get_cloud_storage.return_value = mock_storage - - mock_openai_job = MagicMock( - status="running", - fine_tuned_model=None, - error=None, - ) - mock_openai = MagicMock() - mock_openai.fine_tuning.jobs.retrieve.return_value = mock_openai_job - mock_get_openai_client.return_value = mock_openai - - response = client.get( - f"/api/v1/fine_tuning/{job.id}/refresh", headers=user_api_key_header - ) - - assert response.status_code == 200 - json_data = response.json() - assert json_data["data"]["status"] == "running" - mock_run_model_evaluation.assert_not_called() - - job.status = FineTuningStatus.running - db.add(job) - db.commit() - - mock_openai_job.status = "failed" - mock_openai_job.error = MagicMock(message="Training failed") - - response = client.get( - f"/api/v1/fine_tuning/{job.id}/refresh", headers=user_api_key_header - ) - - assert response.status_code == 200 - json_data = response.json() - assert json_data["data"]["status"] == "failed" - mock_run_model_evaluation.assert_not_called() - - def test_evaluation_not_triggered_for_already_completed_jobs( - self, - mock_run_model_evaluation: Any, - mock_get_cloud_storage: Any, - mock_get_openai_client: Any, - client: TestClient, - db: Session, - user_api_key_header: dict[str, str], - ) -> None: - """Test that evaluation is not triggered when refreshing an already completed job.""" - jobs, _ = create_test_fine_tuning_jobs(db, [0.7]) - job = jobs[0] - job.status = FineTuningStatus.completed - job.provider_job_id = "ftjob-mock_job_123" - job.fine_tuned_model = "ft:gpt-4:custom-model:12345" - db.add(job) - db.commit() - - # Mock cloud storage - mock_storage = MagicMock() - mock_storage.get_signed_url.return_value = ( - "https://test.s3.amazonaws.com/signed-url" - ) - mock_get_cloud_storage.return_value = mock_storage - - # Mock OpenAI response (job remains succeeded) - mock_openai_job = MagicMock( - status="succeeded", - fine_tuned_model="ft:gpt-4:custom-model:12345", - error=None, - ) - mock_openai = MagicMock() - mock_openai.fine_tuning.jobs.retrieve.return_value = mock_openai_job - mock_get_openai_client.return_value = mock_openai - - response = client.get( - f"/api/v1/fine_tuning/{job.id}/refresh", headers=user_api_key_header - ) - - assert response.status_code == 200 - json_data = response.json() - assert json_data["data"]["status"] == "completed" - - mock_run_model_evaluation.assert_not_called() - - # Verify no evaluations exist in database for this job - evaluations = ( - db.query(ModelEvaluation) - .filter(ModelEvaluation.fine_tuning_id == job.id) - .all() - ) - assert len(evaluations) == 0 diff --git a/backend/app/tests/api/routes/test_model_evaluation.py b/backend/app/tests/api/routes/test_model_evaluation.py deleted file mode 100644 index ea485678d..000000000 --- a/backend/app/tests/api/routes/test_model_evaluation.py +++ /dev/null @@ -1,121 +0,0 @@ -from typing import Any -from unittest.mock import patch - -from sqlmodel import Session -from fastapi.testclient import TestClient - -from app.tests.utils.test_data import ( - create_test_finetuning_job_with_extra_fields, - create_test_model_evaluation, -) - - -@patch("app.api.routes.model_evaluation.run_model_evaluation") -def test_evaluate_model( - mock_run_eval: Any, - client: TestClient, - db: Session, - user_api_key_header: dict[str, str], -) -> None: - fine_tuned, _ = create_test_finetuning_job_with_extra_fields(db, [0.5]) - body = {"fine_tuning_ids": [fine_tuned[0].id]} - - resp = client.post( - "/api/v1/model_evaluation/evaluate_models", - json=body, - headers=user_api_key_header, - ) - assert resp.status_code == 200, resp.text - - j = resp.json() - evals = j["data"]["data"] - assert len(evals) == 1 - assert evals[0]["status"] == "pending" - - mock_run_eval.assert_called_once() - assert mock_run_eval.call_args[0][0] == evals[0]["id"] - - -def test_evaluate_model_finetuning_not_found( - client: TestClient, user_api_key_header: dict[str, str] -) -> None: - invalid_fine_tune_id = 9999 - - body = {"fine_tuning_ids": [invalid_fine_tune_id]} - - response = client.post( - "/api/v1/model_evaluation/evaluate_models", - json=body, - headers=user_api_key_header, - ) - - assert response.status_code == 404 - json_data = response.json() - assert json_data["error"] == f"Job not found" - - -def test_top_model_by_doc( - client: TestClient, db: Session, user_api_key_header: dict[str, str] -) -> None: - model_evals = create_test_model_evaluation(db) - model_eval = model_evals[0] - - model_eval.score = { - "mcc_score": 0.85, - } - db.flush() - - response = client.get( - f"/api/v1/model_evaluation/{model_eval.document_id}/top_model", - headers=user_api_key_header, - ) - - assert response.status_code == 200 - json_data = response.json() - - assert json_data["data"]["score"] == { - "mcc_score": 0.85, - } - assert json_data["data"]["fine_tuned_model"] == model_eval.fine_tuned_model - assert json_data["data"]["document_id"] == str(model_eval.document_id) - - assert json_data["data"]["id"] == model_eval.id - - -def test_get_top_model_by_doc_id_no_score( - client: TestClient, db: Session, user_api_key_header: dict[str, str] -) -> None: - model_evals = create_test_model_evaluation(db) - - document_id = model_evals[0].document_id - - response = client.get( - f"/api/v1/model_evaluation/{document_id}/top_model", headers=user_api_key_header - ) - - assert response.status_code == 404 - - json_data = response.json() - assert json_data["error"] == "No top model found" - - -def test_get_evals_by_doc_id( - client: TestClient, db: Session, user_api_key_header: dict[str, str] -) -> None: - model_evals = create_test_model_evaluation(db) - document_id = model_evals[0].document_id - - response = client.get( - f"/api/v1/model_evaluation/{document_id}", headers=user_api_key_header - ) - - assert response.status_code == 200 - json_data = response.json() - - assert json_data["success"] is True - assert json_data["data"] is not None - assert len(json_data["data"]) == 2 - - evaluations = json_data["data"] - assert all(eval["document_id"] == str(document_id) for eval in evaluations) - assert all(eval["status"] == "pending" for eval in evaluations) diff --git a/backend/app/tests/crud/test_fine_tuning.py b/backend/app/tests/crud/test_fine_tuning.py deleted file mode 100644 index 5ac8d7548..000000000 --- a/backend/app/tests/crud/test_fine_tuning.py +++ /dev/null @@ -1,138 +0,0 @@ -import pytest -from sqlmodel import Session -from fastapi import HTTPException - -from app.models import FineTuningUpdate, FineTuningJobCreate, FineTuningStatus -from app.crud import ( - create_fine_tuning_job, - fetch_by_provider_job_id, - fetch_by_id, - fetch_by_document_id, - update_finetune_job, - fetch_active_jobs_by_document_id, -) -from app.tests.utils.test_data import create_test_fine_tuning_jobs -from app.tests.utils.utils import get_project, get_document - - -def test_create_fine_tuning_job(db: Session) -> None: - project = get_project(db, "Dalgo") - document = get_document(db, "dalgo_sample.json") - - job_request = FineTuningJobCreate( - document_id=document.id, - base_model="gpt-4", - split_ratio=[0.8, 0.2], - system_prompt="you are a model able to classify", - ) - - created_job, created = create_fine_tuning_job( - session=db, - request=job_request, - split_ratio=0.8, - project_id=project.id, - organization_id=project.organization_id, - ) - - assert created is True - assert created_job.id is not None - assert created_job.document_id == document.id - assert created_job.split_ratio == 0.8 - assert created_job.project_id == project.id - assert created_job.provider_job_id is None - - -def test_fetch_by_provider_job_id_success(db: Session) -> None: - jobs, _ = create_test_fine_tuning_jobs(db, ratios=[0.3]) - job = jobs[0] - - result = fetch_by_provider_job_id( - db, provider_job_id=job.provider_job_id, project_id=job.project_id - ) - assert result.id == job.id - - -def test_fetch_by_provider_job_id_not_found(db: Session) -> None: - with pytest.raises(HTTPException) as exc: - fetch_by_provider_job_id(db, "invalid_id", project_id=999) - assert exc.value.status_code == 404 - - -def test_fetch_by_id_success(db: Session) -> None: - jobs, _ = create_test_fine_tuning_jobs(db, ratios=[0.3, 0.4]) - job = jobs[0] - - result = fetch_by_id(db, job_id=job.id, project_id=job.project_id) - assert result.id == job.id - - -def test_fetch_by_id_not_found(db: Session) -> None: - with pytest.raises(HTTPException) as exc: - fetch_by_id(db, job_id=9999, project_id=1) - assert exc.value.status_code == 404 - - -def test_fetch_by_document_id_filters(db: Session) -> None: - jobs, _ = create_test_fine_tuning_jobs(db, ratios=[0.3, 0.4]) - job = jobs[0] - - results = fetch_by_document_id( - session=db, - document_id=job.document_id, - project_id=job.project_id, - split_ratio=job.split_ratio, - base_model=job.base_model, - ) - assert len(results) == 1 - assert results[0].id == job.id - - -def test_update_finetune_job(db: Session) -> None: - jobs, _ = create_test_fine_tuning_jobs(db, ratios=[0.3, 0.4]) - job = jobs[0] - - update = FineTuningUpdate(status="completed", fine_tuned_model="ft:gpt-4:custom") - updated_job = update_finetune_job(db, job=job, update=update) - - assert updated_job.status == "completed" - assert updated_job.fine_tuned_model == "ft:gpt-4:custom" - - -def test_fetch_active_jobs_by_document_id(db: Session) -> None: - project = get_project(db, "Dalgo") - document = get_document(db, "dalgo_sample.json") - - job_request = FineTuningJobCreate( - document_id=document.id, - base_model="gpt-4", - split_ratio=[0.3, 0.5, 0.7, 0.9], - system_prompt="you are a model good at classification", - ) - active_job, _ = create_fine_tuning_job( - db, - request=job_request, - split_ratio=0.3, - project_id=project.id, - organization_id=project.organization_id, - status=FineTuningStatus.running, - ) - - failed_job, _ = create_fine_tuning_job( - db, - request=job_request, - split_ratio=0.5, - project_id=project.id, - organization_id=project.organization_id, - status=FineTuningStatus.failed, - ) - - result = fetch_active_jobs_by_document_id( - session=db, - document_id=document.id, - project_id=project.id, - ) - - assert len(result) == 1 - assert result[0].id == active_job.id - assert result[0].status == FineTuningStatus.running - assert result[0].deleted_at is None diff --git a/backend/app/tests/crud/test_model_evaluation.py b/backend/app/tests/crud/test_model_evaluation.py deleted file mode 100644 index d4f47e0fd..000000000 --- a/backend/app/tests/crud/test_model_evaluation.py +++ /dev/null @@ -1,185 +0,0 @@ -from uuid import UUID - -import pytest -from sqlmodel import Session -from fastapi import HTTPException - -from app.core.util import now -from app.tests.utils.utils import get_project, get_non_existent_id -from app.tests.utils.test_data import ( - create_test_model_evaluation, - create_test_finetuning_job_with_extra_fields, -) -from app.models import ( - ModelEvaluation, - ModelEvaluationBase, - ModelEvaluationUpdate, - ModelEvaluationStatus, -) -from app.crud import ( - create_model_evaluation, - fetch_by_eval_id, - fetch_eval_by_doc_id, - fetch_top_model_by_doc_id, - fetch_active_model_evals, - update_model_eval, -) - - -def test_create_model_evaluation(db: Session) -> None: - project = get_project(db, "Dalgo") - - fine_tune_jobs, _ = create_test_finetuning_job_with_extra_fields(db, [0.5]) - fine_tune = fine_tune_jobs[0] - - job_request = ModelEvaluationBase( - fine_tuning_id=fine_tune.id, - system_prompt=fine_tune.system_prompt, - base_model=fine_tune.base_model, - fine_tuned_model=fine_tune.fine_tuned_model, - document_id=fine_tune.document_id, - test_data_s3_object=fine_tune.test_data_s3_object, - status="pending", - ) - - created_eval = create_model_evaluation( - session=db, - request=job_request, - project_id=project.id, - organization_id=project.organization_id, - ) - - assert created_eval.id is not None - assert created_eval.status == "pending" - assert created_eval.document_id == fine_tune.document_id - assert created_eval.fine_tuned_model == fine_tune.fine_tuned_model - assert created_eval.test_data_s3_object == fine_tune.test_data_s3_object - - -def test_fetch_by_eval_id_success(db: Session) -> None: - model_evals = create_test_model_evaluation(db) - model_eval = model_evals[0] - result = fetch_by_eval_id( - db, eval_id=model_eval.id, project_id=model_eval.project_id - ) - assert result.id == model_eval.id - - -def test_fetch_by_eval_id_not_found(db: Session) -> None: - with pytest.raises(HTTPException) as exc: - fetch_by_eval_id( - db, eval_id=get_non_existent_id(db, ModelEvaluation), project_id=1 - ) - assert exc.value.status_code == 404 - - -def test_fetch_eval_by_doc_id_success(db: Session) -> None: - model_evals = create_test_model_evaluation(db) - doc_id = model_evals[0].document_id - - result = fetch_eval_by_doc_id( - db, document_id=doc_id, project_id=model_evals[0].project_id - ) - assert len(result) > 0 - - -def test_fetch_eval_by_doc_id_not_found(db: Session) -> None: - valid_uuid = UUID("c5d479e2-66a5-40b8-aa76-4a2290b6d1f3") - with pytest.raises(HTTPException) as exc: - fetch_eval_by_doc_id(db, document_id=valid_uuid, project_id=1) - assert exc.value.status_code == 404 - - -def test_fetch_top_model_by_doc_id_success(db: Session) -> None: - model_evals = create_test_model_evaluation(db) - model_eval = model_evals[0] - model_eval.score = {"mcc_score": 0.8} - db.flush() - - doc_id = model_eval.document_id - - result = fetch_top_model_by_doc_id( - db, document_id=doc_id, project_id=model_evals[0].project_id - ) - assert result.id == model_eval.id - - -def test_fetch_top_model_by_doc_id_not_found(db: Session) -> None: - valid_uuid = UUID("c5d479e2-66a5-40b8-aa76-4a2290b6d1f3") - with pytest.raises(HTTPException) as exc: - fetch_top_model_by_doc_id(db, document_id=valid_uuid, project_id=1) - assert exc.value.status_code == 404 - - -def test_fetch_top_model_by_doc_id_picks_highest_mcc(db: Session) -> None: - model_evals = create_test_model_evaluation(db) - assert len(model_evals) >= 2 - assert model_evals[0].document_id == model_evals[1].document_id - - model_evals[0].score = {"mcc_score": 0.5} - model_evals[1].score = {"mcc_score": 0.9} - db.flush() - - result = fetch_top_model_by_doc_id( - db, - document_id=model_evals[0].document_id, - project_id=model_evals[0].project_id, - ) - assert result.id == model_evals[1].id - - -def test_fetch_top_model_by_doc_id_excludes_soft_deleted(db: Session) -> None: - model_evals = create_test_model_evaluation(db) - assert len(model_evals) >= 2 - assert model_evals[0].document_id == model_evals[1].document_id - - model_evals[0].score = {"mcc_score": 0.5} - model_evals[1].score = {"mcc_score": 0.9} - model_evals[1].deleted_at = now() - db.flush() - - result = fetch_top_model_by_doc_id( - db, - document_id=model_evals[0].document_id, - project_id=model_evals[0].project_id, - ) - assert result.id == model_evals[0].id - - -def test_fetch_active_model_evals(db: Session) -> None: - model_evals = create_test_model_evaluation(db) - active_evals = fetch_active_model_evals( - db, - fine_tuning_id=model_evals[0].fine_tuning_id, - project_id=model_evals[0].project_id, - ) - assert len(active_evals) > 0 - assert all(eval.status != "failed" for eval in active_evals) - - -def test_update_model_eval_success(db: Session) -> None: - model_evals = create_test_model_evaluation(db) - model_eval = model_evals[0] - - update = ModelEvaluationUpdate(status="completed") - updated_eval = update_model_eval( - db, eval_id=model_eval.id, project_id=model_eval.project_id, update=update - ) - - assert updated_eval.status == "completed" - assert updated_eval.updated_at is not None - - -def test_update_model_eval_not_found(db: Session) -> None: - project = get_project(db) - - with pytest.raises(HTTPException) as exc: - update_model_eval( - db, - eval_id=get_non_existent_id(db, ModelEvaluation), - project_id=project.id, - update=ModelEvaluationUpdate(status=ModelEvaluationStatus.completed), - ) - - assert exc.value.status_code == 404 - assert exc.value.detail == "Model evaluation not found" diff --git a/backend/app/tests/utils/test_data.py b/backend/app/tests/utils/test_data.py index 29678edad..0fa1132ea 100644 --- a/backend/app/tests/utils/test_data.py +++ b/backend/app/tests/utils/test_data.py @@ -5,8 +5,6 @@ from app.models.provider_credentials import Provider from app.crud import ( APIKeyCrud, - create_fine_tuning_job, - create_model_evaluation, create_organization, create_project, set_creds_for_org, @@ -23,11 +21,6 @@ CredsCreate, EvaluationDataset, EvaluationRun, - FineTuning, - FineTuningJobCreate, - ModelEvaluation, - ModelEvaluationBase, - ModelEvaluationStatus, Organization, OrganizationCreate, Project, @@ -187,78 +180,6 @@ def create_test_credential(db: Session) -> tuple[list[Credential], Project]: return (openai_credentials + langfuse_credentials, project) -def create_test_fine_tuning_jobs( - db: Session, - ratios: list[float], -) -> tuple[list[FineTuning], bool]: - project = get_project(db, "Dalgo") - document = get_document(db, "dalgo_sample.json") - jobs = [] - any_created = False - - for ratio in ratios: - job_request = FineTuningJobCreate( - document_id=document.id, - base_model="gpt-4o", - split_ratio=[ratio], - system_prompt="str", - ) - job, created = create_fine_tuning_job( - session=db, - request=job_request, - split_ratio=ratio, - project_id=project.id, - organization_id=project.organization_id, - ) - jobs.append(job) - if created: - any_created = True - - return jobs, any_created - - -def create_test_finetuning_job_with_extra_fields( - db: Session, - ratios: list[float], -) -> tuple[list[FineTuning], bool]: - jobs, _ = create_test_fine_tuning_jobs(db, ratios) - - if jobs: - for job in jobs: - job.test_data_s3_object = "test_data_s3_object_example" - job.fine_tuned_model = "fine_tuned_model_name" - - return jobs, True - - -def create_test_model_evaluation(db: Session) -> list[ModelEvaluation]: - fine_tune_jobs, _ = create_test_finetuning_job_with_extra_fields(db, [0.5, 0.7]) - - model_evaluations = [] - - for fine_tune in fine_tune_jobs: - request = ModelEvaluationBase( - fine_tuning_id=fine_tune.id, - system_prompt=fine_tune.system_prompt, - base_model=fine_tune.base_model, - fine_tuned_model=fine_tune.fine_tuned_model, - document_id=fine_tune.document_id, - test_data_s3_object=fine_tune.test_data_s3_object, - ) - - model_eval = create_model_evaluation( - session=db, - request=request, - project_id=fine_tune.project_id, - organization_id=fine_tune.organization_id, - status=ModelEvaluationStatus.pending, - ) - - model_evaluations.append(model_eval) - - return model_evaluations - - def create_test_config( db: Session, project_id: int | None = None, diff --git a/docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md b/docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md index 810813a1c..ba805b1b1 100644 --- a/docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md +++ b/docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md @@ -521,8 +521,7 @@ is DB + storage only; it never touches collections or the provider: - `DELETE /documents/{id}` sets `deleted_at` on the row. Bytes stay in S3. The document drops out of document endpoints and of `GET /collections/{id}?include_docs=true`. - `DELETE /documents/{id}/permanent` deletes the S3 object, then the row. Rows - that reference the document (legacy transformed documents, `fine_tuning`, - `model_evaluation`, `document_collection`) go via + that reference the document (legacy transformed documents, `document_collection`) go via `ON DELETE CASCADE`. Soft-deleted documents can be purged too. Collections that contain the document keep their vector stores and provider diff --git a/docs/wiki/domain-map.md b/docs/wiki/domain-map.md index 2c9390a3e..c997fe28d 100644 --- a/docs/wiki/domain-map.md +++ b/docs/wiki/domain-map.md @@ -36,13 +36,11 @@ APIKey → Organization, Project, User # programmatic access | STTSample / STTResult | stt_evaluation.py | Dataset, Run, File, Language | human annotation UI (logical) | | TTSResult | tts_evaluation.py | Run, Org, Project | human annotation UI (logical) | | Assessment / AssessmentRun | assessment.py | Config, AssessmentSubmission, BatchJob, Job, Org, Project | console UI (logical); webhook consumers (logical) | -| Document | document.py | Project, Document (parent) | DocumentCollection, FineTuning, ModelEvaluation | +| Document | document.py | Project, Document (parent) | DocumentCollection | | Collection | collection.py | Project | DocumentCollection, CollectionJob; provider vector stores (logical); rag chatbot turns search OpenAI collections by `knowledge_base_id` from the config (logical) | | DocumentCollection | document_collection.py | Document, Collection | RAG lookups (logical) | | CollectionJob | collection_job.py | Collection, Project | async collection create/delete (logical) | | File | file.py | Org, Project | STT samples; object storage keys (logical) | -| FineTuning | fine_tuning.py | Document, Org, Project | ModelEvaluation | -| ModelEvaluation | model_evaluation.py | FineTuning, Document, Org, Project | console UI (logical) | | Assistant | assistants.py | Org, Project | OpenAI assistants API (logical) | | OpenAIThread | threads.py | — | thread results read path (logical) | | Language | language.py (`global.languages`) | — | EvaluationDataset, EvaluationRun, STT |