I am creating a central api for translation and i need gpt api to handle the translation. When I run the code i keep geting method not allowed as the response. I tried it with pycharm default api and it worked. I am working with FASTAPI.
from fastapi import FastAPI
from pydantic import BaseModel
import requests
app = FastAPI()
api_key = ""//openai auth key
api_endpoint = "https://api.openai.com/v1/completions"
class TranslationRequest(BaseModel):
text: str
class TranslationResponse(BaseModel):
translation: str
class ErrorResponse(BaseModel):
error: str
@app.post("/translate", response_model=TranslationResponse, responses={500: {"model": ErrorResponse}})
def translate():
text = "how are you"
header = {
"Content-type": "application/json",
"Authorization": f"Bearer {api_key}"
}
payload = {
"model": "text-davinci-003",
"prompt": f"Translate {text} to dutch",
"max_tokens": 100,
"temperature": 0.5,
}
response = requests.post(api_endpoint, headers=header, json=payload)
if response.status_code == 405:
print(response.json()["choices"][0]["text"])
else:
print(f"Request failed with status: {str(response.status_code)}")
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/hello/{name}")
async def say_hello(name: str):
return {"message": f"Hello {name}"}