3步搞定AI数据格式化:ollama-python结构化输出零基础实战
【免费下载链接】ollama-python 项目地址: https://gitcode.com/GitHub_Trending/ol/ollama-python
你还在为AI返回的非结构化文本头疼?还在手动解析JSON格式错误?本文将通过ollama-python的结构化输出功能,教你用3个步骤实现AI响应的标准化处理,让数据提取效率提升10倍。读完本文你将掌握:同步/异步结构化输出实现、多场景schema设计、Pydantic数据验证全流程。
什么是结构化输出
结构化输出(Structured Output)是指让AI模型按照预设格式(如JSON、XML)返回数据的技术。相比自由文本,它具有三大优势:
- 数据可直接解析:避免字符串切割、正则匹配等繁琐操作
- 类型安全:通过Pydantic模型确保数据类型正确
- 流程自动化:标准化数据可直接对接数据库、API等下游系统
ollama-python通过format参数实现该功能,核心源码位于ollama/_client.py的chat和generate方法中。
同步结构化输出实战
步骤1:定义数据模型
创建Pydantic模型描述期望的数据结构,以好友信息管理为例:
from pydantic import BaseModel
class FriendInfo(BaseModel):
name: str # 姓名(字符串类型)
age: int # 年龄(整数类型)
is_available: bool # 是否有空(布尔类型)
class FriendList(BaseModel):
friends: list[FriendInfo] # 好友列表(FriendInfo数组)
完整代码见examples/structured-outputs.py
步骤2:调用API生成结构化数据
使用chat接口并指定format参数为模型的JSON Schema:
from ollama import chat
response = chat(
model='llama3.1:8b', # 使用的LLM模型
messages=[{
'role': 'user',
'content': '我有两个朋友:Ollama 22岁正在拯救世界,Alonso 23岁想出去玩。用JSON格式返回好友列表'
}],
format=FriendList.model_json_schema(), # 自动生成JSON Schema
options={'temperature': 0} # 设为0确保输出稳定
)
关键参数说明: | 参数 | 作用 | 示例值 | |------|------|--------| | format | 指定输出格式Schema | FriendList.model_json_schema() | | temperature | 控制随机性,0为完全确定 | 0 | | model | 支持结构化输出的模型 | llama3.1:8b, gemma3 |
步骤3:验证并使用数据
通过Pydantic验证返回结果,确保数据符合预期:
# 验证JSON并转换为Python对象
friends = FriendList.model_validate_json(response.message.content)
# 直接访问结构化数据
for friend in friends.friends:
print(f"{friend.name}, {friend.age}岁, {'有空' if friend.is_available else '忙碌'}")
执行examples/structured-outputs.py将得到标准化输出:
friends=[FriendInfo(name='Ollama', age=22, is_available=False), FriendInfo(name='Alonso', age=23, is_available=True)]
异步场景实现方案
对于需要高并发处理的场景,可使用异步客户端:
from ollama import AsyncClient
async def main():
client = AsyncClient()
response = await client.chat(
model='llama3.1:8b',
messages=[{'role': 'user', 'content': '...'}],
format=FriendList.model_json_schema()
)
friends = FriendList.model_validate_json(response.message.content)
异步实现的核心差异在于:
- 使用
AsyncClient替代同步客户端 - 通过
await关键字处理异步调用 - 需在
asyncio.run()中执行
完整异步示例见examples/async-structured-outputs.py
高级应用:多模态结构化输出
ollama-python还支持图像分析的结构化输出,以examples/structured-outputs-image.py为例:
class ImageDescription(BaseModel):
summary: str # 图像摘要
objects: list[Object] # 识别物体列表
colors: list[str] # 主要颜色
time_of_day: Literal['Morning', 'Afternoon', 'Evening', 'Night'] # 时间段
调用时通过images参数传入图片路径:
response = chat(
model='gemma3',
messages=[{
'role': 'user',
'content': '分析图片并返回JSON描述',
'images': [Path('photo.jpg')] # 本地图片路径
}],
format=ImageDescription.model_json_schema()
)
该功能特别适合电商商品识别、安防图像分析等场景,完整实现见examples/structured-outputs-image.py
常见问题解决
Schema设计原则
- 字段最小化:只包含必要字段
- 使用枚举类型:对固定选项使用
Literal(如时间段) - 设置默认值:可选字段指定
None默认值
调试技巧
- 开启调试模式:
client = Client(debug=True) - 检查模型支持性:通过list.py查看模型能力
- 验证Schema有效性:使用JSON Schema Validator
总结与后续学习
本文通过三个步骤实现了结构化输出:定义Pydantic模型→调用API生成数据→验证并使用结果。核心代码来自:
- 同步实现:examples/structured-outputs.py
- 异步实现:examples/async-structured-outputs.py
- 多模态实现:examples/structured-outputs-image.py
下期将讲解如何结合工具调用功能实现结构化数据的自动处理流水线,敬请关注。收藏本文,点赞支持,获取更多ollama-python实战技巧。
【免费下载链接】ollama-python 项目地址: https://gitcode.com/GitHub_Trending/ol/ollama-python
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



