跳到主要内容
本指南展示了如何将 SerpAPI 与 LangChain 结合使用来加载网页搜索结果。

概览

SerpAPI 是一个实时 API,提供对各种搜索引擎搜索结果的访问。它通常用于竞争对手分析和排名跟踪等任务。它使企业能够从所有搜索引擎的结果页面抓取、提取和理解数据。 本指南展示了如何使用 LangChain 中的 SerpAPILoader 加载网页搜索结果。SerpAPILoader 简化了从 SerpAPI 加载和处理网页搜索结果的过程。

设置

您需要注册并获取您的 SerpAPI API 密钥

用法

以下是 SerpAPILoader 的使用示例
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";

// Initialize the necessary components
const llm = new ChatOpenAI({
  model: "gpt-4o-mini",
});
const embeddings = new OpenAIEmbeddings();
const apiKey = "Your SerpAPI API key";

// Define your question and query
const question = "Your question here";
const query = "Your query here";

// Use SerpAPILoader to load web search results
const loader = new SerpAPILoader({ q: query, apiKey });
const docs = await loader.load();

// Use MemoryVectorStore to store the loaded documents in memory
const vectorStore = await MemoryVectorStore.fromDocuments(docs, embeddings);

const questionAnsweringPrompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    "Answer the user's questions based on the below context:\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 如何简化加载和处理网页搜索结果的过程。
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.