Bases: ChainableOutputParser
Pydantic输出解析器。
Parameters:
Name |
Type |
Description |
Default |
output_cls |
BaseModel
|
|
required
|
Source code in llama_index/core/output_parsers/pydantic.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 | class PydanticOutputParser(ChainableOutputParser):
"""Pydantic输出解析器。
Args:
output_cls (BaseModel): Pydantic输出类。"""
def __init__(
self,
output_cls: Type[Model],
excluded_schema_keys_from_format: Optional[List] = None,
pydantic_format_tmpl: str = PYDANTIC_FORMAT_TMPL,
) -> None:
"""初始化参数。"""
self._output_cls = output_cls
self._excluded_schema_keys_from_format = excluded_schema_keys_from_format or []
self._pydantic_format_tmpl = pydantic_format_tmpl
@property
def output_cls(self) -> Type[Model]:
return self._output_cls
@property
def format_string(self) -> str:
"""格式化字符串。"""
return self.get_format_string(escape_json=True)
def get_format_string(self, escape_json: bool = True) -> str:
"""格式化字符串。"""
schema_dict = self._output_cls.schema()
for key in self._excluded_schema_keys_from_format:
del schema_dict[key]
schema_str = json.dumps(schema_dict)
output_str = self._pydantic_format_tmpl.format(schema=schema_str)
if escape_json:
return output_str.replace("{", "{{").replace("}", "}}")
else:
return output_str
def parse(self, text: str) -> Any:
"""解析、验证和通过程序自动纠正错误。"""
json_str = extract_json_str(text)
return self._output_cls.parse_raw(json_str)
def format(self, query: str) -> str:
"""使用结构化的输出格式指令格式化查询。"""
return query + "\n\n" + self.get_format_string(escape_json=True)
|
get_format_string(escape_json: bool = True) -> str
格式化字符串。
Source code in llama_index/core/output_parsers/pydantic.py
44
45
46
47
48
49
50
51
52
53
54
55 | def get_format_string(self, escape_json: bool = True) -> str:
"""格式化字符串。"""
schema_dict = self._output_cls.schema()
for key in self._excluded_schema_keys_from_format:
del schema_dict[key]
schema_str = json.dumps(schema_dict)
output_str = self._pydantic_format_tmpl.format(schema=schema_str)
if escape_json:
return output_str.replace("{", "{{").replace("}", "}}")
else:
return output_str
|
parse
解析、验证和通过程序自动纠正错误。
Source code in llama_index/core/output_parsers/pydantic.py
| def parse(self, text: str) -> Any:
"""解析、验证和通过程序自动纠正错误。"""
json_str = extract_json_str(text)
return self._output_cls.parse_raw(json_str)
|
format(query: str) -> str
使用结构化的输出格式指令格式化查询。
Source code in llama_index/core/output_parsers/pydantic.py
| def format(self, query: str) -> str:
"""使用结构化的输出格式指令格式化查询。"""
return query + "\n\n" + self.get_format_string(escape_json=True)
|