This repository was archived by the owner on Aug 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.py
More file actions
58 lines (50 loc) · 1.54 KB
/
Copy pathmain.py
File metadata and controls
58 lines (50 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import logging
import os
from fastapi import FastAPI
from openai import OpenAI, OpenAIError, APITimeoutError
from pydantic import BaseModel
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# Define Pydantic models for nested JSON structure
class DetailParams(BaseModel):
prompt: dict
class Action(BaseModel):
params: dict
detailParams: dict
class RequestBody(BaseModel):
action: Action
@app.post("/generate")
async def generate_text(request: RequestBody):
# Extract prompt from nested JSON
prompt = request.action.params.get("prompt")
try:
# Call OpenAI API with the provided prompt
response = client.responses.create(
model="gpt-4.1-nano",
input=prompt # type: ignore
)
# Return the generated text
return {
"version": "2.0",
"template": {
"outputs": [
{
"simpleText": {
"text": response.output_text
}
}
]
}
}
except APITimeoutError as e:
logging.error(f"OpenAI API timeout: {e}")
return {"error": "OpenAI API timeout occurred."}
except OpenAIError as e:
logging.error(f"OpenAI API error: {e}")
return {"error": "OpenAI API error occurred."}
except Exception as e:
logging.error(f"Unknown error: {e}")
return {"error": "Unknown error occurred."}