LlamaIndex
LlamaIndex 集成
将 CrawlForge MCP 与 LlamaIndex 集成,构建具备网页抓取能力的数据连接器、索引和查询引擎。非常适合 RAG 应用和知识库。
使用场景
网页数据连接器
创建可自动抓取并索引网页内容的数据连接器
知识库
从网页和文档构建可搜索的知识库
查询引擎
创建带实时网页数据检索的查询引擎
文档处理
从 URL 提取并处理文档以供索引
安装
安装 LlamaIndex。CrawlForge 没有适配器包——下面的读取器和工具都是可直接复制到项目中的普通类。
Bash
npm install llamaindex你还需要一个来自控制台的 CrawlForge API 密钥。
网页数据连接器
将 CrawlForge 用作数据连接器,以抓取并加载网页文档。
crawlforge.tsTypescript
import { Document } from 'llamaindex';
const CRAWLFORGE_API = 'https://www.crawlforge.dev/api/v1/tools';
/** Every CrawlForge tool is a POST to /api/v1/tools/<tool_name>. */
export async function callTool<T>(
tool: string,
params: Record<string, unknown>,
): Promise<T> {
const response = await fetch(`${CRAWLFORGE_API}/${tool}`, {
method: 'POST',
headers: {
'X-API-Key': process.env.CRAWLFORGE_API_KEY!,
'Content-Type': 'application/json',
},
body: JSON.stringify(params),
});
const payload = await response.json();
if (!payload.success) {
throw new Error(payload.error?.message ?? 'CrawlForge request failed');
}
return payload.data as T;
}
interface ExtractedContent {
url: string;
title: string;
content: string;
author: string | null;
publish_date: string | null;
}
/** Reads each URL through extract_content (2 credits per URL). */
export class CrawlForgeReader {
async loadData(urls: string[]): Promise<Document[]> {
return Promise.all(
urls.map(async (url) => {
const data = await callTool<ExtractedContent>('extract_content', { url });
return new Document({
text: data.content,
id_: data.url,
metadata: {
source: data.url,
title: data.title,
author: data.author,
publishedAt: data.publish_date,
},
});
}),
);
}
}
// ---------- usage ----------
const reader = new CrawlForgeReader();
const documents = await reader.loadData([
'https://example.com/page1',
'https://example.com/page2',
]);
console.log(documents[0].text);
console.log(documents[0].metadata.title);提示: 使用
extract_content 进行干净的文章提取,或使用 extract_text 获取整页文本。向量存储索引
从网页文档创建向量存储索引,以进行语义搜索。
Typescript
import { OpenAIEmbedding, VectorStoreIndex } from 'llamaindex';
import { CrawlForgeReader } from './crawlforge';
// 1. Load documents from the web (2 credits per URL)
const documents = await new CrawlForgeReader().loadData([
'https://example.com/doc1',
'https://example.com/doc2',
'https://example.com/doc3',
]);
// 2. Build the vector index
const index = await VectorStoreIndex.fromDocuments(documents, {
embedModel: new OpenAIEmbedding({ model: 'text-embedding-3-small' }),
});
// 3. Query it
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: 'What are the main topics covered?',
});
console.log(response.toString());带工具的查询引擎
创建一个可按需抓取实时网页数据的查询引擎。
tools.tsTypescript
import { FunctionTool } from 'llamaindex';
import { callTool } from './crawlforge';
interface SearchResults {
results: { title: string; url: string; snippet: string }[];
}
export const searchWeb = FunctionTool.from(
async ({ query, limit }: { query: string; limit?: number }) => {
const data = await callTool<SearchResults>('search_web', { query, limit });
return JSON.stringify(data.results);
},
{
name: 'search_web',
description: 'Search the web and return ranked results. Costs 5 credits.',
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: 'What to search for' },
limit: { type: 'number', description: 'How many results, 1-100' },
},
required: ['query'],
},
},
);
export const readPage = FunctionTool.from(
async ({ url }: { url: string }) => {
const data = await callTool<{ title: string; content: string }>(
'extract_content',
{ url },
);
return `${data.title}\n\n${data.content}`;
},
{
name: 'extract_content',
description: 'Extract the main article text from one URL. Costs 2 credits.',
parameters: {
type: 'object',
properties: {
url: { type: 'string', description: 'The page to read' },
},
required: ['url'],
},
},
);
// Pass [searchWeb, readPage] to whichever agent your llamaindex version
// exposes — the tool objects are the same either way.智能体提示: 智能体会根据查询自动选择要使用的工具。设置
verbose=true 即可查看工具选择过程。自定义网页检索器
构建一个根据查询抓取网页数据的自定义检索器。
Typescript
import { Document } from 'llamaindex';
import { callTool } from './crawlforge';
import { CrawlForgeReader } from './crawlforge';
interface SearchResults {
results: { title: string; url: string; snippet: string }[];
}
/**
* Search the web, then read the top hits.
* Costs 5 credits for the search plus 2 per page read.
*/
export class WebRetriever {
private readonly reader = new CrawlForgeReader();
constructor(private readonly topK = 3) {}
async retrieve(query: string): Promise<Document[]> {
const { results } = await callTool<SearchResults>('search_web', {
query,
limit: this.topK,
});
return this.reader.loadData(results.map((result) => result.url));
}
}
// ---------- usage ----------
const documents = await new WebRetriever().retrieve('latest AI safety research');
console.log(`Retrieved ${documents.length} documents`);
// Feed them into an index when you want scored, chunk-level retrieval:
// const index = await VectorStoreIndex.fromDocuments(documents);异步批处理
使用异步批处理操作高效处理多个 URL。
Typescript
import { VectorStoreIndex } from 'llamaindex';
import { CrawlForgeReader } from './crawlforge';
const urls = [
'https://example.com/1',
'https://example.com/2',
'https://example.com/3',
'https://example.com/4',
'https://example.com/5',
'https://example.com/6',
];
// Cap concurrency so you stay inside your plan's requests-per-second limit
// (Free 1/s, Hobby 2/s, Professional 4/s, Business 10/s).
const CONCURRENCY = 2;
const reader = new CrawlForgeReader();
const batches = [];
for (let i = 0; i < urls.length; i += CONCURRENCY) {
batches.push(urls.slice(i, i + CONCURRENCY));
}
const documents = [];
for (const batch of batches) {
documents.push(...(await reader.loadData(batch)));
}
console.log(`Loaded ${documents.length} documents`);
const index = await VectorStoreIndex.fromDocuments(documents);
console.log('Index created successfully');性能提示: 读取一个页面需要 2 credits,因此抓取 50 个 URL 需要 100 credits。请将并发数限制在套餐的速率上限内——Free 1/s、Hobby 2/s、Professional 4/s、Business 10/s。
最佳实践
- 选择高效工具 — 多个 URL 用
batch_scrape,干净文本用extract_content - 实现缓存 — 缓存已索引的文档,避免重复抓取并节省 credits
- 使用异步操作 — 利用 async/await 进行并行处理,以加速批量操作
- 监控 credits — 在文档元数据中跟踪 credits 用量,并在你的控制台中设置告警
准备好用 LlamaIndex 构建了吗?
探索全部 29 个 CrawlForge 工具,或查看其他集成。