Files
firecrawl/apps/api/src/controllers/v0/scrape.ts
T

331 lines
8.8 KiB
TypeScript
Raw Normal View History

2024-08-28 12:46:59 -03:00
import { ExtractorOptions, PageOptions } from "./../../lib/entities";
2024-04-20 16:38:05 -07:00
import { Request, Response } from "express";
2024-08-28 12:46:59 -03:00
import {
billTeam,
2024-12-11 19:51:08 -03:00
checkTeamCredits,
2024-08-28 12:46:59 -03:00
} from "../../services/billing/credit_billing";
2024-08-26 18:48:00 -03:00
import { authenticateUser } from "../auth";
2025-04-10 18:49:23 +02:00
import { RateLimiterMode } from "../../types";
2024-08-15 21:51:59 +02:00
import { logJob } from "../../services/logging/log_job";
2024-12-11 19:46:11 -03:00
import {
fromLegacyCombo,
toLegacyDocument,
2024-12-11 19:51:08 -03:00
url as urlSchema,
2024-12-11 19:46:11 -03:00
} from "../v1/types";
2024-08-15 21:51:59 +02:00
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist"; // Import the isUrlBlocked function
2024-08-28 12:46:59 -03:00
import { numTokensFromString } from "../../lib/LLM-extraction/helpers";
import {
defaultPageOptions,
defaultExtractorOptions,
defaultTimeout,
2024-12-11 19:51:08 -03:00
defaultOrigin,
2024-08-28 12:46:59 -03:00
} from "../../lib/default-values";
import { addScrapeJob, waitForJob } from "../../services/queue-jobs";
import { getScrapeQueue, redisConnection } from "../../services/queue-service";
2024-07-24 14:31:25 +02:00
import { v4 as uuidv4 } from "uuid";
2024-11-07 20:57:33 +01:00
import { logger } from "../../lib/logger";
import * as Sentry from "@sentry/node";
2024-08-28 12:46:59 -03:00
import { getJobPriority } from "../../lib/job-priority";
2024-11-07 20:57:33 +01:00
import { fromLegacyScrapeOptions } from "../v1/types";
import { ZodError } from "zod";
import { Document as V0Document } from "./../../lib/entities";
2024-12-20 18:09:49 -03:00
import { BLOCKLISTED_URL_MESSAGE } from "../../lib/strings";
2024-04-20 16:38:05 -07:00
export async function scrapeHelper(
2024-07-24 15:18:12 +02:00
jobId: string,
2024-04-20 16:38:05 -07:00
req: Request,
team_id: string,
crawlerOptions: any,
2024-05-06 11:36:44 -03:00
pageOptions: PageOptions,
2024-05-06 19:45:56 -03:00
extractorOptions: ExtractorOptions,
2024-05-30 14:46:55 -07:00
timeout: number,
2024-04-20 18:55:39 -07:00
): Promise<{
success: boolean;
error?: string;
data?: V0Document | { url: string };
2024-04-20 19:04:27 -07:00
returnCode: number;
2024-04-20 18:55:39 -07:00
}> {
2024-11-07 20:57:33 +01:00
const url = urlSchema.parse(req.body.url);
2024-09-10 21:18:53 +02:00
if (typeof url !== "string") {
2024-04-20 18:55:39 -07:00
return { success: false, error: "Url is required", returnCode: 400 };
2024-04-20 16:38:05 -07:00
}
if (isUrlBlocked(url)) {
2024-08-28 12:46:59 -03:00
return {
success: false,
2024-12-20 18:09:49 -03:00
error: BLOCKLISTED_URL_MESSAGE,
2024-12-11 19:51:08 -03:00
returnCode: 403,
2024-08-28 12:46:59 -03:00
};
}
2025-04-10 18:49:23 +02:00
const jobPriority = await getJobPriority({ team_id, basePriority: 10 });
2024-08-21 20:54:39 -03:00
2024-12-11 19:46:11 -03:00
const { scrapeOptions, internalOptions } = fromLegacyCombo(
pageOptions,
extractorOptions,
timeout,
2024-12-11 19:51:08 -03:00
crawlerOptions,
2025-04-02 19:52:43 +02:00
team_id,
2024-12-11 19:46:11 -03:00
);
2024-11-07 20:57:33 +01:00
2024-10-25 20:21:12 +02:00
await addScrapeJob(
2024-08-28 12:46:59 -03:00
{
url,
mode: "single_urls",
team_id,
2024-11-07 20:57:33 +01:00
scrapeOptions,
internalOptions,
2024-08-28 12:46:59 -03:00
origin: req.body.origin ?? defaultOrigin,
2024-12-11 19:51:08 -03:00
is_scrape: true,
2024-08-28 12:46:59 -03:00
},
{},
jobId,
2024-12-11 19:51:08 -03:00
jobPriority,
2024-08-28 12:46:59 -03:00
);
2024-07-25 00:14:25 +02:00
2024-08-06 17:25:58 +02:00
let doc;
2024-08-22 16:00:13 +02:00
2024-08-28 12:46:59 -03:00
const err = await Sentry.startSpan(
{
name: "Wait for job to finish",
op: "bullmq.wait",
2024-12-11 19:51:08 -03:00
attributes: { job: jobId },
2024-08-28 12:46:59 -03:00
},
async (span) => {
try {
2024-12-11 19:46:11 -03:00
doc = await waitForJob<Document>(jobId, timeout);
2024-08-28 12:46:59 -03:00
} catch (e) {
2024-12-11 19:46:11 -03:00
if (
e instanceof Error &&
(e.message.startsWith("Job wait") || e.message === "timeout")
) {
2024-08-28 12:46:59 -03:00
span.setAttribute("timedOut", true);
return {
success: false,
error: "Request timed out",
2024-12-11 19:51:08 -03:00
returnCode: 408,
2024-08-28 12:46:59 -03:00
};
} else if (
typeof e === "string" &&
(e.includes("Error generating completions: ") ||
e.includes("Invalid schema for function") ||
e.includes(
2024-12-11 19:51:08 -03:00
"LLM extraction did not match the extraction schema you provided.",
2024-08-28 12:46:59 -03:00
))
) {
return {
success: false,
error: e,
2024-12-11 19:51:08 -03:00
returnCode: 500,
2024-08-28 12:46:59 -03:00
};
} else {
throw e;
2024-08-22 16:00:13 +02:00
}
2024-08-06 17:25:58 +02:00
}
2024-08-28 12:46:59 -03:00
span.setAttribute("result", JSON.stringify(doc));
return null;
2024-12-11 19:51:08 -03:00
},
2024-08-28 12:46:59 -03:00
);
2024-08-22 16:00:13 +02:00
if (err !== null) {
return err;
2024-08-06 17:25:58 +02:00
}
2024-07-25 00:14:25 +02:00
2024-10-25 20:21:12 +02:00
await getScrapeQueue().remove(jobId);
2024-07-25 00:14:25 +02:00
if (!doc) {
2024-10-25 20:21:12 +02:00
console.error("!!! PANIC DOC IS", doc);
2024-08-28 12:46:59 -03:00
return {
success: true,
error: "No page found",
returnCode: 200,
2024-12-11 19:51:08 -03:00
data: doc,
2024-08-28 12:46:59 -03:00
};
2024-04-20 16:38:05 -07:00
}
2024-07-25 00:50:03 +02:00
delete doc.index;
delete doc.provider;
2024-07-01 08:48:21 -04:00
// Remove rawHtml if pageOptions.rawHtml is false and extractorOptions.mode is llm-extraction-from-raw-html
2024-08-28 12:46:59 -03:00
if (
!pageOptions.includeRawHtml &&
extractorOptions.mode == "llm-extraction-from-raw-html"
) {
2024-08-22 15:15:45 -03:00
if (doc.rawHtml) {
delete doc.rawHtml;
}
}
if (!pageOptions.includeHtml) {
if (doc.html) {
delete doc.html;
}
2024-06-28 16:39:09 -04:00
}
2024-04-20 16:38:05 -07:00
return {
success: true,
2024-11-07 20:57:33 +01:00
data: toLegacyDocument(doc, internalOptions),
2024-12-11 19:51:08 -03:00
returnCode: 200,
2024-04-20 16:38:05 -07:00
};
}
export async function scrapeController(req: Request, res: Response) {
try {
2024-07-22 18:30:58 -04:00
let earlyReturn = false;
2024-04-20 16:38:05 -07:00
// make sure to authenticate user first, Bearer <token>
2024-12-11 19:46:11 -03:00
const auth = await authenticateUser(req, res, RateLimiterMode.Scrape);
2024-11-07 20:57:33 +01:00
if (!auth.success) {
return res.status(auth.status).json({ error: auth.error });
2024-04-20 16:38:05 -07:00
}
2024-07-22 18:30:58 -04:00
2025-04-10 18:49:23 +02:00
const { team_id, chunk } = auth;
2024-11-07 20:57:33 +01:00
redisConnection.sadd("teams_using_v0", team_id)
.catch(error => logger.error("Failed to add team to teams_using_v0", { error, team_id }));
2024-04-20 16:38:05 -07:00
const crawlerOptions = req.body.crawlerOptions ?? {};
2024-06-26 09:00:54 -03:00
const pageOptions = { ...defaultPageOptions, ...req.body.pageOptions };
2024-08-28 12:46:59 -03:00
const extractorOptions = {
...defaultExtractorOptions,
2024-12-11 19:51:08 -03:00
...req.body.extractorOptions,
2024-08-28 12:46:59 -03:00
};
2024-07-17 20:44:34 -04:00
const origin = req.body.origin ?? defaultOrigin;
let timeout = req.body.timeout ?? defaultTimeout;
2024-07-22 18:30:58 -04:00
if (extractorOptions.mode.includes("llm-extraction")) {
2024-08-28 12:46:59 -03:00
if (
typeof extractorOptions.extractionSchema !== "object" ||
extractorOptions.extractionSchema === null
) {
2024-08-28 18:32:45 -03:00
return res.status(400).json({
error:
2024-12-11 19:51:08 -03:00
"extractorOptions.extractionSchema must be an object if llm-extraction mode is specified",
2024-08-28 18:32:45 -03:00
});
}
pageOptions.onlyMainContent = true;
2024-07-17 20:44:34 -04:00
timeout = req.body.timeout ?? 90000;
}
2024-04-20 16:38:05 -07:00
// checkCredits
try {
2024-08-28 12:46:59 -03:00
const { success: creditsCheckSuccess, message: creditsCheckMessage } =
await checkTeamCredits(chunk, team_id, 1);
if (!creditsCheckSuccess) {
2024-07-22 18:30:58 -04:00
earlyReturn = true;
2024-12-11 19:48:22 -03:00
return res.status(402).json({
error:
2024-12-11 19:51:08 -03:00
"Insufficient credits. For more credits, you can upgrade your plan at https://firecrawl.dev/pricing",
2024-12-11 19:48:22 -03:00
});
2024-04-20 16:38:05 -07:00
}
} catch (error) {
2024-11-07 20:57:33 +01:00
logger.error(error);
earlyReturn = true;
2024-08-28 18:32:45 -03:00
return res.status(500).json({
error:
2024-12-11 19:51:08 -03:00
"Error checking team credits. Please contact help@firecrawl.com for help.",
2024-08-28 18:32:45 -03:00
});
}
2024-07-22 18:30:58 -04:00
2024-07-24 15:18:12 +02:00
const jobId = uuidv4();
2024-04-20 19:37:45 -07:00
const startTime = new Date().getTime();
2024-04-20 18:55:39 -07:00
const result = await scrapeHelper(
2024-07-24 15:18:12 +02:00
jobId,
2024-04-20 18:55:39 -07:00
req,
team_id,
crawlerOptions,
2024-04-28 15:52:09 -07:00
pageOptions,
2024-05-06 19:45:56 -03:00
extractorOptions,
2024-05-30 14:46:55 -07:00
timeout,
2024-04-20 18:55:39 -07:00
);
2024-04-20 19:37:45 -07:00
const endTime = new Date().getTime();
const timeTakenInSeconds = (endTime - startTime) / 1000;
2024-08-28 12:46:59 -03:00
const numTokens =
result.data && (result.data as V0Document).markdown
2024-12-11 19:46:11 -03:00
? numTokensFromString(
(result.data as V0Document).markdown!,
2024-12-11 19:51:08 -03:00
"gpt-3.5-turbo",
2024-12-11 19:46:11 -03:00
)
2024-08-28 12:46:59 -03:00
: 0;
2024-04-30 09:20:15 -07:00
2024-07-22 18:30:58 -04:00
if (result.success) {
2024-08-28 18:32:45 -03:00
let creditsToBeBilled = 1;
2024-09-12 12:51:14 -04:00
const creditsPerLLMExtract = 4;
2024-07-22 18:30:58 -04:00
if (extractorOptions.mode.includes("llm-extraction")) {
2024-07-22 19:12:51 -04:00
// creditsToBeBilled = creditsToBeBilled + (creditsPerLLMExtract * filteredDocs.length);
2024-07-22 18:30:58 -04:00
creditsToBeBilled += creditsPerLLMExtract;
}
let startTimeBilling = new Date().getTime();
if (earlyReturn) {
// Don't bill if we're early returning
return;
}
2024-08-28 18:32:45 -03:00
if (creditsToBeBilled > 0) {
// billing for doc done on queue end, bill only for llm extraction
2024-12-20 18:09:49 -03:00
billTeam(team_id, chunk?.sub_id, creditsToBeBilled, logger).catch(
(error) => {
logger.error(
`Failed to bill team ${team_id} for ${creditsToBeBilled} credits`,
{ error },
);
// Optionally, you could notify an admin or add to a retry queue here
},
);
2024-07-22 18:30:58 -04:00
}
}
2024-12-11 19:46:11 -03:00
2024-08-30 17:32:41 -03:00
let doc = result.data;
if (!pageOptions || !pageOptions.includeRawHtml) {
if (doc && (doc as V0Document).rawHtml) {
delete (doc as V0Document).rawHtml;
2024-08-30 17:32:41 -03:00
}
}
2024-12-11 19:46:11 -03:00
if (pageOptions && pageOptions.includeExtract) {
if (!pageOptions.includeMarkdown && doc && (doc as V0Document).markdown) {
delete (doc as V0Document).markdown;
2024-08-30 17:32:41 -03:00
}
}
2024-07-22 18:30:58 -04:00
2024-12-11 19:46:11 -03:00
const { scrapeOptions } = fromLegacyScrapeOptions(
pageOptions,
extractorOptions,
2024-12-11 19:51:08 -03:00
timeout,
2025-04-02 19:52:43 +02:00
team_id,
2024-12-11 19:46:11 -03:00
);
2024-11-07 20:57:33 +01:00
2024-04-20 18:55:39 -07:00
logJob({
2024-07-24 15:18:12 +02:00
job_id: jobId,
2024-04-20 18:55:39 -07:00
success: result.success,
message: result.error,
num_docs: 1,
2024-08-30 17:32:41 -03:00
docs: [doc],
2024-04-20 19:37:45 -07:00
time_taken: timeTakenInSeconds,
2024-04-20 18:55:39 -07:00
team_id: team_id,
mode: "scrape",
url: req.body.url,
crawlerOptions: crawlerOptions,
2024-11-07 20:57:33 +01:00
scrapeOptions,
2024-08-28 12:46:59 -03:00
origin: origin,
2024-12-11 19:51:08 -03:00
num_tokens: numTokens,
2024-04-20 18:55:39 -07:00
});
2024-07-22 18:30:58 -04:00
2024-04-20 19:04:27 -07:00
return res.status(result.returnCode).json(result);
2024-04-20 16:38:05 -07:00
} catch (error) {
2024-09-24 10:27:49 +02:00
Sentry.captureException(error);
2024-12-17 22:01:41 +01:00
logger.error("Scrape error occcurred", { error });
2024-09-24 10:27:49 +02:00
return res.status(500).json({
error:
2024-11-07 20:57:33 +01:00
error instanceof ZodError
? "Invalid URL"
: typeof error === "string"
? error
2024-12-11 19:51:08 -03:00
: (error?.message ?? "Internal Server Error"),
2024-09-24 10:27:49 +02:00
});
2024-04-20 16:38:05 -07:00
}
}