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
track search results clickhouse (#3277)
Thomas Kosmasb9c7902459c8
diff --git a/apps/api/package.json b/apps/api/package.jsonindex e3e439d31..a1fbaffa9 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -83,6 +83,7 @@"@bull-board/api": "^6.14.0","@bull-board/express": "^6.14.0","@dqbd/tiktoken": "^1.0.22",+ "@clickhouse/client": "^1.8.1","@google-cloud/storage": "^7.19.0","@mendable/firecrawl-rs": "workspace:*","@openrouter/ai-sdk-provider": "^0.4.5",diff --git a/apps/api/pnpm-lock.yaml b/apps/api/pnpm-lock.yamlindex 736053ebc..3281c8b4c 100644--- a/apps/api/pnpm-lock.yaml+++ b/apps/api/pnpm-lock.yaml@@ -59,6 +59,9 @@ importers:'@bull-board/express':specifier: ^6.14.0version: 6.14.2+ '@clickhouse/client':+ specifier: ^1.8.1+ version: 1.18.2'@dqbd/tiktoken':specifier: ^1.0.22version: 1.0.22@@ -688,6 +691,13 @@ packages:'@bull-board/[email protected]':resolution: {integrity: sha512-OTCsBbMAhYoB2NJc6FxkkREWWPUFvEhL2Az1gAKpdNOBqup4CsKj7eBK3rcWSRLZ4LnaOaPK8E8tiogkhrRuOA==}+ '@clickhouse/[email protected]':+ resolution: {integrity: sha512-J0SG6q9V31ydxonglpj9xhNRsUxCsF71iEZ784yldqMYwsHixj/9xHFDgBDX3DuMiDx/kPDfXnf+pimp08wIBA==}++ '@clickhouse/[email protected]':+ resolution: {integrity: sha512-fuquQswRSHWM6D079ZeuGqkMOsqtcUPL06UdTnowmoeeYjVrqisfVmvnw8pc3OeKS4kVb91oygb/MfLDiMs0TQ==}+ engines: {node: '>=16'}+'@coinbase/[email protected]':resolution: {integrity: sha512-DqgPk/JednX4Tpi1a0EP7zEYi2EH9rsFULIkb8BbjuUUldTh4VCSp624JC3k6b2IJlibRD7oFHVnEAz2+ykSnw==}@@ -6186,6 +6196,12 @@ snapshots:dependencies:'@bull-board/api': 6.14.2(@bull-board/[email protected])+ '@clickhouse/[email protected]': {}++ '@clickhouse/[email protected]':+ dependencies:+ '@clickhouse/client-common': 1.18.2+'@coinbase/[email protected]([email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:'@solana/spl-token': 0.4.13(@solana/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])diff --git a/apps/api/src/config.ts b/apps/api/src/config.tsindex 91e3cee12..37a21a042 100644--- a/apps/api/src/config.ts+++ b/apps/api/src/config.ts@@ -89,6 +89,10 @@ const configSchema = z.object({GCS_INDEX_BUCKET_NAME: z.string().optional(),GCS_MEDIA_BUCKET_NAME: z.string().optional(),+ // ClickHouse (Search Analytics)+ CLICKHOUSE_ANALYTICS_URL: z.string().optional(),+ CLICKHOUSE_ANALYTICS_DATABASE: z.string().optional(),+// Fire EngineFIRE_ENGINE_BETA_URL: z.string().optional(),FIRE_ENGINE_STAGING_URL: z.string().optional(),diff --git a/apps/api/src/controllers/v1/search.ts b/apps/api/src/controllers/v1/search.tsindex 036214ea7..13a432b70 100644--- a/apps/api/src/controllers/v1/search.ts+++ b/apps/api/src/controllers/v1/search.ts@@ -166,6 +166,7 @@ export async function searchController(apiKeyId: req.acuc?.api_key_id ?? null,flags: req.acuc?.flags ?? null,requestId: jobId,+ jobId,bypassBilling: false,zeroDataRetention: false,agentIndexOnly: (req as any).agentIndexOnly ?? false,diff --git a/apps/api/src/controllers/v2/search.ts b/apps/api/src/controllers/v2/search.tsindex cbd0c93f3..f7e0db0dc 100644--- a/apps/api/src/controllers/v2/search.ts+++ b/apps/api/src/controllers/v2/search.ts@@ -137,6 +137,7 @@ export async function searchController(apiKeyId: req.acuc?.api_key_id ?? null,flags: req.acuc?.flags ?? null,requestId: agentRequestId ?? jobId,+ jobId,bypassBilling: !shouldBill,zeroDataRetention: isZDROrAnon,billing,diff --git a/apps/api/src/lib/clickhouse-client.ts b/apps/api/src/lib/clickhouse-client.tsnew file mode 100644index 000000000..5d7b046fc--- /dev/null+++ b/apps/api/src/lib/clickhouse-client.ts@@ -0,0 +1,35 @@+import { createClient } from "@clickhouse/client";+import { config } from "../config";+import { logger } from "./logger";++const client = config.CLICKHOUSE_ANALYTICS_URL+ ? createClient({+ url: config.CLICKHOUSE_ANALYTICS_URL,+ database: config.CLICKHOUSE_ANALYTICS_DATABASE ?? "default",+ clickhouse_settings: {+ async_insert: 1,+ wait_for_async_insert: 0,+ },+ })+ : null;++export async function chInsert(+ table: string,+ rows: Record<string, unknown>[],+): Promise<void> {+ if (!client || rows.length === 0) return;++ try {+ await client.insert({+ table,+ values: rows,+ format: "JSONEachRow",+ });+ } catch (error: any) {+ logger.error("ClickHouse insert failed", {+ table,+ rowCount: rows.length,+ error: error?.message,+ });+ }+}diff --git a/apps/api/src/lib/search-tracking.ts b/apps/api/src/lib/search-tracking.tsnew file mode 100644index 000000000..969fabc9a--- /dev/null+++ b/apps/api/src/lib/search-tracking.ts@@ -0,0 +1,73 @@+import { chInsert } from "./clickhouse-client";+import type { SearchV2Response } from "./entities";++function extractDomain(url: string): string {+ try {+ return new URL(url).hostname;+ } catch {+ return url.replace(/^https?:\/\//, "").split("/")[0];+ }+}++interface SearchResultUrl {+ url: string;+ type: "web" | "news" | "image";+ index: number;+}++function extractUrls(response: SearchV2Response): SearchResultUrl[] {+ const urls: SearchResultUrl[] = [];++ if (response.web) {+ for (let i = 0; i < response.web.length; i++) {+ urls.push({ url: response.web[i].url, type: "web", index: i });+ }+ }+ if (response.news) {+ for (let i = 0; i < response.news.length; i++) {+ if (response.news[i].url) {+ urls.push({ url: response.news[i].url!, type: "news", index: i });+ }+ }+ }+ if (response.images) {+ for (let i = 0; i < response.images.length; i++) {+ if (response.images[i].url) {+ urls.push({ url: response.images[i].url!, type: "image", index: i });+ }+ }+ }++ return urls;+}++interface TrackSearchParams {+ searchId: string;+ teamId: string;+ response: SearchV2Response;+ zeroDataRetention: boolean;+}++export async function trackSearchResults(+ opts: TrackSearchParams,+): Promise<void> {+ if (opts.zeroDataRetention) return;++ const urls = extractUrls(opts.response);+ if (urls.length === 0) return;++ const created_at = new Date().toISOString();++ await chInsert(+ "search_results",+ urls.map(({ url, type, index }) => ({+ search_id: opts.searchId,+ team_id: opts.teamId,+ url,+ url_domain: extractDomain(url),+ result_type: type,+ result_index: index,+ created_at,+ })),+ );+}diff --git a/apps/api/src/search/execute.ts b/apps/api/src/search/execute.tsindex cb876b29e..4e7d2221c 100644--- a/apps/api/src/search/execute.ts+++ b/apps/api/src/search/execute.ts@@ -13,6 +13,7 @@ import {mergeScrapedContent,calculateScrapeCredits,} from "./scrape";+import { trackSearchResults } from "../lib/search-tracking";import type { BillingMetadata } from "../services/billing/types";interface SearchOptions {@@ -36,6 +37,7 @@ interface SearchContext {apiKeyId: number | null;flags: TeamFlags;requestId: string;+ jobId: string;bypassBilling?: boolean;zeroDataRetention?: boolean;billing?: BillingMetadata;@@ -173,6 +175,13 @@ export async function executeSearch(}}+ trackSearchResults({+ searchId: context.jobId,+ teamId,+ response: searchResponse,+ zeroDataRetention: zeroDataRetention ?? false,+ }).catch(err => logger.warn("Search tracking failed", { error: err }));+return {response: searchResponse,totalResultsCount,