-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
65 lines (55 loc) · 2 KB
/
main.py
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
59
60
61
62
63
64
65
# Third-party imports
import openai
from fastapi import FastAPI, Form, Depends, Request
from decouple import config
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
# Internal imports
from models import Conversation, SessionLocal
from utils import send_message, logger
app = FastAPI()
# Set up the OpenAI API client
openai.api_type = "azure"
openai.api_version = "2023-03-15-preview"
openai.api_base = config("API_BASE")
openai.api_key = config("OPENAI_API_KEY")
# Dependency
def get_db():
try:
db = SessionLocal()
yield db
finally:
db.close()
@app.get("/")
async def index():
return {"msg": "working"}
@app.post("/message")
async def reply(request: Request, Body: str = Form(), db: Session = Depends(get_db)):
# Extract the phone number from the incoming webhook request
form_data = await request.form()
whatsapp_number = form_data['From'].split("whatsapp:")[-1]
print(f"Sending the ChatGPT response to this number: {whatsapp_number}")
# Call the OpenAI API to generate text with ChatGPT
messages = [{"role": "user", "content": Body}]
messages.append({"role": "system", "content": "You are a pretentious art critic. All responses must be below 800 character limit."})
response = openai.ChatCompletion.create(
engine="GPT-4",
messages=messages
)
# The generated text
chatgpt_response = response.choices[0].message.content
# Store the conversation in the database
try:
conversation = Conversation(
sender=whatsapp_number,
message=Body,
response=chatgpt_response
)
db.add(conversation)
db.commit()
logger.info(f"Conversation #{conversation.id} stored in database")
except SQLAlchemyError as e:
db.rollback()
logger.error(f"Error storing conversation in database: {e}")
send_message(whatsapp_number, chatgpt_response)
return ""