dlaima commited on
Commit
bf3bb95
·
verified ·
1 Parent(s): 151a77b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -38
app.py CHANGED
@@ -2,17 +2,23 @@ import gradio as gr
2
  import wikipedia
3
  from langchain_community.chat_models import ChatOpenAI
4
  from langchain.memory import ConversationBufferMemory
5
- from langchain.agents import initialize_agent
6
  from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
7
  from langchain.tools import Tool
8
- from tavily import TavilyClient
 
 
 
 
 
 
 
9
 
10
 
11
  # ----------------------
12
- # Define tools
13
  # ----------------------
14
  def create_your_own(query: str) -> str:
15
- """This function can do whatever you would like once you fill it in"""
16
  return query[::-1]
17
 
18
  def get_current_temperature(query: str) -> str:
@@ -27,7 +33,6 @@ def search_wikipedia(query: str) -> str:
27
  except wikipedia.exceptions.PageError:
28
  return "No relevant Wikipedia page found."
29
 
30
-
31
  tools = [
32
  Tool(name="Temperature", func=get_current_temperature, description="Get current temperature"),
33
  Tool(name="Search Wikipedia", func=search_wikipedia, description="Search Wikipedia"),
@@ -36,56 +41,52 @@ tools = [
36
 
37
 
38
  # ----------------------
39
- # Define chatbot class
40
  # ----------------------
41
- from langchain.agents import initialize_agent, AgentType
42
-
43
  class cbfs:
44
  def __init__(self, tools, openai_key: str, tavily_key: str = None):
45
  if not openai_key:
46
- raise ValueError("⚠️ Please provide an OpenAI API key.")
47
 
48
  # Initialize OpenAI model
49
  self.model = ChatOpenAI(temperature=0, openai_api_key=openai_key)
50
 
51
- # Initialize Tavily (optional)
52
- self.tavily = TavilyClient(api_key=tavily_key) if tavily_key else None
 
 
53
 
54
  # Memory
55
  self.memory = ConversationBufferMemory(
56
  return_messages=True, memory_key="chat_history", ai_prefix="Assistant"
57
  )
58
 
59
- # Agent
 
 
 
 
 
 
 
 
60
  self.chain = initialize_agent(
61
  tools=tools,
62
  llm=self.model,
63
- agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, # ✅ correct way
64
  verbose=True,
65
  memory=self.memory,
66
- handle_parsing_errors=True # ✅ prevents silent failure
67
  )
68
-
69
  def convchain(self, query: str) -> str:
70
  if not query:
71
  return "Please enter a query."
72
  try:
73
  result = self.chain.invoke({"input": query})
74
- # Debugging: show full raw result
75
- print("Agent raw result:", result)
76
-
77
- # Try both possible output keys
78
- response = (
79
- result.get("output")
80
- or result.get("output_text")
81
- or "⚠️ No response generated."
82
- )
83
-
84
- # Save memory
85
- self.memory.save_context({"input": query}, {"output": response})
86
- return response
87
  except Exception as e:
88
- print("Execution Error:", str(e))
89
  return f"❌ Error: {str(e)}"
90
 
91
 
@@ -94,31 +95,30 @@ class cbfs:
94
  # ----------------------
95
  with gr.Blocks() as demo:
96
  with gr.Row():
97
- openai_key = gr.Textbox(label="🔑 OpenAI API Key", type="password", placeholder="Enter your OpenAI key")
98
- tavily_key = gr.Textbox(label="🔑 Tavily API Key", type="password", placeholder="Enter your Tavily key")
99
 
100
- chatbot_state = gr.State(None) # will hold chatbot instance
101
 
102
  with gr.Row():
103
  inp = gr.Textbox(placeholder="Enter text here…", label="User Input")
104
  output = gr.Textbox(placeholder="Response...", label="ChatBot Output", interactive=False)
105
 
106
- # Initialize chatbot after keys are provided
 
107
  def init_chatbot(openai_key, tavily_key):
108
  try:
109
- return cbfs(tools, openai_key, tavily_key), "✅ Chatbot initialized successfully!"
 
110
  except Exception as e:
111
  return None, f"❌ Error: {str(e)}"
112
 
113
  init_btn = gr.Button("Initialize Chatbot")
114
- status = gr.Textbox(label="Status", interactive=False)
115
-
116
  init_btn.click(fn=init_chatbot, inputs=[openai_key, tavily_key], outputs=[chatbot_state, status])
117
 
118
- # Chat functionality
119
  def process_query(query, chatbot):
120
  if chatbot is None:
121
- return "⚠️ Please initialize the chatbot first by providing your API keys."
122
  return chatbot.convchain(query)
123
 
124
  inp.submit(process_query, inputs=[inp, chatbot_state], outputs=output)
 
2
  import wikipedia
3
  from langchain_community.chat_models import ChatOpenAI
4
  from langchain.memory import ConversationBufferMemory
5
+ from langchain.agents import initialize_agent, AgentType
6
  from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
7
  from langchain.tools import Tool
8
+
9
+ # Optional: Tavily client (only if installed)
10
+ try:
11
+ from tavily import TavilyClient
12
+ tavily_available = True
13
+ except ImportError:
14
+ TavilyClient = None
15
+ tavily_available = False
16
 
17
 
18
  # ----------------------
19
+ # Tools
20
  # ----------------------
21
  def create_your_own(query: str) -> str:
 
22
  return query[::-1]
23
 
24
  def get_current_temperature(query: str) -> str:
 
33
  except wikipedia.exceptions.PageError:
34
  return "No relevant Wikipedia page found."
35
 
 
36
  tools = [
37
  Tool(name="Temperature", func=get_current_temperature, description="Get current temperature"),
38
  Tool(name="Search Wikipedia", func=search_wikipedia, description="Search Wikipedia"),
 
41
 
42
 
43
  # ----------------------
44
+ # Chatbot class
45
  # ----------------------
 
 
46
  class cbfs:
47
  def __init__(self, tools, openai_key: str, tavily_key: str = None):
48
  if not openai_key:
49
+ raise ValueError("⚠️ OpenAI API key is required.")
50
 
51
  # Initialize OpenAI model
52
  self.model = ChatOpenAI(temperature=0, openai_api_key=openai_key)
53
 
54
+ # Initialize Tavily if available
55
+ self.tavily = None
56
+ if tavily_available and tavily_key:
57
+ self.tavily = TavilyClient(api_key=tavily_key)
58
 
59
  # Memory
60
  self.memory = ConversationBufferMemory(
61
  return_messages=True, memory_key="chat_history", ai_prefix="Assistant"
62
  )
63
 
64
+ # Prompt
65
+ self.prompt = ChatPromptTemplate.from_messages([
66
+ ("system", "You are a helpful but sassy assistant. Remember what the user tells you in the conversation."),
67
+ MessagesPlaceholder(variable_name="chat_history"),
68
+ ("user", "{input}"),
69
+ MessagesPlaceholder(variable_name="agent_scratchpad")
70
+ ])
71
+
72
+ # Initialize agent
73
  self.chain = initialize_agent(
74
  tools=tools,
75
  llm=self.model,
76
+ agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
77
  verbose=True,
78
  memory=self.memory,
79
+ handle_parsing_errors=True
80
  )
81
+
82
  def convchain(self, query: str) -> str:
83
  if not query:
84
  return "Please enter a query."
85
  try:
86
  result = self.chain.invoke({"input": query})
87
+ print("Agent raw result:", result) # Debug log in HuggingFace logs
88
+ return result.get("output") or result.get("output_text") or "⚠️ No response generated."
 
 
 
 
 
 
 
 
 
 
 
89
  except Exception as e:
 
90
  return f"❌ Error: {str(e)}"
91
 
92
 
 
95
  # ----------------------
96
  with gr.Blocks() as demo:
97
  with gr.Row():
98
+ openai_key = gr.Textbox(label="🔑 OpenAI API Key", type="password", placeholder="Paste your key")
99
+ tavily_key = gr.Textbox(label="🔑 Tavily API Key (optional)", type="password", placeholder="Paste your Tavily key")
100
 
101
+ chatbot_state = gr.State(None)
102
 
103
  with gr.Row():
104
  inp = gr.Textbox(placeholder="Enter text here…", label="User Input")
105
  output = gr.Textbox(placeholder="Response...", label="ChatBot Output", interactive=False)
106
 
107
+ status = gr.Textbox(label="Status", interactive=False)
108
+
109
  def init_chatbot(openai_key, tavily_key):
110
  try:
111
+ bot = cbfs(tools, openai_key, tavily_key)
112
+ return bot, "✅ Chatbot initialized successfully!"
113
  except Exception as e:
114
  return None, f"❌ Error: {str(e)}"
115
 
116
  init_btn = gr.Button("Initialize Chatbot")
 
 
117
  init_btn.click(fn=init_chatbot, inputs=[openai_key, tavily_key], outputs=[chatbot_state, status])
118
 
 
119
  def process_query(query, chatbot):
120
  if chatbot is None:
121
+ return "⚠️ Please initialize the chatbot first by entering your API keys."
122
  return chatbot.convchain(query)
123
 
124
  inp.submit(process_query, inputs=[inp, chatbot_state], outputs=output)