You can translate the document:

Team communication platforms like Slack are a critical piece of the software stack within any organization, offering an already widely distributed frontend for running generative artificial intelligence (genAI) applications. In order to remove redundant chat platforms, Slack can be a powerful and intuitive frontend for the Denodo AI SDK, offering a familiar communication platform for users with an already built out feature list. Furthermore, integrating with team messaging reduces the development cycle of building bespoke genAI applications by removing the need to develop and maintain a frontend.

In this document we propose integrating the Denodo AI SDK into Slack so that users can easily perform complex searches, and retrieve relevant information directly within their existing corporate communications channels. Not only does this make the Denodo AI SDK more accessible for your users but also allows further integration with workflows within Slack .

Architecture

In this document, we will cover how to use the various API endpoints provided by Slack to integrate the Denodo AI SDK with its platform, allowing users to query enterprise data directly from their corporate communications channel. To integrate Denodo’s AI SDK, you need to set up a Slack bot within your workspace that uses a signing secret to verify requests from Slack and a bot token to post responses. When a Slack event, such as a user message occurs, the listening server we are designing receives this event, extracts the message text, and forwards it to the Denodo /askquestion API endpoint. The AI SDK processes the request and returns a response, which the server then posts back to Slack through the bot. The general flow of information can be seen below in the diagram:

NOTE: in this guide we will cover a python flask application acting as an event listener between the Denodo AI SDK APIs and the Slack Events API. This can be done in any programming language you are comfortable with.

For more information on how you can design your Slack integration visit Designing Slack apps. 

Prerequirements

Network Prerequirements

Depending on your network configuration, the event messages may not be able to reach your slack event listener. For this, we wanted to demonstrate enabling external access to a locally running Slack event listener by using local tunnel, an open source tunneling software.

Install Node.js: Localtunnel requires Node.js. You can download it from https://nodejs.org.

Open a terminal command and install local tunnel.

npm install -g localtunnel

After installing local tunnel, the localtunnel command will be available from the terminal. Using this, we can open the port serving the AI SDK through local tunnel. This can be done with the following command

npx localtunnel --port 8008

After this runs, the new forwarded URL will be returned.

Slack Prerequirements

In order to get data in and out of Slack, we will need to set up a Slack Application with the correct permissions and a Bot. The Slack application will handle forwarding the chat messages to our event listener every time a message is posted to the AI SDK Channel. The bot will be the interface for returning the response from the Denodo AI SDK. In order to set this up, you will need to follow these steps:

  1. Within Slack, enter the Application Builder panel

  1. Select on Create New App 

  1. Within the Create an App Wizard, specify you want to start developing an application from scratch.

  1. Within your newly created application, you need to activate incoming webhooks. This is how slack will receive messages from our middleware, forwarding a response from the Denodo AI SDK.

  1. You will need to enable Events in the Event Subscription Panel. This setting will  message our slack listener when we want it to.

  1. Next we want to set the scope of when our application should post events. There is a high amount of customization within Event Subscription for the types of interactions you want as posted events. I.E, you could set up your Slack listener to listen to mentions, reactions, etc…. In our sample code, we would need to enable app_mentions:read, channels:history, incoming-webhooks, and chat:write. By enabling these event subscriptions, every time our app is mentioned in a channel an event is forwarded to our slack listener with the text attached. chat:write and incoming webhooks allow our bot to write in the channel we messaged it in, delivering our retrieval augmented generated (RAG) response from the AI SDK.

  1. Next we want to set the scope of when our application should post events. In our sample code, we demonstrate how a user could enable app_mentions:read, channels:history, incoming-webhooks and chat:write. By enabling these event subscriptions, our listening server has the necessary permissions to receive a message every time our app is mentioned in a channel or addressed directly in a 1:1 conversation. There is a high amount of customization within Event Subscription for the types of interactions you want as posted events. e.g. you could set up your Slack listener to listen to mentions, reactions, etc.

Code Walkthrough

Technical Overview

We will now cover the python file with the logic for our Slack event listener. Before continuing ensure you have a python development environment setup and sufficient network permissions to listen to the messages posted from the Events API.

As we covered earlier, the Slack event listener listens to messages in a specific channel using Slack's Events API. When the message is received, the content of the message is forwarded to the Denodo AI SDK. Then the event listener should process the response and return the LLM response as a bot in the same Slack channel.

To start, you will need to create a Slack app in the Slack API dashboard and configure its bot permissions as explained in the prerequirements section. Enable the Events API, specifying the bot’s Request URL (a publicly accessible endpoint to receive events). You will then need to subscribe to specific event types, such as `message.channels`, which triggers when a message is posted in a channel. You can also configure this to act in other ways depending on how the user interacts with messages or any other slack events. You can additionally, configure scopes like `chat:write` and `channels:history` to allow the bot to post and read messages.

Python Dependencies

Slack_bolt: for handling incoming events and interactions in a structured way.

Slack_sdk: for interacting with Slack’s API for sending messages.

