【多模态】01-Anthropic多模态模型与LlamaIndex分析

1. 案例目标

本案例演示如何使用Anthropic的多模态模型Claude 3(包括Opus和Sonnet版本)进行图像理解和推理。主要目标包括:

  • 展示如何使用Anthropic多模态LLM类/抽象进行图像理解和推理
  • 演示Anthropic多模态LLM支持的多种功能:complete、chat、stream complete和stream chat
  • 展示如何从图像中提取结构化信息(如股票信息)
  • 演示如何构建基于图像数据的RAG(检索增强生成)管道

2. 技术栈与核心依赖

本案例使用了以下技术栈和核心依赖:

  • 多模态LLM: Anthropic Claude 3 (Opus和Sonnet) - 用于图像理解和推理
  • 向量数据库: Qdrant - 用于存储和检索图像描述文本
  • 嵌入模型: OpenAI Embedding - 用于将文本转换为向量表示
  • 核心框架: LlamaIndex - 提供多模态处理和向量检索功能
  • 结构化输出: Pydantic - 定义和验证结构化数据模型

主要依赖包:

llama-index-multi-modal-llms-anthropic llama-index-vector-stores-qdrant matplotlib

3. 环境配置

本案例需要配置以下环境变量:

ANTHROPIC_API_KEY - 用于访问Anthropic API的密钥

注意: 需要获取Anthropic的API密钥,并将其设置为环境变量ANTHROPIC_API_KEY。

4. 案例实现

1. 安装依赖和设置API密钥

安装必要的依赖包并设置Anthropic API密钥:

!pip install llama-index-multi-modal-llms-anthropic !pip install llama-index-vector-stores-qdrant !pip install matplotlib import os os.environ["ANTHROPIC_API_KEY"] = "" # Your ANTHROPIC API key here

2. 初始化Anthropic多模态LLM

创建AnthropicMultiModal实例:

from llama_index.multi_modal_llms.anthropic import AnthropicMultiModal anthropic_mm_llm = AnthropicMultiModal(max_tokens=300)

3. 加载图像数据

使用SimpleDirectoryReader加载本地图像文件:

from llama_index.core import SimpleDirectoryReader # 加载本地图像 image_documents = SimpleDirectoryReader(input_dir="./images").load_data()

4. 使用complete方法进行图像理解

使用Anthropic多模态LLM的complete方法对图像进行描述:

response = anthropic_mm_llm.complete( prompt="Describe the images as an alternative text", image_documents=image_documents, ) print(response)

5. 定义结构化数据模型

使用Pydantic定义股票信息的结构化模型:

from typing import List from pydantic import BaseModel class TickerInfo(BaseModel): """股票信息""" direction: str ticker: str company: str shares_traded: int percent_of_total_etf: float class TickerList(BaseModel): """股票代码列表""" fund: str tickers: List[TickerInfo]

6. 使用MultiModalLLMCompletionProgram提取结构化信息

创建多模态LLM完成程序,从图像中提取结构化股票信息:

from llama_index.multi_modal_llms.anthropic import AnthropicMultiModal from llama_index.core.program import MultiModalLLMCompletionProgram from llama_index.core.output_parsers import PydanticOutputParser prompt_template_str = """\ Can you get the stock information in the image \ and return the answer? Pick just one fund. Make sure the answer is a JSON format corresponding to a Pydantic schema. The Pydantic schema is given below. """ # 初始化Anthropic多模态类 anthropic_mm_llm = AnthropicMultiModal(max_tokens=300) llm_program = MultiModalLLMCompletionProgram.from_defaults( output_cls=TickerList, image_documents=image_documents, prompt_template_str=prompt_template_str, multi_modal_llm=anthropic_mm_llm, verbose=True, ) # 执行程序 response = llm_program() print(str(response))

7. 构建图像RAG管道

下载图像数据集,并使用Claude 3提取图像描述,然后构建向量索引:

