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