|
1 | 1 | import inspect |
2 | 2 | import logging |
3 | 3 | import time |
| 4 | +import json |
| 5 | +import ast |
| 6 | +import re |
4 | 7 | from uuid import UUID, uuid4 |
5 | 8 | from typing import Any, List, Optional |
6 | 9 | from dataclasses import dataclass, field, fields, asdict, replace |
|
13 | 16 |
|
14 | 17 | from app.api.deps import CurrentUser, SessionDep, CurrentUserOrgProject |
15 | 18 | from app.core.cloud import AmazonCloudStorage |
| 19 | +from app.api.routes.responses import handle_openai_error |
16 | 20 | from app.core.util import now, post_callback |
17 | 21 | from app.crud import ( |
18 | 22 | DocumentCrud, |
|
28 | 32 | router = APIRouter(prefix="/collections", tags=["collections"]) |
29 | 33 |
|
30 | 34 |
|
| 35 | +def extract_error_message(err: Exception) -> str: |
| 36 | + err_str = str(err).strip() |
| 37 | + |
| 38 | + body = re.sub(r"^Error code:\s*\d+\s*-\s*", "", err_str) |
| 39 | + message = None |
| 40 | + try: |
| 41 | + payload = json.loads(body) |
| 42 | + if isinstance(payload, dict): |
| 43 | + message = payload.get("error", {}).get("message") |
| 44 | + except Exception: |
| 45 | + pass |
| 46 | + |
| 47 | + if message is None: |
| 48 | + try: |
| 49 | + payload = ast.literal_eval(body) |
| 50 | + if isinstance(payload, dict): |
| 51 | + message = payload.get("error", {}).get("message") |
| 52 | + except Exception: |
| 53 | + pass |
| 54 | + |
| 55 | + if not message: |
| 56 | + message = body |
| 57 | + |
| 58 | + return message.strip()[:1000] |
| 59 | + |
| 60 | + |
31 | 61 | @dataclass |
32 | 62 | class ResponsePayload: |
33 | 63 | status: str |
@@ -246,6 +276,9 @@ def do_create_collection( |
246 | 276 | collection = collection_crud.read_one(UUID(payload.key)) |
247 | 277 | collection.status = CollectionStatus.failed |
248 | 278 | collection.updated_at = now() |
| 279 | + message = extract_error_message(err) |
| 280 | + collection.error_message = message |
| 281 | + |
249 | 282 | collection_crud._update(collection) |
250 | 283 | except Exception as suberr: |
251 | 284 | logger.warning( |
@@ -283,7 +316,6 @@ def create_collection( |
283 | 316 | collection_crud = CollectionCrud(session, current_user.id) |
284 | 317 | collection_crud.create(collection) |
285 | 318 |
|
286 | | - # 2. Launch background task |
287 | 319 | background_tasks.add_task( |
288 | 320 | do_create_collection, session, current_user, request, payload, client |
289 | 321 | ) |
|
0 commit comments