【多模态】22-基于Pydantic的多模态LLM应用
2026/9/8 12:59:12 网站建设 项目流程

案例目标

本案例展示了如何使用Pydantic从多模态大语言模型中提取结构化数据。主要目标包括:

  • 使用OpenAI GPT-4V、Fuyu-8B、LLaVA、CogVLM和MiniGPT-4等多模态模型分析图像内容
  • 通过Pydantic定义数据模型,将非结构化图像内容转换为结构化数据
  • 比较不同多模态模型在结构化数据提取方面的性能差异
  • 实现餐厅菜单、亚马逊产品和社交媒体广告等多种场景的结构化数据提取

技术栈与核心依赖

主要技术栈
  • 多模态LLM:OpenAI GPT-4V、Fuyu-8B、LLaVA、CogVLM、MiniGPT-4
  • 数据建模:Pydantic
  • 图像处理:PIL (Python Imaging Library)
  • 数据加载:LlamaIndex SimpleDirectoryReader
  • 可视化:Matplotlib
核心依赖

复制

llama-index-multi-modal-llms-openai replicate pydantic matplotlib PIL requests

环境配置

API密钥配置

复制

import os os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY" os.environ["REPLICATE_API_TOKEN"] = "YOUR_REPLICATE_API_TOKEN"
安装依赖

复制

!pip install llama-index-multi-modal-llms-openai replicate
数据准备

案例中使用了多种图像数据:

  • 餐厅菜单图像
  • 亚马逊产品图像
  • Instagram广告图像

这些图像通过wget命令下载到本地目录中,供后续处理使用。

案例实现

步骤1:导入必要的库

复制

from llama_index.multi_modal_llms.openai import OpenAIMultiModal from llama_index.multi_modal_llms.replicate import ReplicateMultiModal from llama_index import SimpleDirectoryReader from llama_index.program import MultiModalLLMCompletionProgram from llama_index.output_parsers import PydanticOutputParser from pydantic import BaseModel from PIL import Image import matplotlib.pyplot as plt import requests
步骤2:定义Pydantic数据模型

案例中定义了三种不同的数据模型,用于不同场景的结构化数据提取:

餐厅模型

复制

class Restaurant(BaseModel): """Data model for a restaurant.""" restaurant: str food: str discount: str price: str
亚马逊产品模型

复制

class Product(BaseModel): """Data model for a Amazon Product.""" title: str category: str discount: str price: str rating: str review: str description: str inventory: str
Instagram广告模型

复制

class InsAds(BaseModel): """Data model for Instagram Ads.""" account: str brand: str product: str category: str discount: str price: str comments: str review: str description: str
步骤3:初始化多模态LLM

复制

openai_mm_llm = OpenAIMultiModal(model="gpt-4o", max_new_tokens=1000)
步骤4:加载图像数据

复制

# 加载餐厅图像 restaurant_image_documents = SimpleDirectoryReader("./restaurant_images").load_data() # 加载亚马逊产品图像 amazon_image_documents = SimpleDirectoryReader("./amazon_images").load_data() # 加载Instagram广告图像 ins_image_documents = SimpleDirectoryReader("./instagram_images").load_data()
步骤5:定义提示模板

复制

prompt_template_str = """\ can you summarize what is in the image\ and return the answer with json format \ """
步骤6:创建多模态LLM完成程序

复制

openai_program = MultiModalLLMCompletionProgram.from_defaults( output_parser=PydanticOutputParser(Restaurant), image_documents=restaurant_image_documents, prompt_template_str=prompt_template_str, multi_modal_llm=openai_mm_llm, verbose=True, )
步骤7:执行程序并获取结果

复制

response = openai_program() for res in response: print(res)
步骤8:使用Replicate模型进行比较

复制

# 定义使用Replicate模型的函数 def pydantic_replicate(model, output_class, image_documents, prompt_template_str): replicate_mm_llm = ReplicateMultiModal( model=model, ) openai_program = MultiModalLLMCompletionProgram.from_defaults( output_parser=PydanticOutputParser(output_class), image_documents=image_documents, prompt_template_str=prompt_template_str, multi_modal_llm=replicate_mm_llm, verbose=True, ) response = openai_program() print(f"Model: {model}") for res in response: print(res) # 使用不同模型进行比较 pydantic_replicate("fuyu-8b", Restaurant, restaurant_image_documents, prompt_template_str) pydantic_replicate("llava-13b", Restaurant, restaurant_image_documents, prompt_template_str) pydantic_replicate("cogvlm", Restaurant, restaurant_image_documents, prompt_template_str) pydantic_replicate("minigpt-4", Restaurant, restaurant_image_documents, prompt_template_str)

案例效果

餐厅菜单分析结果

使用不同模型分析餐厅菜单图像的结果对比:

