Spaces:
Sleeping
Sleeping
Commit
·
a28cd52
1
Parent(s):
c74caed
feat: implement image generation API route with extended timeout and error handling
Browse files
app/api/v1/images/generate/route.ts
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import { NextRequest, NextResponse } from 'next/server';
|
2 |
+
|
3 |
+
export const maxDuration = 300; // 5 minutes
|
4 |
+
export const dynamic = 'force-dynamic';
|
5 |
+
|
6 |
+
export async function POST(request: NextRequest) {
|
7 |
+
try {
|
8 |
+
const body = await request.json();
|
9 |
+
|
10 |
+
// Forward the request to the Python backend with extended timeout
|
11 |
+
const controller = new AbortController();
|
12 |
+
const timeoutId = setTimeout(() => controller.abort(), 300000); // 5 minutes
|
13 |
+
|
14 |
+
const response = await fetch('http://localhost:8000/api/v1/images/generate', {
|
15 |
+
method: 'POST',
|
16 |
+
headers: {
|
17 |
+
'Content-Type': 'application/json',
|
18 |
+
},
|
19 |
+
body: JSON.stringify(body),
|
20 |
+
signal: controller.signal,
|
21 |
+
});
|
22 |
+
|
23 |
+
clearTimeout(timeoutId);
|
24 |
+
|
25 |
+
if (!response.ok) {
|
26 |
+
throw new Error(`Backend responded with status: ${response.status}`);
|
27 |
+
}
|
28 |
+
|
29 |
+
const data = await response.json();
|
30 |
+
return NextResponse.json(data);
|
31 |
+
|
32 |
+
} catch (error) {
|
33 |
+
console.error('API route error:', error);
|
34 |
+
|
35 |
+
if (error instanceof Error) {
|
36 |
+
if (error.name === 'AbortError') {
|
37 |
+
return NextResponse.json(
|
38 |
+
{ success: false, message: 'Request timeout - the image generation is taking too long. Please try with fewer images or try again later.' },
|
39 |
+
{ status: 408 }
|
40 |
+
);
|
41 |
+
}
|
42 |
+
|
43 |
+
return NextResponse.json(
|
44 |
+
{ success: false, message: `Request failed: ${error.message}` },
|
45 |
+
{ status: 500 }
|
46 |
+
);
|
47 |
+
}
|
48 |
+
|
49 |
+
return NextResponse.json(
|
50 |
+
{ success: false, message: 'An unexpected error occurred' },
|
51 |
+
{ status: 500 }
|
52 |
+
);
|
53 |
+
}
|
54 |
+
}
|
backend/app/services/image_service.py
CHANGED
@@ -16,7 +16,7 @@ class ImageGenerationService:
|
|
16 |
def __init__(self):
|
17 |
self.client = OpenAI(
|
18 |
api_key=os.getenv("OPENAI_API_KEY"),
|
19 |
-
timeout=
|
20 |
max_retries=2, # Reduce retries to fail faster
|
21 |
)
|
22 |
|
|
|
16 |
def __init__(self):
|
17 |
self.client = OpenAI(
|
18 |
api_key=os.getenv("OPENAI_API_KEY"),
|
19 |
+
timeout=300.0, # 5 minutes timeout for multiple image generation
|
20 |
max_retries=2, # Reduce retries to fail faster
|
21 |
)
|
22 |
|