Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, Request
|
2 |
+
from pydantic import BaseModel
|
3 |
+
import openai
|
4 |
+
import os
|
5 |
+
|
6 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
7 |
+
|
8 |
+
app = FastAPI()
|
9 |
+
|
10 |
+
class ChatRequest(BaseModel):
|
11 |
+
message: str
|
12 |
+
history: list = []
|
13 |
+
|
14 |
+
@app.post("/chat")
|
15 |
+
async def chat(data: ChatRequest):
|
16 |
+
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
17 |
+
messages += data.history
|
18 |
+
messages.append({"role": "user", "content": data.message})
|
19 |
+
|
20 |
+
response = openai.ChatCompletion.create(
|
21 |
+
model="gpt-3.5-turbo",
|
22 |
+
messages=messages
|
23 |
+
)
|
24 |
+
|
25 |
+
reply = response['choices'][0]['message']['content']
|
26 |
+
return {
|
27 |
+
"reply": reply,
|
28 |
+
"history": messages + [{"role": "assistant", "content": reply}]
|
29 |
+
}
|