GPT-4V
('restaurant', 'KFC') ('food', 'Fried Chicken') ('discount', '20% off') ('price', '$5.99')
Fuyu-8B
('restaurant', 'KFC') ('food', 'Fried Chicken') ('discount', 'None') ('price', '$5.99')
LLaVA
('restaurant', 'KFC') ('food', 'Fried Chicken') ('discount', 'None') ('price', '$5.99')
CogVLM
('restaurant', 'KFC') ('food', 'Fried Chicken') ('discount', '20% off') ('price', '$5.99')
亚马逊产品分析结果

使用GPT-4V分析亚马逊产品图像的结果:

复制

('title', 'Amazon Echo Dot (4th Gen)') ('category', 'Smart Speaker') ('discount', '20% off') ('price', '$39.99') ('rating', '4.5 out of 5 stars') ('review', 'Great sound quality for its size') ('description', 'Meet the all-new Echo Dot - Our most popular smart speaker with Alexa.') ('inventory', 'In stock')
Instagram广告分析结果

使用不同模型分析Instagram广告图像的结果对比:

GPT-4V
('account', 'jordansdaily') ('brand', 'Air Jordan') ('product', 'Air Jordan 2') ('category', 'Footwear') ('discount', 'None') ('price', '$175') ('comments', 'Liked by cemm2k and others') ('review', 'Not available') ('description', "Release date November 18th - Air Jordan 2 'Italy'")
CogVLM
('account', 'jordansdaily') ('brand', 'AIR JORDAN') ('product', '2') ('category', 'ITALY') ('discount', '') ('price', '$175') ('comments', '') ('review', '') ('description', "AIR JORDAN 2 'ITALY' release NOV 18TH $175")
模型性能观察
  • GPT-4V和CogVLM能够输出所有期望的字段
  • 在这两个模型中,GPT-4V提供更准确的结果
  • 不同模型在细节提取和准确性方面存在差异
  • 对于复杂场景,GPT-4V表现最佳

案例实现思路

核心设计理念

本案例的核心设计理念是将非结构化的图像内容转换为结构化数据,通过以下步骤实现:

  1. 数据建模:使用Pydantic定义结构化数据模型,明确需要提取的字段和类型
  2. 图像处理:使用SimpleDirectoryReader加载图像数据,为多模态模型提供输入
  3. 模型集成:集成多种多模态LLM,包括OpenAI GPT-4V和Replicate上的开源模型
  4. 提示工程:设计简洁有效的提示模板,指导模型提取所需信息
  5. 输出解析:使用PydanticOutputParser将模型输出解析为结构化对象
  6. 模型比较:对比不同模型在相同任务上的表现,评估其优缺点
关键技术点
  • 多模态理解:利用多模态LLM同时处理图像和文本的能力
  • 结构化提取:通过Pydantic模型确保输出数据的结构化和类型安全
  • 模型抽象:使用统一的接口调用不同的多模态模型,便于比较和切换
  • 场景应用:针对餐厅、电商和社交媒体等不同场景设计特定的数据模型
实现流程

复制

1. 定义Pydantic数据模型 2. 初始化多模态LLM 3. 加载图像数据 4. 创建多模态LLM完成程序 5. 执行程序并获取结构化结果 6. 比较不同模型的性能

扩展建议

功能扩展
  • 批量处理:实现批量图像处理功能,提高处理效率
  • 更多数据类型:扩展支持视频、音频等多媒体数据的结构化提取
  • 自定义模型:支持用户自定义Pydantic模型,适应更多应用场景
  • 结果验证:添加结果验证和修正机制,提高提取准确性
  • 交互式界面:开发Web界面,方便用户上传图像并查看提取结果
技术优化
  • 模型微调:针对特定任务微调多模态模型,提高领域适应性
  • 缓存机制:实现结果缓存,避免重复处理相同图像
  • 并行处理:利用并行处理技术加速批量图像处理
  • 模型集成:集成多个模型的结果,通过投票或加权平均提高准确性
  • 错误处理:增强错误处理机制,提高系统稳定性
应用场景扩展
  • 医疗影像分析:从医疗影像中提取结构化诊断信息
  • 工业质检:从产品图像中提取结构化质检数据
  • 文档处理:从扫描文档中提取结构化信息
  • 自动驾驶:从车载摄像头图像中提取结构化道路信息
  • 农业监测:从农田图像中提取结构化作物生长数据

总结

本案例展示了如何使用Pydantic从多模态大语言模型中提取结构化数据的完整流程。通过定义明确的数据模型,我们能够将非结构化的图像内容转换为结构化数据,为后续的数据分析和应用提供便利。

案例比较了多种多模态模型(包括OpenAI GPT-4V、Fuyu-8B、LLaVA、CogVLM和MiniGPT-4)在结构化数据提取方面的性能,发现GPT-4V和CogVLM能够输出所有期望的字段,其中GPT-4V提供更准确的结果。

这种方法可以应用于多种场景,如餐厅菜单分析、电商产品信息提取和社交媒体广告分析等,为企业和开发者提供了一种高效、准确的多模态数据结构化解决方案。

随着多模态大语言模型的不断发展,这种结构化数据提取方法将在更多领域发挥重要作用,帮助用户更好地理解和利用多模态数据。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询