【LLM】 BaseModel的作用

在 Python 里,BaseModel 是 pydantic 库提供的一个基类,pydantic 是用于数据验证和设置管理的强大库。BaseModel 主要有以下作用:

1. 数据验证

BaseModel 能对输入的数据进行验证,保证数据符合定义的类型和约束。要是输入的数据不满足要求,pydantic 会抛出异常。

python 复制代码
from pydantic import BaseModel, Field

class User(BaseModel):
    name: str = Field(..., min_length=2, max_length=50)
    age: int = Field(..., gt=0, lt=120)

# 验证通过
user1 = User(name="Alice", age=25)
print(user1)

# 验证失败,抛出异常
try:
    user2 = User(name="A", age=150)
except Exception as e:
    print(e)

输出结果:

cmd 复制代码
name='Alice' age=25
2 validation errors for User
name
  String should have at least 2 characters [type=string_too_short, input_value='A', input_type=str]
    For further information visit https://errors.pydantic.dev/2.5/v/string_too_short
age
  Input should be less than 120 [type=number_too_big, input_value=150, input_type=int]
    For further information visit https://errors.pydantic.dev/2.5/v/number_too_big

2. 数据解析

BaseModel 可以把不同格式的数据(像字典、JSON 等)解析成 Python 对象,同时进行类型转换。

示例代码:

python 复制代码
from pydantic import BaseModel

class Book(BaseModel):
    title: str
    price: float

# 从字典解析数据
book_data = {"title": "Python Crash Course", "price": 29.99}
book = Book(**book_data)
print(book)

输出结果:

cmd 复制代码
title='Python Crash Course' price=29.99

3. 数据序列化

BaseModel 支持将 Python 对象序列化为字典或 JSON 字符串,方便数据的存储和传输。

py 复制代码
from pydantic import BaseModel

class Product(BaseModel):
    name: str
    quantity: int

product = Product(name="Laptop", quantity=10)

# 序列化为字典
product_dict = product.model_dump()
print(product_dict)

# 序列化为 JSON 字符串
product_json = product.model_dump_json()
print(product_json)

输出结果:

cmd 复制代码
{'name': 'Laptop', 'quantity': 10}
{"name": "Laptop", "quantity": 10}

4. 类型提示

借助 BaseModel 定义数据结构,能为代码提供清晰的类型提示,增强代码的可读性和可维护性。

在你当前编辑的代码里,Fetch 类继承自 BaseModel,目的是定义获取 URL 的参数,对输入参数进行验证和解析:

py 复制代码
class Fetch(BaseModel):
    """Parameters for fetching a URL."""

    url: Annotated[AnyUrl, Field(description="URL to fetch")]
    max_length: Annotated[
        int,
        Field(
            default=5000,
            description="Maximum number of characters to return.",
            gt=0,
            lt=1000000,
        ),
    ]
    start_index: Annotated[
        int,
        Field(
            default=0,
            description="On return output starting at this character index, useful if a previous fetch was truncated and more context is required.",
            ge=0,
        ),
    ]
    raw: Annotated[
        bool,
        Field(
            default=False,
            description="Get the actual HTML content of the requested page, without simplification.",
        ),
    ]
相关推荐
m0_748554812 分钟前
golang如何实现用户订阅偏好管理_golang用户订阅偏好管理实现总结
jvm·数据库·python
RWKV元始智能6 分钟前
RWKV超并发项目教程,RWKV-LM训练提速40%
人工智能·rnn·深度学习·自然语言处理·开源
dyj0958 分钟前
Dify - (一)、本地部署Dify+聊天助手/Agent
人工智能·docker·容器
墨染天姬15 分钟前
【AI】Hermes的GEPA算法
人工智能·算法
小超同学你好17 分钟前
OpenClaw 深度解析系列 · 第8篇:Learning & Adaptation(学习与自适应)
人工智能·语言模型·chatgpt
紫微AI26 分钟前
前端文本测量成了卡死一切创新的最后瓶颈,pretext实现突破了
前端·人工智能·typescript
码途漫谈35 分钟前
Easy-Vibe开发篇阅读笔记(四)——前端开发之结合 Agent Skills 美化界面
人工智能·笔记·ai·开源·ai编程
smj2302_7968265237 分钟前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
易连EDI—EasyLink41 分钟前
易连EDI–EasyLink实现OCR智能数据采集
网络·人工智能·安全·汽车·ocr·edi
冬奇Lab1 小时前
RAG 系列(二):用 LangChain 搭建你的第一个 RAG Pipeline
人工智能·langchain·llm