|
1 | 1 | import uuid
|
2 | 2 | from typing import Any, Dict, List, Optional, Union
|
3 | 3 |
|
4 |
| -import aiohttp |
| 4 | +import httpx |
5 | 5 | from chainlit.logger import logger
|
6 | 6 |
|
7 | 7 | from .base import (
|
@@ -459,41 +459,37 @@ async def upload_element(
|
459 | 459 | if conversation_id:
|
460 | 460 | body["conversationId"] = conversation_id
|
461 | 461 |
|
462 |
| - path = f"/api/upload/file" |
| 462 | + path = "/api/upload/file" |
463 | 463 |
|
464 |
| - async with aiohttp.ClientSession() as session: |
465 |
| - async with session.post( |
| 464 | + async with httpx.AsyncClient() as client: |
| 465 | + response = await client.post( |
466 | 466 | f"{self.chainlit_server}{path}",
|
467 | 467 | json=body,
|
468 | 468 | headers=self.headers,
|
469 |
| - ) as r: |
470 |
| - if not r.ok: |
471 |
| - reason = await r.text() |
472 |
| - logger.error(f"Failed to sign upload url: {reason}") |
473 |
| - return {"object_key": None, "url": None} |
474 |
| - json_res = await r.json() |
| 469 | + ) |
| 470 | + if response.status_code != 200: |
| 471 | + reason = response.text |
| 472 | + logger.error(f"Failed to sign upload url: {reason}") |
| 473 | + return {"object_key": None, "url": None} |
| 474 | + json_res = response.json() |
475 | 475 |
|
476 | 476 | upload_details = json_res["post"]
|
477 | 477 | object_key = upload_details["fields"]["key"]
|
478 | 478 | signed_url = json_res["signedUrl"]
|
479 | 479 |
|
480 |
| - form_data = aiohttp.FormData() |
| 480 | + # Prepare form data |
| 481 | + form_data = upload_details["fields"].copy() |
| 482 | + form_data["file"] = (id, content, "multipart/form-data") |
481 | 483 |
|
482 |
| - # Add fields to the form_data |
483 |
| - for field_name, field_value in upload_details["fields"].items(): |
484 |
| - form_data.add_field(field_name, field_value) |
485 |
| - |
486 |
| - # Add file to the form_data |
487 |
| - form_data.add_field("file", content, content_type="multipart/form-data") |
488 |
| - async with aiohttp.ClientSession() as session: |
489 |
| - async with session.post( |
| 484 | + async with httpx.AsyncClient() as client: |
| 485 | + upload_response = await client.post( |
490 | 486 | upload_details["url"],
|
491 |
| - data=form_data, |
492 |
| - ) as upload_response: |
493 |
| - if not upload_response.ok: |
494 |
| - reason = await upload_response.text() |
495 |
| - logger.error(f"Failed to upload file: {reason}") |
496 |
| - return {"object_key": None, "url": None} |
497 |
| - |
| 487 | + files=form_data, |
| 488 | + ) |
| 489 | + try: |
| 490 | + upload_response.raise_for_status() |
498 | 491 | url = f'{upload_details["url"]}/{object_key}'
|
499 | 492 | return {"object_key": object_key, "url": signed_url}
|
| 493 | + except Exception as e: |
| 494 | + logger.error(f"Failed to upload file: {str(e)}") |
| 495 | + return {"object_key": None, "url": None} |
0 commit comments