Skip to content

Commit

Permalink
WIP bot
Browse files Browse the repository at this point in the history
  • Loading branch information
seldo committed Dec 22, 2023
0 parents commit afcc31e
Show file tree
Hide file tree
Showing 8 changed files with 2,451 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
qdrant_data
.env
23 changes: 23 additions & 0 deletions 1_try.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import dotenv
dotenv.load_dotenv()

from llama_index.tools import FunctionTool
from llama_index.llms import OpenAI
from llama_index.agent import OpenAIAgent

# define sample Tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers and returns the result integer"""
return a * b


multiply_tool = FunctionTool.from_defaults(fn=multiply)

# initialize llm
llm = OpenAI(model="gpt-4")

# initialize ReAct agent
agent = OpenAIAgent.from_tools([multiply_tool], llm=llm, verbose=True)
response = agent.query("multiply 2 and 3")

print(response)
46 changes: 46 additions & 0 deletions 2_slack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import dotenv, os
dotenv.load_dotenv()

# Use the package we installed
from slack_bolt import App
from slack_sdk import WebClient
from flask import Flask, request, jsonify
from slack_bolt.adapter.flask import SlackRequestHandler

# Initialize your app with your bot token and signing secret
app = App(
token=os.environ.get("SLACK_BOT_TOKEN"),
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)
handler = SlackRequestHandler(app)
flask_app = Flask(__name__)

# initialize client also with the bot token
slack_token = os.environ["SLACK_BOT_TOKEN"]
client = WebClient(token=slack_token)

# join the channel so you can listen to messages
channel_list = client.conversations_list().data
channel = next((channel for channel in channel_list.get('channels') if channel.get("name") == "bot-testing"), None)
channel_id = channel.get('id')
client.conversations_join(channel=channel_id)

# this is the challenge route required by Slack
@flask_app.route("/", methods=["POST"])
def slack_challenge():
if request.json and "challenge" in request.json:
print("Received challenge")
return jsonify({"challenge": request.json["challenge"]})
else:
print("Got unknown request incoming")
print(request.json)
return handler.handle(request)

# this handles any incoming message the bot can hear
@app.message()
def reply(message, say):
print(message)
say("Yes?")

if __name__ == "__main__":
flask_app.run(port=3000)
23 changes: 23 additions & 0 deletions 3_incremental.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import dotenv
import logging
import sys
dotenv.load_dotenv()

from llama_index import VectorStoreIndex, Document, set_global_handler

set_global_handler("simple")

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))

index = VectorStoreIndex([])

doc1 = Document(text="Molly is a cat")
doc2 = Document(text="Doug is a dog")
doc3 = Document(text="Carl is a rat")

index.insert(doc1)

query_engine = index.as_query_engine()
response = query_engine.query("Who is Molly?")
print(response)
80 changes: 80 additions & 0 deletions 4_memory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import dotenv, os
dotenv.load_dotenv()

from slack_bolt import App
from slack_sdk import WebClient
from flask import Flask, request, jsonify
from slack_bolt.adapter.flask import SlackRequestHandler

from llama_index import VectorStoreIndex, Document

index = VectorStoreIndex([])

# Initialize your app with your bot token and signing secret
app = App(
token=os.environ.get("SLACK_BOT_TOKEN"),
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)
handler = SlackRequestHandler(app)
flask_app = Flask(__name__)

# join the test channel so you can listen to messages
channel_list = app.client.conversations_list().data
channel = next((channel for channel in channel_list.get('channels') if channel.get("name") == "bot-testing"), None)
channel_id = channel.get('id')
app.client.conversations_join(channel=channel_id)

# get my own ID
auth_response = app.client.auth_test()
print(auth_response)
bot_user_id = auth_response["user_id"]

# this is the challenge route required by Slack
# if it's not the challenge it's something for Bolt to handle
# (why doesn't Bolt handle the challenge? It's their framework, they should know the challenge is coming...)
@flask_app.route("/", methods=["POST"])
def slack_challenge():
if request.json and "challenge" in request.json:
print("Received challenge")
return jsonify({"challenge": request.json["challenge"]})
else:
print("Incoming event:")
print(request.json)
return handler.handle(request)

