|
| 1 | +import re |
| 2 | +import requests |
| 3 | + |
| 4 | +import openai |
| 5 | +from openai import OpenAI |
| 6 | +from fastapi import APIRouter, BackgroundTasks |
| 7 | + |
| 8 | +from app.utils import APIResponse |
| 9 | +from app.core import settings, logging |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | +router = APIRouter(tags=["threads"]) |
| 13 | + |
| 14 | + |
| 15 | +def send_callback(callback_url: str, data: dict): |
| 16 | + """Send results to the callback URL (synchronously).""" |
| 17 | + try: |
| 18 | + session = requests.Session() |
| 19 | + # uncomment this to run locally without SSL |
| 20 | + # session.verify = False |
| 21 | + response = session.post(callback_url, json=data) |
| 22 | + response.raise_for_status() |
| 23 | + return True |
| 24 | + except requests.RequestException as e: |
| 25 | + logger.error(f"Callback failed: {str(e)}") |
| 26 | + return False |
| 27 | + |
| 28 | + |
| 29 | +def process_run(request: dict, client: OpenAI): |
| 30 | + """ |
| 31 | + Background task to run create_and_poll, then send the callback with the result. |
| 32 | + This function is run in the background after we have already returned an initial response. |
| 33 | + """ |
| 34 | + try: |
| 35 | + # Start the run |
| 36 | + run = client.beta.threads.runs.create_and_poll( |
| 37 | + thread_id=request["thread_id"], |
| 38 | + assistant_id=request["assistant_id"], |
| 39 | + ) |
| 40 | + |
| 41 | + if run.status == "completed": |
| 42 | + messages = client.beta.threads.messages.list( |
| 43 | + thread_id=request["thread_id"]) |
| 44 | + latest_message = messages.data[0] |
| 45 | + message_content = latest_message.content[0].text.value |
| 46 | + |
| 47 | + remove_citation = request.get("remove_citation", False) |
| 48 | + |
| 49 | + if remove_citation: |
| 50 | + message = re.sub(r"【\d+(?::\d+)?†[^】]*】", "", message_content) |
| 51 | + else: |
| 52 | + message = message_content |
| 53 | + |
| 54 | + # Update the data dictionary with additional fields from the request, excluding specific keys |
| 55 | + additional_data = {k: v for k, v in request.items( |
| 56 | + ) if k not in {"question", "assistant_id", "callback_url", "thread_id"}} |
| 57 | + callback_response = APIResponse.success_response(data={ |
| 58 | + "status": "success", |
| 59 | + "message": message, |
| 60 | + "thread_id": request["thread_id"], |
| 61 | + "endpoint": getattr(request, "endpoint", "some-default-endpoint"), |
| 62 | + **additional_data |
| 63 | + }) |
| 64 | + else: |
| 65 | + callback_response = APIResponse.failure_response( |
| 66 | + error=f"Run failed with status: {run.status}") |
| 67 | + |
| 68 | + # Send callback with results |
| 69 | + send_callback(request["callback_url"], callback_response.model_dump()) |
| 70 | + |
| 71 | + except openai.OpenAIError as e: |
| 72 | + # Handle any other OpenAI API errors |
| 73 | + if isinstance(e.body, dict) and "message" in e.body: |
| 74 | + error_message = e.body["message"] |
| 75 | + else: |
| 76 | + error_message = str(e) |
| 77 | + |
| 78 | + callback_response = APIResponse.failure_response(error=error_message) |
| 79 | + |
| 80 | + send_callback(request["callback_url"], callback_response.model_dump()) |
| 81 | + |
| 82 | + |
| 83 | +@router.post("/threads") |
| 84 | +async def threads(request: dict, background_tasks: BackgroundTasks): |
| 85 | + """ |
| 86 | + Accepts a question, assistant_id, callback_url, and optional thread_id from the request body. |
| 87 | + Returns an immediate "processing" response, then continues to run create_and_poll in background. |
| 88 | + Once completed, calls send_callback with the final result. |
| 89 | + """ |
| 90 | + client = OpenAI(api_key=settings.OPENAI_API_KEY) |
| 91 | + |
| 92 | + # Use get method to safely access thread_id |
| 93 | + thread_id = request.get("thread_id") |
| 94 | + |
| 95 | + # 1. Validate or check if there's an existing thread with an in-progress run |
| 96 | + if thread_id: |
| 97 | + try: |
| 98 | + runs = client.beta.threads.runs.list(thread_id=thread_id) |
| 99 | + # Get the most recent run (first in the list) if any |
| 100 | + if runs.data and len(runs.data) > 0: |
| 101 | + latest_run = runs.data[0] |
| 102 | + if latest_run.status in ["queued", "in_progress", "requires_action"]: |
| 103 | + return APIResponse.failure_response(error=f"There is an active run on this thread (status: {latest_run.status}). Please wait for it to complete.") |
| 104 | + except openai.OpenAIError: |
| 105 | + # Handle invalid thread ID |
| 106 | + return APIResponse.failure_response(error=f"Invalid thread ID provided {thread_id}") |
| 107 | + |
| 108 | + # Use existing thread |
| 109 | + client.beta.threads.messages.create( |
| 110 | + thread_id=thread_id, role="user", content=request["question"] |
| 111 | + ) |
| 112 | + else: |
| 113 | + try: |
| 114 | + # Create new thread |
| 115 | + thread = client.beta.threads.create() |
| 116 | + client.beta.threads.messages.create( |
| 117 | + thread_id=thread.id, role="user", content=request["question"] |
| 118 | + ) |
| 119 | + request["thread_id"] = thread.id |
| 120 | + except openai.OpenAIError as e: |
| 121 | + # Handle any other OpenAI API errors |
| 122 | + if isinstance(e.body, dict) and "message" in e.body: |
| 123 | + error_message = e.body["message"] |
| 124 | + else: |
| 125 | + error_message = str(e) |
| 126 | + return APIResponse.failure_response(error=error_message) |
| 127 | + |
| 128 | + # 2. Send immediate response to complete the API call |
| 129 | + initial_response = APIResponse.success_response(data={ |
| 130 | + "status": "processing", |
| 131 | + "message": "Run started", |
| 132 | + "thread_id": request.get("thread_id"), |
| 133 | + "success": True, |
| 134 | + }) |
| 135 | + |
| 136 | + # 3. Schedule the background task to run create_and_poll and send callback |
| 137 | + background_tasks.add_task(process_run, request, client) |
| 138 | + |
| 139 | + # 4. Return immediately so the client knows we've accepted the request |
| 140 | + return initial_response |
0 commit comments