|
7 | 7 | from typing import AsyncGenerator, Dict, Any, Callable, cast |
8 | 8 | from pydantic import ValidationError |
9 | 9 | from fastapi.templating import Jinja2Templates |
10 | | -from fastapi import APIRouter, Form, Depends, Request |
| 10 | +from fastapi import APIRouter, Form, Depends, Request, UploadFile, File |
11 | 11 | from fastapi.responses import StreamingResponse, HTMLResponse |
12 | 12 | from openai.types.responses import ( |
13 | 13 | ResponseCreatedEvent, ResponseOutputItemAddedEvent, |
@@ -57,23 +57,42 @@ async def send_message( |
57 | 57 | request: Request, |
58 | 58 | conversation_id: str, |
59 | 59 | userInput: str = Form(...), |
| 60 | + image: UploadFile | None = File(None), |
60 | 61 | client: AsyncOpenAI = Depends(lambda: AsyncOpenAI()) |
61 | 62 | ) -> HTMLResponse: |
| 63 | + # Build multimodal content array |
| 64 | + content: list[dict[str, str]] = [{ |
| 65 | + "type": "input_text", |
| 66 | + "text": f"System: Today's date is {datetime.today().strftime('%Y-%m-%d')}\n{userInput}" |
| 67 | + }] |
| 68 | + |
| 69 | + # If an image was uploaded, send it to OpenAI and add to content |
| 70 | + image_file_id: str | None = None |
| 71 | + if image and image.filename and image.size: |
| 72 | + image_bytes = await image.read() |
| 73 | + if image_bytes: |
| 74 | + openai_file = await client.files.create( |
| 75 | + file=(image.filename, image_bytes), |
| 76 | + purpose="vision" |
| 77 | + ) |
| 78 | + image_file_id = openai_file.id |
| 79 | + content.append({ |
| 80 | + "type": "input_image", |
| 81 | + "file_id": image_file_id, |
| 82 | + }) |
| 83 | + |
62 | 84 | # Create a new conversation item for the user's message |
63 | 85 | await client.conversations.items.create( |
64 | 86 | conversation_id=conversation_id, |
65 | 87 | items=[{ |
66 | 88 | "type": "message", |
67 | 89 | "role": "user", |
68 | | - "content": [{ |
69 | | - "type": "input_text", |
70 | | - "text": f"System: Today's date is {datetime.today().strftime('%Y-%m-%d')}\n{userInput}" |
71 | | - }] |
| 90 | + "content": content |
72 | 91 | }] |
73 | 92 | ) |
74 | 93 |
|
75 | 94 | user_message_html = templates.get_template("components/user-message.html").render( |
76 | | - request=request, user_input=userInput |
| 95 | + request=request, user_input=userInput, image_file_id=image_file_id |
77 | 96 | ) |
78 | 97 | assistant_run_html = templates.get_template("components/assistant-run.html").render( |
79 | 98 | request=request, conversation_id=conversation_id |
|
0 commit comments