pydantic.Field
函数用于自定义模型的字段并为其添加元数据。要了解更多信息,请查阅 Pydantic 的文档,因为此处内容是该文档的近似副本,与提示相关。
默认值¶
default
参数用于为字段定义默认值。
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(default='John Doe')
user = User()
print(user)
#> name='John Doe'
您还可以使用 default_factory
来定义一个可调用对象,该对象将被调用以生成默认值。
from uuid import uuid4
from pydantic import BaseModel, Field
class User(BaseModel):
id: str = Field(default_factory=lambda: uuid4().hex)
信息
default
和 default_factory
参数是互斥的。
注意
如果您使用 typing.Optional
,这并不意味着该字段的默认值是 None
,您必须使用 default
或 default_factory
来定义默认值。然后,在发送给语言模型时,它将被视为 非必需
字段。
使用 Annotated
¶
Field
函数也可以与 Annotated
一起使用。
from uuid import uuid4
from typing_extensions import Annotated
from pydantic import BaseModel, Field
class User(BaseModel):
id: Annotated[str, Field(default_factory=lambda: uuid4().hex)]
排除字段¶
exclude
参数可用于控制在导出模型时应从模型中排除哪些字段。当您想排除与模型生成不相关的字段(例如 scratch_pad
或 chain_of_thought
)时,这会很有帮助。
请参阅以下示例
from pydantic import BaseModel, Field
from datetime import date
class DateRange(BaseModel):
chain_of_thought: str = Field(
description="Reasoning behind the date range.", exclude=True
)
start_date: date
end_date: date
date_range = DateRange(
chain_of_thought="""
I want to find the date range for the last 30 days.
Today is 2021-01-30 therefore the start date
should be 2021-01-01 and the end date is 2021-01-30""",
start_date=date(2021, 1, 1),
end_date=date(2021, 1, 30),
)
print(date_range.model_dump_json())
#> {"start_date":"2021-01-01","end_date":"2021-01-30"}
从发送给语言模型的 schema 中省略字段¶
在某些情况下,您可能希望让语言模型忽略模型中的某些字段。您可以通过使用 Pydantic 的 SkipJsonSchema
注解来实现。这会从 Pydantic 发出的 JSON schema 中省略一个字段(instructor
使用该 schema 来构建其提示和工具定义)。例如:
from pydantic import BaseModel
from pydantic.json_schema import SkipJsonSchema
from typing import Union
class Response(BaseModel):
question: str
answer: str
private_field: SkipJsonSchema[Union[str, None]] = None
assert "private_field" not in Response.model_json_schema()["properties"]
请注意,由于语言模型永远不会为 private_field
返回值,因此您需要一个默认值(这可以通过声明的 Pydantic Field
来实现,该 Field
可以是一个生成器)。
自定义 JSON Schema¶
有些字段专门用于自定义生成的 JSON Schema:
title
: 字段的标题。description
: 字段的描述。examples
: 字段的示例。json_schema_extra
: 要添加到字段的额外 JSON Schema 属性。
所有这些都是向 JSON schema 添加更多信息的好机会,可以作为您的提示工程的一部分。
以下是一个示例:
from pydantic import BaseModel, Field, SecretStr
class User(BaseModel):
age: int = Field(description='Age of the user')
name: str = Field(title='Username')
password: SecretStr = Field(
json_schema_extra={
'title': 'Password',
'description': 'Password of the user',
'examples': ['123456'],
}
)
print(User.model_json_schema())
"""
{
'properties': {
'age': {'description': 'Age of the user', 'title': 'Age', 'type': 'integer'},
'name': {'title': 'Username', 'type': 'string'},
'password': {
'description': 'Password of the user',
'examples': ['123456'],
'format': 'password',
'title': 'Password',
'type': 'string',
'writeOnly': True,
},
},
'required': ['age', 'name', 'password'],
'title': 'User',
'type': 'object',
}
"""
关于 JSON schema 生成的一般说明¶
- Optional 字段的 JSON schema 表明允许使用 null 值。
- Decimal 类型在 JSON schema 中(以及序列化时)表示为字符串。
- JSON schema 不会将 namedtuple 保留为 namedtuple。
- 当它们不同时,您可以指定 JSON schema 是表示验证的输入还是序列化的输出。
- 使用的子模型会根据规范添加到
$defs
JSON 属性中并被引用。 - 带有修改(通过 Field 类,例如自定义标题、描述或默认值)的子模型会递归地包含,而不是被引用。
- 模型的描述取自类的 docstring 或 Field 类的参数描述。