当前位置: 首页 > ops >正文

【LLM】 BaseModel的作用

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

1. 数据验证

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


from pydantic import BaseModel, Fieldclass 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)

输出结果:


name='Alice' age=25
2 validation errors for User
nameString 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
ageInput 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 对象,同时进行类型转换。

示例代码:

from pydantic import BaseModelclass Book(BaseModel):title: strprice: float# 从字典解析数据
book_data = {"title": "Python Crash Course", "price": 29.99}
book = Book(**book_data)
print(book)

输出结果:


title='Python Crash Course' price=29.99

3. 数据序列化

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

from pydantic import BaseModelclass Product(BaseModel):name: strquantity: intproduct = Product(name="Laptop", quantity=10)# 序列化为字典
product_dict = product.model_dump()
print(product_dict)# 序列化为 JSON 字符串
product_json = product.model_dump_json()
print(product_json)

输出结果:

{'name': 'Laptop', 'quantity': 10}
{"name": "Laptop", "quantity": 10}

4. 类型提示

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

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

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.",),]
http://www.xdnf.cn/news/16887.html

相关文章:

  • MySQL面试题及详细答案 155道(021-040)
  • Spring Cloud微服务中的内存泄漏问题定位与解决方案
  • SelectDB数据库,新一代实时数据仓库的全面解析与应用
  • Linux 环境下 Docker 安装与简单使用指南
  • 百度招黑产溯源安全工程师
  • 《软件测试与质量控制》实验报告二 单元测试
  • MSQL-聚簇索引与非聚簇索引的比较
  • Python编程基础与实践:Python文件处理入门
  • SpringBoot 信用卡检测、OpenAI gym、OCR结合、DICOM图形处理、知识图谱、农业害虫识别实战
  • 【7.5 Unity AssetPostprocessor】
  • 【自动化运维神器Ansible】YAML支持的数据类型详解:构建高效Playbook的基石
  • linux ext4缩容home,扩容根目录
  • Trae + Notion MCP:将你的Notion数据库升级为智能对话机器人
  • 元宇宙重构未来交通新图景
  • 无人机光伏巡检漏检率↓78%!陌讯多模态融合算法实战解析
  • 机试备考笔记 2/31
  • Agentic RAG:自主检索增强生成的范式演进与技术突破
  • 深入 Go 底层原理(二):Channel 的实现剖析
  • 深入 Go 底层原理(十四):timer 的实现与高性能定时器
  • cuda编程笔记(12)--学习cuFFT的简单使用
  • 【机器学习】非线性分类算法(上):KNN(基于距离相似度)与朴素(特征独立)贝叶斯(基于概率统计)
  • Lock 接口及实现类详解:从 ReentrantLock 到并发场景实践
  • Node.js 操作 MongoDB
  • 【LeetCode 热题 100】739. 每日温度——(解法一)单调栈+从右到左
  • 最新Windows11系统镜像,23H2 64位ISO镜像
  • 拉格朗日插值法
  • 【软考中级网络工程师】知识点之堆叠
  • MySQL PostgreSQL JDBC URL 配置允许批量操作
  • 系统思考:超越线性分析
  • openwrt下安装istore(基于pve)