Skip to content

Instantly share code, notes, and snippets.

@normandmickey
Created September 14, 2023 10:29
Show Gist options
  • Save normandmickey/7d9e2a8b653eadb7bacf90ae422836a0 to your computer and use it in GitHub Desktop.
Save normandmickey/7d9e2a8b653eadb7bacf90ae422836a0 to your computer and use it in GitHub Desktop.
ChatGPT-Slack
""" GPT-4 Bot For Slack """
import os, json, re, faiss, pickle
from dotenv import load_dotenv
from flask import Flask, request
from slack_sdk import WebClient
from slack_bolt import App, Say
from slack_bolt.adapter.flask import SlackRequestHandler
from langchain.chat_models import ChatOpenAI
from langchain import PromptTemplate, LLMChain
from langchain.chains import OpenAIModerationChain, SequentialChain, LLMChain, SimpleSequentialChain
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
AIMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)
load_dotenv()
app = Flask(__name__)
OPENAI_API_KEY=os.getenv("OPENAI_API_KEY")
client = WebClient(token=os.getenv("SLACK_BOT_TOKEN"))
bolt_app = App(token=os.getenv("SLACK_BOT_TOKEN"), signing_secret=os.getenv("SLACK_SIGNING_SECRET"))
chat = ChatOpenAI(temperature=0, model_kwargs={"model":"gpt-3.5-turbo"})
template="You are a helpful assistant."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
example_human = HumanMessagePromptTemplate.from_template("Hi")
example_ai = AIMessagePromptTemplate.from_template("Hello")
human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, example_human, example_ai, human_message_prompt])
moderation_chain = OpenAIModerationChain()
llm_chain = LLMChain(llm=chat, prompt=chat_prompt)
chain = SimpleSequentialChain(chains=[llm_chain, moderation_chain])
#Message handler for Slack
@bolt_app.message(".*")
def message_handler(message, say, logger):
question = message["text"]
answer = chain.run(question)
say(answer)
@bolt_app.command("/askgpt4")
def askgpt4_command(say, ack, command):
""" This is for slash command /askgpt4 """
ack()
question = command["text"]
answer = chain.run(question)
say(answer)
handler = SlackRequestHandler(bolt_app)
@app.route("/events", methods=["POST"])
def slack_events():
""" Declaring the route where slack will post a request and dispatch method of App """
return handler.handle(request)
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment