Skip to content

New genai connector pattern qbusiness-slack-sam #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
Binary file added .DS_Store
Binary file not shown.
Binary file added qbusiness-slack-sam/.DS_Store
Binary file not shown.
86 changes: 86 additions & 0 deletions qbusiness-slack-sam/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Amazon Q Business to Slack

This pattern contains a sample AWS SAM stack that leverages Amazon Q Business to build a generative AI application to derive insights from content present in Slack. An AWS Lambda function initiates the crawling and indexing of the messages present in the specified Slack App. Users can then ask questions to the Amazon Q Business application to receive a generated response.

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the AWS Pricing page for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Requirements
* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed
* [Enable AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/get-set-up-for-idc.html)
* [Create Users in AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/addusers.html). Note down the Instance ARN by going to the AWS IAM Identity Center console --> Settings --> Instance ARN. You will require it when deploying the stack.
* [Set Up Slack to retrieve Team ID and token](https://docs.aws.amazon.com/amazonq/latest/qbusiness-ug/slack-credentials.html) that you want to be indexed. If you already have a Slack app created with data that you want to crawl, you can skip this step and retrieve the team ID and Slack Bot User OAuth token or Slack User OAuth token.
* [Store Slack Token in Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/managing-secrets.html). Note the ARN of the Slack Secret.


## Deployment Instructions
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```
git clone https://github.com/aws-samples/serverless-patterns
```
1. Change directory to the pattern directory:
```
cd qbusiness-slack-sam
```
1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
```
sam deploy --guided --capabilities CAPABILITY_NAMED_IAM
```
1. During the prompts:

* Enter a stack name.
* Enter the desired AWS Region.
* Enter the AWS IAM Identity Center Instance ARN noted from the instructions followed in Requirements.
* Enter the Slack Secret ARN noted from the instructions followed in Requirements.
* Enter the TeamID from the Slack workspace that you are connecting to.
* Allow SAM CLI to create IAM roles with the required permissions.

Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.*

1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing.

# How it works
Please refer to the architecture diagram below:

![End to End Architecture](images/qbusiness-slack-architecture.png)

Here's a breakdown of the steps:

**Amazon Q Business Application:** Amazon Q Business application created with Slack as the data source.

**Slack:** Slack contains messages and files.

**AWS Lambda:** AWS Lambda function `DataSourceSync` crawls and indexes the content from the Slack. The Amazon Q Business application retrieves data from the indexed content and provides a generated response.

## Testing

1. Go to the Amazon Q Business Console and verify that your application `MyQBusinessApp-${StackName}` has been created.
![Amazon Q Business Application](images/qbusiness-application.png)

1. Click on the Name of the Application. Scroll down to the `Groups and Users` section. Click on `Manage access and Subscriptions`.
![Groups and Users Section](images/groups-users.png)
1. Click on `Add groups and users` and select `Assign existing users and groups`. Click `Next`.

Note: If you have NOT already created a user in the Requirements section, then create one by choosing `Add and assign new users` instead and add the user.
![Assign users](images/assign-users-groups.png)
1. Add the name of the user and click on `Assign`.
![Assign user](images/assign-user.png)
1. Select the user and in the `Change subscription` dropdown, select `Update subscription tier`. In the `New subscription` dropdown, choose `Q Business Lite` and `Confirm`.
![User subscription](images/subscription.png)
1. Go back to your application. Under `Web experience settings`, copy the `Deployed URL` link.
![Deployed URL](images/deployed-url.png)
1. Open the URL in a New Incognito Window. Login to the web experience with the credentials of the created user. Ask a question in the chat interface regarding the messages and files you have in the Slack provided as a data source.
![Q Business Web Experience](images/chat-interface.png)

## Cleanup

1. Delete the stack
```bash
sam delete
```
----
<!-- Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0 -->
26 changes: 26 additions & 0 deletions qbusiness-slack-sam/cfn_nag_results.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
------------------------------------------------------------
template.yaml
------------------------------------------------------------------------------------------------------------------------
| WARN W89
|
| Resource: ["DataSourceSyncLambda"]
| Line Numbers: [170]
|
| Lambda functions should be deployed inside a VPC
------------------------------------------------------------
| WARN W92
|
| Resource: ["DataSourceSyncLambda"]
| Line Numbers: [170]
|
| Lambda functions should define ReservedConcurrentExecutions to reserve simultaneous executions
------------------------------------------------------------
| WARN W28
|
| Resource: ["QBusinessWebExperienceRole"]
| Line Numbers: [19]
|
| Resource found with an explicit name, this disallows updates that require replacement of this resource

Failures count: 0
Warnings count: 3
Binary file added qbusiness-slack-sam/images/.DS_Store
Binary file not shown.
Binary file added qbusiness-slack-sam/images/assign-user.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added qbusiness-slack-sam/images/chat-interface.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added qbusiness-slack-sam/images/deployed-url.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added qbusiness-slack-sam/images/groups-users.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added qbusiness-slack-sam/images/subscription.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions qbusiness-slack-sam/samconfig.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version = 0.1
[default.deploy.parameters]
stack_name = "hgkdjswtahtsyj"
resolve_s3 = true
s3_prefix = "hgkdjswtahtsyj"
region = "us-east-1"
confirm_changeset = true
capabilities = "CAPABILITY_NAMED_IAM"
parameter_overrides = "IdentityCenterInstanceArn=\"arn:aws:sso:::instance/ssoins-72232d339c320c7c\" SlackSecretArn=\"arn:aws:secretsmanager:us-east-1:428325390718:secret:QBusiness-Slack-test-tScPdG\" YOURSLACKTEAMID=\"T062EARNCRF\""
image_repositories = []
Binary file added qbusiness-slack-sam/src/.DS_Store
Binary file not shown.
46 changes: 46 additions & 0 deletions qbusiness-slack-sam/src/dataSourceSync/cfnresponse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

from __future__ import print_function
import urllib3
import json

SUCCESS = "SUCCESS"
FAILED = "FAILED"

http = urllib3.PoolManager()


def send(event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False, reason=None):
responseUrl = event['ResponseURL']

print(responseUrl)

responseBody = {
'Status' : responseStatus,
'Reason' : reason or "See the details in CloudWatch Log Stream: {}".format(context.log_stream_name),
'PhysicalResourceId' : physicalResourceId or context.log_stream_name,
'StackId' : event['StackId'],
'RequestId' : event['RequestId'],
'LogicalResourceId' : event['LogicalResourceId'],
'NoEcho' : noEcho,
'Data' : responseData
}

json_responseBody = json.dumps(responseBody)

print("Response body:")
print(json_responseBody)

headers = {
'content-type' : '',
'content-length' : str(len(json_responseBody))
}

try:
response = http.request('PUT', responseUrl, headers=headers, body=json_responseBody)
print("Status code:", response.status)

except Exception as e:

print("send(..) failed executing http.request(..):", e)
28 changes: 28 additions & 0 deletions qbusiness-slack-sam/src/dataSourceSync/dataSourceSyncLambda.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

import json
import logging
import boto3
import cfnresponse
import os

logger = logging.getLogger()
logger.setLevel(logging.INFO)

INDEX_ID = os.environ['INDEX_ID']
DS_ID = os.environ['DS_ID']
AWS_REGION = os.environ['AWS_REGION']
QBUSINESS = boto3.client('qbusiness')
APP_ID = os.environ['APP_ID']

def start_data_source_sync(dsId, indexId, appID):
logger.info(f"start_data_source_sync(dsId={dsId}, indexId={indexId})")
resp = QBUSINESS.start_data_source_sync_job(dataSourceId=dsId, indexId=indexId, applicationId=appID)
logger.info(f"response:" + json.dumps(resp))

def lambda_handler(event, context):
start_data_source_sync(DS_ID, INDEX_ID, APP_ID)
status = cfnresponse.SUCCESS
cfnresponse.send(event, context, status, {}, None)
return status
Loading