I am trying to connect my custom assistant in OpenAI with Twilio to handle WhatsApp messages. I am following the instructions provided in the forum to use three endpoints: create an assistant, create a thread, and send a message to that thread.
from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse
from dotenv import load_dotenv
import os
import logging
app = Flask(__name__)
load_dotenv()
# Configure logging level
logging.basicConfig(level=logging.INFO)
# Twilio and OpenAI configurations
TWILIO_ACCOUNT_SID = os.getenv('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOKEN = os.getenv('TWILIO_AUTH_TOKEN')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
TWILIO_WHATSAPP_NUMBER = os.getenv('TWILIO_WHATSAPP_NUMBER')
OPENAI_ASSISTANT_ID = os.getenv('OPENAI_ASSISTANT_ID')
app.logger.info(f"OpenAI API Key: {OPENAI_API_KEY}")
app.logger.info(f"OpenAI Assistant ID: {OPENAI_ASSISTANT_ID}")
@app.route('/whatsapp', methods=['POST'])
def whatsapp_webhook():
try:
incoming_msg = request.values.get('Body', '').strip()
from_number = request.values.get('From', '')
app.logger.info(f"Received message from {from_number}: {incoming_msg}")
response_text = get_openai_response(incoming_msg)
resp = MessagingResponse()
msg = resp.message(response_text)
app.logger.info(f"Response to {from_number}: {response_text}")
return str(resp)
except Exception as e:
app.logger.error(f"Error processing message: {e}")
return "Error processing the incoming message.", 500
def get_openai_response(message):
try:
headers = {
'Authorization': f'Bearer {OPENAI_API_KEY}',
'Content-Type': 'application/json'
}
# 1. Create a new thread for the conversation
create_thread_data = {
"assistant_id": OPENAI_ASSISTANT_ID,
"messages": [
{"role": "user", "content": message}
]
}
thread_url = "'https://api.openai.com/v1/threads'"
thread_response = requests.post(thread_url, headers=headers, json=create_thread_data)
thread_response.raise_for_status()
thread_data = thread_response.json()
thread_id = thread_data['id']
# 2. Send the message to the created thread
send_message_url = 'https://api.openai.com/v1/threads/{}/messages'.format(thread_id)"
message_data = {
"role": "user",
"content": message
}
message_response = requests.post(send_message_url, headers=headers, json=message_data)
message_response.raise_for_status()
response_data = message_response.json()
app.logger.info(f"OpenAI response: {response_data}")
bot_message = response_data['messages'][0]['content'].strip()
return bot_message
except requests.exceptions.HTTPError as http_err:
app.logger.error(f"HTTP error occurred: {http_err}") # Log for HTTP errors
app.logger.error(f"Response content: {http_err.response.text}")
return "Error with OpenAI HTTP response: HTTP error"
except Exception as e:
app.logger.error(f"Error getting response from OpenAI: {e}") # Log for other errors
return "General error getting response from OpenAI."
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
I am receiving the following error when trying to send a message:
2024-05-27T18:31:55.708477+00:00 app[web.1]: INFO:app:Received message from whatsapp:+541112341234: hi
2024-05-27T18:31:55.788928+00:00 app[web.1]: ERROR:app:HTTP error occurred: 400 Client Error: Bad Request for htps://api.openai.com/v1/threads
2024-05-27T18:31:55.788951+00:00 app[web.1]: ERROR:app:Response content: {
2024-05-27T18:31:55.788951+00:00 app[web.1]: “error”: {
2024-05-27T18:31:55.788962+00:00 app[web.1]: “message”: “You must provide the ‘OpenAI-Beta’ header to access the Assistants API. Please try again by setting the header ‘OpenAI-Beta: assistants=v1’.”,
2024-05-27T18:31:55.788962+00:00 app[web.1]: “type”: “invalid_request_error”,
2024-05-27T18:31:55.788963+00:00 app[web.1]: “param”: null,
2024-05-27T18:31:55.788963+00:00 app[web.1]: “code”: “invalid_beta”
2024-05-27T18:31:55.788963+00:00 app[web.1]: }
2024-05-27T18:31:55.788963+00:00 app[web.1]: }
2024-05-27T18:31:55.789251+00:00 app[web.1]: INFO:app:Response to
whatsapp:+541112341234: Error with OpenAI HTTP response: HTTP error
2024-05-27T18:31:55.789799+00:00 app[web.1]: 10.1.40.50 - - [27/May/2024:18:31:55 +0000] “POST /whatsapp HTTP/1.1” 200 121 “-” “TwilioProxy/1.1”