整合

Vercel AI SDK

把 Thunderbit 包成 TypeScript tool,給 streamText / generateText agent 用

Vercel AI SDK 的 tool() 助手能把任何 TypeScript function 變成 LLM 可呼叫的工具。把 /distill 包起來,模型就能在對話中即時讀網頁。

安裝

npm install ai @ai-sdk/openai zod

定義 tool

import { tool } from 'ai';
import { z } from 'zod';

const API = 'https://openapi.thunderbit.com/openapi/v1';
const H = { Authorization: `Bearer ${process.env.THUNDERBIT_API_KEY}` };

export const readUrl = tool({
  description:
    'Fetch a URL and return clean Markdown. Use for any web research task: docs, articles, product pages.',
  parameters: z.object({
    url: z.string().url(),
    renderMode: z.enum(['basic', 'advanced']).default('basic'),
  }),
  execute: async ({ url, renderMode }) => {
    const res = await fetch(`${API}/distill`, {
      method: 'POST',
      headers: { ...H, 'Content-Type': 'application/json' },
      body: JSON.stringify({ url, renderMode }),
    });
    const json = await res.json();
    return json.data.markdown;
  },
});

streamText

import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';

const result = streamText({
  model: openai('gpt-4o'),
  tools: { readUrl },
  maxSteps: 5,
  prompt: 'Summarize the latest post on https://vercel.com/blog',
});

for await (const chunk of result.textStream) process.stdout.write(chunk);

小技巧

  • execute 回傳前把 Markdown 截到約 8k token —— 避免吃爆 context
  • 多 URL 平行抓的話,再開一個 /batch/distill 包的 readUrls tool
  • 只在頁面是 JS 重渲染時才用 renderMode: 'advanced' —— basic 便宜 3-5 倍

相關文件