From 953eeec5aaaa6854a9036f7f45a4e99b3bce1d6b Mon Sep 17 00:00:00 2001 From: Ayush <80516839+Ayush8923@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:46:13 +0530 Subject: [PATCH] chore(conversations): Remove the OpenAI Conversations module Remove the /openai-conversation read and delete endpoints, their CRUD, model, docs and tests, and the Project/Organization relationships. Migration 095 drops the openai_conversation table; its downgrade recreates the empty table as it stood at 094. --- .../095_drop_openai_conversation_table.py | 132 +++ .../api/docs/openai_conversation/delete.md | 3 - .../app/api/docs/openai_conversation/get.md | 3 - .../openai_conversation/get_by_ancestor_id.md | 3 - .../openai_conversation/get_by_response_id.md | 3 - .../app/api/docs/openai_conversation/list.md | 3 - backend/app/api/docs/openapi_config.py | 5 - backend/app/api/docs/organization/delete.md | 2 +- backend/app/api/docs/projects/delete.md | 2 +- backend/app/api/main.py | 2 - backend/app/api/routes/openai_conversation.py | 163 ---- backend/app/crud/__init__.py | 11 - backend/app/crud/openai_conversation.py | 188 ---- backend/app/crud/organization.py | 2 +- backend/app/crud/project.py | 2 +- backend/app/models/__init__.py | 6 - backend/app/models/openai_conversation.py | 157 ---- backend/app/models/organization.py | 4 - backend/app/models/project.py | 4 - .../api/routes/test_openai_conversation.py | 466 ---------- .../tests/crud/test_openai_conversation.py | 821 ------------------ docs/wiki/INDEX.md | 2 +- docs/wiki/domain-map.md | 1 - docs/wiki/modules/assistants.md | 8 +- 24 files changed, 140 insertions(+), 1853 deletions(-) create mode 100644 backend/app/alembic/versions/095_drop_openai_conversation_table.py delete mode 100644 backend/app/api/docs/openai_conversation/delete.md delete mode 100644 backend/app/api/docs/openai_conversation/get.md delete mode 100644 backend/app/api/docs/openai_conversation/get_by_ancestor_id.md delete mode 100644 backend/app/api/docs/openai_conversation/get_by_response_id.md delete mode 100644 backend/app/api/docs/openai_conversation/list.md delete mode 100644 backend/app/api/routes/openai_conversation.py delete mode 100644 backend/app/crud/openai_conversation.py delete mode 100644 backend/app/models/openai_conversation.py delete mode 100644 backend/app/tests/api/routes/test_openai_conversation.py delete mode 100644 backend/app/tests/crud/test_openai_conversation.py diff --git a/backend/app/alembic/versions/095_drop_openai_conversation_table.py b/backend/app/alembic/versions/095_drop_openai_conversation_table.py new file mode 100644 index 000000000..357551d85 --- /dev/null +++ b/backend/app/alembic/versions/095_drop_openai_conversation_table.py @@ -0,0 +1,132 @@ +"""drop openai_conversation + +Revision ID: 095 +Revises: 094 +Create Date: 2026-12-04 00:00:00.000000 + +The Responses API and OpenAI Conversations modules were removed, so nothing reads or +writes this table any more. Rows are lost on upgrade; downgrade restores the schema +as it stood at 094 (an empty table) so older code can boot, not the data. +""" + +import sqlalchemy as sa +from alembic import op + +revision = "095" +down_revision = "094" +branch_labels = None +depends_on = None + + +def upgrade(): + op.drop_table("openai_conversation") + + +def downgrade(): + op.create_table( + "openai_conversation", + sa.Column( + "id", + sa.Integer(), + nullable=False, + comment="Unique identifier for the conversation record", + ), + sa.Column( + "response_id", + sa.String(), + nullable=False, + comment="OpenAI response identifier", + ), + sa.Column( + "ancestor_response_id", + sa.String(), + nullable=False, + comment="Root response ID for conversation threading", + ), + sa.Column( + "previous_response_id", + sa.String(), + nullable=True, + comment="Previous response ID in the conversation chain", + ), + sa.Column( + "user_question", + sa.String(), + nullable=False, + comment="User's question or input text", + ), + sa.Column( + "response", + sa.String(), + nullable=True, + comment="Response generated by OpenAI", + ), + sa.Column( + "model", + sa.String(), + nullable=False, + comment="Model used to generate the response", + ), + sa.Column( + "assistant_id", + sa.String(), + nullable=True, + comment="OpenAI assistant identifier if used", + ), + 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 conversation was created", + ), + sa.Column( + "updated_at", + sa.DateTime(), + nullable=False, + comment="Timestamp when the conversation was last updated", + ), + sa.Column( + "deleted_at", + sa.DateTime(), + nullable=True, + comment="Timestamp when the conversation was deleted", + ), + sa.ForeignKeyConstraint( + ["organization_id"], ["organization.id"], ondelete="CASCADE" + ), + sa.ForeignKeyConstraint(["project_id"], ["project.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index( + "ix_openai_conversation_project_id", "openai_conversation", ["project_id"] + ) + op.create_index( + "ix_openai_conversation_response_project_active", + "openai_conversation", + ["response_id", "project_id"], + postgresql_where=sa.text("deleted_at IS NULL"), + ) + op.create_index( + "ix_openai_conversation_ancestor_project_inserted_at_active", + "openai_conversation", + ["ancestor_response_id", "project_id", sa.text("inserted_at DESC")], + postgresql_where=sa.text("deleted_at IS NULL"), + ) + op.create_index( + "ix_openai_conversation_project_inserted_at_active", + "openai_conversation", + ["project_id", sa.text("inserted_at DESC")], + postgresql_where=sa.text("deleted_at IS NULL"), + ) diff --git a/backend/app/api/docs/openai_conversation/delete.md b/backend/app/api/docs/openai_conversation/delete.md deleted file mode 100644 index 905c0b9d2..000000000 --- a/backend/app/api/docs/openai_conversation/delete.md +++ /dev/null @@ -1,3 +0,0 @@ -Delete a conversation by its ID. - -Performs a delete by marking the conversation as deleted. The conversation remains in the database but is hidden from listings. diff --git a/backend/app/api/docs/openai_conversation/get.md b/backend/app/api/docs/openai_conversation/get.md deleted file mode 100644 index 69b3413ad..000000000 --- a/backend/app/api/docs/openai_conversation/get.md +++ /dev/null @@ -1,3 +0,0 @@ -Get a single conversation by its ID. - -Returns conversation details for the specified conversation ID within the current project. diff --git a/backend/app/api/docs/openai_conversation/get_by_ancestor_id.md b/backend/app/api/docs/openai_conversation/get_by_ancestor_id.md deleted file mode 100644 index 2b1aa1cc0..000000000 --- a/backend/app/api/docs/openai_conversation/get_by_ancestor_id.md +++ /dev/null @@ -1,3 +0,0 @@ -Get a conversation by its ancestor response ID. - -Retrieves conversation details using the ancestor response ID for conversation chain lookup. diff --git a/backend/app/api/docs/openai_conversation/get_by_response_id.md b/backend/app/api/docs/openai_conversation/get_by_response_id.md deleted file mode 100644 index d75da7988..000000000 --- a/backend/app/api/docs/openai_conversation/get_by_response_id.md +++ /dev/null @@ -1,3 +0,0 @@ -Get a conversation by its OpenAI response ID. - -Retrieves conversation details using the OpenAI Responses API response ID for lookup. diff --git a/backend/app/api/docs/openai_conversation/list.md b/backend/app/api/docs/openai_conversation/list.md deleted file mode 100644 index 253cf3af7..000000000 --- a/backend/app/api/docs/openai_conversation/list.md +++ /dev/null @@ -1,3 +0,0 @@ -List all conversations in the current project. - -Returns paginated list of conversations with total count metadata for the current project. diff --git a/backend/app/api/docs/openapi_config.py b/backend/app/api/docs/openapi_config.py index 86b320b35..4d33f84a0 100644 --- a/backend/app/api/docs/openapi_config.py +++ b/backend/app/api/docs/openapi_config.py @@ -84,10 +84,6 @@ "Model Evaluation": ( "Evaluate fine-tuned models for a document and find the best-performing one." ), - "OpenAI Conversations": ( - "Read and delete stored OpenAI Responses conversations, looked up by id, " - "response id or ancestor response id." - ), "Assistants": ( "[**Deprecated**] OpenAI Assistant creation and management. This " "feature will be removed in a future version." @@ -171,7 +167,6 @@ "Assessment (Experimental)", "Fine Tuning", "Model Evaluation", - "OpenAI Conversations", "Assistants", "Threads", ], diff --git a/backend/app/api/docs/organization/delete.md b/backend/app/api/docs/organization/delete.md index bcaf2f66f..7b20f9437 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, conversations, 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, fine-tunings, 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 f107c8227..2df363532 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, conversations, 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, fine-tunings, 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 9e0594f18..a6e422cbf 100644 --- a/backend/app/api/main.py +++ b/backend/app/api/main.py @@ -26,7 +26,6 @@ model_config, model_evaluation, onboarding, - openai_conversation, organization, project, threads, @@ -71,7 +70,6 @@ api_router.include_router(model_config.router) api_router.include_router(model_evaluation.router) api_router.include_router(onboarding.router) -api_router.include_router(openai_conversation.router) api_router.include_router(organization.router) api_router.include_router(project.router) api_router.include_router(threads.router) diff --git a/backend/app/api/routes/openai_conversation.py b/backend/app/api/routes/openai_conversation.py deleted file mode 100644 index d7fb98d28..000000000 --- a/backend/app/api/routes/openai_conversation.py +++ /dev/null @@ -1,163 +0,0 @@ -from typing import Annotated - -from fastapi import APIRouter, Depends, Path, HTTPException, Query - -from app.api.deps import AuthContextDep, SessionDep -from app.api.permissions import Permission, require_permission -from app.crud import ( - get_conversation_by_id, - get_conversation_by_response_id, - get_conversation_by_ancestor_id, - get_conversations_by_project, - get_conversations_count_by_project, - delete_conversation, -) -from app.models import ( - OpenAIConversationPublic, -) -from app.utils import APIResponse, load_description - -router = APIRouter(prefix="/openai-conversation", tags=["OpenAI Conversations"]) - - -@router.get( - "/{conversation_id}", - response_model=APIResponse[OpenAIConversationPublic], - summary="Get a single conversation by its ID", - description=load_description("openai_conversation/get.md"), - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def get_conversation_route( - conversation_id: Annotated[int, Path(description="The conversation ID to fetch")], - session: SessionDep, - current_user: AuthContextDep, -): - """ - Fetch a single conversation by its ID. - """ - conversation = get_conversation_by_id( - session, conversation_id, current_user.project_.id - ) - if not conversation: - raise HTTPException( - status_code=404, detail=f"Conversation with ID {conversation_id} not found." - ) - return APIResponse.success_response(conversation) - - -@router.get( - "/response/{response_id}", - response_model=APIResponse[OpenAIConversationPublic], - summary="Get a conversation by its OpenAI response ID", - description=load_description("openai_conversation/get_by_response_id.md"), - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def get_conversation_by_response_id_route( - response_id: Annotated[str, Path(description="The OpenAI response ID to fetch")], - session: SessionDep, - current_user: AuthContextDep, -): - """ - Fetch a conversation by its OpenAI response ID. - """ - conversation = get_conversation_by_response_id( - session, response_id, current_user.project_.id - ) - if not conversation: - raise HTTPException( - status_code=404, - detail=f"Conversation with response ID {response_id} not found.", - ) - return APIResponse.success_response(conversation) - - -@router.get( - "/ancestor/{ancestor_response_id}", - response_model=APIResponse[OpenAIConversationPublic], - summary="Get a conversation by its ancestor response ID", - description=load_description("openai_conversation/get_by_ancestor_id.md"), - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def get_conversation_by_ancestor_id_route( - ancestor_response_id: Annotated[ - str, Path(description="The ancestor response ID to fetch") - ], - session: SessionDep, - current_user: AuthContextDep, -): - """ - Fetch a conversation by its ancestor response ID. - """ - conversation = get_conversation_by_ancestor_id( - session, ancestor_response_id, current_user.project_.id - ) - if not conversation: - raise HTTPException( - status_code=404, - detail=f"Conversation with ancestor response ID {ancestor_response_id} not found.", - ) - return APIResponse.success_response(conversation) - - -@router.get( - "", - response_model=APIResponse[list[OpenAIConversationPublic]], - summary="List all conversations in the current project", - description=load_description("openai_conversation/list.md"), - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def list_conversations_route( - session: SessionDep, - current_user: AuthContextDep, - skip: int = Query(0, ge=0, description="How many items to skip"), - limit: int = Query(100, ge=1, le=100, description="Maximum items to return"), -): - """ - List all conversations in the current project. - """ - conversations = get_conversations_by_project( - session=session, - project_id=current_user.project_.id, - skip=skip, # ← Pagination offset - limit=limit, # ← Page size - ) - - # Get total count for pagination metadata - total = get_conversations_count_by_project( - session=session, - project_id=current_user.project_.id, - ) - - return APIResponse.success_response( - data=conversations, metadata={"skip": skip, "limit": limit, "total": total} - ) - - -@router.delete( - "/{conversation_id}", - response_model=APIResponse, - description=load_description("openai_conversation/delete.md"), - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def delete_conversation_route( - conversation_id: Annotated[int, Path(description="Conversation ID to delete")], - session: SessionDep, - current_user: AuthContextDep, -): - """ - Soft delete a conversation by marking it as deleted. - """ - deleted_conversation = delete_conversation( - session=session, - conversation_id=conversation_id, - project_id=current_user.project_.id, - ) - - if not deleted_conversation: - raise HTTPException( - status_code=404, detail=f"Conversation with ID {conversation_id} not found." - ) - - return APIResponse.success_response( - data={"message": "Conversation deleted successfully."} - ) diff --git a/backend/app/crud/__init__.py b/backend/app/crud/__init__.py index 45954e15d..0d4cde1e3 100644 --- a/backend/app/crud/__init__.py +++ b/backend/app/crud/__init__.py @@ -51,17 +51,6 @@ delete_assistant, ) -from .openai_conversation import ( - get_ancestor_id_from_response, - get_conversation_by_id, - get_conversation_by_response_id, - get_conversation_by_ancestor_id, - get_conversations_by_project, - get_conversations_count_by_project, - create_conversation, - delete_conversation, -) - from .fine_tuning import ( create_fine_tuning_job, fetch_by_id, diff --git a/backend/app/crud/openai_conversation.py b/backend/app/crud/openai_conversation.py deleted file mode 100644 index 83f3316c4..000000000 --- a/backend/app/crud/openai_conversation.py +++ /dev/null @@ -1,188 +0,0 @@ -import logging -from typing import Optional -from sqlmodel import Session, select, func - -from app.models import OpenAIConversation, OpenAIConversationCreate -from app.core.util import now - -logger = logging.getLogger(__name__) - - -def get_conversation_by_id( - session: Session, conversation_id: int, project_id: int -) -> OpenAIConversation | None: - """ - Return a conversation by its ID and project. - """ - statement = select(OpenAIConversation).where( - OpenAIConversation.id == conversation_id, - OpenAIConversation.project_id == project_id, - OpenAIConversation.deleted_at.is_(None), - ) - result = session.exec(statement).first() - return result - - -def get_conversation_by_response_id( - session: Session, response_id: str, project_id: int -) -> OpenAIConversation | None: - """ - Return a conversation by its OpenAI response ID and project. - """ - statement = select(OpenAIConversation).where( - OpenAIConversation.response_id == response_id, - OpenAIConversation.project_id == project_id, - OpenAIConversation.deleted_at.is_(None), - ) - result = session.exec(statement).first() - return result - - -def get_conversation_by_ancestor_id( - session: Session, ancestor_response_id: str, project_id: int -) -> OpenAIConversation | None: - """ - Return the latest conversation by its ancestor response ID and project. - """ - statement = ( - select(OpenAIConversation) - .where( - OpenAIConversation.ancestor_response_id == ancestor_response_id, - OpenAIConversation.project_id == project_id, - OpenAIConversation.deleted_at.is_(None), - ) - .order_by(OpenAIConversation.inserted_at.desc()) - .limit(1) - ) - result = session.exec(statement).first() - return result - - -def get_ancestor_id_from_response( - session: Session, - current_response_id: str, - previous_response_id: str | None, - project_id: int, -) -> str: - """ - Set the ancestor_response_id based on previous_response_id. - - Logic: - 1. If previous_response_id is None, then ancestor_response_id = current_response_id - 2. If previous_response_id is not None, look in db for that ID - - If found, use that conversation's ancestor_id - - If not found, ancestor_response_id = previous_response_id - - Args: - session: Database session - current_response_id: The current response ID - previous_response_id: The previous response ID (can be None) - project_id: The project ID for scoping the search - - Returns: - str: The determined ancestor_response_id - """ - if previous_response_id is None: - # If previous_response_id is None, then ancestor_response_id = current_response_id - return current_response_id - - # If previous_response_id is not None, look in db for that ID - previous_conversation = get_conversation_by_response_id( - session=session, response_id=previous_response_id, project_id=project_id - ) - - if previous_conversation: - # If found, use that conversation's ancestor_id - return previous_conversation.ancestor_response_id - else: - # If not found, ancestor_response_id = previous_response_id - return previous_response_id - - -def get_conversations_count_by_project( - session: Session, - project_id: int, -) -> int: - """ - Return the total count of conversations for a given project. - """ - statement = select(func.count(OpenAIConversation.id)).where( - OpenAIConversation.project_id == project_id, - OpenAIConversation.deleted_at.is_(None), - ) - result = session.exec(statement).one() - return result - - -def get_conversations_by_project( - session: Session, - project_id: int, - skip: int = 0, - limit: int = 100, -) -> list[OpenAIConversation]: - """ - Return all conversations for a given project, with optional pagination. - """ - statement = ( - select(OpenAIConversation) - .where( - OpenAIConversation.project_id == project_id, - OpenAIConversation.deleted_at.is_(None), - ) - .order_by(OpenAIConversation.inserted_at.desc()) - .offset(skip) - .limit(limit) - ) - results = session.exec(statement).all() - return results - - -def create_conversation( - session: Session, - conversation: OpenAIConversationCreate, - project_id: int, - organization_id: int, -) -> OpenAIConversation: - """ - Create a new conversation in the database. - """ - db_conversation = OpenAIConversation( - **conversation.model_dump(), - project_id=project_id, - organization_id=organization_id, - ) - session.add(db_conversation) - session.commit() - session.refresh(db_conversation) - - logger.info( - f"Created conversation with response_id={db_conversation.response_id}, " - f"assistant_id={db_conversation.assistant_id}, project_id={project_id}" - ) - - return db_conversation - - -def delete_conversation( - session: Session, - conversation_id: int, - project_id: int, -) -> OpenAIConversation | None: - """ - Soft delete a conversation by marking it as deleted. - """ - db_conversation = get_conversation_by_id(session, conversation_id, project_id) - if not db_conversation: - return None - - db_conversation.deleted_at = now() - session.add(db_conversation) - session.commit() - session.refresh(db_conversation) - - logger.info( - f"Deleted conversation with id={conversation_id}, " - f"response_id={db_conversation.response_id}, project_id={project_id}" - ) - - return db_conversation diff --git a/backend/app/crud/organization.py b/backend/app/crud/organization.py index 60ef7691b..5254e1d5a 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, conversations, + collections, documents, credentials, assistants, fine-tunings, 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 72af8a621..76edf9fc3 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, conversations, and + documents, credentials, assistants, fine-tunings, 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 85e878bb1..bb8ef9dbe 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -204,12 +204,6 @@ NotificationType, ) from .onboarding import OnboardingRequest, OnboardingResponse -from .openai_conversation import ( - OpenAIConversation, - OpenAIConversationBase, - OpenAIConversationCreate, - OpenAIConversationPublic, -) from .organization import ( Organization, OrganizationCreate, diff --git a/backend/app/models/openai_conversation.py b/backend/app/models/openai_conversation.py deleted file mode 100644 index 297c8fea0..000000000 --- a/backend/app/models/openai_conversation.py +++ /dev/null @@ -1,157 +0,0 @@ -import re -from datetime import datetime - -from pydantic import field_validator -from sqlmodel import Field, Relationship, SQLModel - -from app.core.util import now -from app.models.organization import Organization -from app.models.project import Project - - -def validate_response_id_pattern(v: str) -> str: - """Shared validation function for response ID patterns""" - if v is None: - return v - if not re.match(r"^resp_[a-zA-Z0-9]{10,}$", v): - raise ValueError( - "response_id fields must follow pattern: resp_ followed by at least 10 alphanumeric characters" - ) - return v - - -class OpenAIConversationBase(SQLModel): - # usually follow the pattern of resp_688704e41190819db512c30568xxxxxxx - response_id: str = Field( - index=True, - min_length=10, - sa_column_kwargs={"comment": "OpenAI response identifier"}, - ) - ancestor_response_id: str = Field( - index=True, - description="Ancestor response ID for conversation threading", - sa_column_kwargs={"comment": "Root response ID for conversation threading"}, - ) - previous_response_id: str | None = Field( - default=None, - index=True, - description="Previous response ID in the conversation", - sa_column_kwargs={"comment": "Previous response ID in the conversation chain"}, - ) - user_question: str = Field( - description="User's question/input", - sa_column_kwargs={"comment": "User's question or input text"}, - ) - response: str | None = Field( - default=None, - description="AI response", - sa_column_kwargs={"comment": "Response generated by OpenAI"}, - ) - # there are models with small name like o1 and usually fine tuned models have long names - model: str = Field( - description="The model used for the response", - min_length=1, - max_length=150, - sa_column_kwargs={"comment": "Model used to generate the response"}, - ) - # usually follow the pattern of asst_WD9bumYqTtpSvxxxxx - assistant_id: str | None = Field( - default=None, - description="The assistant ID used", - min_length=10, - max_length=50, - sa_column_kwargs={"comment": "OpenAI assistant identifier if used"}, - ) - 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"}, - ) - - @field_validator("response_id", "ancestor_response_id", "previous_response_id") - @classmethod - def validate_response_ids(cls, v): - return validate_response_id_pattern(v) - - -class OpenAIConversation(OpenAIConversationBase, table=True): - """Stores OpenAI conversation history and responses.""" - - __tablename__ = "openai_conversation" - - id: int = Field( - default=None, - primary_key=True, - sa_column_kwargs={"comment": "Unique identifier for the conversation record"}, - ) - # Timestamps - inserted_at: datetime = Field( - default_factory=now, - nullable=False, - sa_column_kwargs={"comment": "Timestamp when the conversation was created"}, - ) - updated_at: datetime = Field( - default_factory=now, - nullable=False, - sa_column_kwargs={ - "comment": "Timestamp when the conversation was last updated" - }, - ) - deleted_at: datetime | None = Field( - default=None, - nullable=True, - sa_column_kwargs={"comment": "Timestamp when the conversation was deleted"}, - ) - - # Relationships - project: Project = Relationship(back_populates="openai_conversations") - organization: Organization = Relationship(back_populates="openai_conversations") - - -class OpenAIConversationCreate(SQLModel): - # usually follow the pattern of resp_688704e41190819db512c30568dcaebc0a42e02be2c2c49b - response_id: str = Field(min_length=10) - ancestor_response_id: str = Field( - description="Ancestor response ID for conversation threading" - ) - previous_response_id: str | None = Field( - default=None, description="Previous response ID in the conversation" - ) - user_question: str = Field(description="User's question/input", min_length=1) - response: str | None = Field(default=None, description="AI response") - # there are models with small name like o1 and usually fine tuned models have long names - model: str = Field( - description="The model used for the response", min_length=1, max_length=150 - ) - # usually follow the pattern of asst_WD9bumYqTtpSvxxxxx - assistant_id: str | None = Field( - default=None, - description="The assistant ID used", - min_length=10, - max_length=50, - ) - - @field_validator("response_id", "ancestor_response_id", "previous_response_id") - @classmethod - def validate_response_ids(cls, v): - return validate_response_id_pattern(v) - - -class OpenAIConversationPublic(OpenAIConversationBase): - """Public model for OpenAIConversation without sensitive fields""" - - id: int - inserted_at: datetime - updated_at: datetime - - class Config: - from_attributes = True - populate_by_name = True - use_enum_values = True diff --git a/backend/app/models/organization.py b/backend/app/models/organization.py index b9ff9a7f1..e2b520e03 100644 --- a/backend/app/models/organization.py +++ b/backend/app/models/organization.py @@ -9,7 +9,6 @@ from .assistants import Assistant from .collection import Collection from .credentials import Credential - from .openai_conversation import OpenAIConversation from .project import Project @@ -74,9 +73,6 @@ class Organization(OrganizationBase, table=True): assistants: list["Assistant"] = Relationship( back_populates="organization", cascade_delete=True ) - openai_conversations: list["OpenAIConversation"] = Relationship( - back_populates="organization", cascade_delete=True - ) # Properties to return via API diff --git a/backend/app/models/project.py b/backend/app/models/project.py index 67b5e88fa..65652e21b 100644 --- a/backend/app/models/project.py +++ b/backend/app/models/project.py @@ -14,7 +14,6 @@ from .collection import Collection from .credentials import Credential from .fine_tuning import FineTuning - from .openai_conversation import OpenAIConversation from .organization import Organization @@ -126,9 +125,6 @@ class Project(ProjectBase, table=True): fine_tuning: list["FineTuning"] = Relationship( back_populates="project", cascade_delete=True ) - openai_conversations: list["OpenAIConversation"] = Relationship( - back_populates="project", cascade_delete=True - ) # Properties to return via API diff --git a/backend/app/tests/api/routes/test_openai_conversation.py b/backend/app/tests/api/routes/test_openai_conversation.py deleted file mode 100644 index 2620d80b1..000000000 --- a/backend/app/tests/api/routes/test_openai_conversation.py +++ /dev/null @@ -1,466 +0,0 @@ -from sqlmodel import Session -from fastapi.testclient import TestClient - -from app.crud.openai_conversation import create_conversation -from app.models import OpenAIConversationCreate -from app.tests.utils.llm_provider import generate_openai_id -from app.tests.utils.auth import TestAuthContext - - -def test_get_conversation_success( - client: TestClient, - db: Session, - user_api_key: TestAuthContext, -) -> None: - """Test successful conversation retrieval.""" - - response_id = generate_openai_id("resp_", 40) - conversation_data = OpenAIConversationCreate( - response_id=response_id, - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="What is the capital of France?", - response="The capital of France is Paris.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=user_api_key.project_id, - organization_id=user_api_key.organization_id, - ) - response = client.get( - f"/api/v1/openai-conversation/{conversation.id}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - assert response_data["data"]["id"] == conversation.id - assert response_data["data"]["response_id"] == conversation.response_id - - -def test_get_conversation_not_found( - client: TestClient, - user_api_key: TestAuthContext, -) -> None: - """Test conversation retrieval with non-existent ID.""" - response = client.get( - "/api/v1/openai-conversation/99999", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 404 - response_data = response.json() - assert "not found" in response_data["error"] - - -def test_get_conversation_by_response_id_success( - client: TestClient, - db: Session, - user_api_key: TestAuthContext, -) -> None: - """Test successful conversation retrieval by response ID.""" - response_id = generate_openai_id("resp_", 40) - conversation_data = OpenAIConversationCreate( - response_id=response_id, - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="What is the capital of France?", - response="The capital of France is Paris.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=user_api_key.project_id, - organization_id=user_api_key.organization_id, - ) - - response = client.get( - f"/api/v1/openai-conversation/response/{response_id}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - assert response_data["data"]["response_id"] == response_id - assert response_data["data"]["id"] == conversation.id - - -def test_get_conversation_by_response_id_not_found( - client: TestClient, - user_api_key: TestAuthContext, -) -> None: - """Test conversation retrieval with non-existent response ID.""" - response = client.get( - "/api/v1/openai-conversation/response/nonexistent_response_id", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 404 - response_data = response.json() - assert "not found" in response_data["error"] - - -def test_get_conversation_by_ancestor_id_success( - client: TestClient, - db: Session, - user_api_key: TestAuthContext, -) -> None: - """Test successful conversation retrieval by ancestor ID.""" - ancestor_response_id = generate_openai_id("resp_", 40) - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=ancestor_response_id, - previous_response_id=None, - user_question="What is the capital of France?", - response="The capital of France is Paris.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=user_api_key.project_id, - organization_id=user_api_key.organization_id, - ) - - response = client.get( - f"/api/v1/openai-conversation/ancestor/{ancestor_response_id}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - assert response_data["data"]["ancestor_response_id"] == ancestor_response_id - assert response_data["data"]["id"] == conversation.id - - -def test_get_conversation_by_ancestor_id_not_found( - client: TestClient, - user_api_key: TestAuthContext, -) -> None: - """Test conversation retrieval with non-existent ancestor ID.""" - response = client.get( - "/api/v1/openai-conversation/ancestor/nonexistent_ancestor_id", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 404 - response_data = response.json() - assert "not found" in response_data["error"] - - -def test_list_conversations_success( - client: TestClient, - db: Session, - user_api_key: TestAuthContext, -) -> None: - """Test successful conversation listing.""" - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="What is the capital of France?", - response="The capital of France is Paris.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - # Actually create the conversation in the database - create_conversation( - session=db, - conversation=conversation_data, - project_id=user_api_key.project_id, - organization_id=user_api_key.organization_id, - ) - - response = client.get( - "/api/v1/openai-conversation", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - assert isinstance(response_data["data"], list) - assert len(response_data["data"]) > 0 - - -def test_list_conversations_with_pagination( - client: TestClient, - db: Session, - user_api_key: TestAuthContext, -) -> None: - """Test conversation listing with pagination.""" - # Create multiple conversations - conversation_data_1 = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="What is the capital of Japan?", - response="The capital of Japan is Tokyo.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation_data_2 = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="What is the capital of Brazil?", - response="The capital of Brazil is Brasília.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - # Actually create the conversations in the database - create_conversation( - session=db, - conversation=conversation_data_1, - project_id=user_api_key.project_id, - organization_id=user_api_key.organization_id, - ) - - create_conversation( - session=db, - conversation=conversation_data_2, - project_id=user_api_key.project_id, - organization_id=user_api_key.organization_id, - ) - - response = client.get( - "/api/v1/openai-conversation?skip=1&limit=2", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - assert isinstance(response_data["data"], list) - assert len(response_data["data"]) <= 2 - - # Check pagination metadata - assert "metadata" in response_data - metadata = response_data["metadata"] - assert metadata["skip"] == 1 - assert metadata["limit"] == 2 - assert "total" in metadata - assert isinstance(metadata["total"], int) - assert metadata["total"] >= 2 - - -def test_list_conversations_pagination_metadata( - client: TestClient, - db: Session, - user_api_key: TestAuthContext, -) -> None: - """Test conversation listing pagination metadata.""" - # Create 5 conversations - for i in range(5): - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question=f"Test question {i}", - response=f"Test response {i}", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - create_conversation( - session=db, - conversation=conversation_data, - project_id=user_api_key.project_id, - organization_id=user_api_key.organization_id, - ) - - # Test first page - response = client.get( - "/api/v1/openai-conversation?skip=0&limit=3", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - - metadata = response_data["metadata"] - assert metadata["skip"] == 0 - assert metadata["limit"] == 3 - assert ( - metadata["total"] >= 5 - ) # Should include the 5 we created plus any existing ones - - # Test second page - response = client.get( - "/api/v1/openai-conversation?skip=3&limit=3", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - - metadata = response_data["metadata"] - assert metadata["skip"] == 3 - assert metadata["limit"] == 3 - assert metadata["total"] >= 5 - - -def test_list_conversations_default_pagination( - client: TestClient, - db: Session, - user_api_key: TestAuthContext, -) -> None: - """Test conversation listing with default pagination parameters.""" - # Create a conversation - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="Test question", - response="Test response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - create_conversation( - session=db, - conversation=conversation_data, - project_id=user_api_key.project_id, - organization_id=user_api_key.organization_id, - ) - - # Test without pagination parameters (should use defaults) - response = client.get( - "/api/v1/openai-conversation", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - - metadata = response_data["metadata"] - assert metadata["skip"] == 0 # Default skip - assert metadata["limit"] == 100 # Default limit - assert "total" in metadata - assert isinstance(metadata["total"], int) - - -def test_list_conversations_edge_cases( - client: TestClient, - user_api_key: TestAuthContext, -) -> None: - """Test conversation listing edge cases for pagination.""" - # Test with skip larger than total - response = client.get( - "/api/v1/openai-conversation?skip=1000&limit=10", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - assert len(response_data["data"]) == 0 # Should return empty list - - metadata = response_data["metadata"] - assert metadata["skip"] == 1000 - assert metadata["limit"] == 10 - assert "total" in metadata - - # Test with maximum limit - response = client.get( - "/api/v1/openai-conversation?skip=0&limit=100", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - - metadata = response_data["metadata"] - assert metadata["skip"] == 0 - assert metadata["limit"] == 100 - assert "total" in metadata - - -def test_list_conversations_invalid_pagination( - client: TestClient, - user_api_key: TestAuthContext, -) -> None: - """Test conversation listing with invalid pagination parameters.""" - response = client.get( - "/api/v1/openai-conversation?skip=-1&limit=0", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 422 - - -def test_delete_conversation_success( - client: TestClient, - db: Session, - user_api_key: TestAuthContext, -) -> None: - """Test successful conversation deletion.""" - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="What is the capital of Japan?", - response="The capital of Japan is Tokyo.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - # Create the conversation in the database and get the created object with ID - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=user_api_key.project_id, - organization_id=user_api_key.organization_id, - ) - conversation_id = conversation.id - - response = client.delete( - f"/api/v1/openai-conversation/{conversation_id}", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 200 - response_data = response.json() - assert response_data["success"] is True - assert "deleted successfully" in response_data["data"]["message"] - - # Verify the conversation is marked as deleted - response = client.get( - f"/api/v1/openai-conversation/{conversation_id}", - headers={"X-API-KEY": user_api_key.key}, - ) - assert response.status_code == 404 - - -def test_delete_conversation_not_found( - client: TestClient, - user_api_key: TestAuthContext, -) -> None: - """Test conversation deletion with non-existent ID.""" - response = client.delete( - "/api/v1/openai-conversation/99999", - headers={"X-API-KEY": user_api_key.key}, - ) - - assert response.status_code == 404 - response_data = response.json() - assert "not found" in response_data["error"] diff --git a/backend/app/tests/crud/test_openai_conversation.py b/backend/app/tests/crud/test_openai_conversation.py deleted file mode 100644 index 908f7adee..000000000 --- a/backend/app/tests/crud/test_openai_conversation.py +++ /dev/null @@ -1,821 +0,0 @@ -from uuid import uuid4 - -import pytest -from sqlmodel import Session - -from app.crud.openai_conversation import ( - get_conversation_by_id, - get_conversation_by_response_id, - get_conversation_by_ancestor_id, - get_conversations_by_project, - get_ancestor_id_from_response, - get_conversations_count_by_project, - create_conversation, - delete_conversation, -) -from app.models import OpenAIConversationCreate, Project -from app.tests.utils.utils import get_project, get_organization -from app.tests.utils.llm_provider import generate_openai_id - - -def test_get_conversation_by_id_success(db: Session) -> None: - """Test successful conversation retrieval by ID.""" - project = get_project(db) - organization = get_organization(db) - - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="What is the capital of Japan?", - response="The capital of Japan is Tokyo.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - retrieved_conversation = get_conversation_by_id( - session=db, - conversation_id=conversation.id, - project_id=project.id, - ) - - assert retrieved_conversation is not None - assert retrieved_conversation.id == conversation.id - assert retrieved_conversation.response_id == conversation.response_id - - -def test_get_conversation_by_id_not_found(db: Session) -> None: - """Test conversation retrieval by non-existent ID.""" - project = get_project(db) - - retrieved_conversation = get_conversation_by_id( - session=db, - conversation_id=99999, - project_id=project.id, - ) - - assert retrieved_conversation is None - - -def test_get_conversation_by_response_id_success(db: Session) -> None: - """Test successful conversation retrieval by response ID.""" - project = get_project(db) - organization = get_organization(db) - - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="What is the capital of Japan?", - response="The capital of Japan is Tokyo.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - retrieved_conversation = get_conversation_by_response_id( - session=db, - response_id=conversation.response_id, - project_id=project.id, - ) - - assert retrieved_conversation is not None - assert retrieved_conversation.id == conversation.id - assert retrieved_conversation.response_id == conversation.response_id - - -def test_get_conversation_by_response_id_not_found(db: Session) -> None: - """Test conversation retrieval by non-existent response ID.""" - project = get_project(db) - - retrieved_conversation = get_conversation_by_response_id( - session=db, - response_id="nonexistent_response_id", - project_id=project.id, - ) - - assert retrieved_conversation is None - - -def test_get_conversation_by_ancestor_id_success(db: Session) -> None: - """Test successful conversation retrieval by ancestor ID.""" - project = get_project(db) - organization = get_organization(db) - - ancestor_response_id = generate_openai_id("resp_", 40) - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=ancestor_response_id, - previous_response_id=None, - user_question="What is the capital of France?", - response="The capital of France is Paris.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - retrieved_conversation = get_conversation_by_ancestor_id( - session=db, - ancestor_response_id=ancestor_response_id, - project_id=project.id, - ) - - assert retrieved_conversation is not None - assert retrieved_conversation.id == conversation.id - assert retrieved_conversation.ancestor_response_id == ancestor_response_id - - -def test_get_conversation_by_ancestor_id_not_found(db: Session) -> None: - """Test conversation retrieval by non-existent ancestor ID.""" - project = get_project(db) - - retrieved_conversation = get_conversation_by_ancestor_id( - session=db, - ancestor_response_id="nonexistent_ancestor_id", - project_id=project.id, - ) - - assert retrieved_conversation is None - - -def test_get_conversations_by_project_success(db: Session) -> None: - """Test successful conversation listing by project.""" - project = get_project(db) - organization = get_organization(db) - - # Create multiple conversations directly - for i in range(3): - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question=f"Test question {i}", - response=f"Test response {i}", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - conversations = get_conversations_by_project( - session=db, - project_id=project.id, - ) - - assert len(conversations) >= 3 - for conversation in conversations: - assert conversation.project_id == project.id - assert conversation.deleted_at is None - - -def test_get_conversations_by_project_with_pagination(db: Session) -> None: - """Test conversation listing by project with pagination.""" - project = get_project(db) - organization = get_organization(db) - - # Create multiple conversations - for i in range(5): - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question=f"Test question {i}", - response=f"Test response {i}", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - conversations = get_conversations_by_project( - session=db, - project_id=project.id, - skip=1, - limit=2, - ) - - assert len(conversations) <= 2 - - -def test_delete_conversation_success(db: Session) -> None: - """Test successful conversation deletion.""" - project = get_project(db) - organization = get_organization(db) - - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="What is the capital of Japan?", - response="The capital of Japan is Tokyo.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - deleted_conversation = delete_conversation( - session=db, - conversation_id=conversation.id, - project_id=project.id, - ) - - assert deleted_conversation is not None - assert deleted_conversation.id == conversation.id - assert deleted_conversation.deleted_at is not None - - -def test_delete_conversation_not_found(db: Session) -> None: - """Test conversation deletion with non-existent ID.""" - project = get_project(db) - - deleted_conversation = delete_conversation( - session=db, - conversation_id=99999, - project_id=project.id, - ) - - assert deleted_conversation is None - - -def test_conversation_soft_delete_behavior(db: Session) -> None: - """Test that deleted conversations are not returned by get functions.""" - project = get_project(db) - organization = get_organization(db) - - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="What is the capital of Japan?", - response="The capital of Japan is Tokyo.", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - delete_conversation( - session=db, - conversation_id=conversation.id, - project_id=project.id, - ) - - retrieved_conversation = get_conversation_by_id( - session=db, - conversation_id=conversation.id, - project_id=project.id, - ) - assert retrieved_conversation is None - - retrieved_conversation = get_conversation_by_response_id( - session=db, - response_id=conversation.response_id, - project_id=project.id, - ) - assert retrieved_conversation is None - - conversations = get_conversations_by_project( - session=db, - project_id=project.id, - ) - assert conversation.id not in [c.id for c in conversations] - - -def test_get_ancestor_id_from_response_no_previous_response(db: Session) -> None: - """Test get_ancestor_id_from_response when previous_response_id is None.""" - project = get_project(db) - current_response_id = generate_openai_id("resp_", 40) - - ancestor_id = get_ancestor_id_from_response( - session=db, - current_response_id=current_response_id, - previous_response_id=None, - project_id=project.id, - ) - - assert ancestor_id == current_response_id - - -def test_get_ancestor_id_from_response_previous_not_found(db: Session) -> None: - """Test get_ancestor_id_from_response when previous_response_id is not found in DB.""" - project = get_project(db) - current_response_id = generate_openai_id("resp_", 40) - previous_response_id = generate_openai_id("resp_", 40) - - ancestor_id = get_ancestor_id_from_response( - session=db, - current_response_id=current_response_id, - previous_response_id=previous_response_id, - project_id=project.id, - ) - - # When previous_response_id is not found, should return previous_response_id - assert ancestor_id == previous_response_id - - -def test_get_ancestor_id_from_response_previous_found_with_ancestor( - db: Session, -) -> None: - """Test get_ancestor_id_from_response when previous_response_id is found and has an ancestor.""" - project = get_project(db) - organization = get_organization(db) - - # Create a conversation chain: ancestor -> previous -> current - ancestor_response_id = generate_openai_id("resp_", 40) - - ancestor_conversation_data = OpenAIConversationCreate( - response_id=ancestor_response_id, - ancestor_response_id=ancestor_response_id, # Self-referencing - previous_response_id=None, - user_question="Original question", - response="Original response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - ancestor_conversation = create_conversation( - session=db, - conversation=ancestor_conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - previous_response_id = generate_openai_id("resp_", 40) - previous_conversation_data = OpenAIConversationCreate( - response_id=previous_response_id, - ancestor_response_id=ancestor_response_id, - previous_response_id=ancestor_response_id, - user_question="Previous question", - response="Previous response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - create_conversation( - session=db, - conversation=previous_conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - # Test the current conversation - current_response_id = generate_openai_id("resp_", 40) - ancestor_id = get_ancestor_id_from_response( - session=db, - current_response_id=current_response_id, - previous_response_id=previous_response_id, - project_id=project.id, - ) - - # Should return the ancestor_response_id from the previous conversation - assert ancestor_id == ancestor_response_id - - -def test_get_conversations_count_by_project_success(db: Session) -> None: - """Test successful conversation count retrieval by project.""" - project = get_project(db) - organization = get_organization(db) - - initial_count = get_conversations_count_by_project( - session=db, - project_id=project.id, - ) - - for i in range(3): - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question=f"Test question {i}", - response=f"Test response {i}", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - updated_count = get_conversations_count_by_project( - session=db, - project_id=project.id, - ) - - assert updated_count == initial_count + 3 - - -def test_get_ancestor_id_from_response_previous_found_without_ancestor( - db: Session, -) -> None: - """Test get_ancestor_id_from_response when previous_response_id is found but has no ancestor.""" - project = get_project(db) - organization = get_organization(db) - - # Create a previous conversation that is self-referencing - previous_response_id = generate_openai_id("resp_", 40) - previous_conversation_data = OpenAIConversationCreate( - response_id=previous_response_id, - ancestor_response_id=previous_response_id, # Self-referencing for root - previous_response_id=None, - user_question="Previous question", - response="Previous response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - create_conversation( - session=db, - conversation=previous_conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - current_response_id = generate_openai_id("resp_", 40) - ancestor_id = get_ancestor_id_from_response( - session=db, - current_response_id=current_response_id, - previous_response_id=previous_response_id, - project_id=project.id, - ) - - # When previous conversation is root (self-referencing), should return the previous_response_id - assert ancestor_id == previous_response_id - - -def test_get_ancestor_id_from_response_different_project(db: Session) -> None: - """Test get_ancestor_id_from_response respects project scoping.""" - project1 = get_project(db) - organization = get_organization(db) - - project2 = Project( - name=f"test_project_{uuid4()}", - description="Test project for scoping", - is_active=True, - organization_id=organization.id, - ) - db.add(project2) - db.commit() - db.refresh(project2) - - # Create a conversation in project1 - previous_response_id = generate_openai_id("resp_", 40) - previous_conversation_data = OpenAIConversationCreate( - response_id=previous_response_id, - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="Previous question", - response="Previous response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - create_conversation( - session=db, - conversation=previous_conversation_data, - project_id=project1.id, - organization_id=organization.id, - ) - - # Test looking for it in project2 (should not find it) - current_response_id = generate_openai_id("resp_", 40) - ancestor_id = get_ancestor_id_from_response( - session=db, - current_response_id=current_response_id, - previous_response_id=previous_response_id, - project_id=project2.id, - ) - - # Should return previous_response_id since it's not found in project2 - assert ancestor_id == previous_response_id - - -def test_get_ancestor_id_from_response_complex_chain(db: Session) -> None: - """Test get_ancestor_id_from_response with a complex conversation chain.""" - project = get_project(db) - organization = get_organization(db) - - # Create a complex chain: A -> B -> C -> D - # A is the root ancestor - response_a = generate_openai_id("resp_", 40) - conversation_a_data = OpenAIConversationCreate( - response_id=response_a, - ancestor_response_id=response_a, # Self-referencing - previous_response_id=None, - user_question="Question A", - response="Response A", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - create_conversation( - session=db, - conversation=conversation_a_data, - project_id=project.id, - organization_id=organization.id, - ) - - # B references A - response_b = generate_openai_id("resp_", 40) - conversation_b_data = OpenAIConversationCreate( - response_id=response_b, - ancestor_response_id=response_a, - previous_response_id=response_a, - user_question="Question B", - response="Response B", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - create_conversation( - session=db, - conversation=conversation_b_data, - project_id=project.id, - organization_id=organization.id, - ) - - # C references B - response_c = generate_openai_id("resp_", 40) - conversation_c_data = OpenAIConversationCreate( - response_id=response_c, - ancestor_response_id=response_a, # Should inherit from B - previous_response_id=response_b, - user_question="Question C", - response="Response C", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - create_conversation( - session=db, - conversation=conversation_c_data, - project_id=project.id, - organization_id=organization.id, - ) - - # Test D referencing C - response_d = generate_openai_id("resp_", 40) - ancestor_id = get_ancestor_id_from_response( - session=db, - current_response_id=response_d, - previous_response_id=response_c, - project_id=project.id, - ) - - # Should return response_a (the root ancestor) - assert ancestor_id == response_a - - -def test_create_conversation_success(db: Session) -> None: - """Test successful conversation creation.""" - project = get_project(db) - organization = get_organization(db) - - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="Test question", - response="Test response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - assert conversation is not None - assert conversation.response_id == conversation_data.response_id - assert conversation.user_question == conversation_data.user_question - assert conversation.response == conversation_data.response - assert conversation.model == conversation_data.model - assert conversation.project_id == project.id - assert conversation.organization_id == organization.id - - -def test_delete_conversation_excludes_from_count(db: Session) -> None: - """Test that deleted conversations are excluded from count.""" - project = get_project(db) - organization = get_organization(db) - - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question="Test question", - response="Test response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - count_before = get_conversations_count_by_project( - session=db, - project_id=project.id, - ) - - delete_conversation( - session=db, - conversation_id=conversation.id, - project_id=project.id, - ) - - count_after = get_conversations_count_by_project( - session=db, - project_id=project.id, - ) - - assert count_after == count_before - 1 - - -def test_get_conversations_count_by_project_different_projects(db: Session) -> None: - """Test that count is isolated by project.""" - project1 = get_project(db) - organization = get_organization(db) - - # Get another project (assuming there are multiple projects in test data) - project2 = ( - get_project(db, "Dalgo") - if get_project(db, "Dalgo") is not None - else get_project(db) - ) - - # Create conversations in project1 - for i in range(2): - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question=f"Test question {i}", - response=f"Test response {i}", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - create_conversation( - session=db, - conversation=conversation_data, - project_id=project1.id, - organization_id=organization.id, - ) - - # Create conversations in project2 - for i in range(3): - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=generate_openai_id("resp_", 40), - previous_response_id=None, - user_question=f"Test question {i}", - response=f"Test response {i}", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - create_conversation( - session=db, - conversation=conversation_data, - project_id=project2.id, - organization_id=organization.id, - ) - - # Check counts are isolated - count1 = get_conversations_count_by_project(session=db, project_id=project1.id) - count2 = get_conversations_count_by_project(session=db, project_id=project2.id) - - assert count1 >= 2 - assert count2 >= 3 - - -def test_response_id_validation_pattern(db: Session) -> None: - """Test that response ID validation pattern is enforced.""" - project = get_project(db) - organization = get_organization(db) - - # Test valid response ID - valid_response_id = "resp_1234567890abcdef" - conversation_data = OpenAIConversationCreate( - response_id=valid_response_id, - ancestor_response_id="resp_abcdef1234567890", - previous_response_id=None, - user_question="Test question", - response="Test response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - assert conversation is not None - assert conversation.response_id == conversation_data.response_id - assert conversation.user_question == conversation_data.user_question - assert conversation.response == conversation_data.response - assert conversation.model == conversation_data.model - assert conversation.assistant_id == conversation_data.assistant_id - assert conversation.project_id == project.id - assert conversation.organization_id == organization.id - assert conversation.deleted_at is None - - -def test_create_conversation_with_ancestor(db: Session) -> None: - """Test conversation creation with ancestor and previous response IDs.""" - project = get_project(db) - organization = get_organization(db) - - ancestor_response_id = generate_openai_id("resp_", 40) - previous_response_id = generate_openai_id("resp_", 40) - - conversation_data = OpenAIConversationCreate( - response_id=generate_openai_id("resp_", 40), - ancestor_response_id=ancestor_response_id, - previous_response_id=previous_response_id, - user_question="Follow-up question", - response="Follow-up response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - conversation = create_conversation( - session=db, - conversation=conversation_data, - project_id=project.id, - organization_id=organization.id, - ) - - assert conversation is not None - assert conversation.ancestor_response_id == ancestor_response_id - assert conversation.previous_response_id == previous_response_id - assert conversation.response_id == conversation_data.response_id - - invalid_response_id = "resp_123" - with pytest.raises(ValueError, match="String should have at least 10 characters"): - OpenAIConversationCreate( - response_id=invalid_response_id, - ancestor_response_id="resp_abcdef1234567890", - previous_response_id=None, - user_question="Test question", - response="Test response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) - - invalid_response_id2 = "msg_1234567890abcdef" - with pytest.raises(ValueError, match="response_id fields must follow pattern"): - OpenAIConversationCreate( - response_id=invalid_response_id2, - ancestor_response_id="resp_abcdef1234567890", - previous_response_id=None, - user_question="Test question", - response="Test response", - model="gpt-4o", - assistant_id=generate_openai_id("asst_", 20), - ) diff --git a/docs/wiki/INDEX.md b/docs/wiki/INDEX.md index f938a04b9..aa8f5133f 100644 --- a/docs/wiki/INDEX.md +++ b/docs/wiki/INDEX.md @@ -20,7 +20,7 @@ Deep design narrative lives in `docs/architecture/*.md`; open those only for des - [modules/guardrails.md](modules/guardrails.md) — guardrails service integration: `POST /guardrails` async job, inline input/output hooks, management proxies, fail-open/fail-closed matrix. Deep dive: `docs/architecture/kaapi-llm-call-ARCHITECTURE.md` §7 (stale on auth failures). - [modules/evaluations.md](modules/evaluations.md) — text/STT/TTS evals, datasets, runs, batch + cron scoring, fast evals. Deep dive: `docs/architecture/kaapi-evaluations-ARCHITECTURE.md` - [modules/knowledge-base.md](modules/knowledge-base.md) — documents, collections, transforms, vector-store providers. Deep dive: `docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md` -- [modules/assistants.md](modules/assistants.md) — OpenAI assistants, conversations and threads. No deep-dive doc yet. +- [modules/assistants.md](modules/assistants.md) — OpenAI assistants and threads. No deep-dive doc yet. - [modules/assessment.md](modules/assessment.md) — assessments and assessment runs. No deep-dive doc yet. - [modules/chatbot.md](modules/chatbot.md) — chatbots as versioned React Flow graphs (draft/publish) with per-conversation sessions; onboarding agent with per-turn field extraction + completion status (`/chatbots`, `/chatbots/{id}/flow*`, `/chatbots/*sessions*` via Celery + webhook; LangGraph + Anthropic, model from a saved config per agent node). No deep-dive doc yet. - [modules/tenancy.md](modules/tenancy.md) — users, orgs, projects, API keys, onboarding, login. diff --git a/docs/wiki/domain-map.md b/docs/wiki/domain-map.md index a199cc757..d0099b514 100644 --- a/docs/wiki/domain-map.md +++ b/docs/wiki/domain-map.md @@ -45,7 +45,6 @@ APIKey → Organization, Project, User # programmatic access | 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) | -| OpenAIConversation | openai_conversation.py | Org, Project | response service (logical) | | OpenAIThread | threads.py | — | thread results read path (logical) | | Language | language.py (`global.languages`) | — | EvaluationDataset, EvaluationRun, STT | | FeatureFlag | feature_flag.py | Org, Project | route gating (logical) | diff --git a/docs/wiki/modules/assistants.md b/docs/wiki/modules/assistants.md index 5ca3ef38f..8d2c8a5cf 100644 --- a/docs/wiki/modules/assistants.md +++ b/docs/wiki/modules/assistants.md @@ -1,23 +1,21 @@ -# Module: Assistants, Conversations & Threads +# Module: Assistants & Threads -OpenAI assistants, stored conversations and thread results. The Responses API integration was removed. No deep-dive doc yet. +OpenAI assistants and thread results. The Responses API and OpenAI conversations were removed (`openai_conversation` is dropped in migration 095). No deep-dive doc yet. All paths relative to `backend/app/`. ## Routes -- `api/routes/openai_conversation.py` — conversation management - `api/routes/threads.py` — thread results - `api/routes/assistants.py` — assistant CRUD ## Tables (SQLModel) | Table | Model | |---|---| -| `openai_conversation` (OpenAIConversation) | `models/openai_conversation.py` | | `openai_thread` (OpenAIThread) | `models/threads.py` | | `assistant` (Assistant) | `models/assistants.py` | ## Services / CRUD -- `crud/openai_conversation.py`, `crud/assistants.py`, `crud/thread_results.py` +- `crud/assistants.py`, `crud/thread_results.py` ## External - OpenAI Assistants API, Langfuse tracing.