Vidhi00 commited on
Commit
e85de64
·
verified ·
1 Parent(s): e990210

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +84 -24
app.py CHANGED
@@ -19,10 +19,16 @@ from langchain_community.agent_toolkits import create_sql_agent
19
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
20
  from langchain_core.tools import tool
21
  from langchain.agents import create_tool_calling_agent, AgentExecutor
 
 
22
  from langchain_community.vectorstores import Chroma
23
  from huggingface_hub import CommitScheduler
 
 
24
  from pathlib import Path
25
 
 
 
26
  from langchain_core.caches import BaseCache
27
  from langchain_openai.chat_models import ChatOpenAI
28
 
@@ -33,9 +39,8 @@ ChatOpenAI.model_rebuild()
33
 
34
  model_name = "gpt-4o-mini"
35
 
36
- #config = read_config("config_GANLP.json") #Copy and paste the path of the config file uploaded in Colab
37
- api_key = "gl-U2FsdGVkX1/DTLQlsmj+RdJjPy3igB9qINuaX940XtJ0CPnGc/5sbBkPKah/C829"
38
- endpoint = "https://aibe.mygreatlearning.com/openai/v1"
39
 
40
  # Define the location of the SQLite database
41
  db_loc = 'ecomm.db'
@@ -106,11 +111,10 @@ full_prompt = ChatPromptTemplate.from_messages(
106
 
107
  #Initialize the ChatOpenAI model with the extracted configuration
108
  llm = ChatOpenAI(
109
- endpoint="https://aibe.mygreatlearning.com/openai/v1",
110
- api_key="gl-U2FsdGVkX1/DTLQlsmj+RdJjPy3igB9qINuaX940XtJ0CPnGc/5sbBkPKah/C829",
111
- model="gpt-4o-mini",
112
- streaming=False # Explicitly disabling streaming
113
- )
114
 
115
 
116
  # Create the SQL agent using the ChatOpenAI model, database, and prompt template
@@ -123,31 +127,87 @@ sqlite_agent = create_sql_agent(
123
  max_iterations=5,
124
  verbose=True
125
  )
 
 
 
126
  #### Let's convert the sql agent into a tool that our fin agent can use.
127
 
128
- @tool
129
- def sql_tool(user_input):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  """
131
- Gathers information regarding purchases, transactions, returns, refunds, etc.
132
- Executes a SQL query using the sqlite_agent and returns the result.
133
  Args:
134
- user_input (str): a natural language query string explaining what information is required while also providing the necessary details to get the information.
 
135
  Returns:
136
- str: The result of the SQL query execution. If an error occurs, the exception is returned as a string.
137
  """
138
  try:
139
- # Invoke the sqlite_agent with the user input (SQL query)
140
- response = sqlite_agent.invoke(user_input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
- # Extract the output from the response
143
- prediction = response['output']
144
 
145
- except Exception as e:
146
- # If an exception occurs, capture the exception message
147
- prediction = e
148
 
149
- # Return the result or the exception message
150
- return prediction
 
151
 
152
  #=================================== RAG TOOL======================================#
153
  qna_system_message = """
@@ -522,8 +582,8 @@ def chatbot_interface():
522
 
523
  try:
524
  # Pass the history to the agent
 
525
  response = agent_executor.invoke({"input": conversation_input})
526
-
527
  # Add the chatbot's response to the history
528
  chatbot_response = response['output']
529
  st.session_state.conversation_history.append({"role": "assistant", "content": chatbot_response})
 
19
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
20
  from langchain_core.tools import tool
21
  from langchain.agents import create_tool_calling_agent, AgentExecutor
22
+ from langchain.agents import initialize_agent, Tool, AgentType
23
+ from langchain.llms import OpenAI
24
  from langchain_community.vectorstores import Chroma
25
  from huggingface_hub import CommitScheduler
26
+ from pydantic import BaseModel, Field, validator
27
+ from langchain.llms import OpenAI
28
  from pathlib import Path
29
 
30
+ np.float_ = np.float64
31
+
32
  from langchain_core.caches import BaseCache
33
  from langchain_openai.chat_models import ChatOpenAI
34
 
 
39
 
40
  model_name = "gpt-4o-mini"
41
 
42
+ api_key = os.getenv("OPENAI_API_KEY")
43
+ endpoint = os.getenv("OPENAI_API_BASE")
 
44
 
45
  # Define the location of the SQLite database
46
  db_loc = 'ecomm.db'
 
111
 
112
  #Initialize the ChatOpenAI model with the extracted configuration
113
  llm = ChatOpenAI(
114
+ openai_api_base=endpoint,
115
+ openai_api_key=api_key,
116
+ model="gpt-4o-mini", # Fill in the deployment name (e.g., gpt-4o-mini)
117
+ streaming=False)
 
118
 
119
 
120
  # Create the SQL agent using the ChatOpenAI model, database, and prompt template
 
127
  max_iterations=5,
128
  verbose=True
129
  )
130
+
131
+ conn = sqlite3.connect('/content/ecomm.db')
132
+ cursor = conn.cursor()
133
  #### Let's convert the sql agent into a tool that our fin agent can use.
134
 
135
+ # @tool
136
+ # def sql_tool(user_input):
137
+ # """
138
+ # Gathers information regarding purchases, transactions, returns, refunds, etc.
139
+ # Executes a SQL query using the sqlite_agent and returns the result.
140
+ # Args:
141
+ # user_input (str): a natural language query string explaining what information is required while also providing the necessary details to get the information.
142
+ # Returns:
143
+ # str: The result of the SQL query execution. If an error occurs, the exception is returned as a string.
144
+ # """
145
+ # try:
146
+ # # Invoke the sqlite_agent with the user input (SQL query)
147
+ # response = sqlite_agent.invoke(user_input)
148
+
149
+ # # Extract the output from the response
150
+ # prediction = response['output']
151
+
152
+ # except Exception as e:
153
+ # # If an exception occurs, capture the exception message
154
+ # prediction = e
155
+
156
+ # # Return the result or the exception message
157
+ # return prediction
158
+
159
+
160
+ def def_tool(query: str):
161
  """
162
+ Executes a SQL query using the agent and returns the result based on the natural language query.
163
+
164
  Args:
165
+ query (str): A natural language query string to be processed by the agent.
166
+
167
  Returns:
168
+ str: The result of the SQL query execution or any error message.
169
  """
170
  try:
171
+ # Define the sql_tool function which is responsible for executing the query
172
+ @tool
173
+ def sql_tool(query: str):
174
+ """Executes a SQL query on the e-commerce database and returns the result."""
175
+ try:
176
+ conn = sqlite3.connect('/content/ecomm.db')
177
+ cursor = conn.cursor()
178
+ cursor.execute(query)
179
+ result = cursor.fetchall()
180
+ conn.close()
181
+ return result
182
+ except Exception as e:
183
+ return str(e)
184
+
185
+ # Define the tools array for agent
186
+ tools = [
187
+ Tool(
188
+ name="SQLite Tool",
189
+ func=sql_tool,
190
+ description="Execute SQL queries"
191
+ )
192
+ ]
193
+
194
+ # Initialize the agent with the tools
195
+ agent = initialize_agent(
196
+ tools,
197
+ agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
198
+ llm=llm, # Assuming llm is predefined somewhere
199
+ verbose=True
200
+ )
201
 
202
+ # Use the agent to run the natural language query
203
+ response = agent.run(query)
204
 
205
+ # Return the response
206
+ return response
 
207
 
208
+ except Exception as e:
209
+ # If an error occurs in the process, capture and return the exception
210
+ return str(e)
211
 
212
  #=================================== RAG TOOL======================================#
213
  qna_system_message = """
 
582
 
583
  try:
584
  # Pass the history to the agent
585
+ # response = agent_executor.invoke({"input": conversation_input})
586
  response = agent_executor.invoke({"input": conversation_input})
 
587
  # Add the chatbot's response to the history
588
  chatbot_response = response['output']
589
  st.session_state.conversation_history.append({"role": "assistant", "content": chatbot_response})