8个版本
0.1.7 | 2024年1月7日 |
---|---|
0.1.6 | 2024年1月7日 |
#52 in 机器学习
每月下载量 43次
在 4 个crate 中使用
145KB
3K SLoC
GBNF-rs
用于操作 llama.cpp GBNF 文件的库。GBNF 文件表示 AI 输出的语法。该项目旨在通过使用 JSON 模式(一种定义 JSON 数据形状的方法)使约束和引导 GBNF 驱动的 AI(如 llama.cpp)更加容易。希望与系统提示(希望也能在一定程度上了解 JSON 模式)结合使用时,可以生成更有用的输出。
- 表示 GBNF 的数据结构
- 从数据结构渲染 GBNF 文件
- 将 JSON 模式的有用子集转换为 GBNF 语法
- 易于安装的 CLI 转换器 jsonschema2gbnf,使用库
- MIT 许可
此库主要为其姐妹项目,一个 LLM API epistemology 而构建。
安装
cargo add gnbf
JSON 模式支持
目前,此库可以转换 JSON 模式的一个有限但非常有用的子集
- 布尔值、数字、字符串
- 包含所有必需属性的对象
- 枚举
- oneOf
- 对象属性的顺序得到保留
- 数组支持
已知问题
- 带有下划线属性名的对象现在翻译不好
- 没有最小值、最大值、固定长度等。(尽管将模式放入系统提示可能有助于根据模型进行调整)
以下是现在可以处理的复杂 JSON 模式之一
{
"$schema": "https://json-schema.fullstack.org.cn/draft/2019-09/schema",
"type": "object",
"properties": {
"name": {
"description": "name of a computer user",
"type": "string"
},
"age": {
"description": "age of a computer user",
"type": "number"
},
"usesAI": {
"description": "do they use AI",
"type": "boolean"
},
"favoriteAnimal": {
"description": "favorite animal",
"enum": [
"dog",
"cat",
"none"
]
},
"currentAIModel": {
"oneOf": [
{
"type": "object",
"properties": {
"type": {
"value": "hugging_face"
},
"name": {
"description": "name of hugging face model",
"type": "string"
}
}
},
{
"type": "object",
"properties": {
"type": {
"value": "openai"
}
}
}
]
},
"favoriteColors": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
JSON-Schema 转换为 AI 语法
fn simple_json_schema_basic_object_example() {
let schema = r#"
{
"$id": "https://example.com/enumerated-values.schema.json",
"$schema": "https://json-schema.fullstack.org.cn/draft/2020-12/schema",
"title": "Enumerated Values",
"type": "object",
"properties": {
"a": {
"type": "boolean"
},
"b": {
"type": "number"
},
"c": {
"type": "string"
}
}
}
"#;
let g = Grammar::from_json_schema(schema).unwrap();
let s = g.to_string();
pretty_assertions::assert_eq!(
s,
r#"################################################
# DYNAMICALLY GENERATED JSON-SCHEMA GRAMMAR
# $id: https://example.com/enumerated-values.schema.json
# $schema: https://json-schema.fullstack.org.cn/draft/2020-12/schema
# title: Enumerated Values
################################################
symbol1-a-value ::= boolean ws
symbol2-b-value ::= number ws
symbol3-c-value ::= string ws
root ::= "{" ws
"a" ws ":" ws symbol1-a-value
"b" ws ":" ws symbol2-b-value "," ws
"c" ws ":" ws symbol3-c-value "," ws
"}" ws
###############################
# Primitive value type symbols
###############################
null ::= "null" ws
boolean ::= "true" | "false" ws
string ::= "\"" ([^"\\] | "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]))* "\"" ws
number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
ws ::= [ ]
"#
)
}
此项目的未来目标
- 提供标准语法
- 处理 JSON 模式到 GBNF 的有用转换(我们可能无法处理所有内容)。
- 使用 Nom 7 解析 GBNF 文件。
我完全欢迎贡献者,请添加测试。
查看 文档。
归属
从 llama.cpp
的 语法示例 中使用了多个 MIT 许可的 GBNF 示例,用于本项目自动化测试的合规性和灵感来源。感谢。
依赖项
约 2.5–3.5MB
约 69K SLoC