# 下载图像数据集 !wget "https://www.dropbox.com/scl/fi/c1ec6osn0r2ggnitijqhl/mixed_wiki_images_small.zip?rlkey=swwxc7h4qtwlnhmby5fsnderd&dl=1" -O mixed_wiki_images_small.zip !unzip mixed_wiki_images_small.zip # 提取图像描述 from llama_index.core.schema import TextNode from pathlib import Path from llama_index.core import SimpleDirectoryReader nodes = [] for img_file in Path("mixed_wiki_images_small").glob("*.png"): print(img_file) # 加载本地图像 image_documents = SimpleDirectoryReader(input_files=[img_file]).load_data() response = anthropic_mm_llm.complete( prompt="Describe the images as an alternative text", image_documents=image_documents, ) metadata = {"img_file": img_file} nodes.append(TextNode(text=str(response), metadata=metadata))

8. 创建向量索引

使用Qdrant向量存储和OpenAI嵌入模型创建向量索引:

from llama_index.core import VectorStoreIndex, StorageContext from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms.anthropic import Anthropic from llama_index.vector_stores.qdrant import QdrantVectorStore from llama_index.core import Settings from llama_index.core import StorageContext import qdrant_client # 创建本地Qdrant向量存储 client = qdrant_client.QdrantClient(path="qdrant_mixed_img") vector_store = QdrantVectorStore(client=client, collection_name="collection") # 使用OpenAI嵌入模型 embed_model = OpenAIEmbedding() anthropic_mm_llm = AnthropicMultiModal(max_tokens=300) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex( nodes=nodes, storage_context=storage_context, )

9. 创建查询引擎并执行查询

使用Anthropic LLM创建查询引擎,并执行查询:

from llama_index.llms.anthropic import Anthropic query_engine = index.as_query_engine(llm=Anthropic()) response = query_engine.query("Tell me more about porsche") print(str(response))

10. 显示源节点

显示查询结果的源节点,包括相似度得分和文本内容:

from llama_index.core.response.notebook_utils import display_source_node for n in response.source_nodes: display_source_node(n, metadata_mode="all")

5. 案例效果

本案例实现了以下效果:

  • 图像理解: 成功使用Claude 3模型对图像进行描述和分析
  • 结构化信息提取: 从金融图表中提取结构化的股票信息,包括股票代码、公司名称、交易数量等
  • 图像RAG: 构建了基于图像数据的检索增强生成系统,能够根据文本查询检索相关图像并生成回答
  • 多模态查询: 支持基于文本的查询,检索相关的图像描述信息

6. 案例实现思路

本案例的实现思路如下:

  1. 多模态处理: 利用Anthropic Claude 3的多模态能力,理解图像内容并生成文本描述
  2. 结构化输出: 使用Pydantic定义数据模型,结合MultiModalLLMCompletionProgram从图像中提取结构化信息
  3. 向量表示: 将图像描述文本转换为向量表示,便于进行语义检索
  4. RAG架构: 构建检索增强生成系统,结合向量检索和LLM生成能力
  5. 混合模型: 结合Anthropic多模态LLM、OpenAI嵌入模型和Qdrant向量存储,构建完整的多模态系统

7. 扩展建议

本案例可以进一步扩展和优化:

  • 支持更多图像类型: 扩展到处理更多类型的图像,如医学影像、卫星图像等
  • 多语言支持: 支持多语言图像描述和查询
  • 实时图像处理: 支持实时图像流处理和分析
  • 图像相似度搜索: 实现基于图像内容的相似度搜索,而不仅仅是基于文本描述
  • 用户界面: 开发图形用户界面,方便用户上传图像和执行查询
  • 性能优化: 优化向量存储和检索的性能,支持大规模图像处理

8. 总结

本案例展示了如何使用Anthropic Claude 3多模态模型与LlamaIndex结合,构建图像理解和检索系统。通过使用AnthropicMultiModal类,我们能够对图像进行描述和分析,提取结构化信息,并构建基于图像数据的RAG管道。这种方法可以应用于各种需要图像理解和检索的场景,如图像搜索、内容分析、文档处理等。

核心价值: 本案例的核心价值在于展示了Anthropic Claude 3多模态模型与LlamaIndex的结合,为构建智能图像理解和检索系统提供了实用方案。