mayank-chatbot / app.py
Mayank2027's picture
Update app.py
56cacc5 verified
import gradio as gr
import requests
import json
def search_web(query):
"""Search the web for current info"""
try:
url = "https://google.serper.dev/search"
payload = json.dumps({"q": query})
headers = {
'X-API-KEY': 'a4b8933c3ddd8d5a04a86b9ddc75a0db429807e9',
'Content-Type': 'application/json'
}
response = requests.post(url, headers=headers, data=payload)
data = response.json()
if 'organic' in data and len(data['organic']) > 0:
return data['organic'][0]['snippet']
return "No results found"
except Exception as e:
return f"Search error: {str(e)}"
def smart_response(message, history):
"""Your AI's brain with web search and memory"""
# Check if user needs current info (improved detection)
search_words = ["weather", "temperature", "latest", "current", "today", "news", "price", "what's happening", "bitcoin", "btc", "crypto", "stock"]
needs_search = any(word in message.lower() for word in search_words)
# Check for location words
location_words = ["delhi", "mumbai", "bangalore", "chennai", "kolkata", "pune", "hyderabad", "in"]
has_location = any(word in message.lower() for word in location_words)
if "hello" in message.lower() or "hi" in message.lower():
return "Hey! I'm your smart AI assistant with web search powers! What can I help you with?"
elif "what can you do" in message.lower():
return """I can help you with:
πŸ” Search the web for current information
🌀️ Get weather for any city
πŸ’° Get live prices and market data
πŸ“° Find latest news and updates
πŸ’‘ Answer questions and give advice
πŸ’¬ Chat about anything!
Try: "Weather in Delhi" or "Bitcoin price today"!"""
elif needs_search or has_location:
# Search the web for current info
search_result = search_web(message)
return f"Here's what I found:\n\n{search_result}\n\nAnything else you'd like to know?"
elif "what" in message.lower() and "asked" in message.lower():
# User asking about previous question
if history:
last_user_msg = None
for msg in reversed(history):
if msg[0]: # User message
last_user_msg = msg[0]
break
if last_user_msg:
return f"You asked: '{last_user_msg}'\n\nLet me search for that again!"
else:
return "I don't see any previous questions. What would you like to know?"
else:
return "This is our first conversation! What would you like to ask?"
else:
return f"I'd be happy to help! Could you be more specific? Or try asking about current weather, news, or prices - I can search for real-time info!"
# Create chat interface
chatbot = gr.ChatInterface(
smart_response,
title="πŸ€– Smart AI with Memory & Web Search",
description="Your AI assistant with memory and real-time web search!"
)
chatbot.launch()