Template
47 lines
1.4 KiB
TypeScript
47 lines
1.4 KiB
TypeScript
import { tool } from 'ai';
|
|
import { z } from 'zod';
|
|
|
|
export const firecrawlWebFetch = tool({
|
|
description:
|
|
'Fetch a web page and return its content as markdown. Use this tool when the user asks to read, summarize, or extract information from a URL.',
|
|
inputSchema: z.object({
|
|
url: z.string().url().describe('The URL of the web page to fetch'),
|
|
}),
|
|
execute: async ({ url }, { abortSignal }) => {
|
|
try {
|
|
const response = await fetch('https://api.firecrawl.dev/v1/scrape', {
|
|
method: 'POST',
|
|
signal: abortSignal,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Authorization: `Bearer ${process.env.FIRECRAWL_API_KEY!}`,
|
|
},
|
|
body: JSON.stringify({
|
|
url,
|
|
formats: ['markdown'],
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
return { success: false, error: `Firecrawl API error: ${errorText}` };
|
|
}
|
|
|
|
const data = await response.json();
|
|
|
|
if (!data?.data?.markdown) {
|
|
return { success: false, error: 'No content retrieved for this URL' };
|
|
}
|
|
|
|
return { success: true, markdown: data.data.markdown };
|
|
} catch (error) {
|
|
console.error('Error fetching web page:', error);
|
|
return {
|
|
success: false,
|
|
error:
|
|
error instanceof Error ? error.message : 'Failed to fetch web page',
|
|
};
|
|
}
|
|
},
|
|
});
|