Vidhi00 commited on
Commit
30a048a
·
verified ·
1 Parent(s): 7530f2c

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +42 -70
app.py CHANGED
@@ -12,7 +12,6 @@ import weave
12
  from langchain.memory import ConversationSummaryBufferMemory
13
 
14
  from langchain.embeddings import OpenAIEmbeddings
15
- from langchain.chat_models import ChatOpenAI
16
  from langchain_openai import OpenAIEmbeddings
17
  from langchain_community.embeddings.sentence_transformer import SentenceTransformerEmbeddings
18
  from langchain_community.utilities.sql_database import SQLDatabase
@@ -20,15 +19,10 @@ from langchain_community.agent_toolkits import create_sql_agent
20
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
21
  from langchain_core.tools import tool
22
  from langchain.agents import create_tool_calling_agent, AgentExecutor
23
- from langchain.agents import initialize_agent, Tool, AgentType
24
- from langchain.llms import OpenAI
25
  from langchain_community.vectorstores import Chroma
26
  from huggingface_hub import CommitScheduler
27
- from pydantic import BaseModel, Field, validator
28
- from langchain.llms import OpenAI
29
  from pathlib import Path
30
 
31
-
32
  from langchain_core.caches import BaseCache
33
  from langchain_openai.chat_models import ChatOpenAI
34
 
@@ -39,16 +33,9 @@ ChatOpenAI.model_rebuild()
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
-
46
-
47
- llm = ChatOpenAI(
48
- openai_api_base=endpoint, # Fill in the endpoint
49
- openai_api_key="gl-U2FsdGVkX1/DTLQlsmj+RdJjPy3igB9qINuaX940XtJ0CPnGc/5sbBkPKah/C829", # Fill in the API key
50
- model="gpt-4o-mini", # Fill in the deployment name (e.g., gpt-4o-mini)
51
- streaming=False)
52
 
53
  # Define the location of the SQLite database
54
  db_loc = 'ecomm.db'
@@ -117,6 +104,14 @@ full_prompt = ChatPromptTemplate.from_messages(
117
  ]
118
  )
119
 
 
 
 
 
 
 
 
 
120
 
121
  # Create the SQL agent using the ChatOpenAI model, database, and prompt template
122
  sqlite_agent = create_sql_agent(
@@ -128,63 +123,31 @@ sqlite_agent = create_sql_agent(
128
  max_iterations=5,
129
  verbose=True
130
  )
 
131
 
132
- conn = sqlite3.connect('ecomm.db')
133
- cursor = conn.cursor()
134
-
135
-
136
-
137
- def def_tool(query: str):
138
  """
139
- Executes a SQL query using the agent and returns the result based on the natural language query.
140
-
141
  Args:
142
- query (str): A natural language query string to be processed by the agent.
143
-
144
  Returns:
145
- str: The result of the SQL query execution or any error message.
146
  """
147
  try:
148
- # Define the sql_tool function which is responsible for executing the query
149
- @tool
150
- def sql_tool(query: str):
151
- """Executes a SQL query on the e-commerce database and returns the result."""
152
- try:
153
- conn = sqlite3.connect('/ecomm.db')
154
- cursor = conn.cursor()
155
- cursor.execute(query)
156
- result = cursor.fetchall()
157
- conn.close()
158
- return result
159
- except Exception as e:
160
- return str(e)
161
-
162
- # Define the tools array for agent
163
- tools = [
164
- Tool(
165
- name="SQLite Tool",
166
- func=sql_tool,
167
- description="Execute SQL queries"
168
- )
169
- ]
170
-
171
- # Initialize the agent with the tools
172
- agent = initialize_agent(
173
- tools,
174
- agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
175
- llm=llm, # Assuming llm is predefined somewhere
176
- verbose=True
177
- )
178
-
179
- # Use the agent to run the natural language query
180
- response = agent.run(query)
181
 
182
- # Return the response
183
- return response
184
 
185
  except Exception as e:
186
- # If an error occurs in the process, capture and return the exception
187
- return str(e)
 
 
 
188
 
189
  #=================================== RAG TOOL======================================#
190
  qna_system_message = """
@@ -238,10 +201,10 @@ retriever = vector_store.as_retriever(
238
  search_kwargs={'k': 5}
239
  )
240
 
241
- # client = OpenAI(
242
- # api_key=api_key,
243
- # base_url=endpoint
244
- # )
245
 
246
  @tool
247
  def rag(user_input: str) -> str:
@@ -268,7 +231,7 @@ def rag(user_input: str) -> str:
268
  }
269
  ]
270
  try:
271
- response = llm.chat.completions.create(
272
  model="gpt-4o-mini",
273
  messages=prompt
274
  )
@@ -527,7 +490,16 @@ def chatbot_interface():
527
  prompt = build_prompt(details)
528
  tools = [sql_tool,defer_to_human, rag, register_feedback, days_since]
529
 
530
- agent = create_tool_calling_agent(llm, tools, prompt)
 
 
 
 
 
 
 
 
 
531
  agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
532
 
533
  # Display chat messages from history on app rerun
 
12
  from langchain.memory import ConversationSummaryBufferMemory
13
 
14
  from langchain.embeddings import OpenAIEmbeddings
 
15
  from langchain_openai import OpenAIEmbeddings
16
  from langchain_community.embeddings.sentence_transformer import SentenceTransformerEmbeddings
17
  from langchain_community.utilities.sql_database import SQLDatabase
 
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
 
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'
 
104
  ]
105
  )
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
117
  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 = """
 
201
  search_kwargs={'k': 5}
202
  )
203
 
204
+ client = OpenAI(
205
+ api_key=api_key,
206
+ base_url=endpoint
207
+ )
208
 
209
  @tool
210
  def rag(user_input: str) -> str:
 
231
  }
232
  ]
233
  try:
234
+ response = client.chat.completions.create(
235
  model="gpt-4o-mini",
236
  messages=prompt
237
  )
 
490
  prompt = build_prompt(details)
491
  tools = [sql_tool,defer_to_human, rag, register_feedback, days_since]
492
 
493
+
494
+ chatbot = ChatOpenAI(
495
+ openai_api_base=endpoint,
496
+ openai_api_key=api_key,
497
+ model="gpt-4o-mini",
498
+ streaming=False, # Explicitly disabling streaming
499
+ temperature=0
500
+ )
501
+
502
+ agent = create_tool_calling_agent(chatbot, tools, prompt)
503
  agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
504
 
505
  # Display chat messages from history on app rerun