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
fix: replace hardcoded search billing with calculateCreditsToBeBilled (#1714)
devin-ai-integration[bot]82e76a740599
diff --git a/apps/api/src/__tests__/snips/billing.test.ts b/apps/api/src/__tests__/snips/billing.test.tsindex c0fee2025..959eca36c 100644--- a/apps/api/src/__tests__/snips/billing.test.ts+++ b/apps/api/src/__tests__/snips/billing.test.ts@@ -215,6 +215,31 @@ describe("Billing tests", () => {expect(rc1 - rc2).toBe(results.length);}, 600000);+ it.concurrent("bills search with PDF scrape correctly", async () => {+ const identity = await idmux({+ name: "billing/bills search with PDF scrape correctly",+ credits: 100,+ });++ const rc1 = (await creditUsage(identity)).remaining_credits;++ const results = await search({+ query: "firecrawl filetype:pdf",+ scrapeOptions: {+ formats: ["markdown"],+ parsePDF: true,+ },+ }, identity);++ await sleepForBatchBilling();++ const rc2 = (await creditUsage(identity)).remaining_credits;++ const shouldUse = results.reduce((sum, doc) => sum + (doc.metadata?.numPages || 1), 0);++ expect(rc1 - rc2).toBe(shouldUse);+ }, 600000);+it.concurrent("bills extract correctly", async () => {const identity = await idmux({name: "billing/bills extract correctly",diff --git a/apps/api/src/controllers/v1/search.ts b/apps/api/src/controllers/v1/search.tsindex 2fdaca2c6..0d9433df3 100644--- a/apps/api/src/controllers/v1/search.ts+++ b/apps/api/src/controllers/v1/search.ts@@ -22,6 +22,13 @@ import { BLOCKLISTED_URL_MESSAGE } from "../../lib/strings";import { logger as _logger } from "../../lib/logger";import type { Logger } from "winston";import { CostTracking } from "../../lib/extract/extraction-service";+import { calculateCreditsToBeBilled } from "../../lib/scrape-billing";+import { supabase_service } from "../../services/supabase";++interface DocumentWithCostTracking {+ document: Document;+ costTracking: ReturnType<typeof CostTracking.prototype.toJSON>;+}// Used for deep researchexport async function searchAndScrapeSearchResult(@@ -33,16 +40,15 @@ export async function searchAndScrapeSearchResult(scrapeOptions: ScrapeOptions;},logger: Logger,- costTracking: CostTracking,flags: TeamFlags,-): Promise<Document[]> {+): Promise<DocumentWithCostTracking[]> {try {const searchResults = await search({query,num_results: 5,});- const documents = await Promise.all(+ const documentsWithCostTracking = await Promise.all(searchResults.map((result) =>scrapeSearchResult({@@ -52,13 +58,12 @@ export async function searchAndScrapeSearchResult(},options,logger,- costTracking,flags,),),);- return documents;+ return documentsWithCostTracking;} catch (error) {return [];}@@ -73,16 +78,17 @@ async function scrapeSearchResult(scrapeOptions: ScrapeOptions;},logger: Logger,- costTracking: CostTracking,flags: TeamFlags,directToBullMQ: boolean = false,isSearchPreview: boolean = false,-): Promise<Document> {+): Promise<DocumentWithCostTracking> {const jobId = uuidv4();const jobPriority = await getJobPriority({team_id: options.teamId,basePriority: 10,});++ const costTracking = new CostTracking();const zeroDataRetention = flags?.forceZDR ?? false;@@ -119,7 +125,7 @@ async function scrapeSearchResult();const doc: Document = await waitForJob(jobId, options.timeout);-+logger.info("Scrape job completed", {scrapeId: jobId,url: searchResult.url,@@ -128,13 +134,33 @@ async function scrapeSearchResult(});await getScrapeQueue().remove(jobId);- // Move SERP results to top level- return {+ const document = {title: searchResult.title,description: searchResult.description,url: searchResult.url,...doc,};++ let costTracking: ReturnType<typeof CostTracking.prototype.toJSON>;+ if (process.env.USE_DB_AUTHENTICATION === "true") {+ const { data: costTrackingResponse, error: costTrackingError } = await supabase_service.from("firecrawl_jobs")+ .select("cost_tracking")+ .eq("job_id", jobId);++ if (costTrackingError) {+ logger.error("Error getting cost tracking", { error: costTrackingError });+ throw costTrackingError;+ }++ costTracking = costTrackingResponse?.[0]?.cost_tracking;+ } else {+ costTracking = new CostTracking().toJSON();+ }++ return {+ document,+ costTracking,+ };} catch (error) {logger.error(`Error in scrapeSearchResult: ${error}`, {scrapeId: jobId,@@ -146,8 +172,8 @@ async function scrapeSearchResult(if (error?.message?.includes("Could not scrape url")) {statusCode = 403;}- // Return a minimal document with SERP results at top level- return {++ const document: Document = {title: searchResult.title,description: searchResult.description,url: searchResult.url,@@ -157,6 +183,11 @@ async function scrapeSearchResult(proxyUsed: "basic",},};++ return {+ document,+ costTracking: new CostTracking().toJSON(),+ };}}@@ -182,8 +213,10 @@ export async function searchController(data: [],};const startTime = new Date().getTime();- const costTracking = new CostTracking();const isSearchPreview = process.env.SEARCH_PREVIEW_TOKEN !== undefined && process.env.SEARCH_PREVIEW_TOKEN === req.body.__searchPreviewToken;++ let credits_billed = 0;+ let allDocsWithCostTracking: DocumentWithCostTracking[] = [];try {req.body = searchRequestSchema.parse(req.body);@@ -238,6 +271,7 @@ export async function searchController(title: r.title,description: r.description,})) as Document[];+ credits_billed = responseData.data.length;} else {logger.info("Scraping search results");const scrapePromises = searchResults.map((result) =>@@ -250,18 +284,18 @@ export async function searchController(scrapeOptions: req.body.scrapeOptions,},logger,- costTracking,req.acuc?.flags ?? null,(req.acuc?.price_credits ?? 0) <= 3000,isSearchPreview,),);- const docs = await Promise.all(scrapePromises);+ const docsWithCostTracking = await Promise.all(scrapePromises);logger.info("Scraping completed", {- num_docs: docs.length,+ num_docs: docsWithCostTracking.length,});+ const docs = docsWithCostTracking.map(item => item.document);const filteredDocs = docs.filter((doc) =>doc.serpResults || (doc.markdown && doc.markdown.trim().length > 0),@@ -277,16 +311,37 @@ export async function searchController(} else {responseData.data = filteredDocs;}- }- // TODO: This is horrid. Fix soon - mogery- const credits_billed = responseData.data.reduce((a, x) => {- if (x.metadata?.numPages !== undefined && x.metadata.numPages > 0 && req.body.scrapeOptions?.parsePDF !== false) {- return a + x.metadata.numPages;- } else {- return a + 1;+ const finalDocsForBilling = responseData.data;++ const creditPromises = finalDocsForBilling.map(async (finalDoc) => {+ const matchingDocWithCost = docsWithCostTracking.find(item =>+ item.document.metadata && finalDoc.metadata && item.document.metadata.scrapeId === finalDoc.metadata.scrapeId+ );++ if (matchingDocWithCost) {+ return await calculateCreditsToBeBilled(+ req.body.scrapeOptions,+ { teamId: req.auth.team_id, bypassBilling: true, zeroDataRetention: false },+ matchingDocWithCost.document,+ matchingDocWithCost.costTracking,+ req.acuc.flags,+ );+ } else {+ return 1;+ }+ });++ try {+ const individualCredits = await Promise.all(creditPromises);+ credits_billed = individualCredits.reduce((sum, credit) => sum + credit, 0);+ } catch (error) {+ logger.error("Error calculating credits for billing", { error });+ credits_billed = responseData.data.length;}- }, 0)++ allDocsWithCostTracking = docsWithCostTracking;+ }// Bill team once for all successful resultsif (!isSearchPreview) {@@ -322,7 +377,6 @@ export async function searchController(scrapeOptions: req.body.scrapeOptions,origin: req.body.origin,integration: req.body.integration,- cost_tracking: costTracking,credits_billed,zeroDataRetention: false, // not supported},diff --git a/apps/api/src/lib/deep-research/deep-research-service.ts b/apps/api/src/lib/deep-research/deep-research-service.tsindex 1b3e56be7..0f44bcebc 100644--- a/apps/api/src/lib/deep-research/deep-research-service.ts+++ b/apps/api/src/lib/deep-research/deep-research-service.ts@@ -134,7 +134,7 @@ export async function performDeepResearch(options: DeepResearchServiceOptions) {maxAge: 4 * 60 * 60 * 1000,storeInCache: true,},- }, logger, costTracking, acuc?.flags ?? null);+ }, logger, acuc?.flags ?? null);return response.length > 0 ? response : [];});@@ -164,10 +164,10 @@ export async function performDeepResearch(options: DeepResearchServiceOptions) {// Filter out already seen URLs and track new onesconst newSearchResults: typeof searchResults = [];for (const result of searchResults) {- if (!result.url || state.hasSeenUrl(result.url)) {+ if (!result.document.url || state.hasSeenUrl(result.document.url)) {continue;}- state.addSeenUrl(result.url);+ state.addSeenUrl(result.document.url);urlsAnalyzed++;if (urlsAnalyzed >= maxUrls) {@@ -183,10 +183,10 @@ export async function performDeepResearch(options: DeepResearchServiceOptions) {}await state.addSources(newSearchResults.map((result) => ({- url: result.url ?? "",- title: result.title ?? "",- description: result.description ?? "",- icon: result.metadata?.favicon ?? "",+ url: result.document.url ?? "",+ title: result.document.title ?? "",+ description: result.document.description ?? "",+ icon: result.document.metadata?.favicon ?? "",})));logger.debug("[Deep Research] New unique results count:",@@ -218,8 +218,8 @@ export async function performDeepResearch(options: DeepResearchServiceOptions) {await state.addFindings(newSearchResults.map((result) => ({- text: result.markdown ?? "",- source: result.url ?? "",+ text: result.document.markdown ?? "",+ source: result.document.url ?? "",})),);diff --git a/apps/api/src/lib/scrape-billing.ts b/apps/api/src/lib/scrape-billing.tsindex 7030734b2..2c2a9077f 100644--- a/apps/api/src/lib/scrape-billing.ts+++ b/apps/api/src/lib/scrape-billing.ts@@ -5,13 +5,15 @@ import { CostTracking } from "./extract/extraction-service";const creditsPerPDFPage = 1;const stealthProxyCostBonus = 4;-export async function calculateCreditsToBeBilled(options: ScrapeOptions, internalOptions: InternalOptions, document: Document | null, costTracking: CostTracking, flags: TeamFlags) {+export async function calculateCreditsToBeBilled(options: ScrapeOptions, internalOptions: InternalOptions, document: Document | null, costTracking: CostTracking | ReturnType<typeof CostTracking.prototype.toJSON>, flags: TeamFlags) {+ const costTrackingJSON: ReturnType<typeof CostTracking.prototype.toJSON> = costTracking instanceof CostTracking ? costTracking.toJSON() : costTracking;+if (document === null) {// Failure -- check cost tracking if FIRE-1let creditsToBeBilled = 0;if (options.agent?.model?.toLowerCase() === "fire-1" || options.extract?.agent?.model?.toLowerCase() === "fire-1" || options.jsonOptions?.agent?.model?.toLowerCase() === "fire-1") {- creditsToBeBilled = Math.ceil((costTracking.toJSON().totalCost ?? 1) * 1800);+ creditsToBeBilled = Math.ceil((costTrackingJSON.totalCost ?? 1) * 1800);}return creditsToBeBilled;@@ -23,14 +25,14 @@ export async function calculateCreditsToBeBilled(options: ScrapeOptions, interna}if (options.agent?.model?.toLowerCase() === "fire-1" || options.extract?.agent?.model?.toLowerCase() === "fire-1" || options.jsonOptions?.agent?.model?.toLowerCase() === "fire-1") {- creditsToBeBilled = Math.ceil((costTracking.toJSON().totalCost ?? 1) * 1800);+ creditsToBeBilled = Math.ceil((costTrackingJSON.totalCost ?? 1) * 1800);}if (internalOptions.zeroDataRetention) {creditsToBeBilled += (flags?.zdrCost ?? 1);}- if (document.metadata.numPages !== undefined && document.metadata.numPages > 1) {+ if (document.metadata?.numPages !== undefined && document.metadata.numPages > 1) {creditsToBeBilled += creditsPerPDFPage * (document.metadata.numPages - 1);}@@ -39,4 +41,4 @@ export async function calculateCreditsToBeBilled(options: ScrapeOptions, interna}return creditsToBeBilled;-}\ No newline at end of file+}