chatbot with searxng
To upload files, please first save the app
import streamlit as st
import requests
from bs4 import BeautifulSoup
import json
# SearXNG instance
SEARX_URL = "https://corsproxy.io/?https://searx.be/search"
def search_searxng(query):
# NOTE: Using corsproxy.io because we're in a WASM environment. If running locally,
# you can remove the corsproxy.io prefix. Some websites don't work with the proxy,
# in those cases try removing the proxy prefix.
params = {
'q': query,
'format': 'json',
}
try:
response = requests.get(SEARX_URL, params=params)
results = response.json()
return results['results'][:5] # Return top 5 results
except Exception as e:
st.error(f"Error performing search: {str(e)}")
return []
def generate_response(query):
# Search using SearXNG
results = search_searxng(query)
if not results:
return "I'm sorry, I couldn't find any relevant information for your query."
# Format the response with search results
response = f"Here's what I found for '{query}':\n\n"
for i, result in enumerate(results, 1):
response += f"{i}. {result['title']}\n"
response += f" {result['url']}\n"
if 'content' in result:
response += f" Summary: {result['content']}\n"
response += "\n"
return response
st.title("Search Assistant")
st.write("Ask me anything, and I'll search the web using SearXNG!")
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat messages from history on app rerun
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Accept user input
if prompt := st.chat_input("What would you like to know?"):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
# Generate and display assistant response
with st.chat_message("assistant"):
response = generate_response(prompt)
st.markdown(response)
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response})
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?