Spaces:
Sleeping
Sleeping
Create ai_agent.py
Browse files- ai_agent.py +37 -0
ai_agent.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import getpass
|
2 |
+
import os
|
3 |
+
import pandas as pd
|
4 |
+
import tabulate
|
5 |
+
from sqlalchemy import create_engine
|
6 |
+
|
7 |
+
from langchain_community.utilities import SQLDatabase
|
8 |
+
from langchain_community.agent_toolkits import create_sql_agent
|
9 |
+
from langchain_openai import ChatOpenAI
|
10 |
+
from langchain.output_parsers.openai_tools import JsonOutputKeyToolsParser
|
11 |
+
from langchain_experimental.agents import create_pandas_dataframe_agent
|
12 |
+
from langchain_core.prompts import ChatPromptTemplate
|
13 |
+
from langchain_experimental.tools import PythonAstREPLTool
|
14 |
+
from langchain_experimental.agents import create_pandas_dataframe_agent
|
15 |
+
|
16 |
+
# Get the API key
|
17 |
+
api_key = os.getenv('OPENAI_API_KEY')
|
18 |
+
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.5)
|
19 |
+
|
20 |
+
def sql_agent(file, agent_input):
|
21 |
+
# Read the uploaded file into a DataFrame
|
22 |
+
df = pd.read_csv(file)
|
23 |
+
# Create SQLAlchemy engine
|
24 |
+
engine = create_engine("sqlite:///uploaded_data.db")
|
25 |
+
# Write the DataFrame to the SQLite database
|
26 |
+
df.to_sql("uploaded_data", engine, index=False, if_exists='replace')
|
27 |
+
db = SQLDatabase(engine=engine)
|
28 |
+
# Create SQL agent
|
29 |
+
agent_executor = create_sql_agent(llm, db=db, agent_type="openai-tools", verbose=True)
|
30 |
+
agent_output = agent_executor.invoke(agent_input)
|
31 |
+
return agent_output
|
32 |
+
|
33 |
+
def pandas_agent(file, agent_input):
|
34 |
+
df = pd.read_csv(file)
|
35 |
+
agent = create_pandas_dataframe_agent(llm, df, agent_type="openai-tools", verbose=True)
|
36 |
+
agent_output = agent.invoke(agent_input)
|
37 |
+
return agent_output
|