From ef6dbd6c33f6b0effb1a4a2dd9b081ea42d908ce Mon Sep 17 00:00:00 2001 From: ganyouxuan Date: Mon, 17 Aug 2026 09:44:43 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=B0=86=E8=A7=86=E8=A7=89=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=E5=8A=A0=E5=85=A5=E4=B8=BBLLM=E7=9A=84=E4=B8=8A?= =?UTF-8?q?=E4=B8=8B=E6=96=87=EF=BC=8C=E7=94=B1=E4=B8=BBLLM=E8=BF=9B?= =?UTF-8?q?=E8=A1=8C=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../resources/db/changelog/202608161000.sql | 21 +++ .../db/changelog/db.changelog-master.yaml | 7 + main/xiaozhi-server/config.yaml | 3 + .../xiaozhi-server/core/api/vision_handler.py | 76 ++++++++- main/xiaozhi-server/core/connection.py | 148 +++++++++--------- .../tools/device_mcp/mcp_executor.py | 4 +- .../core/providers/vllm/base.py | 9 ++ .../core/providers/vllm/multimodal_llm.py | 19 +++ .../xiaozhi-server/core/utils/cache/config.py | 1 + main/xiaozhi-server/plugins_func/register.py | 1 + 10 files changed, 203 insertions(+), 86 deletions(-) create mode 100644 main/manager-api/src/main/resources/db/changelog/202608161000.sql create mode 100644 main/xiaozhi-server/core/providers/vllm/multimodal_llm.py diff --git a/main/manager-api/src/main/resources/db/changelog/202608161000.sql b/main/manager-api/src/main/resources/db/changelog/202608161000.sql new file mode 100644 index 000000000..aa3b0f1d5 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202608161000.sql @@ -0,0 +1,21 @@ +-- 使用当前主 LLM 的多模态视觉供应器。 +-- 此供应器不单独配置模型或密钥,图片会作为多模态消息交给智能体配置的 LLM。 +INSERT INTO `ai_model_provider` + (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) +SELECT 'SYSTEM_VLLM_multimodal_llm', 'VLLM', 'multimodal_llm', '使用主LLM(多模态)', '[]', 10, 1, NOW(), 1, NOW() +WHERE NOT EXISTS ( + SELECT 1 FROM `ai_model_provider` WHERE `id` = 'SYSTEM_VLLM_multimodal_llm' +); + +INSERT INTO `ai_model_config` +SELECT + 'VLLM_MultimodalLLM', 'VLLM', 'MultimodalLLM', '使用主LLM(多模态)', + 0, 1, '{"type":"multimodal_llm"}', NULL, NULL, 3, NULL, NULL, NULL, NULL +WHERE NOT EXISTS ( + SELECT 1 FROM `ai_model_config` WHERE `id` = 'VLLM_MultimodalLLM' +); + +UPDATE `ai_model_config` +SET `remark` = '使用当前智能体已选择的LLM处理图片和问题。请确保该LLM支持OpenAI兼容的多模态消息(text + image_url)。', + `doc_link` = NULL +WHERE `id` = 'VLLM_MultimodalLLM'; diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index 3ce5d2340..da9d9a9e3 100644 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -711,3 +711,10 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202607101200.sql + - changeSet: + id: 202608161000 + author: ganyouxuan + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202608161000.sql diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 323b562ec..7146424c7 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -744,6 +744,9 @@ LLM: base_url: http://localhost:9997 # Xinference服务地址 # VLLM配置(视觉语言大模型) VLLM: + MultimodalLLM: + # 复用当前选中的 LLM 处理图片;该 LLM 须支持 OpenAI 兼容的多模态消息。 + type: multimodal_llm ChatGLMVLLM: type: openai # glm-4v-flash是智谱免费AI的视觉模型,需要先在智谱AI平台创建API密钥并获取api_key diff --git a/main/xiaozhi-server/core/api/vision_handler.py b/main/xiaozhi-server/core/api/vision_handler.py index c3e683cfe..7529ea5e7 100644 --- a/main/xiaozhi-server/core/api/vision_handler.py +++ b/main/xiaozhi-server/core/api/vision_handler.py @@ -1,5 +1,6 @@ import json import copy +import uuid from aiohttp import web from config.logger import setup_logging from core.api.base_handler import BaseHandler @@ -10,6 +11,8 @@ from core.utils.auth import AuthToken import base64 from typing import Tuple, Optional from plugins_func.register import Action +from core.utils.cache.config import CacheType +from core.utils.cache.manager import cache_manager TAG = __name__ @@ -44,6 +47,50 @@ class VisionHandler(BaseHandler): token = auth_header[7:] # 移除"Bearer "前缀 return self.auth.verify_token(token) + @staticmethod + def _get_image_mime_type(image_data: bytes) -> str: + """Return the MIME type for the image signatures accepted by this API.""" + if image_data.startswith(b"\xff\xd8\xff"): + return "image/jpeg" + if image_data.startswith(b"\x89PNG\r\n\x1a\n"): + return "image/png" + if image_data.startswith((b"GIF87a", b"GIF89a")): + return "image/gif" + if image_data.startswith(b"BM"): + return "image/bmp" + if image_data.startswith((b"II*\x00", b"MM\x00*")): + return "image/tiff" + if image_data.startswith(b"RIFF") and image_data[8:12] == b"WEBP": + return "image/webp" + # is_valid_image_file has already checked the data. Keep a safe default + # for image formats whose MIME type is not recognized above. + return "image/jpeg" + + def _cache_vision_data( + self, question: str, image_data: bytes, image_base64: str + ) -> str: + """Cache an image until its originating MCP tool call is recorded.""" + image_url = ( + f"data:{self._get_image_mime_type(image_data)};base64,{image_base64}" + ) + vision_data_key = uuid.uuid4().hex + cache_manager.set( + CacheType.VISION_DATA, + vision_data_key, + [ + { + "type": "text", + "text": question or "上传了一张图片。", + }, + { + "type": "image_url", + "image_url": {"url": image_url}, + }, + ], + ) + self.logger.bind(tag=TAG).info(f"已缓存图片,缓存键: {vision_data_key}") + return vision_data_key + async def handle_post(self, request): """处理 MCP Vision POST 请求""" response = None # 初始化response变量 @@ -126,14 +173,29 @@ class VisionHandler(BaseHandler): vllm = create_instance( vllm_type, current_config["VLLM"][select_vllm_module] ) + if vllm.use_multimodal_llm(): + # The current LLM receives the original question and image as + # OpenAI-compatible multimodal message content. Returning + # REQMLLM resumes the tool-call conversation after this result. + vision_data_key = self._cache_vision_data( + question, image_data, image_base64 + ) - result = vllm.response(question, image_base64) - - return_json = { - "success": True, - "action": Action.RESPONSE.name, - "response": result, - } + return_json = { + "success": True, + "action": Action.REQMLLM.name, + "result": { + "type": "vision_data", + "vision_data_key": vision_data_key, + }, + } + else: + result = vllm.response(question, image_base64) + return_json = { + "success": True, + "action": Action.RESPONSE.name, + "response": result, + } response = web.Response( text=json.dumps(return_json, separators=(",", ":")), diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 4e45032c4..bed5f2199 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -45,6 +45,8 @@ from core.utils.prompt_manager import PromptManager from core.utils.voiceprint_provider import VoiceprintProvider from core.utils.util import get_system_error_response from core.utils import textUtils +from core.utils.cache.config import CacheType +from core.utils.cache.manager import cache_manager TAG = __name__ @@ -1374,15 +1376,37 @@ class ConnectionHandler: return True def _handle_function_result(self, tool_results, depth, streamed_text=""): - need_llm_tools = [] - record_tools = [] + tool_actions = { + Action.REQLLM, + Action.REQMLLM, + Action.RECORD, + } + all_tool_calls = [ + { + "id": tool_call_data["id"], + "function": { + "arguments": tool_call_data["arguments"] or "{}", + "name": tool_call_data["name"], + }, + "type": "function", + "index": index, + } + for index, (_, tool_call_data) in enumerate( + item for item in tool_results if item[0].action in tool_actions + ) + ] + if all_tool_calls: + self.dialogue.put(Message(role="assistant", tool_calls=all_tool_calls)) + need_chat = False + vision_messages = [] + record_response_parts = [] for result, tool_call_data in tool_results: - if result.action in [ + if result.action in ( Action.RESPONSE, Action.NOTFOUND, Action.ERROR, - ]: + ): text = result.response if result.response else result.result if streamed_text and text in streamed_text: self.logger.bind(tag=TAG).debug( @@ -1392,38 +1416,33 @@ class ConnectionHandler: self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text) self.tts.store_tts_text(self.sentence_id, text) self.dialogue.put(Message(role="assistant", content=text)) + continue + + tool_content = None + if result.action == Action.RECORD: + tool_content = result.result or "" + response = result.response or result.result + if response: + record_response_parts.append(response) elif result.action == Action.REQLLM: - need_llm_tools.append((result, tool_call_data)) - elif result.action == Action.RECORD: - record_tools.append((result, tool_call_data)) - else: - pass + tool_content = result.result or "" + need_chat = True + elif result.action == Action.REQMLLM: + tool_content = "" + tool_result = result.result + if ( + isinstance(tool_result, dict) + and tool_result.get("type") == "vision_data" + ): + vision_content = self._pop_vision_message( + tool_result.get("vision_data_key") + ) + tool_content = "获取图片成功" if vision_content else "获取图片失败" + if vision_content is not None: + vision_messages.append(vision_content) + need_chat = True - # Action.RECORD:写入完整工具调用链(assistant(tool_calls) → tool(result) → assistant(response)) - # 模型从历史中学到工具调用模式,不额外调用LLM - if record_tools: - # 构造 assistant 消息(含 tool_calls),记录"模型调用了哪些工具" - all_tool_calls = [ - { - "id": tool_call_data["id"], - "function": { - "arguments": ( - "{}" - if tool_call_data["arguments"] == "" - else tool_call_data["arguments"] - ), - "name": tool_call_data["name"], - }, - "type": "function", - "index": idx, - } - for idx, (_, tool_call_data) in enumerate(record_tools) - ] - self.dialogue.put(Message(role="assistant", tool_calls=all_tool_calls)) - - # 写入每条工具的执行结果,记录"工具返回了什么" - for result, tool_call_data in record_tools: - text = result.result or "" + if tool_content is not None: self.dialogue.put( Message( role="tool", @@ -1432,55 +1451,30 @@ class ConnectionHandler: if tool_call_data["id"] is None else tool_call_data["id"] ), - content=text, + content=tool_content, ) ) - # 用固定文本作为最终回复,补全标准三段式,保证下一条消息是 user 而非接 tool - response_parts = [] - for result, _ in record_tools: - resp = result.response or result.result - if resp: - response_parts.append(resp) - if response_parts: - self.dialogue.put(Message(role="assistant", content=",".join(response_parts))) - - if need_llm_tools: - all_tool_calls = [ - { - "id": tool_call_data["id"], - "function": { - "arguments": ( - "{}" - if tool_call_data["arguments"] == "" - else tool_call_data["arguments"] - ), - "name": tool_call_data["name"], - }, - "type": "function", - "index": idx, - } - for idx, (_, tool_call_data) in enumerate(need_llm_tools) - ] - self.dialogue.put(Message(role="assistant", tool_calls=all_tool_calls)) - - for result, tool_call_data in need_llm_tools: - text = result.result - if text is not None and len(text) > 0: - self.dialogue.put( - Message( - role="tool", - tool_call_id=( - str(uuid.uuid4()) - if tool_call_data["id"] is None - else tool_call_data["id"] - ), - content=text, - ) - ) + if record_response_parts: + self.dialogue.put( + Message(role="assistant", content=",".join(record_response_parts)) + ) + for vision_content in vision_messages: + self.dialogue.put(Message(role="user", content=vision_content)) + if need_chat: self.chat(None, depth=depth + 1) + @staticmethod + def _pop_vision_message(vision_data_key): + """Read and remove an image context cached by the vision HTTP endpoint.""" + if not vision_data_key: + return None + vision_content = cache_manager.get(CacheType.VISION_DATA, vision_data_key) + if vision_content is not None: + cache_manager.delete(CacheType.VISION_DATA, vision_data_key) + return vision_content + def _report_worker(self): """聊天记录上报工作线程""" while not self.stop_event.is_set(): diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py index 4047657be..71db5f4f4 100644 --- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py +++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py @@ -47,7 +47,6 @@ class DeviceMCPExecutor(ToolExecutor): except Exception as e: pass - # 视觉大模型不经过二次LLM处理 if ( resultJson is not None and isinstance(resultJson, dict) @@ -55,7 +54,8 @@ class DeviceMCPExecutor(ToolExecutor): ): return ActionResponse( action=Action[resultJson["action"]], - response=resultJson.get("response", ""), + result=resultJson.get("result", None), + response=resultJson.get("response", None), ) return ActionResponse(action=Action.REQLLM, result=str(result)) diff --git a/main/xiaozhi-server/core/providers/vllm/base.py b/main/xiaozhi-server/core/providers/vllm/base.py index 843873c90..d7a7518bf 100644 --- a/main/xiaozhi-server/core/providers/vllm/base.py +++ b/main/xiaozhi-server/core/providers/vllm/base.py @@ -6,6 +6,15 @@ logger = setup_logging() class VLLMProviderBase(ABC): + def use_multimodal_llm(self) -> bool: + """Whether the image should be handled by the configured main LLM. + + Most visual providers answer the vision request themselves. Providers + that return ``True`` instead add the image to the dialogue and let the + selected LLM complete the tool-call conversation. + """ + return False + @abstractmethod def response(self, question, base64_image): """VLLM response generator""" diff --git a/main/xiaozhi-server/core/providers/vllm/multimodal_llm.py b/main/xiaozhi-server/core/providers/vllm/multimodal_llm.py new file mode 100644 index 000000000..7a8b2f72b --- /dev/null +++ b/main/xiaozhi-server/core/providers/vllm/multimodal_llm.py @@ -0,0 +1,19 @@ +from core.providers.vllm.base import VLLMProviderBase + + +class VLLMProvider(VLLMProviderBase): + """Route vision requests to the currently selected multimodal LLM. + + This provider intentionally has no endpoint settings. The image and its + question are appended to the current conversation, so the normal ``LLM`` + configuration supplies the model, credentials, and response handling. + """ + + def __init__(self, config): + self.config = config + + def use_multimodal_llm(self) -> bool: + return True + + def response(self, question, base64_image): + raise RuntimeError("multimodal_llm 供应器应由主 LLM 处理图片请求") diff --git a/main/xiaozhi-server/core/utils/cache/config.py b/main/xiaozhi-server/core/utils/cache/config.py index f85e40bbf..1e17165b6 100644 --- a/main/xiaozhi-server/core/utils/cache/config.py +++ b/main/xiaozhi-server/core/utils/cache/config.py @@ -20,6 +20,7 @@ class CacheType(Enum): DEVICE_PROMPT = "device_prompt" VOICEPRINT_HEALTH = "voiceprint_health" # 声纹识别健康检查 AUDIO_DATA = "audio_data" # 音频数据缓存 + VISION_DATA = "vision_data" # 视觉工具图片缓存 @dataclass diff --git a/main/xiaozhi-server/plugins_func/register.py b/main/xiaozhi-server/plugins_func/register.py index 33a881615..f1a210ffd 100644 --- a/main/xiaozhi-server/plugins_func/register.py +++ b/main/xiaozhi-server/plugins_func/register.py @@ -29,6 +29,7 @@ class Action(Enum): RESPONSE = (2, "直接回复") REQLLM = (3, "调用函数后再请求llm生成回复") RECORD = (4, "记录工具调用到对话历史,不调用LLM") + REQMLLM = (5, "调用函数后再请求llm生成回复(llm需支持多模态)") def __init__(self, code, message): self.code = code