from dotenv import load_dotenv from openai import OpenAI import json import os import requests from pypdf import PdfReader import gradio as gr import os import threading from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler from pydantic import BaseModel, Field import os from typing import Dict load_dotenv(override=True) api_key = os.getenv("OPENAI_API_KEY") openai = OpenAI(api_key=api_key) slack_app = App(token=os.environ.get("SLACK_BOT_TOKEN")) @slack_app.event("app_mention") def handle_mention(event, say): # Extract text and remove the bot mention tag user_query = event['text'].split('> ')[-1] if '>' in event['text'] else event['text'] # Use your existing chat logic to get an answer # Note: History is empty for a single Slack mention unless you implement tracking response_text = chat(user_query, []) # Send answer back to the same Slack channel say(response_text) # 2. Function to run Slack bot in a background thread def run_slack(): handler = SocketModeHandler(slack_app, os.environ.get("SLACK_APP_TOKEN")) handler.start() reader = PdfReader("input/dashie_bot_input.pdf") input = "" for page in reader.pages: text = page.extract_text() if text: input += text instructions = f"You are a data analyst helping connect people having a question about data to the correct dashboard containing the needed data. \ You are given the full descriptions of the dashboards and each graph and filtering that they contain in the file dashie_bot_input\ Do not use any information outside of the information provided. If requested data is not in described in the sheet or you do not know answer, refer the requester to #ask_product_owners channel on Slack or directly to Audrius\ When giving answers, be coincise and practical, share the link to the relevant dashboard" instructions += f"\n\n## Dashie_bot_input:\n{input}\n\n" def chat(message, history): # Prepare the message list messages = [{"role": "system", "content": instructions}] + history + [{"role": "user", "content": message}] # Simple call to OpenAI (no loop needed) response = openai.chat.completions.create( model="gpt-4o-mini", messages=messages ) # Return the content immediately return response.choices[0].message.content if __name__ == "__main__": # Start Slack bot in the background threading.Thread(target=run_slack, daemon=True).start() # Launch Gradio as usual gr.ChatInterface(chat).launch()