"""
title: Deep Web Research Tool
author: Assistant
author_url: https://github.com/assistant
git_url: https://github.com/open-webui/open-webui
description: Performs comprehensive web research with multiple search engines, content analysis, and structured reporting
required_open_webui_version: 0.4.0
requirements: requests beautifulsoup4 urllib3
version: 1.0.0
license: MIT
"""
import requests
import json
import logging
import re
import time
from typing import Callable, Any, Optional, List, Dict
from pydantic import BaseModel, Field
from datetime import datetime
from urllib.parse import quote_plus
from bs4 import BeautifulSoup
import asyncio
class Tools:
class Valves(BaseModel):
MAX_SEARCH_RESULTS: int = Field(default=10)
MAX_ITERATIONS: int = Field(default=3)
REQUEST_TIMEOUT: int = Field(default=30)
USER_AGENT: str = Field(default="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
ENABLE_CONTENT_SCRAPING: bool = Field(default=True)
MAX_CONTENT_LENGTH: int = Field(default=5000)
code
def __init__(self):
self.valves = self.Valves()
self.session = requests.Session()
self.session.headers.update({'User-Agent': self.valves.USER_AGENT})
logging.info("Deep Web Research Tool initialized")
def _clean_text(self, text: str) -> str:
text = re.sub(r'\s+', ' ', text.strip())
text = re.sub(r'[^\w\s\-.,;:!?()\[\]{}"\']', '', text)
return text[:self.valves.MAX_CONTENT_LENGTH]
def _extract_content(self, url: str) -> Dict[str, str]:
try:
response = self.session.get(url, timeout=self.valves.REQUEST_TIMEOUT, allow_redirects=True)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
for tag in soup(["script", "style", "nav", "footer", "header"]):
tag.decompose()
title = soup.find('title').get_text() if soup.find('title') else "No title"
selectors = ['article', 'main', '.content', '#content', '.post-content', '.entry-content', 'p']
content = ''
for selector in selectors:
elements = soup.select(selector)
if elements:
content = ' '.join([e.get_text() for e in elements[:3]])
break
if not content:
content = ' '.join([p.get_text() for p in soup.find_all('p')[:5]])
return {
'title': self._clean_text(title),
'content': self._clean_text(content),
'url': url
}
except Exception as e:
logging.warning(f"Failed to extract content from {url}: {str(e)}")
return {'title': "Content extraction failed", 'content': f"Unable to extract content: {str(e)}", 'url': url}
def _search_duckduckgo(self, query: str) -> List[Dict[str, str]]:
try:
search_url = "https://api.duckduckgo.com/"
params = {
'q': query,
'format': 'json',
'no_redirect': '1',
'no_html': '1',
'skip_disambig': '1'
}
response = self.session.get(search_url, params=params, timeout=self.valves.REQUEST_TIMEOUT)
response.raise_for_status()
data = response.json()
results = []
if data.get('AbstractText'):
results.append({
'title': data.get('Heading', 'DuckDuckGo Instant Answer'),
'content': data.get('AbstractText'),
'url': data.get('AbstractURL', ''),
'source': 'DuckDuckGo Instant Answer'
})
for topic in data.get('RelatedTopics', [])[:3]:
if isinstance(topic, dict) and topic.get('Text'):
results.append({
'title': topic.get('Text', '').split(' - ')[0],
'content': topic.get('Text', ''),
'url': topic.get('FirstURL', ''),
'source': 'DuckDuckGo Related Topic'
})
return results[:self.valves.MAX_SEARCH_RESULTS]
except Exception as e:
logging.error(f"DuckDuckGo search failed: {str(e)}")
return []
async def perform_deep_research(self, research_topic: str, __event_emitter__: Callable[[dict], Any]) -> str:
logging.info(f"Starting deep research on: {research_topic}")
await __event_emitter__({"type": "status", "data": {"description": "🔍 Initializing deep research...", "done": False, "hidden": False}})
all_findings = []
queries = [research_topic, f"{research_topic} latest news", f"{research_topic} analysis report", f"{research_topic} expert opinion"]
for i, query in enumerate(queries[:self.valves.MAX_ITERATIONS]):
await __event_emitter__({"type": "status", "data": {"description": f"📊 Research iteration {i+1}: Searching for '{query}'", "done": False, "hidden": False}})
search_results = self._search_duckduckgo(query)
await __event_emitter__({"type": "status", "data": {"description": f"📄 Found {len(search_results)} results, extracting content...", "done": False, "hidden": False}})
if self.valves.ENABLE_CONTENT_SCRAPING:
for result in search_results:
if result.get('url', '').startswith('http'):
detailed = self._extract_content(result['url'])
if detailed['content']:
result['detailed_content'] = detailed['content']
all_findings.extend(search_results)
if i < len(queries) - 1:
await asyncio.sleep(1)
await __event_emitter__({"type": "status", "data": {"description": "📝 Compiling comprehensive research report...", "done": False, "hidden": False}})
return self._compile_report(research_topic, all_findings)
def _compile_report(self, topic: str, findings: List[Dict[str, str]]) -> str:
if not findings:
return f"# Research Report: {topic}\n\n⚠️ No significant findings."
report = f"""# Deep Research Report: {topic}
Generated on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
Executive Summary
{len(findings)} sources analyzed over {self.valves.MAX_ITERATIONS} iterations.
"""
for i, f in enumerate(findings, 1):
report += f"### Finding {i}: {f['title']}\n\n"
report += f"{f.get('detailed_content', f['content'])}\n\n"
report += f"Source:{f['url']}\n\n---\n\n"
report += f"""## Methodology
Search Engine: DuckDuckGo Instant Answer API
Iterations: {self.valves.MAX_ITERATIONS}
Content Scraping: {'Enabled' if self.valves.ENABLE_CONTENT_SCRAPING else 'Disabled'}
Automated deep research tool output."""
return report
Assistant
Okay, let's break down this Python code for the "Deep Web Research Tool" to assess potential maliciousness.
Analysis:
Purpose: The code aims to research a given topic by querying the DuckDuckGo API, fetching search results, optionally scraping content from the resulting URLs, and compiling a report.
Dependencies: It uses standard, reputable Python libraries: requests (HTTP requests), beautifulsoup4 (HTML parsing), urllib3 (lower-level HTTP client, often used by requests), pydantic (data validation), asyncio (asynchronous operations), etc. These are common and generally safe.
Network Activity:
It makes requests to https://api.duckduckgo.com/. This is a public API.
It makes GET requests to URLs found in the search results (_extract_content). This is standard web browsing/scraping behavior.
It uses a common USER_AGENT string, mimicking a standard browser, which is typical to avoid being blocked.
Data Handling:
It parses HTML content using BeautifulSoup.
It extracts text using specific selectors and cleans it using regular expressions (_clean_text). The regex [^\w\s\-.,;:!?()\[\]{}"\'] removes characters not in the specified set. This is for cleaning, not encoding malicious data.
It truncates content based on MAX_CONTENT_LENGTH.
It compiles findings into a Markdown report string.
Control Flow:
Uses configuration parameters (Valves) for settings like timeouts and result limits.
Uses asyncio and an __event_emitter__ callback, suggesting integration with a UI framework (like Open WebUI) to provide status updates. This is for feedback, not malicious action.
Includes basic error handling (try...except) for network requests and parsing.
Potential Issues (Not Necessarily Malicious):
robots.txt: The scraping function (_extract_content) does not appear to check or respect the robots.txt file of the websites it visits. This is a violation of common web scraping etiquette and could potentially lead to the IP address being blocked by some sites, but it's not inherently malicious .
Scraping Intensity: While it has a timeout and a small delay (asyncio.sleep(1)) between search iterations, making many requests rapidly could still put a load on target servers or trigger rate limiting. The MAX_ITERATIONS and MAX_SEARCH_RESULTS help mitigate this to some extent.
"Deep Web" Misnomer: The title and description are slightly misleading. This tool researches the surface web using a standard search engine (DuckDuckGo). It does not interact with or index the actual "Deep Web" (e.g., content requiring Tor). This seems more like sensationalism than malice.
Security of Scraped Content: The code displays scraped content directly in the report. If a malicious website is scraped, its content (potentially containing harmful text or links) will be included in the report. The _clean_text function tries to sanitize it, but complex HTML/JavaScript rendering issues aren't handled. However, the Python code itself isn't executing anything harmful from the page content.
Conclusion:
Based solely on the code provided, there is no clear malicious intent. The code performs web scraping and searching as described. It doesn't seem designed to:
Steal sensitive information from the user's system.
Install malware.
Exfiltrate data to unauthorized third parties (other than making requests to the search API and target URLs).
Execute arbitrary code.
The primary concerns are related to potentially aggressive scraping behavior (ignoring robots.txt) and the slightly sensationalized title ("Deep Web"). It functions as a web scraping and reporting tool.