Skip to main content

SerpAPI 加载器

本指南展示了如何在 LangChain 中使用 SerpAPI 加载网页搜索结果。

概览

SerpAPI 是一个实时 API,可提供来自多个搜索引擎的搜索结果。它通常用于竞争对手分析和排名跟踪等任务。它使企业能够从所有搜索引擎的结果页面中抓取、提取和分析数据。

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

准备工作

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

使用方法

以下是如何使用 SerpAPILoader 的示例:

:::提示 请参阅安装集成包的一般说明部分。 :::

npm install @langchain/community @langchain/core @langchain/openai
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { SerpAPILoader } from "@langchain/community/document_loaders/web/serpapi";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { createStuffDocumentsChain } from "langchain/chains/combine_documents";
import { createRetrievalChain } from "langchain/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);

API Reference:

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


Was this page helpful?


You can also leave detailed feedback on GitHub.