|
| 1 | +import streamlit as st |
| 2 | +import pandas as pd |
| 3 | +import os |
| 4 | +import re |
| 5 | +import pickle |
| 6 | +import jwt |
| 7 | + |
| 8 | +from dotenv import load_dotenv |
| 9 | +from langchain import OpenAI |
| 10 | +from langchain.embeddings import OpenAIEmbeddings |
| 11 | +from langchain.vectorstores.faiss import FAISS |
| 12 | +from langchain.document_loaders import CubeSemanticLoader |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +from utils import ( |
| 16 | + create_docs_from_values, |
| 17 | + create_vectorstore, |
| 18 | + init_vectorstore, |
| 19 | + check_input, |
| 20 | + log, |
| 21 | + call_sql_api, |
| 22 | + CUBE_SQL_API_PROMPT, |
| 23 | + _NO_ANSWER_TEXT, |
| 24 | + PROMPT_POSTFIX, |
| 25 | +) |
| 26 | + |
| 27 | +load_dotenv() |
| 28 | + |
| 29 | +def ingest_cube_meta(): |
| 30 | + security_context = {} |
| 31 | + token = jwt.encode(security_context, os.environ["CUBE_API_SECRET"], algorithm="HS256") |
| 32 | + |
| 33 | + loader = CubeSemanticLoader(os.environ["CUBE_API_URL"], token) |
| 34 | + documents = loader.load() |
| 35 | + |
| 36 | + embeddings = OpenAIEmbeddings() |
| 37 | + vectorstore = FAISS.from_documents(documents, embeddings) |
| 38 | + |
| 39 | + # Save vectorstore |
| 40 | + with open("vectorstore.pkl", "wb") as f: |
| 41 | + pickle.dump(vectorstore, f) |
| 42 | + |
| 43 | +if not Path("vectorstore.pkl").exists(): |
| 44 | + with st.spinner('Loading context from Cube API...'): |
| 45 | + ingest_cube_meta(); |
| 46 | + |
| 47 | +llm = OpenAI( |
| 48 | + temperature=0, openai_api_key=os.environ.get("OPENAI_API_KEY"), verbose=True |
| 49 | +) |
| 50 | + |
| 51 | +st.title("Cube and LangChain demo 🤖🚀") |
| 52 | + |
| 53 | +multi = ''' |
| 54 | +Follow [this tutorial on Github](https://github.com/cube-js/cube/tree/master/examples/langchain) to clone this project and run it locally. |
| 55 | +
|
| 56 | +You can use these sample questions to quickly test the demo -- |
| 57 | +* How many orders? |
| 58 | +* How many completed orders? |
| 59 | +* What are top selling product categories? |
| 60 | +* What product category drives the highest average order value? |
| 61 | +''' |
| 62 | +st.markdown(multi) |
| 63 | + |
| 64 | +question = st.text_input( |
| 65 | + "Your question: ", placeholder="Ask me anything ...", key="input" |
| 66 | +) |
| 67 | + |
| 68 | +if st.button("Submit", type="primary"): |
| 69 | + check_input(question) |
| 70 | + vectorstore = init_vectorstore() |
| 71 | + |
| 72 | + # log("Quering vectorstore and building the prompt...") |
| 73 | + |
| 74 | + docs = vectorstore.similarity_search(question) |
| 75 | + # take the first document as the best guess |
| 76 | + table_name = docs[0].metadata["table_name"] |
| 77 | + |
| 78 | + # Columns |
| 79 | + columns_question = "All available columns" |
| 80 | + column_docs = vectorstore.similarity_search( |
| 81 | + columns_question, filter=dict(table_name=table_name), k=15 |
| 82 | + ) |
| 83 | + |
| 84 | + lines = [] |
| 85 | + for column_doc in column_docs: |
| 86 | + column_title = column_doc.metadata["column_title"] |
| 87 | + column_name = column_doc.metadata["column_name"] |
| 88 | + column_data_type = column_doc.metadata["column_data_type"] |
| 89 | + print(column_name) |
| 90 | + lines.append( |
| 91 | + f"title: {column_title}, column name: {column_name}, datatype: {column_data_type}, member type: {column_doc.metadata['column_member_type']}" |
| 92 | + ) |
| 93 | + columns = "\n\n".join(lines) |
| 94 | + |
| 95 | + # Construct the prompt |
| 96 | + prompt = CUBE_SQL_API_PROMPT.format( |
| 97 | + input_question=question, |
| 98 | + table_info=table_name, |
| 99 | + columns_info=columns, |
| 100 | + top_k=1000, |
| 101 | + no_answer_text=_NO_ANSWER_TEXT, |
| 102 | + ) |
| 103 | + |
| 104 | + # Call LLM API to get the SQL query |
| 105 | + log("Calling LLM API to generate SQL query...") |
| 106 | + llm_answer = llm(prompt) |
| 107 | + bare_llm_answer = re.sub(r"(?i)Answer:\s*", "", llm_answer) |
| 108 | + |
| 109 | + if llm_answer.strip() == _NO_ANSWER_TEXT: |
| 110 | + st.stop() |
| 111 | + |
| 112 | + sql_query = llm_answer |
| 113 | + |
| 114 | + log("Query generated by LLM:") |
| 115 | + st.info(sql_query) |
| 116 | + |
| 117 | + # Call Cube SQL API |
| 118 | + log("Sending the above query to Cube...") |
| 119 | + columns, rows = call_sql_api(sql_query) |
| 120 | + |
| 121 | + # Display the result |
| 122 | + df = pd.DataFrame(rows, columns=columns) |
| 123 | + st.table(df) |
0 commit comments