# this handles any incoming message the bot can hear
# right now it's only in one channel so it's every message in that channel
@app.message()
def reply(message, say):
# if message contains a "blocks" key
# then look for a "block" with the type "rich text"
# if you find it
# then look inside that block for an "elements" key
# if you find it
# then examine each one of those for an "elements" key
# if you find it
# then look inside each "element" for one with type "user"
# if you find it
# and if that user matches the bot_user_id
# then it's a message from the bot
if message.get('blocks'):
for block in message.get('blocks'):
if block.get('type') == 'rich_text':
for rich_text_section in block.get('elements'):
for element in rich_text_section.get('elements'):
if element.get('type') == 'user' and element.get('user_id') == bot_user_id:
for element in rich_text_section.get('elements'):
if element.get('type') == 'text':
query = element.get('text')
print("Using query", query)
query_engine = index.as_query_engine()
response = query_engine.query(query)
print(response)
say(str(response))
return
# otherwise treat it as a document to store
index.insert(Document(text=message.get('text')))
print("Stored message", message.get('text'))

if __name__ == "__main__":
flask_app.run(port=3000)
102 changes: 102 additions & 0 deletions 5_qdrant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# env first
import dotenv
dotenv.load_dotenv()

# slack app deps
import os
from slack_bolt import App
from slack_sdk import WebClient
from flask import Flask, request, jsonify
from slack_bolt.adapter.flask import SlackRequestHandler

# RAG app deps
import qdrant_client
from llama_index import VectorStoreIndex, Document, StorageContext
from llama_index.vector_stores.qdrant import QdrantVectorStore

# initialize qdrant client
client = qdrant_client.QdrantClient(
path="./qdrant_data"
)
vector_store = QdrantVectorStore(client=client, collection_name="tweets")
storage_context = StorageContext.from_defaults(vector_store=vector_store)

index = VectorStoreIndex([],storage_context=storage_context)

# Initialize your app with your bot token and signing secret
app = App(
token=os.environ.get("SLACK_BOT_TOKEN"),
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)
handler = SlackRequestHandler(app)
flask_app = Flask(__name__)

# join the test channel so you can listen to messages
channel_list = app.client.conversations_list().data
channel = next((channel for channel in channel_list.get('channels') if channel.get("name") == "bot-testing"), None)
channel_id = channel.get('id')
app.client.conversations_join(channel=channel_id)

# get my own ID
auth_response = app.client.auth_test()
print(auth_response)
bot_user_id = auth_response["user_id"]

# get a user's username and display name from their user id
def get_user_name(user_id):
user_info = app.client.users_info(user=user_id)
user_name = user_info['user']['name']
user_display_name = user_info['user']['profile']['display_name']
return user_name, user_display_name

# this is the challenge route required by Slack
# if it's not the challenge it's something for Bolt to handle
# (why doesn't Bolt handle the challenge? It's their framework, they should know the challenge is coming...)
@flask_app.route("/", methods=["POST"])
def slack_challenge():
if request.json and "challenge" in request.json:
print("Received challenge")
return jsonify({"challenge": request.json["challenge"]})
else:
print("Incoming event:")
print(request.json)
return handler.handle(request)

# this handles any incoming message the bot can hear
# right now it's only in one channel so it's every message in that channel
@app.message()
def reply(message, say):
# if message contains a "blocks" key
# then look for a "block" with the type "rich text"
# if you find it
# then look inside that block for an "elements" key
# if you find it
# then examine each one of those for an "elements" key
# if you find it
# then look inside each "element" for one with type "user"
# if you find it
# and if that user matches the bot_user_id
# then it's a message from the bot
if message.get('blocks'):
for block in message.get('blocks'):
if block.get('type') == 'rich_text':
for rich_text_section in block.get('elements'):
for element in rich_text_section.get('elements'):
if element.get('type') == 'user' and element.get('user_id') == bot_user_id:
for element in rich_text_section.get('elements'):
if element.get('type') == 'text':
query = element.get('text')
print("Using query", query)
query_engine = index.as_query_engine()
response = query_engine.query(query)
print(response)
say(str(response))
return
# if it's not a question, we store it in the index along with all relevant metadata
user_name, user_display_name = get_user_name(message.get('user'))
text = user_display_name + " said " + message.get('text')
index.insert(Document(text=text))
print("Stored message:", text)

if __name__ == "__main__":
flask_app.run(port=3000)
Loading

0 comments on commit afcc31e

Please sign in to comment.