> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# SerpAPI 加载器集成

> 使用 LangChain JavaScript 与 SerpAPI 加载器文档加载器集成。

本指南展示如何将 SerpApi 与 LangChain 结合使用来加载网络搜索结果。

## 概述

[SerpApi](https://serpapi.com/) 是一个实时 API，提供对来自各种搜索引擎的搜索结果的访问。它通常用于竞争对手分析和排名跟踪等任务。它使企业能够从所有搜索引擎的结果页面中抓取、提取和理解数据。

本指南展示如何使用 LangChain 中的 `SerpAPILoader` 加载网络搜索结果。`SerpAPILoader` 简化了从 SerpApi 加载和处理网络搜索结果的过程。

## 设置

您需要注册并获取您的 [SerpApi API 密钥](https://serpapi.com/dashboard)。

## 用法

以下是使用 `SerpAPILoader` 的示例：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { MemoryVectorStore } from "@langchain/classic/vectorstores/memory";
import { SerpAPILoader } from "@langchain/community/document_loaders/web/serpapi";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { createStuffDocumentsChain } from "@langchain/classic/chains/combine_documents";
import { createRetrievalChain } from "@langchain/classic/chains/retrieval";

// 初始化必要的组件
const llm = new ChatOpenAI({
  model: "gpt-5.4-mini",
});
const embeddings = new OpenAIEmbeddings();
const apiKey = "您的 SerpApi API 密钥";

// 定义您的问题和查询
const question = "您的问题在这里";
const query = "您的查询在这里";

// 使用 SerpAPILoader 加载网络搜索结果
const loader = new SerpAPILoader({ q: query, apiKey });
const docs = await loader.load();

// 使用 MemoryVectorStore 将加载的文档存储在内存中
const vectorStore = await MemoryVectorStore.fromDocuments(docs, embeddings);

const questionAnsweringPrompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    "根据以下上下文回答用户的问题：\n\n{context}",
  ],
  ["human", "{input}"],
]);

const combineDocsChain = await createStuffDocumentsChain({
  llm,
  prompt: questionAnsweringPrompt,
});

const chain = await createRetrievalChain({
  retriever: vectorStore.asRetriever(),
  combineDocsChain,
});

const res = await chain.invoke({
  input: question,
});

console.log(res.answer);
```

在此示例中，`SerpAPILoader` 用于加载网络搜索结果，然后使用 `MemoryVectorStore` 将这些结果存储在内存中。接着，使用检索链从内存中检索最相关的文档，并基于这些文档回答问题。这展示了 `SerpAPILoader` 如何简化加载和处理网络搜索结果的过程。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [连接这些文档](/use-these-docs) 到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/document_loaders/web_loaders/serpapi.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
