Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion sample.env
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ PGVECTOR_PORT="5432"


OPENAI_API_KEY="sk-..."
AGENT_SERVICE_URL="http://localhost:8001"
AGENT_SERVICE_URL="http://localhost:8001"
SLACK_BOT_TOKEN=""
SLACK_APP_SECRET=""
87 changes: 42 additions & 45 deletions services/slack_service.py
Original file line number Diff line number Diff line change
@@ -1,87 +1,84 @@
from flask import Flask, request, jsonify
import os
import slack_sdk
# import slack_sdk
from slack_sdk.web import WebClient
from slack_sdk.signature import SignatureVerifier
# from rag_model import get_rag_response

import requests
import json
import threading
from dotenv import load_dotenv

load_dotenv()


app = Flask(__name__)

slack_token = "xoxb-8848313668450-8848330175890-NxONtME4RybfiHlAZfIDsJVf"
signing_secret = "165bb0d941425645b37d1ff7a6d77f30"
slack_token = os.getenv("SLACK_BOT_TOKEN")
signing_secret = os.getenv("SLACK_APP_SECRET")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

slack_token = os.environ.get("SLACK_APP_SECRET", default="")
signing_secret = os.environ.get("SLACK_SIGNING_SECRET", default="")

Get secrets like above to make sure default value is a string and not Null. This is because SignatureVerifier does not accept Null value


client = WebClient(token=slack_token)
verifier = SignatureVerifier(signing_secret)

def get_rag_response(query: str) -> str:
"""
Query the agent service and get response
"""
import requests
import json

# Configure the endpoint URL - adjust host/port as needed
agent_service_url = f"{os.getenv("AGENT_SERVICE_URL")}/query"

agent_service_url = f"{os.getenv('AGENT_SERVICE_URL')}/query"
try:
# Make POST request to the agent service
response = requests.post(
agent_service_url,
json={"query": query},
headers={"Content-Type": "application/json"}
)

# Check if request was successful
response.raise_for_status()

# Parse JSON response
result = response.json()

# Return the response text
return result.get("response", "No response received from agent")

except requests.exceptions.RequestException as e:
# Handle connection errors
print(f"Error querying agent service: {e}")
return f"Sorry, I couldn't reach the knowledge base. Error: {str(e)}"

except json.JSONDecodeError:
# Handle invalid JSON response
print(f"Invalid response from agent service: {response.text}")
return "Sorry, I received an invalid response from the knowledge base."

@app.route("/slack/commands", methods=["POST"])
def slack_commands():
data = request.form
command = data.get("command")
if command == "/ping":
return jsonify({
"response_type": "in_channel",
"text": "Pong! 🚀"
})
return "Unknown command", 200
def send_delayed_response(response_url: str, user_id: str, query: str):
"""Process the query and send the response back to Slack."""
response_text = get_rag_response(query)
payload = {
"response_type": "in_channel", # or "ephemeral" for private replies
"text": f"<@{user_id}> {response_text}"
}
try:
requests.post(response_url, json=payload)
except requests.exceptions.RequestException as e:
print(f"Error sending response to Slack: {e}")

@app.route("/slack/prompt", methods=["POST"])
def slack_prompt():
# Verify the request (optional, but recommended)
if not verifier.is_valid_request(request.get_data(), request.headers):
return jsonify({"text": "Invalid request signature"}), 403

data = request.form
user_id = data.get("user_id")
query = data.get("text") # This is the user's prompt message
query = data.get("text")
response_url = data.get("response_url") # Slack provides this for delayed responses

# Change this to your RAG model's response function
# This is where you would call your RAG model
# For example, if you have a function `get_rag_response`:
response = get_rag_response(query)
# Start a background thread to process the query
thread = threading.Thread(target=send_delayed_response, args=(response_url, user_id, query))
thread.start()

# Respond back publicly in the slack channel or privately to the user
# Immediately acknowledge the command
return jsonify({
"response_type": "in_channel", # or "ephemeral" for private replies
"text": f"<@{user_id}> {response}"
"response_type": "in_channel",
"text": "Processing your request, please wait..."
})

@app.route("/slack/commands", methods=["POST"])
def slack_commands():
data = request.form
command = data.get("command")
if command == "/ping":
return jsonify({
"response_type": "in_channel",
"text": "Pong! 🚀"
})
return jsonify({"text": "Unknown command"}), 200

if __name__ == "__main__":
app.run(debug=True,port=3000)
app.run(debug=True, port=3000)