Created
December 23, 2025 16:46
-
-
Save amElnagdy/043a1b00aff525ccb09d7c7c3a7a8fd7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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