Flask: as our lightweight server framework.

Requests: for communicating with the Denodo AI SDK.

Os: for managing environment variables like API keys and Slack bot token.

Slack Event Listener Code

In this section we will review step by step the code that makes up the event listener. Although they are shown separately, all the code is meant to run together within the same file.

We will now cover how to establish a connection to a Slack app with authentication tokens and secrets retrieved from environment variables. The following function leverages Slack native python libraries objects like App and Webclient that streamline the connection process.

from slack_bolt import App

from slack_bolt.adapter.flask import SlackRequestHandler

from slack_sdk.web import WebClient

from flask import Flask, request

import requests

from requests.auth import HTTPBasicAuth

import os

slack_bot_token=os.environ.get("SLACK_BOT_TOKEN")

signing_secret=os.environ.get("SLACK_SIGNING_SECRET")

# Initializes your app with your bot token and signing secret

app = App(

    token=slack_bot_token,

    signing_secret=signing_secret

)

slack_client = WebClient(slack_bot_token)

In the Slack SDK, the WebClient and App objects serve distinct purposes for interacting with the Slack API and handling events:

The Web Client is a low level API client for sending requests directly to Slack's Web API. With WebClient, the idea is to perform various operations like sending messages, fetching user or channel information, and updating channel topics. This will be in charge of handling our bot response.

The App is a higher-level object in the Slack SDK designed to handle event-driven functionality in a Slack app. It includes built-in methods for managing events, commands, actions, and shortcuts that the app might encounter. In our case, when a user mentions the bot or triggers a specific event, the App object processes these actions allowing us to listen to events happening in the Slack environment.

For more information visit GitHub - slackapi/python-slack-sdk: Slack Developer Kit for Python 

Next we define a function that calls our /answerquestion API endpoint in our Denodo AI SDK using the requests library. We will need to call this function call_answer_question_api from our slack listener function in order to pass the messages from our slack channel. Remember to modify the url to match your SDK instance.

def call_answer_question_api(question):

    url = "http://localhost:8008/answerQuestion" #Replace with your URL

    params = {

        "question": question,

           }

    response = requests.get(url, params=params, auth=HTTPBasicAuth('admin', 'admin'))

    if response.status_code == 200:

        data = response.json()

        return f"{data['answer']}\n{data['sql_query']}"

    else:

        response.raise_for_status()

call_answer_question_api is a function that sends a GET request to the AI SDK /answerquestion API with a given question parameter, the user query. The URL endpoint for the API is specified as "http://localhost:8008/answerQuestion", and should be replaced with another endpoint as needed.

Next we will need to build our listening function. In our demo code, we take mentions of our bot in a channel as the necessary event to trigger our API request function. For app mentions, we will need to listen to posts from the Slack Events API with the extension /app_mention. For other extensions, refer to this document.

@app.event("app_mention")

def handle_message_events(body, logger):

    logger.info(body)

    event = body['event']

    user_input = event.get('text')

    response = query_api(user_input)

    slack_client.chat_postMessage(channel=event["channel"], text=response)

This code defines handle_message_events, which is triggered whenever the app is mentioned in Slack (@app.event("app_mention")). When the app receives a mention, it logs the event details, extracts the user's message from event['text'], and processes the input with query_api. Then, it sends the response back to the same Slack channel where the message was received using slack_client.chat_postMessage.

Finally, we define some error handling for our flask application and define the connection profile. You can modify the port this application is running on by modifying  app.run(port=3000).

# Error events

@app.error

def error_handler(error, body, logger):

    logger.error(f"Error: {error}")

# Flask adapter

flask_handler = SlackRequestHandler(app)

# Start the app

if __name__ == "__main__":

    app = Flask(__name__)

    @app.route("/slack/events", methods=["POST"])

    def slack_events():

        return flask_handler.handle(request)

    app.run(port=3000)

The error_handler function, decorated with @app.error, logs any errors that occur within the Slack app, providing useful debugging information.  Then, if the script is run directly, the Flask app starts on port 3000 and waits for slack events to be posted to it.

Conclusion

In summary, integrating Denodo’s AI SDK into Slack provides a highly efficient front end solution for  leveraging generative artificial intelligence on enterprise data. With Slack as a familiar framework, organizations can streamline their operations without needing to maintain additional platforms or interfaces, delivering feature-sets to where their users already are. This integration not only enhances accessibility, but also simplifies the development process by enabling users to perform advanced data analytics and introspection on enterprise information seamlessly within their existing Slack workflows.

Disclaimer
The information provided in the Denodo Knowledge Base is intended to assist our users in advanced uses of Denodo. Please note that the results from the application of processes and configurations detailed in these documents may vary depending on your specific environment. Use them at your own discretion.
For an official guide of supported features, please refer to the User Manuals. For questions on critical systems or complex environments we recommend you to contact your Denodo Customer Success Manager.

Questions

Ask a question

You must sign in to ask a question. If you do not have an account, you can register here