import type { ChatCompletionTool } from "openai/resources/chat/completions"; import z from "zod"; import { env } from "../env"; const MAX_CHARS = 8000; export const validator = z.object({ url: z.url().describe("The URL of the page to read."), }); export const definition: ChatCompletionTool = { type: "function", function: { name: "fetch_url", description: "Fetches a web page and returns its content as markdown.", parameters: z.toJSONSchema(validator), }, }; type FetchResponse = { results: { url: string; final_url?: string; title?: string; text: string }[]; errors: { url: string; error: string }[]; }; export async function handler(args: z.infer) { const res = await fetch("https://api.fetch.tinyfish.ai", { method: "POST", headers: { "X-API-Key": env.TINYFISH_API_KEY!, "Content-Type": "application/json", }, body: JSON.stringify({ urls: [args.url], format: "markdown" }), }); if (!res.ok) throw new Error(`TinyFish fetch failed (${res.status})`); const data = (await res.json()) as FetchResponse; const page = data.results[0]; if (!page) { throw new Error(data.errors[0]?.error ?? "Could not fetch page"); } return { url: page.final_url ?? page.url, title: page.title, text: page.text.slice(0, MAX_CHARS), }; }