Spaces:
Sleeping
Sleeping
File size: 2,471 Bytes
6708edd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | from langchain_community.utilities import SQLDatabase
from langchain_community.agent_toolkits import create_sql_agent
from langchain_aws import ChatBedrock
import streamlit as st
import os
from dotenv import load_dotenv
load_dotenv()
class ExcelAnalyser:
def __init__(self, uri): # Fix the method name
self.uri = uri
def connect_to_uri(self):
db = SQLDatabase.from_uri(self.uri)
llm = ChatBedrock(
model="anthropic.claude-3-5-sonnet-20240620-v1:0",
model_kwargs={
"temperature": 0,
},
region='us-east-1',
aws_access_key_id=os.getenv('aws_access_key'),
aws_secret_access_key=os.getenv('aws_secret_key')
)
agent_executor = create_sql_agent(llm, db=db, verbose=True)
return agent_executor
def chat_interface():
st.title("Chat with your Excel Data")
# Add debug info
# Check if database path exists in session state
if 'db_path' not in st.session_state:
st.warning("Please upload an Excel file first!")
return
db = SQLDatabase.from_uri(st.session_state['db_path'])
tables = db.get_usable_table_names()
st.write(f"Available tables: {tables}")
# Initialize chat history
if 'messages' not in st.session_state:
st.session_state.messages = []
# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Accept user input
if prompt := st.chat_input("Ask questions about your Excel data"):
# Display user message
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
try:
analyser = ExcelAnalyser(st.session_state['db_path'])
agent = analyser.connect_to_uri()
response = agent.invoke(prompt)
st.markdown(response['output'])
st.session_state.messages.append({"role": "assistant", "content": response['output']})
except Exception as e:
error_message = f"Error: {str(e)}"
st.error(error_message)
st.session_state.messages.append({"role": "assistant", "content": error_message})
if __name__ == '__main__':
chat_interface() |