Advertisement
Guest User

Untitled

a guest
Dec 15th, 2024
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.94 KB | None | 0 0
  1. 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.
  2.  
  3. Key Changes:
  4. • Ensure you are using openai.ChatCompletion.create and the messages parameter as shown.
  5. • Confirm that the decorators are correctly prefixed with @app.route.
  6. • Remove any outdated references to older OpenAI API versions.
  7. • Check your .env and environment variables for correctness.
  8.  
  9. import os
  10. from flask import Flask, request
  11. from dotenv import load_dotenv
  12. import openai
  13. from heyoo import WhatsApp
  14. import json
  15.  
  16. # Load environment variables
  17. load_dotenv()
  18.  
  19. # Initialize OpenAI
  20. openai.api_key = os.getenv('OPENAI_API_KEY')
  21.  
  22. # Initialize Flask and WhatsApp
  23. app = Flask(__name__)
  24. messenger = WhatsApp(
  25. os.getenv('WHATSAPP_API_KEY'),
  26. phone_number_id=os.getenv('WHATSAPP_PHONE_NUMBER_ID')
  27. )
  28.  
  29. chat_history = {}
  30.  
  31. # Define the assistant role
  32. ASSISTANT_ROLE = """You are a professional real estate agent representative for 'Real Estate Agency'.
  33. You should:
  34. 1. Provide brief and professional responses
  35. 2. Focus on information about properties in the Haifa area
  36. 3. Ask relevant questions to understand client needs, such as:
  37. - Number of rooms needed
  38. - Price range
  39. - Preferred neighborhood
  40. - Special requirements (parking, balcony, etc.)
  41. - Desired move-in date
  42. 4. Offer to schedule meetings when appropriate
  43. 5. Avoid prohibited topics such as religion, politics, or economic forecasts
  44. """
  45.  
  46. def get_ai_response(message, phone_number):
  47. try:
  48. if phone_number not in chat_history:
  49. chat_history[phone_number] = []
  50.  
  51. chat_history[phone_number].append({"role": "user", "content": message})
  52. # Keep only the last 5 messages to manage token count
  53. chat_history[phone_number] = chat_history[phone_number][-5:]
  54.  
  55. messages = [{"role": "system", "content": ASSISTANT_ROLE}] + chat_history[phone_number]
  56.  
  57. response = openai.ChatCompletion.create(
  58. model="gpt-3.5-turbo",
  59. messages=messages,
  60. max_tokens=int(os.getenv('MAX_TOKENS', 150)),
  61. temperature=float(os.getenv('TEMPERATURE', 0.7))
  62. )
  63.  
  64. ai_response = response.choices[0].message.content
  65. chat_history[phone_number].append({"role": "assistant", "content": ai_response})
  66. return ai_response
  67. except Exception as e:
  68. with open('/var/log/chatbot_debug.log', 'a') as f:
  69. f.write(f"AI Response Error: {str(e)}\n")
  70. return "Sorry, we're experiencing technical difficulties. Please try again or contact a representative."
  71.  
  72. @app.route('/webhook', methods=['GET'])
  73. def verify():
  74. mode = request.args.get("hub.mode")
  75. token = request.args.get("hub.verify_token")
  76. challenge = request.args.get("hub.challenge")
  77.  
  78. if mode == "subscribe" and token == os.getenv("WEBHOOK_VERIFY_TOKEN"):
  79. return str(challenge), 200
  80. return "Invalid verification", 403
  81.  
  82. @app.route('/webhook', methods=['POST'])
  83. def webhook():
  84. try:
  85. with open('/var/log/chatbot_debug.log', 'a') as f:
  86. f.write("\n=== New Webhook Request ===\n")
  87.  
  88. data = json.loads(request.data.decode("utf-8"))
  89. with open('/var/log/chatbot_debug.log', 'a') as f:
  90. f.write(f"Received data: {data}\n")
  91.  
  92. if 'entry' in data and data['entry']:
  93. if 'changes' in data['entry'][0]:
  94. with open('/var/log/chatbot_debug.log', 'a') as f:
  95. f.write("Found changes in entry\n")
  96.  
  97. if 'value' in data['entry'][0]['changes'][0]:
  98. value = data['entry'][0]['changes'][0]['value']
  99. if 'messages' in value and value['messages']:
  100. message = value['messages'][0]
  101. if 'from' in message and 'text' in message and 'body' in message['text']:
  102. phone_number = message['from']
  103. message_text = message['text']['body']
  104. response_text = get_ai_response(message_text, phone_number)
  105. messenger.send_message(response_text, phone_number)
  106.  
  107. return "OK", 200
  108.  
  109. except Exception as e:
  110. with open('/var/log/chatbot_debug.log', 'a') as f:
  111. f.write(f"Webhook Error: {str(e)}\n")
  112. return "Error", 500
  113.  
  114. if __name__ == "__main__":
  115. app.run(host='0.0.0.0', port=8000)
  116.  
  117. Additional Tips:
  118. • Ensure you have the latest openai package: pip install --upgrade openai.
  119. • Double-check your OpenAI account usage and billing to ensure you haven’t exceeded your quota.
  120. • 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