如何从LLM中提取结构化数据?xmllm工具实测解析
AI Summary (BLUF)
xmllm is a JavaScript utility that extracts structured data from LLMs using a flexible XML-based approach, offering resilience to errors and provider-agnostic compatibility.
原文翻译: xmllm 是一个 JavaScript 工具,通过灵活的基于 XML 的方法从大型语言模型中提取结构化数据,具有容错性和提供商无关的兼容性。
xmllm 是一个 JavaScript 工具库,它使得从大型语言模型(LLM)中获取结构化数据变得简单。它采用了一种经过时间考验、语义丰富、人类可读写且具有容错性的语法,能够灵活处理人为(因此也包括 LLM 生成)的错误。
xmllm 是一个 JavaScript 工具库,它使得从大型语言模型(LLM)中获取结构化数据变得简单。它采用了一种经过时间考验、语义丰富、人类可读写且具有容错性的语法,能够灵活处理人为(因此也包括 LLM 生成)的错误。
请注意:这是一个实验性项目。不过,我已经使用 xmllm 成功部署了完全可运行的应用程序。但在尝试从 LLM 中提取结构化数据时,请保持耐心。它不像常规编程那样具有确定性。你可以在 xmllm_demos 仓库中找到演示和示例,或者直接访问 xmllm.j11y.io 进行在线体验(由于存在速率限制,如遇问题请见谅!)
我正在寻找协作者和测试者来帮助改进这个库。
核心概念与工作原理
一个简单的例子
import { simple, types } from 'xmllm';
const names = await simple('fun pet names', {
schema: {
name: [String]
}
});
names; // => { name: ["Daisy", "Whiskers", "Rocky"] }
// 提示:使用 `[String]` 作为模式值
// 是 `types.items(types.string())` 的快捷方式。
import { simple, types } from 'xmllm'; const names = await simple('fun pet names', { schema: { name: [String] } }); names; // => { name: ["Daisy", "Whiskers", "Rocky"] } // 提示:使用 `[String]` 作为模式值 // 是 `types.items(types.string())` 的快捷方式。
幕后流程
┌─────────────────────────┐
│ │
│ "fun pet names" │
│ │
└───┬─────────────────────┘
│
│ 你的提示词与 xmllm 选定的策略性系统提示、
│ 模式指令及示例一起发送给配置的 LLM
│
▼
┌─────────────────────────┐
│ LLM 生成 │
│ <name>Daisy</name> │
│ <name>Whiskers</name> │
│ <name>Rocky</name> │
└───┬─────────────────────┘
│
│ 解析 LLM 的自然输出
│
▼
┌─────────────────────────┐
│ 通过模式 │
│ {name: [String]} │
│ 将 XML 解析为结构化数据│
└───┬─────────────────────┘
│
│ 数据转换与验证
│
▼
┌────────────────────────┐
│ 最终结果: │
│ { │
│ name: [ │
│ "Daisy", │
│ "Whiskers", │
│ "Rocky" │
│ ] │
│ } │
└────────────────────────┘
┌─────────────────────────┐ │ │ │ "fun pet names" │ │ │ └───┬─────────────────────┘ │ │ 你的提示词与 xmllm 选定的策略性系统提示、 │ 模式指令及示例一起发送给配置的 LLM │ ▼ ┌─────────────────────────┐ │ LLM 生成 │ │ <name>Daisy</name> │ │ <name>Whiskers</name> │ │ <name>Rocky</name> │ └───┬─────────────────────┘ │ │ 解析 LLM 的自然输出 │ ▼ ┌─────────────────────────┐ │ 通过模式 │ │ {name: [String]} │ │ 将 XML 解析为结构化数据│ └───┬─────────────────────┘ │ │ 数据转换与验证 │ ▼ ┌────────────────────────┐ │ 最终结果: │ │ { │ │ name: [ │ │ "Daisy", │ │ "Whiskers", │ │ "Rocky" │ │ ] │ │ } │ └────────────────────────┘
杂乱的 XML 也可恢复!
由于 xmllm 使用了相当灵活的 HTML 解析器,即使 LLM 提供了奇怪的修饰或非连续的 XML,仍然能够被解析,例如:
Hi im a plucky and annoying
little llm and sure i can
help with your request for
PET NAMES, how about <name>
Charlie</name> or
maybe <name>Bella </ IM MESSING THINGS UP ></name>
<name>King
Julian
Hi im a plucky and annoying little llm and sure i can help with your request for PET NAMES, how about <name> Charlie</name> or maybe <name>Bella </ IM MESSING THINGS UP ></name> <name>King Julian
...我们仍然可以从中恢复:
{
name: ['Charlie', 'Bella', 'King Julian']
}
{ name: ['Charlie', 'Bella', 'King Julian'] }
为什么选择 XML?—— 透过宽容的 HTML 解析器视角
(为什么不使用函数调用或“工具使用”?)
为什么是 XML? – XML 允许 LLM 以“自由散文”的最佳优点进行自然交流,同时仍能返回结构化数据。相比之下,通过“函数调用”或“工具使用”从 LLM 派生 JSON 的常规做法是出了名的脆弱。此类 API 也仅在某些提供商和模型中可用。
此外——根据经验——JSON 由于其通常在训练数据中出现的位置,会使 LLM 偏向于更“机械化”的事务性完成,可以说缺乏我们从语言模型中获得的更流畅或更具创造性的高温度完成。这种抽象也使流式传输变得棘手。然而,像 XML 和 HTML 这样的标记语言在这些弱点上表现出色。
Why XML? – XML allows LLMs to communicate naturally with the best merits of 'free prose' while still giving you structured data back. In contrast, the norm of deriving JSON from LLMs via 'Function Calling' or 'Tool Use' is famously brittle. Such APIs are also only available with some providers and models.
And–anecdotally–JSON, by nature of where it usually appears in training data, will bias the LLM to more "robotic" transactional completions, arguably lacking some of the more fluid or creative higher-temperature completions we have come to value from language models. Such abstractions also make streaming a headache. Markup languages like XML and HTML, however, excel at all of these weaknesses.
为了展示 xmllm 流式处理的流畅性,这里有一个通过流式 LLM “外星物种”生成器逐步填充 UI 的示例(代码在此):
As an example of how fluid an xmllm stream can be, here's an example of a UI being progressively populated by a streaming LLM 'alien species' generator (code here):
演示与沙盒
克隆并体验 xmllm demos 仓库,或者:
🔥 在线体验:xmllm.j11y.io
Fork and play with the xmllm demos repo, or:
🔥 See it live here: xmllm.j11y.io
供应商无关性与高模型兼容性
xmllm 能够针对大多数可想象的端点运行,因为你可以定义自定义提供者。我们内置了一些提供者,如 anthropic、openai、openrouter、togetherai、perplexityai。你通常会将 API 密钥放在 .env 文件中,但也可以内联放置。此外,如果你担心速率限制或随机故障,可以定义备用模型。
stream('fun pet names', {
schema: {
name: Array(String)
},
// 如果我非常担心网络或 LLM 提供者的稳定性,
// 我可以定义备用模型:
model: [
// 首选模型:
'openrouter:mistralai/ministral-3b',
// 备用模型:
'anthropic:claude-3-haiku-20240307',
'togetherai:Qwen/Qwen2.5-7B-Instruct-Turbo',
// 超级自定义备用模型:
{
inherit: 'openai', // 表示与 OpenAI 端点兼容
endpoint: 'https://api.myCustomLLM.com/v1/chat/completions',
key: 'sk-...'
}
]
});
stream('fun pet names', { schema: { name: Array(String) }, // If I am super cautious about network or LLM provider stability, // I can define fallback models: model: [ // Preferred model: 'openrouter:mistralai/ministral-3b', // Fallback models: 'anthropic:claude-3-haiku-20240307', 'togetherai:Qwen/Qwen2.5-7B-Instruct-Turbo', // Super-custom fallback model: { inherit: 'openai', // indicating open-ai endpoint compatibility endpoint: 'https://api.myCustomLLM.com/v1/chat/completions', key: 'sk-...' } ] });
开箱即用,仅配置了部分提供者:
| 提供者 | 环境变量键 | 支持模型示例 |
|---|---|---|
Anthropic (anthropic) |
ANTHROPIC_API_KEY |
Claude Sonnet, Haiku, Opus |
OpenAI (openai) |
OPENAI_API_KEY |
GPT-4o, GPT-4o-mini |
Together.ai (togetherai) |
TOGETHERAI_API_KEY |
Qwen, Mistral, Llama 等 |
Perplexity (perplexityai) |
PERPLEXITYAI_API_KEY |
Llama, Mistral 等 |
OpenRouter (openrouter) |
OPENROUTER_API_KEY |
几乎所有模型! |
Out of the box, only some providers are configured:
Provider Key Models such as... Anthropic ( anthropic)ANTHROPIC_API_KEYClaude Sonnet, Haiku, Opus OpenAI ( openai)OPENAI_API_KEYGPT-4o, GPT-4o-mini Together.ai ( togetherai)TOGETHERAI_API_KEYQwen, Mistral, Llama, etc. Perplexity ( perplexityai)PERPLEXITYAI_API_KEYLlama, Mistral, etc. OpenRouter ( openrouter)OPENROUTER_API_KEYEverything! 在模式遵循方面,xmllm 在 Llama 3.1 8B、Qwen2.5-7B-Instruct-Turbo、Nous Hermes 2 Mixtral、Qwen 2.5 Coder 32B 等中低参数模型上取得了令人印象深刻的结果。如果遵循度不足,通常可以通过在模式之外使用
hints,以及尝试配置不同的策略来提高。更多详情请参阅提供者设置指南。
In regards to schema compliance xmllm has impressive results on mid-to-low-param models like: Llama 3.1 8B, Qwen2.5-7B-Instruct-Turbo, Nous Hermes 2 Mixtral, Qwen 2.5 Coder 32B. And, where lacking, compliance can usually be improved by using
hintsin addition to schemas and by experimenting with configuring different strategies.See many more details in the Provider Setup guide.
示例:程序化的情感分析
此示例演示了如何以编程方式使用 LLM 分析客户情感,从自然文本中提取结构化见解:
const analysis = await simple( ` Analyze this customer review: "I absolutely love the new smartphone. The camera quality is outstanding, but the battery life sucks!" `, { schema: { sentiment: types.enum( "Overall sentiment", ["POSITIVE", "NEUTRAL", "NEGATIVE"] ), pros: types.items(types.string("Positive aspects")), cons: types.items(types.string("Negative aspects")), summary: types.string("Brief analysis explanation") }, model: 'openrouter:mistralai/ministral-3b', max_tokens: 1000 } );const analysis = await simple( ` Analyze this customer review: "I absolutely love the new smartphone. The camera quality is outstanding, but the battery life sucks!" `, { schema: { sentiment: types.enum( "Overall sentiment", ["POSITIVE", "NEUTRAL", "NEGATIVE"] ), pros: types.items(types.string("Positive aspects")), cons: types.items(types.string("Negative aspects")), summary: types.string("Brief analysis explanation") }, model: 'openrouter:mistralai/ministral-3b', max_tokens: 1000 } );LLM 以 XML 形式自然响应:
<sentiment>POSITIVE</sentiment> <pros> <item>Outstanding camera quality</item> <item>Overall positive user experience</item> </pros> <cons> <item ## 常见问题(FAQ) ### xmllm 是什么工具,它如何从 LLM 提取数据? xmllm 是一个 JavaScript 工具库,通过灵活的 XML 方法从大型语言模型提取结构化数据。它利用语义丰富、人类可读的 XML 语法,并具有容错性,能处理 LLM 生成的不规则输出。 ### xmllm 相比函数调用或工具使用有什么优势? xmllm 使用 XML 允许 LLM 以自然语言交流同时返回结构化数据,避免 JSON 函数调用的脆弱性。它不依赖特定提供商 API,兼容性更广,且能通过宽容的 HTML 解析器恢复杂乱 XML。 ### xmllm 如何处理 LLM 生成的错误或不规则 XML? xmllm 内置容错机制,使用灵活的 HTML 解析器。即使 LLM 输出包含奇怪修饰、非连续标签或不规范格式,它仍能解析并恢复结构化数据,如从杂乱文本中提取宠物名称列表。
版权与免责声明:本文仅用于信息分享与交流,不构成任何形式的法律、投资、医疗或其他专业建议,也不构成对任何结果的承诺或保证。
文中提及的商标、品牌、Logo、产品名称及相关图片/素材,其权利归各自合法权利人所有。本站内容可能基于公开资料整理,亦可能使用 AI 辅助生成或润色;我们尽力确保准确与合规,但不保证完整性、时效性与适用性,请读者自行甄别并以官方信息为准。
若本文内容或素材涉嫌侵权、隐私不当或存在错误,请相关权利人/当事人联系本站,我们将及时核实并采取删除、修正或下架等处理措施。 也请勿在评论或联系信息中提交身份证号、手机号、住址等个人敏感信息。