Skip to content

Instantly share code, notes, and snippets.

@amElnagdy
Created December 23, 2025 16:46
Show Gist options
  • Select an option

  • Save amElnagdy/043a1b00aff525ccb09d7c7c3a7a8fd7 to your computer and use it in GitHub Desktop.

Select an option

Save amElnagdy/043a1b00aff525ccb09d7c7c3a7a8fd7 to your computer and use it in GitHub Desktop.
from fastapi import FastAPI, HTTPException
from openai import OpenAI
import os
app = FastAPI()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
conversation_history = []
@app.post("/chat")
async def chat(message: str):
conversation_history.append({"role": "user", "content": message})
try:
response = client.chat.completions.create(
model="gpt-4.1",
messages=conversation_history,
timeout=5
)
assistant_message = response.choices[0].message.content
conversation_history.append({"role": "assistant", "content": assistant_message})
return {"response": assistant_message}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment