Last active
July 21, 2023 15:51
-
-
Save ranfysvalle02/b0432a2e0c56df1e39a7749d808d60f0 to your computer and use it in GitHub Desktop.
GPT-Slackbot w/ Python / Bolt + Socket mode enabled
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# inspired by: https://github.com/hollaugo/chatgpt-slack-app/blob/main/app.py | |
import json | |
import pymongo | |
from langchain.embeddings.openai import OpenAIEmbeddings | |
from langchain.llms import AzureOpenAI | |
import os | |
import requests | |
from slack_bolt import App | |
from slack_bolt.adapter.socket_mode import SocketModeHandler | |
from dotenv import load_dotenv | |
from langchain.vectorstores import MongoDBAtlasVectorSearch | |
from langchain.chains import RetrievalQAWithSourcesChain | |
load_dotenv() # take environment variables from .env | |
# Initializes your app with your bot token and socket mode handler | |
app = App(token=os.environ.get("SLACK_BOT_TOKEN")) | |
MONGO_URI = os.environ.get("MONGODB_URI") | |
MONGODB_DATABASE = "" | |
MONGODB_COLLECTION = "" | |
# Connect to the MongoDB server | |
client = pymongo.MongoClient(MONGO_URI) | |
# Get the collection | |
collection = client[MONGODB_DATABASE][MONGODB_COLLECTION] | |
os.environ["OPENAI_API_TYPE"] = "azure" | |
os.environ["OPENAI_API_KEY"] = os.environ.get("AZURE_OPENAI_TOKEN") | |
os.environ["OPENAI_API_BASE"] = "https://.openai.azure.com/" | |
os.environ["OPENAI_API_VERSION"] = "2023-05-15" | |
azureEmbeddings = OpenAIEmbeddings( | |
deployment="", | |
model="text-embedding-ada-002", | |
openai_api_base="https://.openai.azure.com/", | |
openai_api_key=os.environ.get("AZURE_OPENAI_TOKEN"), | |
openai_api_type="azure", | |
chunk_size=1 | |
) | |
llm = AzureOpenAI( | |
model_name="gpt-4", | |
engine="gpt-4", | |
openai_api_base="https://.openai.azure.com/", | |
openai_api_key=os.environ.get("AZURE_OPENAI_TOKEN"), | |
temperature=0.7 | |
) | |
vectorstore = MongoDBAtlasVectorSearch(collection, azureEmbeddings) | |
mdb_retriever = vectorstore.as_retriever() | |
#Langchain implementation | |
qa = RetrievalQAWithSourcesChain.from_chain_type(llm=llm, chain_type="stuff", retriever=mdb_retriever, verbose=True) | |
#Message handler for Slack | |
@app.action({ | |
"action_id": "thumbs_up" | |
}) | |
def handleMessageFeedbackThumbsUp(ack, body, say, respond): | |
ack() | |
print(str(body['message']['text']).replace(":+1: button :-1: button","")) | |
blocks = [ | |
{ | |
"type": "section", | |
"text": { | |
"type": "mrkdwn", | |
"text": "Thank you for your feedback! \n\n You rated the below response (:+1:) \n\n"+(str(body['message']['text']).replace(":+1: button :-1: button","")) | |
} | |
} | |
] | |
url = body['response_url'] | |
headers = {"Content-type": "application/json"} | |
payload = { | |
"replace_original": "true", | |
"blocks": blocks, | |
"text":"Thank you for your feedback! \n\n You rated the below response (:+1:) \n\n"+(str(body['message']['text']).replace(":+1: button :-1: button","")) | |
} | |
response = requests.post(url, headers=headers, data=json.dumps(payload)) | |
print(response.status_code) | |
print(response.text) | |
@app.action({ | |
"action_id": "thumbs_down" | |
}) | |
def handleMessageFeedbackThumbsDown(ack, client, body, say, respond): | |
ack() | |
print(str(body['message']['text']).replace(":+1: button :-1: button","")) | |
blocks = [ | |
{ | |
"type": "section", | |
"text": { | |
"type": "mrkdwn", | |
"text": "Thank you for your feedback! \n\n You rated the below response (:-1:) \n\n"+(str(body['message']['text']).replace(":+1: button :-1: button","")) | |
} | |
} | |
] | |
url = body['response_url'] | |
headers = {"Content-type": "application/json"} | |
payload = { | |
"replace_original": "true", | |
"blocks": blocks, | |
"text":"Thank you for your feedback! \n\n You rated the below response (:-1:) \n\n"+(str(body['message']['text']).replace(":+1: button :-1: button","")) | |
} | |
response = requests.post(url, headers=headers, data=json.dumps(payload)) | |
print(response.status_code) | |
print(response.text) | |
@app.event("app_mention") | |
def handleAppMentionEvent(body, say, logger): | |
event = body["event"] | |
thread_ts = event.get("thread_ts", None) or event["ts"] | |
templated_Q = """<USERINPUT> | |
""" | |
QUESTION =str(body['event']['text']).replace("<@U05GTJQCARG>","") #replace the mention of your specific BOT before sending to LLM | |
QUESTION=str(QUESTION).strip() | |
templated_Q = templated_Q.replace("<USERINPUT>",QUESTION) | |
output = qa({"question":templated_Q}) | |
blocks = [ | |
{ | |
"type": "section", | |
"text": { | |
"type": "mrkdwn", | |
"text": output['answer'] | |
} | |
}, | |
{ | |
"type": "divider" | |
}, | |
{ | |
"type": "section", | |
"text": { | |
"type": "mrkdwn", | |
"text": output['sources'].replace(",","\n").replace("("," (").strip() #change the commas for \n | |
} | |
}, | |
{ | |
"type": "divider" | |
}, | |
{ | |
"type": "actions", | |
"elements": [ | |
{ | |
"type": "button", | |
"text": { | |
"type": "plain_text", | |
"emoji": True, | |
"text": ":+1:" | |
}, | |
"value": ":+1:", | |
"action_id": "thumbs_up" | |
}, | |
{ | |
"type": "button", | |
"text": { | |
"type": "plain_text", | |
"emoji": True, | |
"text": ":-1:" | |
}, | |
"value": ":-1:", | |
"action_id": "thumbs_down" | |
} | |
] | |
} | |
] | |
say(blocks=blocks,thread_ts=thread_ts) | |
# Start your app | |
if __name__ == "__main__": | |
SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment