Reasoner API数据格式的Pydantic模型
项目描述
Reasoner-Pydantic
Pydantic 为 Reasoner API 数据格式提供的模型。
当使用 FastAPI 设置Reasoner API时,这些模型非常有用。
示例用法
from reasoner_pydantic import (
Query,
Message,
QNode,
KnowledgeGraph,
Node,
Result,
NodeBinding,
)
def add_result_to_query(query_dict):
query = Query.parse_obj(query_dict)
message: Message = query.message
# get query graph node
qnode_id = next(iter(message.query_graph.nodes))
# add knowledge graph node
knode = Node.parse_obj({"categories": ["biolink:FooBar"]})
knode_id = "foo:bar"
message.knowledge_graph.nodes[knode_id] = knode
# add result
result: Result = Result.parse_obj(
{
"node_bindings": {qnode_id: [{"id": knode_id}]}
}
)
message.results.add(result)
return message.json()
add_result_to_query({
"message": {
"query_graph": {"nodes": {"n0": {}}, "edges": {}},
"knowledge_graph": {"nodes": {}, "edges": {}},
"results" : []
}
})
验证用法
由于性能考虑,以及Python中类型实现的性质,这些模型上没有强制执行赋值验证。例如
from reasoner_pydantic import KnowledgeGraph
# This will not throw an error
kg = KnowledgeGraph(nodes = "hi")
在构建使用容器对象时,这一点尤为重要。此库使用自定义容器类型:HashableMapping,HashableSequence,HashableSet
from reasoner_pydantic import KnowledgeGraph, Node, CURIE
# This is not correct and will not throw an error, but will cause problems later
kg = KnowledgeGraph(nodes = {})
# Instead, if you would like to build models this way, use a typed container constructor
kg = KnowledgeGraph(nodes = HashableMapping[CURIE, Node](__root__ = {}))
因此,我们建议以下选项之一
- 仅限使用
parse_obj
构建模型。这将为您执行验证。如果性能不重要,此选项最佳。 - 使用静态类型检查器以确保模型构建正确。以这种方式构建对象性能更高,静态类型检查器将确保其正确执行。我们建议在您的编辑器中使用 pyright。
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。
源代码分发
reasoner-pydantic-5.0.6.tar.gz (13.3 kB 查看哈希值)