mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: 将视觉信息加入主LLM的上下文,由主LLM进行处理
This commit is contained in:
parent
27e57631a7
commit
ef6dbd6c33
10 changed files with 203 additions and 86 deletions
|
|
@ -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';
|
||||||
|
|
@ -711,3 +711,10 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/202607101200.sql
|
path: classpath:db/changelog/202607101200.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202608161000
|
||||||
|
author: ganyouxuan
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202608161000.sql
|
||||||
|
|
|
||||||
|
|
@ -744,6 +744,9 @@ LLM:
|
||||||
base_url: http://localhost:9997 # Xinference服务地址
|
base_url: http://localhost:9997 # Xinference服务地址
|
||||||
# VLLM配置(视觉语言大模型)
|
# VLLM配置(视觉语言大模型)
|
||||||
VLLM:
|
VLLM:
|
||||||
|
MultimodalLLM:
|
||||||
|
# 复用当前选中的 LLM 处理图片;该 LLM 须支持 OpenAI 兼容的多模态消息。
|
||||||
|
type: multimodal_llm
|
||||||
ChatGLMVLLM:
|
ChatGLMVLLM:
|
||||||
type: openai
|
type: openai
|
||||||
# glm-4v-flash是智谱免费AI的视觉模型,需要先在智谱AI平台创建API密钥并获取api_key
|
# glm-4v-flash是智谱免费AI的视觉模型,需要先在智谱AI平台创建API密钥并获取api_key
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import json
|
import json
|
||||||
import copy
|
import copy
|
||||||
|
import uuid
|
||||||
from aiohttp import web
|
from aiohttp import web
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.api.base_handler import BaseHandler
|
from core.api.base_handler import BaseHandler
|
||||||
|
|
@ -10,6 +11,8 @@ from core.utils.auth import AuthToken
|
||||||
import base64
|
import base64
|
||||||
from typing import Tuple, Optional
|
from typing import Tuple, Optional
|
||||||
from plugins_func.register import Action
|
from plugins_func.register import Action
|
||||||
|
from core.utils.cache.config import CacheType
|
||||||
|
from core.utils.cache.manager import cache_manager
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
@ -44,6 +47,50 @@ class VisionHandler(BaseHandler):
|
||||||
token = auth_header[7:] # 移除"Bearer "前缀
|
token = auth_header[7:] # 移除"Bearer "前缀
|
||||||
return self.auth.verify_token(token)
|
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):
|
async def handle_post(self, request):
|
||||||
"""处理 MCP Vision POST 请求"""
|
"""处理 MCP Vision POST 请求"""
|
||||||
response = None # 初始化response变量
|
response = None # 初始化response变量
|
||||||
|
|
@ -126,9 +173,24 @@ class VisionHandler(BaseHandler):
|
||||||
vllm = create_instance(
|
vllm = create_instance(
|
||||||
vllm_type, current_config["VLLM"][select_vllm_module]
|
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
|
||||||
|
)
|
||||||
|
|
||||||
|
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)
|
result = vllm.response(question, image_base64)
|
||||||
|
|
||||||
return_json = {
|
return_json = {
|
||||||
"success": True,
|
"success": True,
|
||||||
"action": Action.RESPONSE.name,
|
"action": Action.RESPONSE.name,
|
||||||
|
|
|
||||||
|
|
@ -45,6 +45,8 @@ from core.utils.prompt_manager import PromptManager
|
||||||
from core.utils.voiceprint_provider import VoiceprintProvider
|
from core.utils.voiceprint_provider import VoiceprintProvider
|
||||||
from core.utils.util import get_system_error_response
|
from core.utils.util import get_system_error_response
|
||||||
from core.utils import textUtils
|
from core.utils import textUtils
|
||||||
|
from core.utils.cache.config import CacheType
|
||||||
|
from core.utils.cache.manager import cache_manager
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
@ -1374,15 +1376,37 @@ class ConnectionHandler:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def _handle_function_result(self, tool_results, depth, streamed_text=""):
|
def _handle_function_result(self, tool_results, depth, streamed_text=""):
|
||||||
need_llm_tools = []
|
tool_actions = {
|
||||||
record_tools = []
|
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:
|
for result, tool_call_data in tool_results:
|
||||||
if result.action in [
|
if result.action in (
|
||||||
Action.RESPONSE,
|
Action.RESPONSE,
|
||||||
Action.NOTFOUND,
|
Action.NOTFOUND,
|
||||||
Action.ERROR,
|
Action.ERROR,
|
||||||
]:
|
):
|
||||||
text = result.response if result.response else result.result
|
text = result.response if result.response else result.result
|
||||||
if streamed_text and text in streamed_text:
|
if streamed_text and text in streamed_text:
|
||||||
self.logger.bind(tag=TAG).debug(
|
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.tts_one_sentence(self, ContentType.TEXT, content_detail=text)
|
||||||
self.tts.store_tts_text(self.sentence_id, text)
|
self.tts.store_tts_text(self.sentence_id, text)
|
||||||
self.dialogue.put(Message(role="assistant", content=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:
|
elif result.action == Action.REQLLM:
|
||||||
need_llm_tools.append((result, tool_call_data))
|
tool_content = result.result or ""
|
||||||
elif result.action == Action.RECORD:
|
need_chat = True
|
||||||
record_tools.append((result, tool_call_data))
|
elif result.action == Action.REQMLLM:
|
||||||
else:
|
tool_content = ""
|
||||||
pass
|
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))
|
if tool_content is not None:
|
||||||
# 模型从历史中学到工具调用模式,不额外调用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 ""
|
|
||||||
self.dialogue.put(
|
self.dialogue.put(
|
||||||
Message(
|
Message(
|
||||||
role="tool",
|
role="tool",
|
||||||
|
|
@ -1432,55 +1451,30 @@ class ConnectionHandler:
|
||||||
if tool_call_data["id"] is None
|
if tool_call_data["id"] is None
|
||||||
else tool_call_data["id"]
|
else tool_call_data["id"]
|
||||||
),
|
),
|
||||||
content=text,
|
content=tool_content,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
# 用固定文本作为最终回复,补全标准三段式,保证下一条消息是 user 而非接 tool
|
if record_response_parts:
|
||||||
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(
|
self.dialogue.put(
|
||||||
Message(
|
Message(role="assistant", content=",".join(record_response_parts))
|
||||||
role="tool",
|
|
||||||
tool_call_id=(
|
|
||||||
str(uuid.uuid4())
|
|
||||||
if tool_call_data["id"] is None
|
|
||||||
else tool_call_data["id"]
|
|
||||||
),
|
|
||||||
content=text,
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
for vision_content in vision_messages:
|
||||||
|
self.dialogue.put(Message(role="user", content=vision_content))
|
||||||
|
|
||||||
|
if need_chat:
|
||||||
self.chat(None, depth=depth + 1)
|
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):
|
def _report_worker(self):
|
||||||
"""聊天记录上报工作线程"""
|
"""聊天记录上报工作线程"""
|
||||||
while not self.stop_event.is_set():
|
while not self.stop_event.is_set():
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,6 @@ class DeviceMCPExecutor(ToolExecutor):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 视觉大模型不经过二次LLM处理
|
|
||||||
if (
|
if (
|
||||||
resultJson is not None
|
resultJson is not None
|
||||||
and isinstance(resultJson, dict)
|
and isinstance(resultJson, dict)
|
||||||
|
|
@ -55,7 +54,8 @@ class DeviceMCPExecutor(ToolExecutor):
|
||||||
):
|
):
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action[resultJson["action"]],
|
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))
|
return ActionResponse(action=Action.REQLLM, result=str(result))
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,15 @@ logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class VLLMProviderBase(ABC):
|
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
|
@abstractmethod
|
||||||
def response(self, question, base64_image):
|
def response(self, question, base64_image):
|
||||||
"""VLLM response generator"""
|
"""VLLM response generator"""
|
||||||
|
|
|
||||||
19
main/xiaozhi-server/core/providers/vllm/multimodal_llm.py
Normal file
19
main/xiaozhi-server/core/providers/vllm/multimodal_llm.py
Normal file
|
|
@ -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 处理图片请求")
|
||||||
|
|
@ -20,6 +20,7 @@ class CacheType(Enum):
|
||||||
DEVICE_PROMPT = "device_prompt"
|
DEVICE_PROMPT = "device_prompt"
|
||||||
VOICEPRINT_HEALTH = "voiceprint_health" # 声纹识别健康检查
|
VOICEPRINT_HEALTH = "voiceprint_health" # 声纹识别健康检查
|
||||||
AUDIO_DATA = "audio_data" # 音频数据缓存
|
AUDIO_DATA = "audio_data" # 音频数据缓存
|
||||||
|
VISION_DATA = "vision_data" # 视觉工具图片缓存
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ class Action(Enum):
|
||||||
RESPONSE = (2, "直接回复")
|
RESPONSE = (2, "直接回复")
|
||||||
REQLLM = (3, "调用函数后再请求llm生成回复")
|
REQLLM = (3, "调用函数后再请求llm生成回复")
|
||||||
RECORD = (4, "记录工具调用到对话历史,不调用LLM")
|
RECORD = (4, "记录工具调用到对话历史,不调用LLM")
|
||||||
|
REQMLLM = (5, "调用函数后再请求llm生成回复(llm需支持多模态)")
|
||||||
|
|
||||||
def __init__(self, code, message):
|
def __init__(self, code, message):
|
||||||
self.code = code
|
self.code = code
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue