WikipediaRetriever
總覽
維基百科是一個多語言的免費線上百科全書,由一群志願者(稱為維基人)透過開放協作和使用名為 MediaWiki 的 wiki 式編輯系統編寫和維護。
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[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 參考。