manoj1hcl commited on
Commit
80008d6
·
verified ·
1 Parent(s): ffb1be6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY', 'your-key-if-not-using-env')
17
+ os.environ['SERPAPI_API_KEY'] = os.getenv('SERP_KEY', 'your-key-if-not-using-env')
18
+ MODEL = "gpt-4o-mini"
19
+
20
+ # serpapi wrapper
21
+ search = SerpAPIWrapper()
22
+
23
+ # here is the defination of the tool
24
+ tools = [
25
+ Tool(
26
+ name="Google Search",
27
+ func=search.run,
28
+ description="Useful for answering real-time or current event questions."
29
+ )
30
+ ]
31
+
32
+ #define llm with temperature 0
33
+ llm = ChatOpenAI(temperature=0.7, model=MODEL)
34
+ # define an agent using athe tool that we have defined above
35
+ agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, handle_parsing_errors=True, verbose=True)
36
+
37
+ # chat bot definition with history
38
+ def chatbot(user_input):
39
+ if user_input.lower().strip() in ["hi", "hello", "hey"]:
40
+ return "Hello! How can I help you today?"
41
+ try:
42
+ # Example agent usage (replace with your real agent.run)
43
+ output = agent.run(user_input)
44
+ except OutputParserException:
45
+ output = "Agent encountered a parsing issue. Please rephrase your query."
46
+ except Exception as e:
47
+ output = f"Unexpected Error: {e}"
48
+ return output
49
+ # UI USING GRADIO
50
+ with gr.Blocks() as demo:
51
+ chatbot_ui = gr.Chatbot(type="messages")
52
+ user_input = gr.Textbox(placeholder="Ask Anything...")
53
+ submit = gr.Button("Ask")
54
+ def respond(user_message, chat_history):
55
+ chat_history = chat_history or []
56
+ chat_history.append({"role": "user", "content": user_message})
57
+ response = chatbot(user_message)
58
+ chat_history.append({"role": "assistant", "content": response})
59
+ return chat_history, ""
60
+ user_input.submit(respond, inputs=[user_input, chatbot_ui], outputs=[chatbot_ui, user_input])
61
+ submit.click(respond, inputs=[user_input, chatbot_ui], outputs=[chatbot_ui, user_input])
62
+
63
+ demo.launch(inline=False)