跳到主要內容

WikipediaRetriever

概觀

Wikipedia 是一個多語言的免費線上百科全書,由志願者社群(稱為維基人)透過開放協作和使用名為 MediaWiki 的 wiki 式編輯系統編寫和維護。Wikipedia 是歷史上規模最大、閱讀次數最多的參考作品。

本筆記本展示如何將維基頁面從 wikipedia.org 檢索到 Document 格式,以便在下游使用。

整合詳細資訊

檢索器來源套件
WikipediaRetrieverWikipedia 文章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"。使用它在特定語言版本的 Wikipedia 中搜尋
  • 選用 load_max_docs:預設值=100。使用它來限制下載的文件數量。下載所有 100 份文件需要時間,因此實驗時請使用較小的數字。目前硬性限制為 300。
  • 選用 load_all_available_meta:預設值=False。預設情況下,僅下載最重要的欄位:Published(文件發布/上次更新的日期)、titleSummary。如果為 True,則也會下載其他欄位。

get_relevant_documents() 有一個參數,query:用於在 Wikipedia 中尋找文件的自由文字

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-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_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini")
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 參考資料


此頁面是否對您有幫助?