跳到主要内容
Open In ColabOpen on GitHub

WikipediaRetriever

维基百科是一个多语言的免费在线百科全书,由一群被称为维基人的志愿者通过开放协作和使用基于维基的编辑系统MediaWiki编写和维护。Wikipedia是历史上规模最大、阅读量最多的参考著作。

本笔记本展示了如何从wikipedia.org检索维基页面,并将其转换为下游使用的Document格式。

集成详情

检索器来源
WikipediaRetriever维基百科文章langchain_community

设置

为了启用单个工具的自动追踪,请设置您的 LangSmith API 密钥

# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"

安装

该集成位于langchain-community包中。我们还需要安装wikipedia Python包本身。

%pip install -qU langchain_community wikipedia

实例化

现在我们可以实例化我们的检索器

WikipediaRetriever参数包括

  • 可选参数lang:默认值="en"。用于在维基百科的特定语言部分进行搜索。
  • 可选参数load_max_docs:默认值=100。用于限制下载文档的数量。下载全部 100 篇文档需要时间,因此在实验时请使用较小的数字。目前硬性限制为 300 篇。
  • 可选参数load_all_available_meta:默认值=False。默认情况下,仅下载最重要的字段:Published(文档发布/上次更新日期)、title(标题)、Summary(摘要)。如果为 True,则也会下载其他字段。

get_relevant_documents()有一个参数query:用于在维基百科中查找文档的自由文本。

from langchain_community.retrievers import WikipediaRetriever

retriever = WikipediaRetriever()
API 参考:WikipediaRetriever

使用

docs = retriever.invoke("TOKYO GHOUL")
print(docs[0].page_content[:400])
Tokyo Ghoul (Japanese: 東京喰種(トーキョーグール), Hepburn: Tōkyō Gūru) is a Japanese dark fantasy manga series written and illustrated by Sui Ishida. It was serialized in Shueisha's seinen manga magazine Weekly Young Jump from September 2011 to September 2014, with its chapters collected in 14 tankōbon volumes. The story is set in an alternate version of Tokyo where humans coexist with ghouls, beings who loo

在链中使用

与其他检索器一样,WikipediaRetriever可以通过集成到 LLM 应用程序中。

我们需要一个 LLM 或聊天模型

pip install -qU "langchain[google-genai]"
import getpass
import os

if not os.environ.get("GOOGLE_API_KEY"):
os.environ["GOOGLE_API_KEY"] = getpass.getpass("Enter API key for Google Gemini: ")

from langchain.chat_models import init_chat_model

llm = init_chat_model("gemini-2.0-flash", model_provider="google_genai")
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

prompt = ChatPromptTemplate.from_template(
"""
Answer the question based only on the context provided.
Context: {context}
Question: {question}
"""
)


def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)


chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
chain.invoke(
"Who is the main character in `Tokyo Ghoul` and does he transform into a ghoul?"
)
'The main character in Tokyo Ghoul is Ken Kaneki, who transforms into a ghoul after receiving an organ transplant from a ghoul named Rize.'

API 参考

有关WikipediaRetriever所有功能和配置的详细文档,请查阅API 参考