diff --git a/backend/app/alembic/versions/098_drop_openai_thread_table.py b/backend/app/alembic/versions/098_drop_openai_thread_table.py new file mode 100644 index 000000000..1cd3b99db --- /dev/null +++ b/backend/app/alembic/versions/098_drop_openai_thread_table.py @@ -0,0 +1,80 @@ +"""drop openai_thread + +Revision ID: 098 +Revises: 097 +Create Date: 2026-12-04 00:00:00.000000 + +The Threads module was removed, so nothing reads or writes this table any more. +Rows are lost on upgrade; downgrade restores the schema as it stood at 097 (an +empty table) so older code can boot, not the data. +""" + +import sqlalchemy as sa +from alembic import op + +revision = "098" +down_revision = "097" +branch_labels = None +depends_on = None + + +def upgrade(): + op.drop_table("openai_thread") + + +def downgrade(): + op.create_table( + "openai_thread", + sa.Column( + "id", + sa.Integer(), + nullable=False, + comment="Unique identifier for the thread record", + ), + sa.Column( + "thread_id", + sa.String(), + nullable=False, + comment="OpenAI thread identifier", + ), + sa.Column( + "prompt", + sa.String(), + nullable=False, + comment="User prompt sent to the thread", + ), + sa.Column( + "response", + sa.String(), + nullable=True, + comment="Response received from OpenAI", + ), + sa.Column( + "status", + sa.String(), + nullable=True, + comment="Current status of the thread interaction", + ), + sa.Column( + "error", + sa.String(), + nullable=True, + comment="Error message if the interaction failed", + ), + sa.Column( + "inserted_at", + sa.DateTime(), + nullable=False, + comment="Timestamp when the record was created", + ), + sa.Column( + "updated_at", + sa.DateTime(), + nullable=False, + comment="Timestamp when the record was last updated", + ), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index( + "ix_openai_thread_thread_id", "openai_thread", ["thread_id"], unique=True + ) diff --git a/backend/app/api/docs/openapi_config.py b/backend/app/api/docs/openapi_config.py index 1a3b3c210..69b569d6f 100644 --- a/backend/app/api/docs/openapi_config.py +++ b/backend/app/api/docs/openapi_config.py @@ -81,10 +81,6 @@ "[**Deprecated**] OpenAI Assistant creation and management. This " "feature will be removed in a future version." ), - "Threads": ( - "[**Deprecated**] Conversation thread management for assistants. This " - "feature will be removed in a future version." - ), "Users": ( "User accounts: read, update or delete your own profile and change your " "password; superusers can also create users." @@ -159,7 +155,6 @@ "Assessment", "Assessment (Experimental)", "Assistants", - "Threads", ], }, { @@ -194,7 +189,7 @@ def customize_openapi_schema(openapi_schema: dict) -> dict: """ openapi_schema = inject_component_schemas(openapi_schema) openapi_schema["x-tagGroups"] = tag_groups - deprecated_tags = ["Assistants", "Threads"] + deprecated_tags = ["Assistants"] for _, path_item in openapi_schema.get("paths", {}).items(): for method, operation in path_item.items(): diff --git a/backend/app/api/docs/threads/examples.py b/backend/app/api/docs/threads/examples.py deleted file mode 100644 index 1e5e8e94a..000000000 --- a/backend/app/api/docs/threads/examples.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Request-body examples for the Threads routes. - - -""" - -from app.api.openapi_docs import Examples - -THREAD_CREATE_EXAMPLES: Examples = { - "new_thread": ( - "Ask a question on a new thread", - { - "question": "What documents do I need to apply for the scholarship?", - "assistant_id": "asst_abc123def456", - "callback_url": "https://example.com/webhooks/threads", - "remove_citation": True, - }, - ), -} - -THREAD_SYNC_EXAMPLES: Examples = { - "continue_thread": ( - "Ask a follow-up question on an existing thread and wait for the answer", - { - "question": "What documents do I need to apply for the scholarship?", - "assistant_id": "asst_abc123def456", - "thread_id": "thread_abc123def456", - "remove_citation": True, - }, - ), -} - -THREAD_START_EXAMPLES: Examples = { - "basic": ( - "Start a thread and poll for the answer", - { - "question": "What documents do I need to apply for the scholarship?", - "assistant_id": "asst_abc123def456", - "remove_citation": True, - }, - ), -} diff --git a/backend/app/api/main.py b/backend/app/api/main.py index 75ddad991..9ed7c3cf7 100644 --- a/backend/app/api/main.py +++ b/backend/app/api/main.py @@ -25,7 +25,6 @@ onboarding, organization, project, - threads, user_project, users, utils, @@ -66,7 +65,6 @@ api_router.include_router(onboarding.router) api_router.include_router(organization.router) api_router.include_router(project.router) -api_router.include_router(threads.router) api_router.include_router(user_project.router) api_router.include_router(users.router) api_router.include_router(utils.router) diff --git a/backend/app/api/routes/threads.py b/backend/app/api/routes/threads.py deleted file mode 100644 index d3596a125..000000000 --- a/backend/app/api/routes/threads.py +++ /dev/null @@ -1,525 +0,0 @@ -import re -import openai -import requests - -from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException -from openai import OpenAI -from pydantic import BaseModel, Field -from typing import Optional - -from app.api.deps import AuthContextDep, SessionDep -from app.api.docs.threads.examples import ( - THREAD_CREATE_EXAMPLES, - THREAD_START_EXAMPLES, - THREAD_SYNC_EXAMPLES, -) -from app.api.openapi_docs import request_examples -from app.api.permissions import Permission, require_permission -from app.core import logging -from app.models import OpenAIThreadCreate -from app.crud import upsert_thread_result, get_thread_result -from app.utils import APIResponse, mask_string -from app.crud.credentials import get_provider_credential -from app.core.util import configure_openai -from app.core.langfuse.langfuse import LangfuseTracer - -logger = logging.getLogger(__name__) -router = APIRouter(tags=["Threads"]) - - -class StartThreadRequest(BaseModel): - question: str = Field(..., description="The user's input question.") - assistant_id: str = Field(..., description="The ID of the assistant to be used.") - remove_citation: bool = Field( - default=False, description="Whether to remove citations from the response." - ) - thread_id: Optional[str] = Field( - default=None, - description="An optional existing thread ID to continue the conversation.", - ) - - -def send_callback(callback_url: str, data: dict): - """Send results to the callback URL (synchronously).""" - try: - session = requests.Session() - # uncomment this to run locally without SSL - # session.verify = False - response = session.post(callback_url, json=data) - response.raise_for_status() - logger.info(f"[send_callback] Callback sent successfully to {callback_url}") - return True - except requests.RequestException as e: - logger.error(f"[send_callback] Callback failed: {str(e)}", exc_info=True) - return False - - -def handle_openai_error(e: openai.OpenAIError) -> str: - """Extract error message from OpenAI error.""" - if isinstance(e.body, dict) and "message" in e.body: - return e.body["message"] - return str(e) - - -def validate_thread(client: OpenAI, thread_id: str) -> tuple[bool, str]: - """Validate if a thread exists and has no active runs.""" - if not thread_id: - return True, None - - try: - runs = client.beta.threads.runs.list(thread_id=thread_id) - if runs.data and len(runs.data) > 0: - latest_run = runs.data[0] - if latest_run.status in ["queued", "in_progress", "requires_action"]: - logger.warning( - f"[validate_thread] Thread ID {mask_string(thread_id)} is currently {latest_run.status}." - ) - return ( - False, - f"There is an active run on this thread (status: {latest_run.status}). Please wait for it to complete.", - ) - return True, None - except openai.OpenAIError as e: - logger.error( - f"[validate_thread] Failed to validate thread ID {mask_string(thread_id)}: {str(e)}", - exc_info=True, - ) - return False, f"Invalid thread ID provided {thread_id}" - - -def setup_thread(client: OpenAI, request: dict) -> tuple[bool, str]: - """Set up thread and add message, either creating new or using existing.""" - thread_id = request.get("thread_id") - if thread_id: - try: - client.beta.threads.messages.create( - thread_id=thread_id, role="user", content=request["question"] - ) - logger.info( - f"[setup_thread] Added message to existing thread {mask_string(thread_id)}" - ) - return True, None - except openai.OpenAIError as e: - logger.error( - f"[setup_thread] Failed to add message to existing thread {mask_string(thread_id)}: {str(e)}", - exc_info=True, - ) - return False, handle_openai_error(e) - else: - try: - thread = client.beta.threads.create() - client.beta.threads.messages.create( - thread_id=thread.id, role="user", content=request["question"] - ) - request["thread_id"] = thread.id - logger.info( - f"[setup_thread] Created new thread with ID: {mask_string(thread.id)}" - ) - return True, None - except openai.OpenAIError as e: - logger.error( - f"[setup_thread] Failed to create new thread: {str(e)}", exc_info=True - ) - return False, handle_openai_error(e) - - -def process_message_content(message_content: str, remove_citation: bool) -> str: - """Process message content, optionally removing citations.""" - if remove_citation: - return re.sub(r"【\d+(?::\d+)?†[^】]*】", "", message_content) - return message_content - - -def get_additional_data(request: dict) -> dict: - """Extract additional data from request, excluding specific keys.""" - return { - k: v - for k, v in request.items() - if k not in {"question", "assistant_id", "callback_url", "thread_id"} - } - - -def create_success_response(request: dict, message: str) -> APIResponse: - """Create a success response with the given message and request data.""" - additional_data = get_additional_data(request) - return APIResponse.success_response( - data={ - "status": "success", - "message": message, - "thread_id": request["thread_id"], - "endpoint": getattr(request, "endpoint", "some-default-endpoint"), - **additional_data, - } - ) - - -def run_and_poll_thread(client: OpenAI, thread_id: str, assistant_id: str): - """Runs and polls a thread with the specified assistant using the OpenAI client.""" - return client.beta.threads.runs.create_and_poll( - thread_id=thread_id, - assistant_id=assistant_id, - ) - - -def extract_response_from_thread( - client: OpenAI, thread_id: str, remove_citation: bool = False -) -> str: - """Fetches and processes the latest message from a thread.""" - messages = client.beta.threads.messages.list(thread_id=thread_id) - latest_message = messages.data[0] - message_content = latest_message.content[0].text.value - return process_message_content(message_content, remove_citation) - - -def process_run_core( - request: dict, client: OpenAI, tracer: LangfuseTracer -) -> tuple[dict, str]: - """Core function to process a run and return the response and message with Langfuse tracing.""" - tracer.start_generation( - name="openai_thread_run", - input={"question": request["question"]}, - metadata={"assistant_id": request["assistant_id"]}, - ) - - try: - logger.info( - f"[process_run_core] Starting run for thread ID: {mask_string(request.get('thread_id'))} with assistant ID: {mask_string(request.get('assistant_id'))}" - ) - run = client.beta.threads.runs.create_and_poll( - thread_id=request["thread_id"], - assistant_id=request["assistant_id"], - ) - - if run.status == "completed": - message = extract_response_from_thread( - client, request["thread_id"], request.get("remove_citation", False) - ) - tracer.end_generation( - output={ - "thread_id": request["thread_id"], - "message": message, - }, - usage={ - "input": run.usage.prompt_tokens, - "output": run.usage.completion_tokens, - "total": run.usage.total_tokens, - "unit": "TOKENS", - }, - model=run.model, - ) - tracer.update_trace( - tags=[request["thread_id"]], - output={"status": "success", "message": message, "error": None}, - ) - diagnostics = { - "input_tokens": run.usage.prompt_tokens, - "output_tokens": run.usage.completion_tokens, - "total_tokens": run.usage.total_tokens, - "model": run.model, - } - request = {**request, **{"diagnostics": diagnostics}} - logger.info( - f"[process_run_core] Run completed successfully for thread ID: {mask_string(request.get('thread_id'))}" - ) - return create_success_response(request, message).model_dump(), None - else: - error_msg = f"Run failed with status: {run.status}" - logger.error( - f"[process_run_core] Run failed with error: {run.last_error} for thread ID: {mask_string(request.get('thread_id'))}" - ) - tracer.log_error(error_msg) - return APIResponse.failure_response(error=error_msg).model_dump(), error_msg - - except openai.OpenAIError as e: - error_msg = handle_openai_error(e) - tracer.log_error(error_msg) - logger.error( - f"[process_run_core] OpenAI error: {error_msg} for thread ID: {mask_string(request.get('thread_id'))}", - exc_info=True, - ) - return APIResponse.failure_response(error=error_msg).model_dump(), error_msg - finally: - tracer.flush() - - -def process_run(request: dict, client: OpenAI, tracer: LangfuseTracer): - """Process a run and send callback with results with Langfuse tracing.""" - response, _ = process_run_core(request, client, tracer) - send_callback(request["callback_url"], response) - - -def poll_run_and_prepare_response(request: dict, client: OpenAI, db: SessionDep): - """Handles a thread run, processes the response, and upserts the result to the database.""" - thread_id = request["thread_id"] - prompt = request["question"] - - logger.info( - f"[poll_run_and_prepare_response] Starting run for thread ID: {mask_string(thread_id)}" - ) - - try: - run = run_and_poll_thread(client, thread_id, request["assistant_id"]) - status = run.status or "unknown" - response = None - error = None - - if status == "completed": - response = extract_response_from_thread( - client, thread_id, request.get("remove_citation", False) - ) - logger.info( - f"[poll_run_and_prepare_response] Successfully executed run for thread ID: {mask_string(thread_id)}" - ) - - except openai.OpenAIError as e: - status = "failed" - error = str(e) - response = None - logger.error( - f"[poll_run_and_prepare_response] Run failed for thread ID {mask_string(thread_id)}: {error}", - exc_info=True, - ) - - upsert_thread_result( - db, - OpenAIThreadCreate( - thread_id=thread_id, - prompt=prompt, - response=response, - status=status, - error=error, - ), - ) - - -@router.post( - "/threads", - dependencies=[Depends(require_permission(Permission.REQUIRE_ORGANIZATION))], - openapi_extra=request_examples(THREAD_CREATE_EXAMPLES), -) -async def threads( - request: dict, - background_tasks: BackgroundTasks, - session: SessionDep, - _current_user: AuthContextDep, -): - """Asynchronous endpoint that processes requests in background.""" - credentials = get_provider_credential( - session=session, - org_id=_current_user.organization_.id, - provider="openai", - project_id=request.get("project_id"), - ) - client, success = configure_openai(credentials) - if not success: - logger.warning( - f"[threads] OpenAI API key not configured for this organization. | organization_id: {_current_user.organization_.id}, project_id: {request.get('project_id')}" - ) - return APIResponse.failure_response( - error="OpenAI API key not configured for this organization." - ) - - langfuse_credentials = get_provider_credential( - session=session, - org_id=_current_user.organization_.id, - provider="langfuse", - project_id=request.get("project_id"), - ) - - # Validate thread - is_valid, error_message = validate_thread(client, request.get("thread_id")) - if not is_valid: - raise Exception(error_message) - # Setup thread - is_success, error_message = setup_thread(client, request) - if not is_success: - raise Exception(error_message) - - # Send immediate response - initial_response = APIResponse.success_response( - data={ - "status": "processing", - "message": "Run started", - "thread_id": request.get("thread_id"), - "success": True, - } - ) - - tracer = LangfuseTracer( - credentials=langfuse_credentials, - session_id=request.get("thread_id"), - ) - - tracer.start_trace( - name="threads_async_endpoint", - input={ - "question": request["question"], - "assistant_id": request["assistant_id"], - }, - metadata={"thread_id": request["thread_id"]}, - ) - # Schedule background task - background_tasks.add_task(process_run, request, client, tracer) - logger.info( - f"[threads] Background task scheduled for thread ID: {mask_string(request.get('thread_id'))} | organization_id: {_current_user.organization_.id}, project_id: {request.get('project_id')}" - ) - return initial_response - - -@router.post( - "/threads/sync", - dependencies=[Depends(require_permission(Permission.REQUIRE_ORGANIZATION))], - openapi_extra=request_examples(THREAD_SYNC_EXAMPLES), -) -async def threads_sync( - request: dict, - session: SessionDep, - _current_user: AuthContextDep, -): - """Synchronous endpoint that processes requests immediately.""" - credentials = get_provider_credential( - session=session, - org_id=_current_user.organization_.id, - provider="openai", - project_id=request.get("project_id"), - ) - - # Configure OpenAI client - client, success = configure_openai(credentials) - if not success: - logger.warning( - f"[threads_sync] OpenAI API key not configured for this organization. | organization_id: {_current_user.organization_.id}, project_id: {request.get('project_id')}" - ) - return APIResponse.failure_response( - error="OpenAI API key not configured for this organization." - ) - - # Get Langfuse credentials - langfuse_credentials = get_provider_credential( - session=session, - org_id=_current_user.organization_.id, - provider="langfuse", - project_id=request.get("project_id"), - ) - - # Validate thread - is_valid, error_message = validate_thread(client, request.get("thread_id")) - if not is_valid: - raise Exception(error_message) - - # Setup thread - is_success, error_message = setup_thread(client, request) - if not is_success: - raise Exception(error_message) - - tracer = LangfuseTracer( - credentials=langfuse_credentials, - session_id=request.get("thread_id"), - ) - - tracer.start_trace( - name="threads_sync_endpoint", - input={ - "question": request.get("question"), - "assistant_id": request.get("assistant_id"), - }, - metadata={"thread_id": request.get("thread_id")}, - ) - - response, error_message = process_run_core(request, client, tracer) - return response - - -@router.post( - "/threads/start", - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], - openapi_extra=request_examples(THREAD_START_EXAMPLES), -) -async def start_thread( - request: StartThreadRequest, - background_tasks: BackgroundTasks, - db: SessionDep, - _current_user: AuthContextDep, -): - """ - Create a new OpenAI thread for the given question and start polling in the background. - """ - request = request.model_dump() - prompt = request["question"] - credentials = get_provider_credential( - session=db, - org_id=_current_user.organization_.id, - provider="openai", - project_id=_current_user.project_.id, - ) - - # Configure OpenAI client - client, success = configure_openai(credentials) - if not success: - logger.warning( - f"[start_thread] OpenAI API key not configured for this organization. | project_id: {_current_user.project_.id}" - ) - return APIResponse.failure_response( - error="OpenAI API key not configured for this organization." - ) - - is_success, error = setup_thread(client, request) - if not is_success: - raise Exception(error) - - thread_id = request["thread_id"] - - upsert_thread_result( - db, - OpenAIThreadCreate( - thread_id=thread_id, - prompt=prompt, - response=None, - status="processing", - error=None, - ), - ) - - background_tasks.add_task(poll_run_and_prepare_response, request, client, db) - - logger.info( - f"[start_thread] Background task scheduled to process response for thread ID: {mask_string(thread_id)} | project_id: {_current_user.project_.id}" - ) - return APIResponse.success_response( - data={ - "thread_id": thread_id, - "prompt": prompt, - "status": "processing", - "message": "Thread created and polling started in background.", - } - ) - - -@router.get( - "/threads/result/{thread_id}", - dependencies=[Depends(require_permission(Permission.REQUIRE_ORGANIZATION))], -) -async def get_thread( - thread_id: str, - db: SessionDep, - _current_user: AuthContextDep, -): - """ - Retrieve the result of a previously started OpenAI thread using its thread ID. - """ - result = get_thread_result(db, thread_id) - - if not result: - raise HTTPException(404, "thread not found") - - status = result.status or ("success" if result.response else "processing") - - return APIResponse.success_response( - data={ - "thread_id": result.thread_id, - "prompt": result.prompt, - "status": status, - "response": result.response, - "error": result.error, - } - ) diff --git a/backend/app/core/langfuse/langfuse.py b/backend/app/core/langfuse/langfuse.py index 27d5e0224..b755204f5 100644 --- a/backend/app/core/langfuse/langfuse.py +++ b/backend/app/core/langfuse/langfuse.py @@ -1,14 +1,12 @@ import json import logging import threading -import uuid from collections.abc import Callable from functools import wraps from typing import Any -from asgi_correlation_id import correlation_id from langfuse import Langfuse, LangfuseOtelSpanAttributes -from langfuse._client.span import LangfuseGeneration, LangfuseSpan +from langfuse._client.span import LangfuseSpan from langfuse.api.core.api_error import ApiError from opentelemetry.sdk.trace import TracerProvider @@ -67,18 +65,6 @@ def _serialize(value: Any) -> str: return str(value) -def _to_usage_details(usage: dict[str, Any] | None) -> dict[str, int] | None: - """Convert a v2-style usage dict to the v4 ``usage_details`` (int-only) format. - - v2 callers pass ``{"input", "output", "total", "unit": "TOKENS"}``; v4 expects - ``usage_details: dict[str, int]`` and has no ``unit`` field, so non-int values - (e.g. ``"TOKENS"``) are dropped. - """ - if not usage: - return None - return {k: v for k, v in usage.items() if isinstance(v, int)} - - def set_trace_attributes( span: LangfuseSpan, *, @@ -144,160 +130,6 @@ def extract_response_output( return str(llm_output) -class LangfuseTracer: - def __init__( - self, - credentials: dict | None = None, - session_id: str | None = None, - response_id: str | None = None, - ) -> None: - self.session_id = session_id or str(uuid.uuid4()) - self.langfuse: Langfuse | None = None - self.trace: LangfuseSpan | None = None - self.generation: LangfuseGeneration | None = None - self._failed = False - - has_credentials = ( - credentials - and "public_key" in credentials - and "secret_key" in credentials - and "host" in credentials - ) - - if has_credentials: - try: - # v4 caches one client per public_key (thread-safe singleton); passing - # explicit creds keeps this multi-tenant. Never use bare get_client() — - # with multiple projects in-process it returns a disabled no-op client. - self.langfuse = Langfuse( - public_key=credentials["public_key"], - secret_key=credentials["secret_key"], - host=credentials["host"], - tracing_enabled=True, # This ensures the client is active - tracer_provider=get_langfuse_tracer_provider(), - ) - except Exception as e: - logger.warning( - f"[LangfuseTracer] Failed to initialize: {format_langfuse_error(e)}" - ) - self._failed = True - return - - if response_id: - try: - traces = self.langfuse.api.trace.list(tags=response_id).data - if traces: - self.session_id = traces[0].session_id - except Exception as e: - logger.debug( - f"[LangfuseTracer] Session resume failed: {format_langfuse_error(e)}" - ) - - logger.info( - f"[LangfuseTracer] Tracing enabled | session_id={self.session_id}" - ) - else: - logger.warning("[LangfuseTracer] Tracing disabled - missing credentials") - - def _langfuse_call(self, fn: Callable, *args: Any, **kwargs: Any) -> Any: - if self._failed: - return None - try: - return fn(*args, **kwargs) - except Exception as e: - logger.warning( - f"[LangfuseTracer] {getattr(fn, '__name__', 'operation')} failed: {format_langfuse_error(e)}" - ) - self._failed = True - return None - - def start_trace( - self, - name: str, - input: Any, - metadata: dict[str, Any] | None = None, - tags: list[str] | None = None, - ) -> None: - if self._failed or not self.langfuse: - return - metadata = metadata or {} - metadata["request_id"] = correlation_id.get() or "N/A" - self.trace = self._langfuse_call( - self.langfuse.start_observation, - as_type="span", - name=name, - input=input, - metadata=metadata, - ) - if self.trace: - self._langfuse_call( - set_trace_attributes, - self.trace, - name=name, - input=input, - session_id=self.session_id, - tags=tags, - ) - - def start_generation( - self, - name: str, - input: Any, - metadata: dict[str, Any] | None = None, - ) -> None: - if self._failed or not self.trace: - return - self.generation = self._langfuse_call( - self.trace.start_observation, - as_type="generation", - name=name, - input=input, - metadata=metadata or {}, - ) - - def end_generation( - self, - output: dict[str, Any], - usage: dict[str, Any] | None = None, - model: str | None = None, - ) -> None: - if self._failed or not self.generation: - return - self._langfuse_call( - self.generation.update, - output=output, - usage_details=_to_usage_details(usage), - model=model, - ) - self._langfuse_call(self.generation.end) - - def update_trace(self, tags: list[str], output: dict[str, Any]) -> None: - if self._failed or not self.trace: - return - self._langfuse_call(set_trace_attributes, self.trace, tags=tags, output=output) - self._langfuse_call(self.trace.end) - - def log_error(self, error_message: str, response_id: str | None = None) -> None: - if self._failed: - return - if self.generation: - self._langfuse_call(self.generation.update, output={"error": error_message}) - self._langfuse_call(self.generation.end) - if self.trace: - self._langfuse_call( - set_trace_attributes, - self.trace, - tags=[response_id] if response_id else None, - output={"status": "failure", "error": error_message}, - ) - self._langfuse_call(self.trace.end) - - def flush(self) -> None: - if self._failed or not self.langfuse: - return - self._langfuse_call(self.langfuse.flush) - - def observe_llm_execution( session_id: str | None = None, credentials: dict | None = None, @@ -324,8 +156,9 @@ def wrapper( return func(completion_config, query, **kwargs) try: - # See LangfuseTracer.__init__: explicit per-key client keeps this - # multi-tenant under v4's public_key-keyed client cache. + # v4 caches one client per public_key; passing explicit creds keeps + # this multi-tenant. Never use bare get_client() — with multiple + # projects in-process it returns a disabled no-op client. langfuse = Langfuse( public_key=credentials.get("public_key"), secret_key=credentials.get("secret_key"), diff --git a/backend/app/core/util.py b/backend/app/core/util.py index c7470edae..5ffd29795 100644 --- a/backend/app/core/util.py +++ b/backend/app/core/util.py @@ -3,7 +3,6 @@ from fastapi import HTTPException -from openai import OpenAI from sqlalchemy.exc import IntegrityError logger = logging.getLogger(__name__) @@ -29,25 +28,3 @@ def raise_from_unknown(error: Exception, status_code=500): ) ) raise HTTPException(status_code=status_code, detail=str(error)) - - -def configure_openai(credentials: dict) -> tuple[OpenAI, bool]: - """ - Configure OpenAI client with the provided credentials. - - Args: - credentials: Dictionary containing OpenAI credentials (api_key) - - Returns: - Tuple of (OpenAI client instance, success boolean) - """ - if not credentials or "api_key" not in credentials: - return None, False - - try: - # Configure OpenAI client - client = OpenAI(api_key=credentials["api_key"]) - return client, True - except Exception as e: - logger.warning(f"Failed to configure OpenAI client: {str(e)}") - return None, False diff --git a/backend/app/crud/__init__.py b/backend/app/crud/__init__.py index 1752b99dd..0e3e95821 100644 --- a/backend/app/crud/__init__.py +++ b/backend/app/crud/__init__.py @@ -38,7 +38,6 @@ remove_provider_credential, ) -from .thread_results import upsert_thread_result, get_thread_result from .assistants import ( get_assistant_by_id, diff --git a/backend/app/crud/thread_results.py b/backend/app/crud/thread_results.py deleted file mode 100644 index 3f9c05c5a..000000000 --- a/backend/app/crud/thread_results.py +++ /dev/null @@ -1,34 +0,0 @@ -import logging -from sqlmodel import Session, select -from datetime import datetime -from app.models import OpenAIThreadCreate, OpenAIThread -from app.utils import mask_string - -logger = logging.getLogger(__name__) - - -def upsert_thread_result(session: Session, data: OpenAIThreadCreate): - statement = select(OpenAIThread).where(OpenAIThread.thread_id == data.thread_id) - existing = session.exec(statement).first() - - if existing: - existing.prompt = data.prompt - existing.response = data.response - existing.status = data.status - existing.error = data.error - existing.updated_at = datetime.utcnow() - logger.info( - f"[upsert_thread_result] Updated existing thread result in the db with ID: {mask_string(data.thread_id)}" - ) - else: - new_thread = OpenAIThread(**data.dict()) - session.add(new_thread) - logger.info( - f"[upsert_thread_result] Created new thread result in the db with ID: {mask_string(new_thread.thread_id)}" - ) - session.commit() - - -def get_thread_result(session: Session, thread_id: str) -> OpenAIThread | None: - statement = select(OpenAIThread).where(OpenAIThread.thread_id == thread_id) - return session.exec(statement).first() diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 01b91f759..3d2c96bcb 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -194,7 +194,6 @@ ProjectSettingsUpdate, ProjectUpdate, ) -from .threads import OpenAIThread, OpenAIThreadBase, OpenAIThreadCreate from .user import ( NewPassword, UpdatePassword, diff --git a/backend/app/models/threads.py b/backend/app/models/threads.py deleted file mode 100644 index d4dff77e9..000000000 --- a/backend/app/models/threads.py +++ /dev/null @@ -1,62 +0,0 @@ -from datetime import datetime - -from sqlmodel import Field, SQLModel - -from app.core.util import now - - -class OpenAIThreadBase(SQLModel): - thread_id: str = Field(index=True, unique=True) - prompt: str - response: str | None = None - status: str | None = None - error: str | None = None - - -class OpenAIThreadCreate(OpenAIThreadBase): - pass # Used for requests, no `id` or timestamps - - -class OpenAIThread(OpenAIThreadBase, table=True): - """Stores OpenAI thread interactions and their responses.""" - - __tablename__ = "openai_thread" - - id: int = Field( - default=None, - primary_key=True, - sa_column_kwargs={"comment": "Unique identifier for the thread record"}, - ) - thread_id: str = Field( - index=True, - unique=True, - sa_column_kwargs={"comment": "OpenAI thread identifier"}, - ) - prompt: str = Field( - sa_column_kwargs={"comment": "User prompt sent to the thread"}, - ) - response: str | None = Field( - default=None, - sa_column_kwargs={"comment": "Response received from OpenAI"}, - ) - status: str | None = Field( - default=None, - sa_column_kwargs={"comment": "Current status of the thread interaction"}, - ) - error: str | None = Field( - default=None, - sa_column_kwargs={"comment": "Error message if the interaction failed"}, - ) - - # Timestamps - inserted_at: datetime = Field( - default_factory=now, - sa_column_kwargs={"comment": "Timestamp when the record was created"}, - ) - updated_at: datetime = Field( - default_factory=now, - sa_column_kwargs={ - "comment": "Timestamp when the record was last updated", - "onupdate": now, - }, - ) diff --git a/backend/app/tests/api/routes/test_threads.py b/backend/app/tests/api/routes/test_threads.py deleted file mode 100644 index 56284de44..000000000 --- a/backend/app/tests/api/routes/test_threads.py +++ /dev/null @@ -1,605 +0,0 @@ -import uuid -from unittest.mock import MagicMock, patch - -import pytest -import openai -from openai import OpenAIError -from sqlmodel import select - -from app.api.routes.threads import ( - process_run, - validate_thread, - setup_thread, - process_message_content, - handle_openai_error, - poll_run_and_prepare_response, -) -from app.models import OpenAIThread -from app.crud import get_thread_result -from app.core.langfuse.langfuse import LangfuseTracer - - -@patch("app.api.routes.threads.configure_openai") -@patch("app.api.routes.threads.get_provider_credential") -@patch("app.api.routes.threads.send_callback") -@patch("app.api.routes.threads.process_run") -def test_threads_endpoint( - mock_process_run, - mock_send_callback, - mock_get_provider_credential, - mock_configure_openai, - client, - db, - user_api_key_header, -): - """ - Test the /threads endpoint when creating a new thread. - The patched configure_openai function simulates: - - A successful assistant ID validation. - - New thread creation with a dummy thread id. - - No existing runs. - The expected response should have status "processing" and include a thread_id. - """ - # Create a dummy client to simulate OpenAI API behavior. - dummy_client = MagicMock() - # Simulate a valid assistant ID by ensuring retrieve doesn't raise an error. - dummy_client.beta.assistants.retrieve.return_value = None - # Simulate thread creation. - dummy_thread = MagicMock() - dummy_thread.id = "dummy_thread_id" - dummy_client.beta.threads.create.return_value = dummy_thread - # Simulate message creation. - dummy_client.beta.threads.messages.create.return_value = None - # Simulate that no active run exists. - dummy_client.beta.threads.runs.list.return_value = MagicMock(data=[]) - - # Mock get_provider_credential to return dummy credentials - mock_get_provider_credential.return_value = {"api_key": "dummy_api_key"} - # Mock configure_openai to return our dummy client - mock_configure_openai.return_value = (dummy_client, True) - - request_data = { - "question": "What is Glific?", - "assistant_id": "assistant_123", - "callback_url": "http://example.com/callback", - } - response = client.post( - "/api/v1/threads", json=request_data, headers=user_api_key_header - ) - assert response.status_code == 200 - response_json = response.json() - assert response_json["success"] is True - assert response_json["data"]["status"] == "processing" - assert response_json["data"]["message"] == "Run started" - assert response_json["data"]["thread_id"] == "dummy_thread_id" - - -@patch("app.api.routes.threads.configure_openai") -@patch("app.api.routes.threads.get_provider_credential") -@pytest.mark.parametrize( - "remove_citation, expected_message", - [ - ( - True, - "Glific is an open-source, two-way messaging platform designed for nonprofits to scale their outreach via WhatsApp", - ), - ( - False, - "Glific is an open-source, two-way messaging platform designed for nonprofits to scale their outreach via WhatsApp【1:2†citation】", - ), - ], -) -def test_process_run_variants( - mock_get_provider_credential, - mock_configure_openai, - remove_citation, - expected_message, -): - """ - Test process_run for both remove_citation variants: - - Mocks the configure_openai function to simulate a completed run. - - Verifies that send_callback is called with the expected message based on the remove_citation flag. - """ - # Setup the mock client. - mock_client = MagicMock() - mock_get_provider_credential.return_value = {"api_key": "dummy_api_key"} - mock_configure_openai.return_value = (mock_client, True) - - # Create the request with the variable remove_citation flag. - request = { - "question": "What is Glific?", - "assistant_id": "assistant_123", - "callback_url": "http://example.com/callback", - "thread_id": "thread_123", - "remove_citation": remove_citation, - } - - # Simulate a completed run. - mock_run = MagicMock() - mock_run.status = "completed" - mock_client.beta.threads.runs.create_and_poll.return_value = mock_run - - # Set up the dummy message based on the remove_citation flag. - base_message = "Glific is an open-source, two-way messaging platform designed for nonprofits to scale their outreach via WhatsApp" - citation_message = ( - base_message if remove_citation else f"{base_message}【1:2†citation】" - ) - dummy_message = MagicMock() - dummy_message.content = [MagicMock(text=MagicMock(value=citation_message))] - mock_client.beta.threads.messages.list.return_value.data = [dummy_message] - - tracer = LangfuseTracer() - # Patch send_callback and invoke process_run. - with patch("app.api.routes.threads.send_callback") as mock_send_callback: - process_run(request, mock_client, tracer) - mock_send_callback.assert_called_once() - callback_url, payload = mock_send_callback.call_args[0] - assert callback_url == request["callback_url"] - assert payload["data"]["message"] == expected_message - assert payload["data"]["status"] == "success" - assert payload["data"]["thread_id"] == "thread_123" - assert payload["success"] is True - - -@patch("app.api.routes.threads.configure_openai") -@patch("app.api.routes.threads.get_provider_credential") -def test_threads_sync_endpoint_active_run( - mock_get_provider_credential, mock_configure_openai, client, db, user_api_key_header -): - """Test the /threads/sync endpoint when there's an active run.""" - # Setup mock client - mock_client = MagicMock() - mock_get_provider_credential.return_value = {"api_key": "dummy_api_key"} - mock_configure_openai.return_value = (mock_client, True) - - # Simulate active run - mock_run = MagicMock() - mock_run.status = "in_progress" - mock_client.beta.threads.runs.list.return_value = MagicMock(data=[mock_run]) - - request_data = { - "question": "Test question", - "assistant_id": "assistant_123", - "thread_id": "existing_thread", - } - - # Expect the endpoint to raise when there's an active run - with pytest.raises(Exception) as excinfo: - client.post( - "/api/v1/threads/sync", json=request_data, headers=user_api_key_header - ) - assert "active run" in str(excinfo.value).lower() - - -@patch("app.api.routes.threads.configure_openai") -@patch("app.api.routes.threads.get_provider_credential") -def test_threads_sync_endpoint_success( - mock_get_provider_credential, mock_configure_openai, client, db, user_api_key_header -): - """Test the /threads/sync endpoint for successful completion.""" - # Setup mock client - mock_client = MagicMock() - mock_get_provider_credential.return_value = {"api_key": "dummy_api_key"} - mock_configure_openai.return_value = (mock_client, True) - - # Simulate thread validation (no active runs) - mock_client.beta.threads.runs.list.return_value = MagicMock(data=[]) - - # Simulate thread creation - dummy_thread = MagicMock() - dummy_thread.id = "sync_thread_id" - mock_client.beta.threads.create.return_value = dummy_thread - - # Simulate message creation - mock_client.beta.threads.messages.create.return_value = None - - # Simulate successful run - mock_run = MagicMock() - mock_run.status = "completed" - mock_run.usage.prompt_tokens = 10 - mock_run.usage.completion_tokens = 20 - mock_run.usage.total_tokens = 30 - mock_run.model = "gpt-4" - mock_client.beta.threads.runs.create_and_poll.return_value = mock_run - - # Simulate message retrieval - dummy_message = MagicMock() - dummy_message.content = [MagicMock(text=MagicMock(value="Test response"))] - mock_client.beta.threads.messages.list.return_value.data = [dummy_message] - - request_data = { - "question": "Test question", - "assistant_id": "assistant_123", - } - - response = client.post( - "/api/v1/threads/sync", json=request_data, headers=user_api_key_header - ) - - assert response.status_code == 200 - response_json = response.json() - assert response_json["success"] is True - assert response_json["data"]["status"] == "success" - assert response_json["data"]["message"] == "Test response" - assert response_json["data"]["thread_id"] == "sync_thread_id" - assert "diagnostics" in response_json["data"] - assert response_json["data"]["diagnostics"]["total_tokens"] == 30 - - -def test_validate_thread_no_thread_id(): - """Test validate_thread when no thread_id is provided.""" - mock_client = MagicMock() - is_valid, error = validate_thread(mock_client, None) - assert is_valid is True - assert error is None - - -def test_validate_thread_invalid_thread(): - """Test validate_thread with an invalid thread_id.""" - mock_client = MagicMock() - error = openai.OpenAIError() - error.message = "Invalid thread" - error.response = MagicMock(status_code=404) - error.body = {"message": "Invalid thread"} - mock_client.beta.threads.runs.list.side_effect = error - - is_valid, error = validate_thread(mock_client, "invalid_thread") - assert is_valid is False - assert "Invalid thread ID" in error - - -def test_validate_thread_with_active_run(): - """Test validate_thread when there is an active run.""" - mock_client = MagicMock() - mock_run = MagicMock() - mock_run.status = "in_progress" - mock_client.beta.threads.runs.list.return_value = MagicMock(data=[mock_run]) - - is_valid, error = validate_thread(mock_client, "thread_123") - assert is_valid is False - assert "active run" in error.lower() - assert "in_progress" in error - - -def test_validate_thread_with_queued_run(): - """Test validate_thread when there is a queued run.""" - mock_client = MagicMock() - mock_run = MagicMock() - mock_run.status = "queued" - mock_client.beta.threads.runs.list.return_value = MagicMock(data=[mock_run]) - - is_valid, error = validate_thread(mock_client, "thread_123") - assert is_valid is False - assert "active run" in error.lower() - assert "queued" in error - - -def test_validate_thread_with_requires_action_run(): - """Test validate_thread when there is a run requiring action.""" - mock_client = MagicMock() - mock_run = MagicMock() - mock_run.status = "requires_action" - mock_client.beta.threads.runs.list.return_value = MagicMock(data=[mock_run]) - - is_valid, error = validate_thread(mock_client, "thread_123") - assert is_valid is False - assert "active run" in error.lower() - assert "requires_action" in error - - -def test_validate_thread_with_completed_run(): - """Test validate_thread when there is a completed run.""" - mock_client = MagicMock() - mock_run = MagicMock() - mock_run.status = "completed" - mock_client.beta.threads.runs.list.return_value = MagicMock(data=[mock_run]) - - is_valid, error = validate_thread(mock_client, "thread_123") - assert is_valid is True - assert error is None - - -def test_validate_thread_with_no_runs(): - """Test validate_thread when there are no runs.""" - mock_client = MagicMock() - mock_client.beta.threads.runs.list.return_value = MagicMock(data=[]) - - is_valid, error = validate_thread(mock_client, "thread_123") - assert is_valid is True - assert error is None - - -def test_setup_thread_new_thread(): - """Test setup_thread for creating a new thread.""" - mock_client = MagicMock() - mock_thread = MagicMock() - mock_thread.id = "new_thread_id" - mock_client.beta.threads.create.return_value = mock_thread - mock_client.beta.threads.messages.create.return_value = None - - request = {"question": "Test question"} - is_success, error = setup_thread(mock_client, request) - - assert is_success is True - assert error is None - assert request["thread_id"] == "new_thread_id" - - -def test_setup_thread_existing_thread(): - """Test setup_thread for using an existing thread.""" - mock_client = MagicMock() - mock_client.beta.threads.messages.create.return_value = None - - request = {"question": "Test question", "thread_id": "existing_thread"} - is_success, error = setup_thread(mock_client, request) - - assert is_success is True - assert error is None - - -def test_process_message_content(): - """Test process_message_content with and without citation removal.""" - message = "Test message【1:2†citation】" - - # Test with citation removal - processed = process_message_content(message, True) - assert processed == "Test message" - - # Test without citation removal - processed = process_message_content(message, False) - assert processed == message - - -def test_handle_openai_error(): - """Test handle_openai_error with different error types.""" - # Test with error containing message in body - error = MagicMock() - error.body = {"message": "Test error message"} - assert handle_openai_error(error) == "Test error message" - - # Test with error without message in body - error = MagicMock() - error.body = {} - error.__str__.return_value = "Generic error" - assert handle_openai_error(error) == "Generic error" - - -def test_handle_openai_error_with_message(): - """Test handle_openai_error when error has a message in its body.""" - error = MagicMock() - error.body = {"message": "Test error message"} - result = handle_openai_error(error) - assert result == "Test error message" - - -def test_handle_openai_error_without_message(): - """Test handle_openai_error when error doesn't have a message in its body.""" - error = MagicMock() - error.body = {"some_other_field": "value"} - error.__str__.return_value = "Generic error message" - result = handle_openai_error(error) - assert result == "Generic error message" - - -def test_handle_openai_error_with_empty_body(): - """Test handle_openai_error when error has an empty body.""" - error = MagicMock() - error.body = {} - error.__str__.return_value = "Empty body error" - result = handle_openai_error(error) - assert result == "Empty body error" - - -def test_handle_openai_error_with_non_dict_body(): - """Test handle_openai_error when error body is not a dictionary.""" - error = MagicMock() - error.body = "Not a dictionary" - error.__str__.return_value = "Non-dict body error" - result = handle_openai_error(error) - assert result == "Non-dict body error" - - -def test_handle_openai_error_with_none_body(): - """Test handle_openai_error when error body is None.""" - error = MagicMock() - error.body = None - error.__str__.return_value = "None body error" - result = handle_openai_error(error) - assert result == "None body error" - - -@patch("app.api.routes.threads.configure_openai") -@patch("app.api.routes.threads.get_provider_credential") -def test_poll_run_and_prepare_response_completed( - mock_get_provider_credential, mock_configure_openai, db -): - mock_client = MagicMock() - mock_run = MagicMock() - mock_run.status = "completed" - mock_client.beta.threads.runs.create_and_poll.return_value = mock_run - - mock_message = MagicMock() - mock_message.content = [MagicMock(text=MagicMock(value="Answer"))] - mock_client.beta.threads.messages.list.return_value.data = [mock_message] - mock_get_provider_credential.return_value = {"api_key": "dummy_api_key"} - mock_configure_openai.return_value = (mock_client, True) - - request = { - "question": "What is Glific?", - "assistant_id": "assist_123", - "thread_id": "test_thread_001", - "remove_citation": True, - } - - poll_run_and_prepare_response(request, mock_client, db) - - result = get_thread_result(db, "test_thread_001") - assert result.response.strip() == "Answer" - - -@patch("app.api.routes.threads.configure_openai") -@patch("app.api.routes.threads.get_provider_credential") -def test_poll_run_and_prepare_response_openai_error_handling( - mock_get_provider_credential, mock_configure_openai, db -): - mock_client = MagicMock() - mock_error = OpenAIError("Simulated OpenAI error") - mock_client.beta.threads.runs.create_and_poll.side_effect = mock_error - mock_get_provider_credential.return_value = {"api_key": "dummy_api_key"} - mock_configure_openai.return_value = (mock_client, True) - - request = { - "question": "Failing run", - "assistant_id": "assist_123", - "thread_id": "test_openai_error", - } - - poll_run_and_prepare_response(request, mock_client, db) - - # Since thread_id is not the primary key, use select query - statement = select(OpenAIThread).where( - OpenAIThread.thread_id == "test_openai_error" - ) - result = db.exec(statement).first() - - assert result is not None - assert result.response is None - assert result.status == "failed" - assert "Simulated OpenAI error" in (result.error or "") - - -@patch("app.api.routes.threads.configure_openai") -@patch("app.api.routes.threads.get_provider_credential") -def test_poll_run_and_prepare_response_non_completed( - mock_get_provider_credential, mock_configure_openai, db -): - mock_client = MagicMock() - mock_run = MagicMock(status="failed") - mock_client.beta.threads.runs.create_and_poll.return_value = mock_run - mock_get_provider_credential.return_value = {"api_key": "dummy_api_key"} - mock_configure_openai.return_value = (mock_client, True) - - request = { - "question": "Incomplete run", - "assistant_id": "assist_123", - "thread_id": "test_non_complete", - } - - poll_run_and_prepare_response(request, mock_client, db) - - # thread_id is not the primary key, so we query using SELECT - statement = select(OpenAIThread).where( - OpenAIThread.thread_id == "test_non_complete" - ) - result = db.exec(statement).first() - - assert result is not None - assert result.response is None - assert result.status == "failed" - - -@patch("app.api.routes.threads.configure_openai") -@patch("app.api.routes.threads.get_provider_credential") -@patch("app.api.routes.threads.poll_run_and_prepare_response") -def test_threads_start_endpoint_creates_thread( - mock_poll_run, - mock_get_provider_credential, - mock_configure_openai, - client, - db, - user_api_key_header, -): - """Test /threads/start creates thread and schedules background task.""" - mock_client = MagicMock() - mock_thread = MagicMock() - mock_thread.id = "mock_thread_001" - mock_client.beta.threads.create.return_value = mock_thread - mock_client.beta.threads.messages.create.return_value = None - mock_get_provider_credential.return_value = {"api_key": "dummy_api_key"} - mock_configure_openai.return_value = (mock_client, True) - - data = {"question": "What's 2+2?", "assistant_id": "assist_123"} - - response = client.post( - "/api/v1/threads/start", json=data, headers=user_api_key_header - ) - assert response.status_code == 200 - res_json = response.json() - assert res_json["success"] - assert res_json["data"]["thread_id"] == "mock_thread_001" - assert res_json["data"]["status"] == "processing" - assert res_json["data"]["prompt"] == "What's 2+2?" - - -def test_threads_result_endpoint_success(client, db, user_api_key_header): - """Test /threads/result/{thread_id} returns completed thread.""" - thread_id = f"test_processing_{uuid.uuid4()}" - question = "Capital of France?" - message = "Paris." - - db.add(OpenAIThread(thread_id=thread_id, prompt=question, response=message)) - db.commit() - - response = client.get( - f"/api/v1/threads/result/{thread_id}", headers=user_api_key_header - ) - - assert response.status_code == 200 - data = response.json()["data"] - assert data["status"] == "success" - assert data["response"] == "Paris." - assert data["thread_id"] == thread_id - assert data["prompt"] == question - - -def test_threads_result_endpoint_processing(client, db, user_api_key_header): - """Test /threads/result/{thread_id} returns processing status if no message yet.""" - thread_id = f"test_processing_{uuid.uuid4()}" - question = "What is Glific?" - - db.add(OpenAIThread(thread_id=thread_id, prompt=question, response=None)) - db.commit() - - response = client.get( - f"/api/v1/threads/result/{thread_id}", headers=user_api_key_header - ) - - assert response.status_code == 200 - data = response.json()["data"] - assert data["status"] == "processing" - assert data["response"] is None - assert data["thread_id"] == thread_id - assert data["prompt"] == question - - -def test_threads_result_not_found(client, user_api_key_header): - """Test /threads/result/{thread_id} returns error for nonexistent thread.""" - response = client.get( - "/api/v1/threads/result/nonexistent_thread", headers=user_api_key_header - ) - assert response.status_code == 404 - response_data = response.json() - assert response_data["success"] is False - assert "thread not found" in response_data["error"].lower() - - -@patch("app.api.routes.threads.configure_openai") -@patch("app.api.routes.threads.get_provider_credential") -def test_threads_start_missing_question( - mock_get_provider_credential, mock_configure_openai, client, user_api_key_header -): - """Test /threads/start with missing 'question' key in request.""" - mock_get_provider_credential.return_value = {"api_key": "dummy_api_key"} - mock_configure_openai.return_value = (MagicMock(), True) - - bad_data = {"assistant_id": "assist_123"} # no "question" key - - response = client.post( - "/api/v1/threads/start", json=bad_data, headers=user_api_key_header - ) - - assert response.status_code == 422 # Unprocessable Entity (FastAPI will raise 422) - error_response = response.json() - assert error_response["success"] is False - assert error_response["errors"] - assert any("question" in e["field"] for e in error_response["errors"]) diff --git a/backend/app/tests/core/test_langfuse/conftest.py b/backend/app/tests/core/test_langfuse/conftest.py index 9821f2467..d085a9be9 100644 --- a/backend/app/tests/core/test_langfuse/conftest.py +++ b/backend/app/tests/core/test_langfuse/conftest.py @@ -1,5 +1,5 @@ """ -Local conftest for LangfuseTracer unit tests. +Local conftest for Langfuse helper unit tests. These tests don't require database access, so we override the session-scoped seed_baseline fixture to skip database seeding. diff --git a/backend/app/tests/core/test_langfuse/test_langfuse_tracer.py b/backend/app/tests/core/test_langfuse/test_langfuse_tracer.py deleted file mode 100644 index 1d678ee12..000000000 --- a/backend/app/tests/core/test_langfuse/test_langfuse_tracer.py +++ /dev/null @@ -1,294 +0,0 @@ -"""Unit tests for LangfuseTracer class (Langfuse v4 SDK).""" - -import pytest -from unittest.mock import MagicMock, patch - -from app.core.langfuse.langfuse import LangfuseTracer - - -@pytest.fixture -def valid_credentials() -> dict: - def _create(**overrides) -> dict: - defaults = { - "public_key": "pk-test-123", - "secret_key": "sk-test-456", - "host": "https://langfuse.example.com", - } - return {**defaults, **overrides} - - return _create() - - -def make_langfuse_mock() -> tuple[MagicMock, MagicMock, MagicMock]: - """Build a mock v4 Langfuse client plus its root span and generation. - - v4 flow: ``client.start_observation(as_type="span")`` -> root span; - ``root.start_observation(as_type="generation")`` -> generation. Trace-level - attributes are written via ``root._otel_span.set_attributes(...)`` (auto-mocked). - """ - client = MagicMock() - root_span = MagicMock() - root_span.trace_id = "trace-abc123" - generation = MagicMock() - root_span.start_observation.return_value = generation - client.start_observation.return_value = root_span - # No prior traces by default (session resume returns empty) - client.api.trace.list.return_value.data = [] - return client, root_span, generation - - -class TestLangfuseTracerInit: - """Tests for LangfuseTracer initialization.""" - - def test_no_credentials_sets_langfuse_to_none(self) -> None: - tracer = LangfuseTracer(credentials=None) - assert tracer.langfuse is None - assert tracer.trace is None - assert tracer.generation is None - - def test_empty_credentials_sets_langfuse_to_none(self) -> None: - tracer = LangfuseTracer(credentials={}) - assert tracer.langfuse is None - - def test_missing_public_key_sets_langfuse_to_none(self) -> None: - tracer = LangfuseTracer( - credentials={"secret_key": "sk", "host": "https://x.com"} - ) - assert tracer.langfuse is None - - def test_missing_secret_key_sets_langfuse_to_none(self) -> None: - tracer = LangfuseTracer( - credentials={"public_key": "pk", "host": "https://x.com"} - ) - assert tracer.langfuse is None - - def test_missing_host_sets_langfuse_to_none(self) -> None: - tracer = LangfuseTracer(credentials={"public_key": "pk", "secret_key": "sk"}) - assert tracer.langfuse is None - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_langfuse_exception_sets_langfuse_to_none( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - mock_langfuse_class.side_effect = Exception("Connection failed") - tracer = LangfuseTracer(credentials=valid_credentials) - assert tracer.langfuse is None - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_session_resume_failure_keeps_tracer_enabled( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, _, _ = make_langfuse_mock() - client.api.trace.list.side_effect = Exception("Network error") - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials, response_id="resp-123") - - assert tracer.langfuse is not None - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_resumes_session_from_existing_traces( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - existing_trace = MagicMock() - existing_trace.session_id = "existing-session-456" - - client, _, _ = make_langfuse_mock() - client.api.trace.list.return_value.data = [existing_trace] - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials, response_id="resp-123") - - assert tracer.session_id == "existing-session-456" - client.api.trace.list.assert_called_once_with(tags="resp-123") - - -class TestLangfuseTracerMethodsDisabled: - """Tests that methods are no-ops when Langfuse is disabled.""" - - def test_start_trace_is_noop(self) -> None: - tracer = LangfuseTracer(credentials=None) - tracer.start_trace(name="test", input={"question": "hello"}) - assert tracer.trace is None - - def test_start_generation_is_noop(self) -> None: - tracer = LangfuseTracer(credentials=None) - tracer.start_generation(name="test", input={"question": "hello"}) - assert tracer.generation is None - - def test_end_generation_is_noop(self) -> None: - tracer = LangfuseTracer(credentials=None) - tracer.end_generation(output={"response": "world"}) - - def test_update_trace_is_noop(self) -> None: - tracer = LangfuseTracer(credentials=None) - tracer.update_trace(tags=["test"], output={"status": "success"}) - - def test_log_error_is_noop(self) -> None: - tracer = LangfuseTracer(credentials=None) - tracer.log_error(error_message="Test error", response_id="resp-123") - - def test_flush_is_noop(self) -> None: - tracer = LangfuseTracer(credentials=None) - tracer.flush() - - -class TestLangfuseTracerMethodsFailure: - """Tests that method failures are caught and don't propagate.""" - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_start_trace_exception_is_caught( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, _, _ = make_langfuse_mock() - client.start_observation.side_effect = Exception("Trace creation failed") - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials) - tracer.start_trace(name="test", input={"q": "hello"}) - - assert tracer.trace is None - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_start_generation_exception_is_caught( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, root_span, _ = make_langfuse_mock() - root_span.start_observation.side_effect = Exception("Generation failed") - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials) - tracer.start_trace(name="test", input={"q": "hello"}) - tracer.start_generation(name="gen", input={"q": "hello"}) - - assert tracer.generation is None - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_end_generation_exception_is_caught( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, _, generation = make_langfuse_mock() - generation.update.side_effect = Exception("End failed") - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials) - tracer.start_trace(name="test", input={"q": "hello"}) - tracer.start_generation(name="gen", input={"q": "hello"}) - tracer.end_generation(output={"response": "world"}) - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_update_trace_exception_is_caught( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, root_span, _ = make_langfuse_mock() - root_span.end.side_effect = Exception("Update failed") - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials) - tracer.start_trace(name="test", input={"q": "hello"}) - tracer.update_trace(tags=["test"], output={"status": "success"}) - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_flush_exception_is_caught( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, _, _ = make_langfuse_mock() - client.flush.side_effect = Exception("Flush failed") - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials) - tracer.flush() - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_log_error_exception_is_caught( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, root_span, generation = make_langfuse_mock() - generation.update.side_effect = Exception("End failed") - root_span.end.side_effect = Exception("Log error failed") - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials) - tracer.start_trace(name="test", input={"q": "hello"}) - tracer.start_generation(name="gen", input={"q": "hello"}) - tracer.log_error(error_message="Test error", response_id="resp-123") - - -class TestLangfuseTracerSuccess: - """Tests for successful tracer operations.""" - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_full_tracing_flow( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, root_span, generation = make_langfuse_mock() - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials) - tracer.start_trace(name="test", input={"q": "hello"}) - tracer.start_generation(name="gen", input={"q": "hello"}) - tracer.end_generation( - output={"response": "world"}, - usage={"input": 10, "output": 20, "total": 30}, - model="gpt-4", - ) - tracer.update_trace(tags=["resp-123"], output={"status": "success"}) - tracer.flush() - - client.start_observation.assert_called_once() - root_span.start_observation.assert_called_once() - generation.update.assert_called_once() - generation.end.assert_called_once() - root_span.end.assert_called_once() - client.flush.assert_called_once() - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_end_generation_converts_usage_to_usage_details( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, _, generation = make_langfuse_mock() - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials) - tracer.start_trace(name="test", input={"q": "hello"}) - tracer.start_generation(name="gen", input={"q": "hello"}) - tracer.end_generation( - output={"response": "world"}, - usage={"input": 10, "output": 20, "total": 30, "unit": "TOKENS"}, - model="gpt-4", - ) - - # v4 uses usage_details (int-only) and drops the v2 "unit" string field - _, kwargs = generation.update.call_args - assert kwargs["usage_details"] == {"input": 10, "output": 20, "total": 30} - assert kwargs["model"] == "gpt-4" - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_start_generation_without_trace_is_noop( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, _, _ = make_langfuse_mock() - client.start_observation.side_effect = Exception("Trace failed") - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials) - tracer.start_trace(name="test", input={"q": "hello"}) # Fails - assert tracer.trace is None - - tracer.start_generation(name="gen", input={"q": "hello"}) - assert tracer.generation is None - - @patch("app.core.langfuse.langfuse.Langfuse") - def test_end_generation_without_generation_is_noop( - self, mock_langfuse_class: MagicMock, valid_credentials: dict - ) -> None: - client, root_span, _ = make_langfuse_mock() - root_span.start_observation.side_effect = Exception("Generation failed") - mock_langfuse_class.return_value = client - - tracer = LangfuseTracer(credentials=valid_credentials) - tracer.start_trace(name="test", input={"q": "hello"}) - tracer.start_generation(name="gen", input={"q": "hello"}) # Fails - assert tracer.generation is None - - tracer.end_generation(output={"response": "world"}) # No exception diff --git a/backend/app/tests/crud/test_thread_result.py b/backend/app/tests/crud/test_thread_result.py deleted file mode 100644 index b82a5a8d5..000000000 --- a/backend/app/tests/crud/test_thread_result.py +++ /dev/null @@ -1,46 +0,0 @@ -from sqlmodel import Session - -from app.models import OpenAIThreadCreate -from app.crud import upsert_thread_result, get_thread_result - - -def test_upsert_and_get_thread_result(db: Session): - thread_id = "thread_test_123" - prompt = "What is the capital of Spain?" - response = "Madrid is the capital of Spain." - - # Insert - upsert_thread_result( - db, - OpenAIThreadCreate( - thread_id=thread_id, - prompt=prompt, - response=response, - status="completed", - error=None, - ), - ) - - # Retrieve - result = get_thread_result(db, thread_id) - - assert result is not None - assert result.thread_id == thread_id - assert result.prompt == prompt - assert result.response == response - - # Update with new response - updated_response = "Madrid." - upsert_thread_result( - db, - OpenAIThreadCreate( - thread_id=thread_id, - prompt=prompt, - response=updated_response, - status="completed", - error=None, - ), - ) - - result_updated = get_thread_result(db, thread_id) - assert result_updated.response == updated_response diff --git a/docs/wiki/INDEX.md b/docs/wiki/INDEX.md index 83ce11467..924498517 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, vector-store providers. Deep dive: `docs/architecture/kaapi-knowledge-base-ARCHITECTURE.md` -- [modules/assistants.md](modules/assistants.md) — OpenAI assistants and threads. No deep-dive doc yet. +- [modules/assistants.md](modules/assistants.md) — OpenAI assistant CRUD. 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 c997fe28d..8e1550d91 100644 --- a/docs/wiki/domain-map.md +++ b/docs/wiki/domain-map.md @@ -42,7 +42,6 @@ APIKey → Organization, Project, User # programmatic access | CollectionJob | collection_job.py | Collection, Project | async collection create/delete (logical) | | File | file.py | Org, Project | STT samples; object storage keys (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 | | FeatureFlag | feature_flag.py | Org, Project | route gating (logical) | | Notification | notification.py | Project, User | notification service | diff --git a/docs/wiki/modules/assistants.md b/docs/wiki/modules/assistants.md index 8d2c8a5cf..64d1c73c6 100644 --- a/docs/wiki/modules/assistants.md +++ b/docs/wiki/modules/assistants.md @@ -1,21 +1,19 @@ -# Module: Assistants & Threads +# Module: Assistants -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. +OpenAI assistant CRUD. The Responses API, OpenAI conversations and Threads were removed (`openai_conversation` and `openai_thread` are dropped in migrations 095 and 098). No deep-dive doc yet. All paths relative to `backend/app/`. ## Routes -- `api/routes/threads.py` — thread results -- `api/routes/assistants.py` — assistant CRUD +- `api/routes/assistants.py` — assistant CRUD (tagged deprecated in OpenAPI) ## Tables (SQLModel) | Table | Model | |---|---| -| `openai_thread` (OpenAIThread) | `models/threads.py` | | `assistant` (Assistant) | `models/assistants.py` | ## Services / CRUD -- `crud/assistants.py`, `crud/thread_results.py` +- `crud/assistants.py` ## External -- OpenAI Assistants API, Langfuse tracing. +- OpenAI Assistants API.