File size: 2,635 Bytes
6cfd892
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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()