Skip to main content
Open In Colab在 GitHub 上打开

维基百科检索器

概述

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

此笔记本演示如何从wikipedia.org转换为下游使用的 Document 格式。

集成详细信息

Retriever
WikipediaRetrieverWikipedia articleslangchain_community

设置

要启用单个工具的自动跟踪,请设置您的 LangSmith API 密钥:

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

安装

集成位于langchain-community包。我们还需要安装wikipediapython 包本身。

%pip install -qU langchain_community wikipedia

实例

现在我们可以实例化我们的 retriever:

WikipediaRetriever参数包括:

  • 自选lang: default=“en” 的 API API 中。使用它来搜索维基百科的特定语言部分
  • 自选load_max_docs: default=100 的 intent 的 ID 值。使用它来限制下载的文档数量。下载所有 100 个文档需要花费时间,因此请使用较小的数字进行实验。目前有 300 个的硬性限制。
  • 自选load_all_available_meta: default=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

在链内使用

像其他Retriever一样,WikipediaRetriever可以通过Chains合并到 LLM 应用程序中。

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

pip install -qU "langchain[openai]"
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain.chat_models import init_chat_model

llm = init_chat_model("gpt-4o-mini", model_provider="openai")
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 参考