manoj1hcl commited on
Commit
a6b5a06
·
verified ·
1 Parent(s): 900cbb4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -22
app.py CHANGED
@@ -1,62 +1,78 @@
1
- import os
2
- import langchain
3
- import openai
4
  from dotenv import load_dotenv
 
5
  from langchain.chat_models import ChatOpenAI
6
  from langchain.tools import Tool
7
  from langchain.utilities import SerpAPIWrapper
8
  from langchain.agents import initialize_agent, AgentType
9
  from langchain_core.exceptions import OutputParserException
10
-
11
  import gradio as gr
12
 
13
-
14
-
15
  load_dotenv(override=True)
16
 
17
- MODEL = "gpt-4o-mini"
18
 
19
- # serpapi wrapper
20
- search = SerpAPIWrapper()
21
 
22
- # here is the defination of the tool
23
  tools = [
24
  Tool(
25
- name="Google Search",
26
  func=search.run,
27
- description="Always use this tool for up-to-date or current event questions. Do not guess if the answer is about ongoing events, news, or recent updates."
28
  )
29
  ]
30
 
31
- #define llm with temperature 0
32
- llm = ChatOpenAI(temperature=0.7, model=MODEL)
33
- # define an agent using athe tool that we have defined above
34
- agent = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS, handle_parsing_errors=True, verbose=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- # chat bot definition with history
37
  def chatbot(user_input):
38
  if user_input.lower().strip() in ["hi", "hello", "hey"]:
39
- return "Hello! How can I help you today?"
40
  try:
41
- # Example agent usage (replace with your real agent.run)
42
- output = agent.run(user_input)
43
  except OutputParserException:
44
  output = "Agent encountered a parsing issue. Please rephrase your query."
45
  except Exception as e:
46
  output = f"Unexpected Error: {e}"
47
  return output
48
- # UI USING GRADIO
 
49
  with gr.Blocks() as demo:
50
  chatbot_ui = gr.Chatbot(type="messages")
51
- user_input = gr.Textbox(placeholder="Ask Anything...")
52
  submit = gr.Button("Ask")
 
53
  def respond(user_message, chat_history):
54
  chat_history = chat_history or []
55
  chat_history.append({"role": "user", "content": user_message})
56
  response = chatbot(user_message)
57
  chat_history.append({"role": "assistant", "content": response})
58
  return chat_history, ""
 
59
  user_input.submit(respond, inputs=[user_input, chatbot_ui], outputs=[chatbot_ui, user_input])
60
  submit.click(respond, inputs=[user_input, chatbot_ui], outputs=[chatbot_ui, user_input])
61
 
 
62
  demo.launch(inline=False)
 
 
1
+ import os
 
 
2
  from dotenv import load_dotenv
3
+ from datetime import datetime
4
  from langchain.chat_models import ChatOpenAI
5
  from langchain.tools import Tool
6
  from langchain.utilities import SerpAPIWrapper
7
  from langchain.agents import initialize_agent, AgentType
8
  from langchain_core.exceptions import OutputParserException
 
9
  import gradio as gr
10
 
11
+ # Load environment variables
 
12
  load_dotenv(override=True)
13
 
14
+ MODEL = "gpt-4o"
15
 
16
+ # Setup the serpapi wrapper
17
+ search = SerpAPIWrapper(params={"num": "10", "hl": "en", "gl": "in"})
18
 
19
+ # Define tool with valid name pattern and enhanced description
20
  tools = [
21
  Tool(
22
+ name="google_search",
23
  func=search.run,
24
+ description="Use this tool ONLY to fetch real-time data or current events. Always add today's date to ensure accuracy. Never rely on prior knowledge or make assumptions about ongoing events."
25
  )
26
  ]
27
 
28
+ # Initialize the LLM
29
+ llm = ChatOpenAI(temperature=0, model=MODEL)
30
+
31
+ # Initialize agent with OPENAI_FUNCTIONS mode
32
+ agent = initialize_agent(
33
+ tools,
34
+ llm,
35
+ agent=AgentType.OPENAI_FUNCTIONS,
36
+ handle_parsing_errors=True,
37
+ verbose=True
38
+ )
39
+
40
+ # Function to inject current date into query if missing
41
+ def add_current_date_to_query(query):
42
+ today = datetime.now().strftime("%B %Y")
43
+ if today.lower() not in query.lower():
44
+ query = f"{query} ({today})"
45
+ return query
46
 
47
+ # Chatbot function with exception handling and enforced date
48
  def chatbot(user_input):
49
  if user_input.lower().strip() in ["hi", "hello", "hey"]:
50
+ return "Hello! How can I assist you today?"
51
  try:
52
+ enhanced_input = add_current_date_to_query(user_input)
53
+ output = agent.run(enhanced_input)
54
  except OutputParserException:
55
  output = "Agent encountered a parsing issue. Please rephrase your query."
56
  except Exception as e:
57
  output = f"Unexpected Error: {e}"
58
  return output
59
+
60
+ # Gradio UI with chat history
61
  with gr.Blocks() as demo:
62
  chatbot_ui = gr.Chatbot(type="messages")
63
+ user_input = gr.Textbox(placeholder="Ask about latest events, news, or anything...")
64
  submit = gr.Button("Ask")
65
+
66
  def respond(user_message, chat_history):
67
  chat_history = chat_history or []
68
  chat_history.append({"role": "user", "content": user_message})
69
  response = chatbot(user_message)
70
  chat_history.append({"role": "assistant", "content": response})
71
  return chat_history, ""
72
+
73
  user_input.submit(respond, inputs=[user_input, chatbot_ui], outputs=[chatbot_ui, user_input])
74
  submit.click(respond, inputs=[user_input, chatbot_ui], outputs=[chatbot_ui, user_input])
75
 
76
+ # Launch app
77
  demo.launch(inline=False)
78
+