Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat: DDG search
amplitudes1a2393c3ca8c
diff --git a/apps/api/src/search/googlesearch.ts b/apps/api/src/search/googlesearch.tsdeleted file mode 100644index 2344b7786..000000000--- a/apps/api/src/search/googlesearch.ts+++ /dev/null@@ -1,217 +0,0 @@-import axios from "axios";-import { JSDOM } from "jsdom";-import { SearchResult } from "../../src/lib/entities";-import { logger } from "../../src/lib/logger";-import https from "https";--const getRandomInt = (min: number, max: number): number =>- Math.floor(Math.random() * (max - min + 1)) + min;--function get_useragent(): string {- const lynx_version = `Lynx/${getRandomInt(2, 3)}.${getRandomInt(8, 9)}.${getRandomInt(0, 2)}`;- const libwww_version = `libwww-FM/${getRandomInt(2, 3)}.${getRandomInt(13, 15)}`;- const ssl_mm_version = `SSL-MM/${getRandomInt(1, 2)}.${getRandomInt(3, 5)}`;- const openssl_version = `OpenSSL/${getRandomInt(1, 3)}.${getRandomInt(0, 4)}.${getRandomInt(0, 9)}`;- return `${lynx_version} ${libwww_version} ${ssl_mm_version} ${openssl_version}`;-}--async function _req(- term: string,- results: number,- lang: string,- country: string,- start: number,- proxies: any,- timeout: number,- tbs: string | undefined = undefined,- filter: string | undefined = undefined,-) {- const params = {- q: term,- num: results + 2, // Number of results to return- hl: lang,- gl: country,- safe: "active",- start: start,- };- if (tbs) {- params["tbs"] = tbs;- }- if (filter) {- params["filter"] = filter;- }- var agent = get_useragent();- try {- const resp = await axios.get("https://www.google.com/search", {- headers: {- "User-Agent": agent,- Accept:- "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",- "Accept-Language": "en-US,en;q=0.9",- "Accept-Charset": "utf-8", // Explicitly request UTF-8- "Accept-Encoding": "gzip, deflate",- },- params: params,- proxy: proxies,- timeout: timeout,- responseType: "arraybuffer", // Get raw bytes to handle encoding properly- httpsAgent: new https.Agent({- rejectUnauthorized: true,- }),- withCredentials: true,- });- return resp;- } catch (error) {- if (error.response && error.response.status === 429) {- logger.warn("Google Search: Too many requests, try again later.", {- status: error.response.status,- statusText: error.response.statusText,- });- throw new Error("Google Search: Too many requests, try again later.");- }- throw error;- }-}--export async function googleSearch(- term: string,- advanced = false,- num_results = 5,- tbs = undefined as string | undefined,- filter = undefined as string | undefined,- lang = "en",- country = "us",- proxy = undefined as string | undefined,- sleep_interval = 0,- timeout = 5000,-): Promise<SearchResult[]> {- let proxies: any = null;- if (proxy) {- if (proxy.startsWith("https")) {- proxies = { https: proxy };- } else {- proxies = { http: proxy };- }- }- // TODO: knowledge graph, answer box, etc.-- let start = 0;- let results: SearchResult[] = [];- let attempts = 0;- const maxAttempts = 20; // Define a maximum number of attempts to prevent infinite loop-- while (start < num_results && attempts < maxAttempts) {- try {- const resp = await _req(- term,- num_results - start,- lang,- country,- start,- proxies,- timeout,- tbs,- filter,- );-- // Convert ArrayBuffer to string with proper encoding- let htmlContent: string;- try {- // Try to decode as UTF-8 first- htmlContent = new TextDecoder("utf-8", { fatal: true }).decode(- resp.data,- );- } catch (e) {- // Fallback to latin1 if UTF-8 fails- logger.warn("UTF-8 decoding failed, trying latin1");- htmlContent = new TextDecoder("latin1").decode(resp.data);- }-- // Alternative: Try to detect charset from response headers- const contentType = resp.headers["content-type"];- if (contentType) {- const charsetMatch = contentType.match(/charset=([^;]+)/i);- if (charsetMatch) {- const detectedCharset = charsetMatch[1].toLowerCase();- if (detectedCharset !== "utf-8") {- try {- htmlContent = new TextDecoder(detectedCharset).decode(resp.data);- } catch (e) {- logger.warn(- `Failed to decode with detected charset ${detectedCharset}, using UTF-8`,- );- }- }- }- }-- const dom = new JSDOM(htmlContent, {- contentType: "text/html",- includeNodeLocations: false,- storageQuota: 10000000,- });-- const document = dom.window.document;- const result_block = document.querySelectorAll("div.ezO2md");- let new_results = 0;- let unique = true;- let fetched_results = 0;-- const fetched_links = new Set<string>();- if (result_block.length === 0) {- start += 1;- attempts += 1;- } else {- attempts = 0;- }-- for (const result of result_block) {- const link_tag = result.querySelector(- "a[href].fuLhoc.ZWRArf",- ) as HTMLAnchorElement;- const title_tag = link_tag- ? link_tag.querySelector("span.CVA68e")- : null;- const description_tag = result.querySelector("span.FrIlee span.fYyStc");-- if (link_tag && title_tag && description_tag) {- const link = decodeURIComponent(- link_tag.href.split("&")[0].replace("/url?q=", ""),- );- if (fetched_links.has(link) && unique) continue;- fetched_links.add(link);-- // Clean up text content and normalize Unicode- const title = (title_tag.textContent || "").trim().normalize("NFC");- const description = (description_tag.textContent || "")- .trim()- .normalize("NFC");-- fetched_results++;- new_results++;- if (link && title && description) {- start += 1;- results.push(new SearchResult(link, title, description));- }- if (fetched_results >= num_results) break;- }- }-- await new Promise(resolve => setTimeout(resolve, sleep_interval * 1000));- } catch (error) {- if (error.message === "Too many requests") {- logger.warn("Too many requests, breaking the loop");- break;- }- throw error;- }-- if (start === 0) {- return results;- }- }- if (attempts >= maxAttempts) {- logger.warn("Max attempts reached, breaking the loop");- }- return results;-}diff --git a/apps/api/src/search/index.ts b/apps/api/src/search/index.tsindex 79fed7b51..2948e8f58 100644--- a/apps/api/src/search/index.ts+++ b/apps/api/src/search/index.ts@@ -1,10 +1,10 @@import { SearchResult } from "../../src/lib/entities";-import { googleSearch } from "./googlesearch";import { searchapi_search } from "./searchapi";import { serper_search } from "./serper";import { searxng_search } from "./searxng";import { fire_engine_search } from "./fireEngine";import { Logger } from "winston";+import { ddgSearch } from "./v2/ddgsearch";export async function search({query,@@ -82,18 +82,19 @@ export async function search({});if (results.length > 0) return results;}- logger.info("Using google search");- return await googleSearch(- query,- advanced,- num_results,+ logger.info("Using DuckDuckGo search");+ const ddg = await ddgSearch(query, num_results, {tbs,- filter,lang,country,proxy,- sleep_interval,timeout,+ });+ return (+ ddg.web?.map(+ result =>+ new SearchResult(result.url, result.title, result.description),+ ) || []);} catch (error) {logger.error(`Error in search function`, { error });diff --git a/apps/api/src/search/v2/ddgsearch.ts b/apps/api/src/search/v2/ddgsearch.tsnew file mode 100644index 000000000..8ab73d8ed--- /dev/null+++ b/apps/api/src/search/v2/ddgsearch.ts@@ -0,0 +1,205 @@+import axios from "axios";+import { JSDOM } from "jsdom";+import { SearchV2Response, WebSearchResult } from "../../lib/entities";+import { logger } from "../../lib/logger";+import https from "https";++const USER_AGENTS = [+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15",+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0",+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:120.0) Gecko/20100101 Firefox/120.0",+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",+];++interface SearchOptions {+ tbs?: string;+ lang?: string;+ country?: string;+ location?: string;+ proxy?: string;+ timeout?: number;+}++function cleanUrl(href: string): string {+ if (href.includes("uddg=")) {+ const url = new URL(href, "https://duckduckgo.com");+ const uddg = url.searchParams.get("uddg");+ return uddg ? decodeURIComponent(uddg) : href;+ }+ return href;+}++function extractResults(+ document: Document,+ seenUrls: Set<string>,+): WebSearchResult[] {+ const results: WebSearchResult[] = [];+ const blocks = Array.from(document.querySelectorAll(".result.web-result"));++ for (const block of blocks) {+ const titleLink = block.querySelector(+ ".result__a",+ ) as HTMLAnchorElement | null;+ const snippet = block.querySelector(".result__snippet");++ if (!titleLink || !snippet) continue;++ const rawUrl = titleLink.href?.trim();+ const title = titleLink.textContent?.trim();+ const description = snippet.textContent?.trim();++ if (rawUrl && title && description) {+ const url = cleanUrl(rawUrl);+ if (!seenUrls.has(url)) {+ seenUrls.add(url);+ results.push({ url, title, description });+ }+ }+ }++ return results;+}++function getNextPageData(document: Document): URLSearchParams | null {+ const nextButton = document.querySelector(+ 'input[type="submit"][class="btn btn--alt"][value="Next"]',+ ) as HTMLInputElement | null;++ if (!nextButton) return null;++ const nextForm = nextButton.closest("form") as HTMLFormElement | null;+ if (!nextForm) return null;++ const formData = new URLSearchParams();+ const inputs = Array.from(nextForm.querySelectorAll("input"));++ for (const input of inputs) {+ const name = input.getAttribute("name");+ const value = input.getAttribute("value");+ if (name && value !== null) {+ formData.set(name, value);+ }+ }++ return formData;+}++export async function ddgSearch(+ term: string,+ num_results = 5,+ options: SearchOptions = {},+): Promise<SearchV2Response> {+ const {+ lang = "en",+ country = "us",+ location,+ tbs,+ proxy,+ timeout = 5000,+ } = options;++ let proxies: any = null;+ if (proxy) {+ if (proxy.startsWith("https")) {+ proxies = { https: proxy };+ } else {+ proxies = { http: proxy };+ }+ }++ try {+ const userAgent =+ USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];++ const params = new URLSearchParams({ q: term, kp: "1" });++ if (location) {+ params.set("kl", location);+ } else if (country && lang) {+ params.set("kl", `${country.toLowerCase()}-${lang.toLowerCase()}`);+ }++ if (tbs && (["d", "w", "m", "y"].includes(tbs) || tbs.includes(".."))) {+ params.set("df", tbs);+ }++ const results: WebSearchResult[] = [];+ const seenUrls = new Set<string>();+ let isFirstPage = true;+ let nextPageData: URLSearchParams | null = params;++ while (results.length < num_results && nextPageData) {+ let response;++ if (isFirstPage) {+ response = await axios.get(+ `https://html.duckduckgo.com/html?${params.toString()}`,+ {+ headers: {+ "User-Agent": userAgent,+ Accept:+ "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",+ "Accept-Language": "en-US,en;q=0.5",+ "Accept-Encoding": "gzip, deflate, br",+ "Upgrade-Insecure-Requests": "1",+ },+ proxy: proxies,+ timeout,+ httpsAgent: new https.Agent({ rejectUnauthorized: true }),+ },+ );+ isFirstPage = false;+ } else {+ response = await axios.post(+ "https://html.duckduckgo.com/html/",+ nextPageData.toString(),+ {+ headers: {+ "User-Agent": userAgent,+ Accept:+ "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",+ "Accept-Language": "en-US,en;q=0.5",+ "Accept-Encoding": "gzip, deflate, br",+ "Content-Type": "application/x-www-form-urlencoded",+ },+ proxy: proxies,+ timeout,+ httpsAgent: new https.Agent({ rejectUnauthorized: true }),+ },+ );+ }++ const dom = new JSDOM(response.data);+ const doc = dom.window.document;++ const newResults = extractResults(doc, seenUrls);+ results.push(...newResults);++ if (newResults.length === 0) break;++ nextPageData = getNextPageData(doc);++ await new Promise(r => setTimeout(r, 1000));+ }++ if (results.length === 0) {+ logger.warn("DuckDuckGo: No results found", { term });+ return {};+ }++ return { web: results.slice(0, num_results) };+ } catch (error: any) {+ if (error.response?.status === 429) {+ logger.warn("DuckDuckGo: Too many requests, try again later.", {+ status: error.response.status,+ statusText: error.response.statusText,+ });+ throw new Error("DuckDuckGo: Too many requests, try again later.");+ }+ logger.error("DuckDuckGo search error", { error: error.message, term });+ throw error;+ }+}diff --git a/apps/api/src/search/v2/googlesearch.ts b/apps/api/src/search/v2/googlesearch.tsdeleted file mode 100644index 76de00389..000000000--- a/apps/api/src/search/v2/googlesearch.ts+++ /dev/null@@ -1,174 +0,0 @@-import axios from "axios";-import { JSDOM } from "jsdom";-import { SearchV2Response, WebSearchResult } from "../../lib/entities";-import { logger } from "../../lib/logger";-import https from "https";--const getRandomInt = (min: number, max: number): number =>- Math.floor(Math.random() * (max - min + 1)) + min;--function get_useragent(): string {- const lynx_version = `Lynx/${getRandomInt(2, 3)}.${getRandomInt(8, 9)}.${getRandomInt(0, 2)}`;- const libwww_version = `libwww-FM/${getRandomInt(2, 3)}.${getRandomInt(13, 15)}`;- const ssl_mm_version = `SSL-MM/${getRandomInt(1, 2)}.${getRandomInt(3, 5)}`;- const openssl_version = `OpenSSL/${getRandomInt(1, 3)}.${getRandomInt(0, 4)}.${getRandomInt(0, 9)}`;- return `${lynx_version} ${libwww_version} ${ssl_mm_version} ${openssl_version}`;-}--async function _req(- term: string,- results: number,- lang: string,- country: string,- start: number,- proxies: any,- timeout: number,- tbs: string | undefined = undefined,- filter: string | undefined = undefined,-) {- const params = {- q: term,- num: results + 2, // Number of results to return- hl: lang,- gl: country,- safe: "active",- start: start,- };- if (tbs) {- params["tbs"] = tbs;- }- if (filter) {- params["filter"] = filter;- }- var agent = get_useragent();- try {- const resp = await axios.get("https://www.google.com/search", {- headers: {- "User-Agent": agent,- Accept: "*/*",- },- params: params,- proxy: proxies,- timeout: timeout,- httpsAgent: new https.Agent({- rejectUnauthorized: true,- }),- withCredentials: true,- });- return resp;- } catch (error) {- if (error.response && error.response.status === 429) {- logger.warn("Google Search: Too many requests, try again later.", {- status: error.response.status,- statusText: error.response.statusText,- });- throw new Error("Google Search: Too many requests, try again later.");- }- throw error;- }-}--export async function googleSearch(- term: string,- advanced = false,- num_results = 5,- tbs = undefined as string | undefined,- filter = undefined as string | undefined,- lang = "en",- country = "us",- proxy = undefined as string | undefined,- sleep_interval = 0,- timeout = 5000,-): Promise<SearchV2Response> {- let proxies: any = null;- if (proxy) {- if (proxy.startsWith("https")) {- proxies = { https: proxy };- } else {- proxies = { http: proxy };- }- }-- // TODO: knowledge graph, answer box, etc.-- let start = 0;- let results: WebSearchResult[] = [];- let attempts = 0;- const maxAttempts = 20; // Define a maximum number of attempts to prevent infinite loop- while (start < num_results && attempts < maxAttempts) {- try {- const resp = await _req(- term,- num_results - start,- lang,- country,- start,- proxies,- timeout,- tbs,- filter,- );- const dom = new JSDOM(resp.data);- const document = dom.window.document;- const result_block = document.querySelectorAll("div.ezO2md");- let new_results = 0;- let unique = true;- let fetched_results = 0;-- const fetched_links = new Set<string>();- if (result_block.length === 0) {- start += 1;- attempts += 1;- } else {- attempts = 0;- }-- for (const result of result_block) {- const link_tag = result.querySelector(- "a[href].fuLhoc.ZWRArf",- ) as HTMLAnchorElement;- const title_tag = link_tag- ? link_tag.querySelector("span.CVA68e")- : null;- const description_tag = result.querySelector("span.FrIlee span.fYyStc");-- if (link_tag && title_tag && description_tag) {- const link = decodeURIComponent(- link_tag.href.split("&")[0].replace("/url?q=", ""),- );- if (fetched_links.has(link) && unique) continue;- fetched_links.add(link);- const title = title_tag.textContent || "";- const description = description_tag.textContent || "";- fetched_results++;- new_results++;- if (link && title && description) {- start += 1;- results.push({- url: link,- title: title,- description: description,- });- }- if (fetched_results >= num_results) break;- }- }-- await new Promise(resolve => setTimeout(resolve, sleep_interval * 1000));- } catch (error) {- if (error.message === "Too many requests") {- logger.warn("Too many requests, breaking the loop");- break;- }- throw error;- }-- if (start === 0) {- return results.length > 0 ? { web: results } : {};- }- }- if (attempts >= maxAttempts) {- logger.warn("Max attempts reached, breaking the loop");- }- return results.length > 0 ? { web: results } : {};-}diff --git a/apps/api/src/search/v2/index.ts b/apps/api/src/search/v2/index.tsindex cd3c9776c..13bb73f47 100644--- a/apps/api/src/search/v2/index.ts+++ b/apps/api/src/search/v2/index.ts@@ -1,10 +1,9 @@-import { logger } from "../../lib/logger";import { SearchV2Response, SearchResultType } from "../../lib/entities";import { fire_engine_search_v2 } from "./fireEngine-v2";import { serper_search } from "./serper";import { searchapi_search } from "./searchapi";import { searxng_search } from "./searxng";-import { googleSearch } from "./googlesearch";+import { ddgSearch } from "./ddgsearch";import { Logger } from "winston";export async function search({@@ -89,20 +88,15 @@ export async function search({if (results.web && results.web.length > 0) return results;}- logger.info("Using google search");- const googleResults = await googleSearch(- query,- advanced,- num_results,+ logger.info("Using DuckDuckGo search");+ const ddgResults = await ddgSearch(query, num_results, {tbs,- filter,lang,country,proxy,- sleep_interval,timeout,- );- if (googleResults.web && googleResults.web.length > 0) return googleResults;+ });+ if (ddgResults.web && ddgResults.web.length > 0) return ddgResults;// Fallback to empty responsereturn {};