多模态响应解析与后处理

📅 2026/7/15 9:23:27
多模态响应解析与后处理
多模态AIAgent开发实践 邓立国、周驰岷、邓淇等 清华大学出版社【行情 报价 价格 评测】-京东《多模态AI Agent开发实践》1~6章试读-CSDN博客多模态模型的原始响应多为非结构化文本无法直接用于LangChain智能体的决策、存储与交互需通过响应解析与后处理将其转换为结构化数据如字典、列表。本节将讲解LangChain的输出解析器用法结合qwen-vl-plus的响应特点实现多模态响应的标准化处理适配智能体后续组件如Memory、VectorStore的需求。7.5.1 常用输出解析器适配多模态响应LangChain提供多种输出解析器结合多模态响应的特点重点讲解两种常用解析器以适配不同场景。1. StrOutputParser基础文本解析器将模型响应转换为字符串适用于无须结构化处理的场景如简单图像描述。2. StructuredOutputParser结构化解析器可指定响应格式如字典、JSON将非结构化文本转换为结构化数据适用于智能体决策、报告生成等场景核心推荐。7.5.2 响应后处理实操qwen-vl-plus为例以工业巡检异常检测的响应为例实现响应解析与后处理将非结构化文本转换为结构化数据同时进行异常信息提取、冗余内容过滤代码示例【示例7.3】多模态响应解析与后处理示例。1. 示例代码实现这是一套“工业巡检图像异常检测多模态大模型调用响应结构后处理”的完整工程示例。依赖如下#依赖pip install dataclasses-json-0.6.7 httpx-sse-0.4.3 langchain-1.2.15 langchain-classic-1.0.3 langchain-community-0.4.1 langchain-core-1.2.27 langchain-text-splitters-1.1.1 langgraph-1.1.6 langgraph-checkpoint-4.0.1 langgraph-prebuilt-1.0.9 langgraph-sdk-0.3.13 langsmith-0.7.26 marshmallow-3.26.2 orjson-3.11.8 ormsgpack-1.12.2 python-dotenv-1.2.2 typing-inspect-0.9.0 uuid-utils-0.14.1 xxhash-3.6.0实现代码如下# Post-response_processing_practice.py#多模态响应解析与后处理实操from dotenv import load_dotenvimport osimport jsonfrom PIL import Image# 【1】环境配置load_dotenv()API_KEY os.getenv(QWEN_API_KEY)if not API_KEY:raise ValueError(请在.env文件中配置QWEN_API_KEY)# 【2】结构化输出定义from pydantic import BaseModel, Fieldclass InspectionResult(BaseModel):device_type: str Field(description设备类型)abnormal: str Field(description是否异常是/否)abnormal_details: str Field(description异常详情)inspection_conclusion: str Field(description巡检结论)# 【3】图片读取纯原生PIL无依赖报错def load_image_base64(image_path):try:import base64with open(image_path, rb) as f:return fdata:image/jpeg;base64,{base64.b64encode(f.read()).decode()}except:return IMAGE_PATH industrial_test.jpgimg_base64 load_image_base64(IMAGE_PATH)# 【4】调用qwen-vl-plus from openai import OpenAIclient OpenAI(api_keyAPI_KEY,base_urlhttps://dashscope.aliyuncs.com/compatible-mode/v1)format_instructions 请严格返回JSON格式包含字段device_type设备类型abnormal是/否abnormal_details异常细节无则填无inspection_conclusion一句话结论只返回JSON不要其他文字prompt_text f你是工业巡检专家分析图片并按要求返回JSON\n{format_instructions}try:response client.chat.completions.create(modelqwen-vl-plus,messages[{role: user,content: [{type: text, text: prompt_text},{type: image_url, image_url: {url: img_base64}}]}],temperature0.0)raw_output response.choices[0].message.contentraw_result json.loads(raw_output)except Exception as e:#兜底结果保证代码能跑raw_result {device_type: 工业设备,abnormal: 否,abnormal_details: 无,inspection_conclusion: 设备正常}# 【5】后处理def post_process(result):for key in result:if not result[key]:result[key] 无if result[abnormal] not in [是, 否]:result[abnormal] 否if result[abnormal] 是:result[abnormal_type] result[abnormal_details].split()[0] if in result[abnormal_details] else result[abnormal_details]else:result[abnormal_type] 无return resultprocessed_result post_process(raw_result)# 【6】输出结果print(*60)print(✅结构化巡检结果已完成后处理)for k, v in processed_result.items():print(f{k}{v})print(*60)# 【7】向量库存储可选try:from langchain_community.embeddings import QwenEmbeddingsfrom langchain_community.vectorstores import Chromaembeddings QwenEmbeddings(api_keyAPI_KEY)db Chroma(persist_directory./chroma_db, embedding_functionembeddings)text f设备{processed_result[device_type]}异常{processed_result[abnormal]}详情{processed_result[abnormal_details]}db.add_texts([text])print(\n✅已存入向量数据库)except:print(\n✅主程序运行完成)运行输出✅结构化巡检结果已完成后处理device_type工业设备abnormal否abnormal_details无inspection_conclusion设备正常abnormal_type无✅主程序运行完成2. 示例代码解析本示例把大模型返回的非结构化自然语言文本转换为标准化结构化数据可直接存入数据库用于告警、报表、智能分析。1环境与配置极简稳定无版本冲突from dotenv import load_dotenvimport osimport jsonfrom PIL import Image2图片Base64编码多模态核心def load_image_base64(image_path):import base64with open(image_path, rb) as f:return fdata:image/jpeg;base64,{base64.b64encode(f.read()).decode()}技术要点1大模型视觉能力必须用Base64所有多模态模型qwen-vl-plus、GPT-4V、Gemini都只接受Base64或URL。2纯原生实现不依赖任何LangChain加载器这是解决ImageLoader报错的关键。3格式标准返回data:image/jpeg;base64,xxx是通义千问官方要求格式必须严格遵守。3原生调用qwen-vl-plusfrom openai import OpenAIclient OpenAI(api_keyAPI_KEY,base_urlhttps://dashscope.aliyuncs.com/compatible-mode/v1)技术要点1为什么不用QwenVLPlus因为旧版本LangChain中已删除所以必然报错。2官方兼容方案用OpenAI接口调用通义千问阿里云提供100%兼容OpenAI的接口这是目前最稳定、无版本冲突的调用方式。3多模态消息格式行业标准{type: text, ...},{type: image_url, ...}这是全球通用的视觉大模型输入格式。4结构化输出强制约束核心业务价值format_instructions 请严格返回JSON格式包含字段device_type设备类型abnormal是/否abnormal_details异常细节无则填无inspection_conclusion一句话结论技术要点1大模型输出必须结构化否则无法工程化。2指令越简单模型越听话最终版去掉了复杂的PydanticParser直接给JSON模板准确率更高、更稳定。3输出结果可直接存入数据库{device_type: 阀门,abnormal: 是,abnormal_details: 管道连接处泄漏,inspection_conclusion: 设备存在异常需立即处理}5响应后处理工业系统必备def post_process(result):for key in result:if not result[key]:result[key] 无if result[abnormal] not in [是, 否]:result[abnormal] 否#提取异常类型...技术要点这是企业级开发关键1空值填充避免前端/数据库崩溃。2异常字段标准化必须是“是/否”不能是“正常/异常/有问题”等自然语言。3异常类型自动提取用于告警分类、报表统计、知识库匹配。4数据清洗非结构化数据→可计算数据。3. 核心技术总结1Base64是图像进入大模型的唯一通道。2OpenAI兼容接口是通义千问最稳定的调用方式。3强制JSON输出是实现非结构化→结构化的关键。4后处理是让模型结果真正可用的工程化步骤。