llama_chatbot.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import langchain
  2. from langchain.llms import Replicate
  3. from flask import Flask
  4. from flask import request
  5. import os
  6. import requests
  7. import json
  8. class WhatsAppClient:
  9. API_URL = "https://graph.facebook.com/v17.0/"
  10. WHATSAPP_API_TOKEN = "<Temporary access token from your WhatsApp API Setup>"
  11. WHATSAPP_CLOUD_NUMBER_ID = "<Phone number ID from your WhatsApp API Setup>"
  12. def __init__(self):
  13. self.headers = {
  14. "Authorization": f"Bearer {self.WHATSAPP_API_TOKEN}",
  15. "Content-Type": "application/json",
  16. }
  17. self.API_URL = self.API_URL + self.WHATSAPP_CLOUD_NUMBER_ID
  18. def send_text_message(self,message, phone_number):
  19. payload = {
  20. "messaging_product": 'whatsapp',
  21. "to": phone_number,
  22. "type": "text",
  23. "text": {
  24. "preview_url": False,
  25. "body": message
  26. }
  27. }
  28. response = requests.post(f"{self.API_URL}/messages", json=payload,headers=self.headers)
  29. print(response.status_code)
  30. assert response.status_code == 200, "Error sending message"
  31. return response.status_code
  32. os.environ["REPLICATE_API_TOKEN"] = "<your replicate api token>"
  33. llama2_13b_chat = "meta/llama-2-13b-chat:f4e2de70d66816a838a89eeeb621910adffb0dd0baba3976c96980970978018d"
  34. llm = Replicate(
  35. model=llama2_13b_chat,
  36. model_kwargs={"temperature": 0.01, "top_p": 1, "max_new_tokens":500}
  37. )
  38. client = WhatsAppClient()
  39. app = Flask(__name__)
  40. @app.route("/")
  41. def hello_llama():
  42. return "<p>Hello Llama 2</p>"
  43. @app.route('/msgrcvd', methods=['POST', 'GET'])
  44. def msgrcvd():
  45. message = request.args.get('message')
  46. #client.send_template_message("hello_world", "en_US", "14086745477")
  47. answer = llm(message)
  48. print(message)
  49. print(answer)
  50. client.send_text_message(llm(message), "14086745477")
  51. return message + "<p/>" + answer