Commit ·
e66d103
1
Parent(s): 3b8060f
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,10 @@
|
|
| 1 |
-
import os
|
| 2 |
-
os.environ['SENTENCE_TRANSFORMERS_HOME'] = './.cache'
|
| 3 |
-
|
| 4 |
-
few_shots = {"What are the top 10 performing areas?": "SELECT TOP 10 destn_area_name, AVG(score) AS AvgScore FROM All_data GROUP BY destn_area_name ORDER BY AvgScore DESC",
|
| 5 |
-
"What are the worst 10 performing areas?": "SELECT TOP 10 destn_area_name, AVG(score) AS AvgScore FROM All_data GROUP BY destn_area_name ORDER BY AvgScore ASC",
|
| 6 |
-
"What districts have the highest volume of mail?": "SELECT TOP 10 destn_district_name, COUNT(*) AS Volume FROM All_data GROUP BY destn_district_name ORDER BY Volume DESC",
|
| 7 |
-
"What districts have the lowest volume of mail?": "SELECT TOP 10 destn_district_name, COUNT(*) AS Volume FROM All_data GROUP BY destn_district_name ORDER BY Volume ASC",
|
| 8 |
-
"What are the top 10 performing districts?": "SELECT TOP 10 destn_district_name, AVG(score) AS AvgScore FROM All_data GROUP BY destn_district_name ORDER BY AvgScore DESC",
|
| 9 |
-
"What are the worst 10 performing districts?": "SELECT TOP 10 destn_district_name, AVG(score) AS AvgScore FROM All_data GROUP BY destn_district_name ORDER BY AvgScore ASC",
|
| 10 |
-
"What districts gave the fastest delivery time?": "SELECT TOP 10 destn_district_name, AVG(avg_days_todelr) AS AvgDeliveryTime FROM All_data GROUP BY destn_district_name ORDER BY AvgDeliveryTime ASC"}
|
| 11 |
|
| 12 |
from langchain.embeddings import HuggingFaceEmbeddings
|
| 13 |
#from langchain.vectorstores import FAISS
|
| 14 |
from langchain.schema import Document
|
| 15 |
|
| 16 |
-
from langchain.vectorstores import Chroma
|
| 17 |
from langchain.llms import AzureMLOnlineEndpoint
|
| 18 |
-
import chromadb
|
| 19 |
from langchain.chat_models.azureml_endpoint import ContentFormatterBase
|
| 20 |
import json
|
| 21 |
|
|
@@ -26,26 +15,6 @@ import chainlit as cl
|
|
| 26 |
|
| 27 |
from typing import Dict
|
| 28 |
|
| 29 |
-
embeddings_model_name = 'sentence-transformers/msmarco-distilbert-base-tas-b'
|
| 30 |
-
embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)
|
| 31 |
-
|
| 32 |
-
few_shot_docs = [Document(page_content=question, metadata={'sql_query': few_shots[question]}) for question in few_shots.keys()]
|
| 33 |
-
vector_db = Chroma.from_documents(few_shot_docs, embeddings)
|
| 34 |
-
retriever = vector_db.as_retriever()
|
| 35 |
-
|
| 36 |
-
# Create custom tool and append it as a new tool in the create_sql_agent function:
|
| 37 |
-
from langchain.agents.agent_toolkits import create_retriever_tool
|
| 38 |
-
|
| 39 |
-
tool_description = """
|
| 40 |
-
This tool will help answers questions about the USPS Service Performance Measurement (SPM) data.
|
| 41 |
-
"""
|
| 42 |
-
|
| 43 |
-
retriever_tool = create_retriever_tool(
|
| 44 |
-
retriever,
|
| 45 |
-
name='spm_chat',
|
| 46 |
-
description=tool_description
|
| 47 |
-
)
|
| 48 |
-
custom_tool_list = [retriever_tool]
|
| 49 |
|
| 50 |
# Now we can create the agent, adjusting the standard SQL Agent suffix to consider our use case.
|
| 51 |
# Although the most straightforward way to handle this would be to include it just in the tool description,
|
|
@@ -57,60 +26,21 @@ from langchain.utilities import SQLDatabase
|
|
| 57 |
from langchain.chat_models import ChatOpenAI
|
| 58 |
|
| 59 |
import os
|
| 60 |
-
|
| 61 |
-
PWD = os.environ['SQL_PWD']
|
| 62 |
-
SQL_USR_NM = os.environ['SQL_USR_NM']
|
| 63 |
-
SQL_HOST = os.environ['SQL_HOST']
|
| 64 |
-
SQL_TBL = os.environ['SQL_TBL']
|
| 65 |
-
|
| 66 |
-
conn_str = "mssql+pyodbc://" + SQL_USR_NM + ":" + PWD + "@" + SQL_HOST + "/" + SQL_TBL# + "#?driver=ODBC+Driver+18+for+SQL+Server"
|
| 67 |
-
#conn = pymssql.connect(server="127.0.0.1", port="33412", user="reader", password="passwd", database="db_name")
|
| 68 |
|
| 69 |
|
| 70 |
-
# Create the SQLDatabase object
|
| 71 |
-
db = SQLDatabase.from_uri(conn_str)
|
| 72 |
|
| 73 |
-
model_name = os.environ['MODEL_NAME']
|
| 74 |
-
endpoint_api_key = os.environ['ENDPOINT_API_KEY']
|
| 75 |
-
endpoint_url = os.environ['ENDPOINT_URL']
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
accepts = "application/json"
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
"input_string": [
|
| 87 |
-
{
|
| 88 |
-
"role": "user",
|
| 89 |
-
"content": prompt
|
| 90 |
-
}
|
| 91 |
-
],
|
| 92 |
-
"parameters": {
|
| 93 |
-
"temperature": 0.6,
|
| 94 |
-
"top_p": 0.9,
|
| 95 |
-
"max_new_tokens": 20000
|
| 96 |
-
}
|
| 97 |
-
}
|
| 98 |
-
}
|
| 99 |
-
)
|
| 100 |
-
return str.encode(input_str)
|
| 101 |
|
| 102 |
-
|
| 103 |
-
response_json = json.loads(output)
|
| 104 |
-
return response_json["output"]
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
llm = AzureMLOnlineEndpoint(endpoint_name=model_name,
|
| 109 |
-
endpoint_api_key=endpoint_api_key,
|
| 110 |
-
endpoint_url=endpoint_url,
|
| 111 |
-
content_formatter = CustomFormatter())#,
|
| 112 |
-
|
| 113 |
-
toolkit = SQLDatabaseToolkit(db=db, llm=llm)
|
| 114 |
|
| 115 |
custom_suffix = """
|
| 116 |
Compose a query in the All_data table in the db database.
|
|
@@ -138,14 +68,14 @@ score: The score of the destination area.
|
|
| 138 |
score_plus_1: The score of the destination area plus 1.
|
| 139 |
"""
|
| 140 |
|
| 141 |
-
agent = create_sql_agent(llm=llm,
|
| 142 |
-
toolkit=toolkit,
|
| 143 |
-
verbose=
|
| 144 |
-
|
| 145 |
-
extra_tools=custom_tool_list,
|
| 146 |
-
suffix=custom_suffix,
|
| 147 |
-
handle_parsing_errors=True
|
| 148 |
-
)
|
| 149 |
|
| 150 |
from langchain.prompts import PromptTemplate
|
| 151 |
|
|
@@ -195,27 +125,32 @@ def build_sql_chain(llm, db):
|
|
| 195 |
# Set verbose=True to see the full prompt:
|
| 196 |
return create_sql_query_chain(llm=llm, db=db)
|
| 197 |
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
@cl.on_chat_start
|
| 201 |
-
def main():
|
| 202 |
# Parse the command line arguments
|
| 203 |
# args = parse_arguments()
|
| 204 |
-
|
| 205 |
-
|
| 206 |
# activate/deactivate the streaming StdOut callback for LLMs
|
| 207 |
#callbacks = [StreamingStdOutCallbackHandler()]
|
| 208 |
|
| 209 |
-
sql_chain = build_sql_chain(llm, db)
|
| 210 |
|
| 211 |
|
| 212 |
@cl.on_message
|
| 213 |
async def msg(message: str):
|
| 214 |
# Retrieve the chain from the user session
|
| 215 |
-
|
|
|
|
| 216 |
m = message.content
|
| 217 |
-
res = sql_chain.invoke({"question": m})
|
|
|
|
| 218 |
# Call the chain asynchronously
|
| 219 |
|
| 220 |
print(res)
|
| 221 |
-
await cl.Message(content=res).send()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
|
| 2 |
from langchain.embeddings import HuggingFaceEmbeddings
|
| 3 |
#from langchain.vectorstores import FAISS
|
| 4 |
from langchain.schema import Document
|
| 5 |
|
| 6 |
+
#from langchain.vectorstores import Chroma
|
| 7 |
from langchain.llms import AzureMLOnlineEndpoint
|
|
|
|
| 8 |
from langchain.chat_models.azureml_endpoint import ContentFormatterBase
|
| 9 |
import json
|
| 10 |
|
|
|
|
| 15 |
|
| 16 |
from typing import Dict
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# Now we can create the agent, adjusting the standard SQL Agent suffix to consider our use case.
|
| 20 |
# Although the most straightforward way to handle this would be to include it just in the tool description,
|
|
|
|
| 26 |
from langchain.chat_models import ChatOpenAI
|
| 27 |
|
| 28 |
import os
|
| 29 |
+
OPENAI_API_KEY = os.environ['OPENAI_API_KEY']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
|
|
|
|
|
|
|
| 32 |
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
def create_agent():
|
| 35 |
+
# conn_str = "mssql+pyodbc://" + SQL_USR_NM + ":" + PWD + "@" + SQL_HOST + "/" + SQL_TBL + "?driver=ODBC+Driver+18+for+SQL+Server"
|
|
|
|
| 36 |
|
| 37 |
+
# Create the SQLDatabase object
|
| 38 |
+
db = SQLDatabase.from_uri('sqlite:///spm.db')
|
| 39 |
+
llm = ChatOpenAI(temperature=0.05, model="gpt-3.5-turbo-16k-0613")
|
| 40 |
+
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True)
|
| 41 |
+
return db_chain
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
#toolkit = SQLDatabaseToolkit(db=db, llm=llm)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
custom_suffix = """
|
| 46 |
Compose a query in the All_data table in the db database.
|
|
|
|
| 68 |
score_plus_1: The score of the destination area plus 1.
|
| 69 |
"""
|
| 70 |
|
| 71 |
+
#agent = create_sql_agent(llm=llm,
|
| 72 |
+
# toolkit=toolkit,
|
| 73 |
+
# verbose=False,
|
| 74 |
+
# agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
|
| 75 |
+
# extra_tools=custom_tool_list,
|
| 76 |
+
# suffix=custom_suffix,
|
| 77 |
+
# handle_parsing_errors=True
|
| 78 |
+
# )
|
| 79 |
|
| 80 |
from langchain.prompts import PromptTemplate
|
| 81 |
|
|
|
|
| 125 |
# Set verbose=True to see the full prompt:
|
| 126 |
return create_sql_query_chain(llm=llm, db=db)
|
| 127 |
|
| 128 |
+
#from langchain.llms import OpenAI
|
| 129 |
+
from langchain_experimental.sql import SQLDatabaseChain
|
| 130 |
+
#sql_chain = build_sql_chain(llm, db)
|
| 131 |
+
|
| 132 |
|
| 133 |
@cl.on_chat_start
|
| 134 |
+
async def main():
|
| 135 |
# Parse the command line arguments
|
| 136 |
# args = parse_arguments()
|
| 137 |
+
await cl.Message(content="Welcome to GeoData!").send()
|
| 138 |
+
|
| 139 |
# activate/deactivate the streaming StdOut callback for LLMs
|
| 140 |
#callbacks = [StreamingStdOutCallbackHandler()]
|
| 141 |
|
| 142 |
+
#sql_chain = build_sql_chain(llm, db)
|
| 143 |
|
| 144 |
|
| 145 |
@cl.on_message
|
| 146 |
async def msg(message: str):
|
| 147 |
# Retrieve the chain from the user session
|
| 148 |
+
#sql_chain = cl.user_session.get("sql_chain") # type: RetrievalQA
|
| 149 |
+
agent = create_agent()
|
| 150 |
m = message.content
|
| 151 |
+
#res = sql_chain.invoke({"question": m})
|
| 152 |
+
res = agent.run({"query": m})
|
| 153 |
# Call the chain asynchronously
|
| 154 |
|
| 155 |
print(res)
|
| 156 |
+
await cl.Message(content=res).send()
|