Technical Article

Python script to write SQL using Amazon Bedrock Generative AI

In this script we will leverage the capabilities of Amazon Bedrock's Generative AI service to author SQL statements. The Generative AI service provides advanced natural language processing to understand requirements and generate customized SQL code. This allows us to automate the creation of SQL queries for data analysis and reporting. The service is versatile and can be adapted for many different use cases across industries and domains. By integrating the Generative AI into our scripts, we enable intelligent SQL generation tailored to the specific data and insights we want to uncover. This simplifies and accelerates the process of gleaning actionable business intelligence from data.

Command1:

python3 Bedrock1.py WriteSQL "top ten customers by sales"

Output1:

SELECT Customer_Name FROM Customers ORDER BY Sales DESC LIMIT 10

 

Command2:

python3 Bedrock1.py WriteSQL "get the top ten customers by sales but print all fields from account object include costofliving"

Output2:

SELECT

customer__c,

last_name__c,

first_name__c,

sales__c,

cost_of_living__c

FROM

Account

ORDER BY

sales__c DESC

LIMIT

10;

#=====================================================================
# Bedrock1.py:
# Usage: python3 Bedrock1.py
# Usage: python3 Bedrock1.py WriteSQL "top ten customers by sales"
# Usage: python3 Bedrock1.py WriteSQL "get the top ten customers by sales but print all fields from account object include costofliving"
#=====================================================================
import boto3
import json
import base64
import sys

# Global Variables
client = boto3.client("bedrock-runtime")
strBedrockConfig =  " "maxTokens":200,"temperature":0.7,"topP":1,"stopSequences":[]," + 
" "countPenalty":{"scale":0}," + 
" "presencePenalty":{"scale":0}," + 
" "frequencyPenalty":{"scale":0}"

def main():
WriteSQL(sys.argv[1])
# End main()

def WriteSQL(lstArgs):
strQuestion = lstArgs[1]
strQuestion = strQuestion.replace("n","")
strQuestion = "write sql for " + strQuestion
input_data = {
"modelId":"ai21.j2-mid-v1",
"contentType":"application/json",
"accept":"*/*",
"body":"{"prompt":"" + strQuestion + "", " + strBedrockConfig + "}"
}
response = client.invoke_model(contentType='application/json',body=input_data['body'], modelId=input_data['modelId'])
Data = json.loads(response['body'].read().decode('utf-8'))
print(Data['completions'][0]['data']['text'])
# End WriteSQL()


if __name__ == "__main__":
main()

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating