Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Below is an updated version of the code that should work with openai>=1.0.0. Make sure you have the correct versions installed by running pip install --upgrade openai. Also, verify your API keys, tokens, and ensure that your billing/quota on OpenAI is not exceeded.
- Key Changes:
- • Ensure you are using openai.ChatCompletion.create and the messages parameter as shown.
- • Confirm that the decorators are correctly prefixed with @app.route.
- • Remove any outdated references to older OpenAI API versions.
- • Check your .env and environment variables for correctness.
- import os
- from flask import Flask, request
- from dotenv import load_dotenv
- import openai
- from heyoo import WhatsApp
- import json
- # Load environment variables
- load_dotenv()
- # Initialize OpenAI
- openai.api_key = os.getenv('OPENAI_API_KEY')
- # Initialize Flask and WhatsApp
- app = Flask(__name__)
- messenger = WhatsApp(
- os.getenv('WHATSAPP_API_KEY'),
- phone_number_id=os.getenv('WHATSAPP_PHONE_NUMBER_ID')
- )
- chat_history = {}
- # Define the assistant role
- ASSISTANT_ROLE = """You are a professional real estate agent representative for 'Real Estate Agency'.
- You should:
- 1. Provide brief and professional responses
- 2. Focus on information about properties in the Haifa area
- 3. Ask relevant questions to understand client needs, such as:
- - Number of rooms needed
- - Price range
- - Preferred neighborhood
- - Special requirements (parking, balcony, etc.)
- - Desired move-in date
- 4. Offer to schedule meetings when appropriate
- 5. Avoid prohibited topics such as religion, politics, or economic forecasts
- """
- def get_ai_response(message, phone_number):
- try:
- if phone_number not in chat_history:
- chat_history[phone_number] = []
- chat_history[phone_number].append({"role": "user", "content": message})
- # Keep only the last 5 messages to manage token count
- chat_history[phone_number] = chat_history[phone_number][-5:]
- messages = [{"role": "system", "content": ASSISTANT_ROLE}] + chat_history[phone_number]
- response = openai.ChatCompletion.create(
- model="gpt-3.5-turbo",
- messages=messages,
- max_tokens=int(os.getenv('MAX_TOKENS', 150)),
- temperature=float(os.getenv('TEMPERATURE', 0.7))
- )
- ai_response = response.choices[0].message.content
- chat_history[phone_number].append({"role": "assistant", "content": ai_response})
- return ai_response
- except Exception as e:
- with open('/var/log/chatbot_debug.log', 'a') as f:
- f.write(f"AI Response Error: {str(e)}\n")
- return "Sorry, we're experiencing technical difficulties. Please try again or contact a representative."
- @app.route('/webhook', methods=['GET'])
- def verify():
- mode = request.args.get("hub.mode")
- token = request.args.get("hub.verify_token")
- challenge = request.args.get("hub.challenge")
- if mode == "subscribe" and token == os.getenv("WEBHOOK_VERIFY_TOKEN"):
- return str(challenge), 200
- return "Invalid verification", 403
- @app.route('/webhook', methods=['POST'])
- def webhook():
- try:
- with open('/var/log/chatbot_debug.log', 'a') as f:
- f.write("\n=== New Webhook Request ===\n")
- data = json.loads(request.data.decode("utf-8"))
- with open('/var/log/chatbot_debug.log', 'a') as f:
- f.write(f"Received data: {data}\n")
- if 'entry' in data and data['entry']:
- if 'changes' in data['entry'][0]:
- with open('/var/log/chatbot_debug.log', 'a') as f:
- f.write("Found changes in entry\n")
- if 'value' in data['entry'][0]['changes'][0]:
- value = data['entry'][0]['changes'][0]['value']
- if 'messages' in value and value['messages']:
- message = value['messages'][0]
- if 'from' in message and 'text' in message and 'body' in message['text']:
- phone_number = message['from']
- message_text = message['text']['body']
- response_text = get_ai_response(message_text, phone_number)
- messenger.send_message(response_text, phone_number)
- return "OK", 200
- except Exception as e:
- with open('/var/log/chatbot_debug.log', 'a') as f:
- f.write(f"Webhook Error: {str(e)}\n")
- return "Error", 500
- if __name__ == "__main__":
- app.run(host='0.0.0.0', port=8000)
- Additional Tips:
- • Ensure you have the latest openai package: pip install --upgrade openai.
- • Double-check your OpenAI account usage and billing to ensure you haven’t exceeded your quota.
- • Verify that your .env file contains the correct OPENAI_API_KEY, WHATSAPP_API_KEY, WHATSAPP_PHONE_NUMBER_ID, WEBHOOK_VERIFY_TOKEN, and any other required environment variables.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement