feat: integrate SparkBot ZGC agent and vision capture

This commit is contained in:
yanyufei 2026-08-20 09:53:24 +08:00
parent c9c1aea47f
commit da0d820065
8 changed files with 448 additions and 57 deletions

View file

@ -1,5 +1,11 @@
import json
import copy
import asyncio
import os
import re
import uuid
from datetime import datetime
from pathlib import Path
from aiohttp import web
from config.logger import setup_logging
from core.api.base_handler import BaseHandler
@ -15,6 +21,13 @@ TAG = __name__
# 设置最大文件大小为5MB
MAX_FILE_SIZE = 5 * 1024 * 1024
VISION_UPLOAD_DIR = Path(os.getenv("VISION_UPLOAD_DIR", "/uploadfile/vision"))
try:
VISION_MAX_IMAGES_PER_DEVICE = int(
os.getenv("VISION_MAX_IMAGES_PER_DEVICE", "200")
)
except ValueError:
VISION_MAX_IMAGES_PER_DEVICE = 200
class VisionHandler(BaseHandler):
@ -27,6 +40,45 @@ class VisionHandler(BaseHandler):
"""创建统一的错误响应格式"""
return {"success": False, "message": message}
def _get_image_extension(self, image_data: bytes) -> str:
if image_data.startswith(b"\xff\xd8\xff"):
return "jpg"
if image_data.startswith(b"\x89PNG\r\n\x1a\n"):
return "png"
if image_data.startswith((b"GIF87a", b"GIF89a")):
return "gif"
if image_data.startswith(b"BM"):
return "bmp"
if image_data.startswith((b"II*\x00", b"MM\x00*")):
return "tiff"
if image_data.startswith(b"RIFF") and image_data[8:12] == b"WEBP":
return "webp"
return "jpg"
def _save_image_sync(self, device_id: str, image_data: bytes) -> str:
device_key = re.sub(r"[^A-Za-z0-9_-]", "_", device_id) or "unknown"
device_dir = VISION_UPLOAD_DIR / device_key
device_dir.mkdir(parents=True, exist_ok=True)
extension = self._get_image_extension(image_data)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
filename = f"{timestamp}_{uuid.uuid4().hex[:8]}.{extension}"
image_path = device_dir / filename
image_path.write_bytes(image_data)
images = sorted(
(path for path in device_dir.iterdir() if path.is_file()),
key=lambda path: path.stat().st_mtime,
reverse=True,
)
for stale_image in images[VISION_MAX_IMAGES_PER_DEVICE:]:
stale_image.unlink(missing_ok=True)
return f"/mcp/vision/image/{device_key}/{filename}"
async def _save_image(self, device_id: str, image_data: bytes) -> str:
return await asyncio.to_thread(self._save_image_sync, device_id, image_data)
def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]:
"""验证认证token"""
# 测试模式:允许特定测试令牌或跳过验证
@ -129,10 +181,16 @@ class VisionHandler(BaseHandler):
result = vllm.response(question, image_base64)
image_url = await self._save_image(device_id, image_data)
self.logger.bind(tag=TAG).info(
f"保存视觉图片: device={device_id}, size={len(image_data)}, path={image_url}"
)
return_json = {
"success": True,
"action": Action.RESPONSE.name,
"response": result,
"image_url": image_url,
}
response = web.Response(
@ -158,6 +216,25 @@ class VisionHandler(BaseHandler):
self._add_cors_headers(response)
return response
async def handle_image_get(self, request):
"""读取已保存的视觉图片。"""
device_key = request.match_info.get("device_id", "")
filename = request.match_info.get("filename", "")
if not re.fullmatch(r"[A-Za-z0-9_-]+", device_key) or not re.fullmatch(
r"[A-Za-z0-9_-]+\.(jpg|jpeg|png|gif|bmp|tiff|webp)", filename
):
raise web.HTTPNotFound()
upload_root = VISION_UPLOAD_DIR.resolve()
image_path = (upload_root / device_key / filename).resolve()
if upload_root not in image_path.parents or not image_path.is_file():
raise web.HTTPNotFound()
response = web.FileResponse(image_path)
response.headers["Cache-Control"] = "private, max-age=86400"
self._add_cors_headers(response)
return response
async def handle_get(self, request):
"""处理 MCP Vision GET 请求"""
try:

View file

@ -1155,7 +1155,7 @@ class ConnectionHandler:
break
if self.intent_type == "function_call" and functions is not None:
content, tools_call = response
if "content" in response:
if isinstance(response, dict) and "content" in response:
content = response["content"]
tools_call = None
if content is not None and len(content) > 0:

View file

@ -217,7 +217,9 @@ def enqueue_tool_report(conn: "ConnectionHandler", tool_name: str, tool_input: d
# 构建工具结果内容
if tool_result:
result_display = f'{{"result":"{str(tool_result)}"}}'
result_display = json.dumps(
{"result": str(tool_result)}, ensure_ascii=False
)
result_content = json.dumps([{"type": "tool_result", "text": result_display}], ensure_ascii=False)
conn.report_queue.put((3, result_content, None, timestamp + 1))
except Exception as e:

View file

@ -69,6 +69,10 @@ class SimpleHttpServer:
web.post(
"/mcp/vision/explain", self.vision_handler.handle_post
),
web.get(
"/mcp/vision/image/{device_id}/{filename}",
self.vision_handler.handle_image_get,
),
web.options(
"/mcp/vision/explain", self.vision_handler.handle_options
),

View file

@ -0,0 +1,307 @@
import json
import threading
import time
import uuid
from collections import OrderedDict
import requests
from config.logger import setup_logging
from core.providers.llm.base import LLMProviderBase
TAG = __name__
logger = setup_logging()
class LLMProvider(LLMProviderBase):
"""Bridge XiaoZhi text turns to the ZGC External Agent API."""
FINAL_STATES = {"completed", "failed", "canceled"}
def __init__(self, config):
self.base_url = config.get(
"base_url", "https://agents.zgci.org/api/v1/public"
).rstrip("/")
self.api_key = config.get("api_key", "").strip()
if not self.api_key:
raise ValueError("ZGC Agent API key is required")
self.connect_timeout = float(config.get("connect_timeout", 5))
self.read_timeout = float(config.get("read_timeout", 180))
self.poll_interval = float(config.get("poll_interval", 0.5))
self.max_sessions = int(config.get("max_sessions", 512))
self.session_title = config.get("session_title", "XiaoZhi SparkBot")
self._sessions = OrderedDict()
self._sessions_lock = threading.Lock()
@property
def _headers(self):
return {"Authorization": f"Bearer {self.api_key}"}
def _request(self, method, path, **kwargs):
headers = {**self._headers, **kwargs.pop("headers", {})}
timeout = kwargs.pop(
"timeout", (self.connect_timeout, self.read_timeout)
)
response = requests.request(
method,
f"{self.base_url}{path}",
headers=headers,
timeout=timeout,
**kwargs,
)
if response.ok:
return response
try:
payload = response.json()
error = payload.get("error", {})
code = error.get("code", "http_error")
message = error.get("message", response.text)
except (ValueError, AttributeError):
code = "http_error"
message = response.text
raise ZgcApiError(response.status_code, code, message)
def _create_remote_session(self, local_session_id):
suffix = local_session_id[-12:] if local_session_id else "background"
response = self._request(
"POST",
"/sessions",
json={"title": f"{self.session_title} {suffix}"},
)
return {"session_id": response.json()["session_id"], "cursor": 0}
def _get_session(self, local_session_id, force_new=False):
if not local_session_id:
return self._create_remote_session("")
with self._sessions_lock:
if not force_new and local_session_id in self._sessions:
session = self._sessions.pop(local_session_id)
self._sessions[local_session_id] = session
return session
session = self._create_remote_session(local_session_id)
with self._sessions_lock:
self._sessions[local_session_id] = session
while len(self._sessions) > self.max_sessions:
self._sessions.popitem(last=False)
return session
def _set_cursor(self, local_session_id, session, cursor):
session["cursor"] = max(int(session.get("cursor", 0)), int(cursor or 0))
if not local_session_id:
return
with self._sessions_lock:
if self._sessions.get(local_session_id) is session:
self._sessions.move_to_end(local_session_id)
@staticmethod
def _last_user_text(dialogue):
for message in reversed(dialogue):
if message.get("role") != "user":
continue
content = message.get("content", "")
if isinstance(content, str):
if content.strip():
return content
continue
if isinstance(content, list):
parts = []
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
parts.append(str(item.get("text", "")))
text = "\n".join(part for part in parts if part.strip())
if text:
return text
raise ValueError("No user message found in dialogue")
def _submit_turn(self, remote_session_id, text):
response = self._request(
"POST",
f"/sessions/{remote_session_id}/messages",
headers={"Idempotency-Key": str(uuid.uuid4())},
json={"text": text},
)
return response.json()["turn_id"]
@staticmethod
def _iter_sse(response):
event_name = None
event_id = None
data_lines = []
for raw_line in response.iter_lines(decode_unicode=True):
line = raw_line.decode("utf-8") if isinstance(raw_line, bytes) else raw_line
if line == "":
if data_lines:
yield event_name, event_id, "\n".join(data_lines)
event_name = None
event_id = None
data_lines = []
continue
if not line or line.startswith(":"):
continue
field, separator, value = line.partition(":")
if not separator:
continue
value = value[1:] if value.startswith(" ") else value
if field == "event":
event_name = value
elif field == "id":
event_id = value
elif field == "data":
data_lines.append(value)
if data_lines:
yield event_name, event_id, "\n".join(data_lines)
def _stream_turn(self, local_session_id, session, turn_id):
start_cursor = int(session.get("cursor", 0))
response = self._request(
"GET",
f"/sessions/{session['session_id']}/stream",
headers={"Last-Event-ID": str(start_cursor)},
stream=True,
timeout=(self.connect_timeout, self.read_timeout),
)
emitted = ""
final_state = None
stored_messages = []
max_cursor = start_cursor
try:
for event_name, event_id, raw_data in self._iter_sse(response):
if event_id:
try:
max_cursor = max(max_cursor, int(event_id))
except ValueError:
pass
try:
envelope = json.loads(raw_data)
except json.JSONDecodeError:
logger.bind(tag=TAG).warning("Ignored malformed ZGC SSE frame")
continue
frame_turn_id = envelope.get("turn_id")
frame_type = envelope.get("type") or event_name
frame_data = envelope.get("data") or {}
if frame_turn_id == turn_id and frame_type == "delta":
text = frame_data.get("text", "")
if text:
emitted += text
yield text
elif frame_turn_id == turn_id and frame_type == "message":
text = frame_data.get("text", "")
if text:
stored_messages.append(text)
elif frame_turn_id == turn_id and frame_type == "turn_state":
state = frame_data.get("state") or envelope.get("state")
if state in self.FINAL_STATES:
final_state = state
finally:
response.close()
self._set_cursor(local_session_id, session, max_cursor)
final_state = final_state or self._wait_for_turn(session["session_id"], turn_id)
if final_state != "completed":
raise RuntimeError(f"ZGC Agent turn ended with state: {final_state}")
final_text, next_cursor = self._fetch_final_message(
session["session_id"], turn_id, start_cursor
)
self._set_cursor(local_session_id, session, next_cursor)
if not final_text and stored_messages:
final_text = stored_messages[-1]
if final_text.startswith(emitted):
remainder = final_text[len(emitted) :]
if remainder:
yield remainder
elif not emitted and final_text:
yield final_text
elif final_text and final_text != emitted:
logger.bind(tag=TAG).warning(
"ZGC stored message did not match the emitted delta prefix"
)
def _wait_for_turn(self, remote_session_id, turn_id):
deadline = time.monotonic() + self.read_timeout
while time.monotonic() < deadline:
response = self._request(
"GET", f"/sessions/{remote_session_id}/turns/{turn_id}"
)
state = response.json().get("state")
if state in self.FINAL_STATES:
return state
time.sleep(self.poll_interval)
raise TimeoutError("Timed out waiting for ZGC Agent turn")
def _fetch_final_message(self, remote_session_id, turn_id, after_id):
messages = []
cursor = int(after_id)
while True:
response = self._request(
"GET",
f"/sessions/{remote_session_id}/events",
params={"after_id": cursor, "limit": 500},
)
payload = response.json()
for event in payload.get("events", []):
event_id = int(event.get("event_id") or 0)
cursor = max(cursor, event_id)
if (
event.get("turn_id") == turn_id
and event.get("role") == "agent"
and event.get("type") == "message"
):
text = (event.get("data") or {}).get("text", "")
if text:
messages.append(text)
next_cursor = payload.get("next_after_id")
if next_cursor is not None:
cursor = max(cursor, int(next_cursor))
if not payload.get("has_more"):
break
return (messages[-1] if messages else ""), cursor
def _cancel_turn(self, remote_session_id, turn_id):
try:
self._request(
"POST", f"/sessions/{remote_session_id}/turns/{turn_id}/cancel"
)
except Exception as error:
logger.bind(tag=TAG).warning(f"Failed to cancel ZGC turn: {error}")
def response(self, session_id, dialogue, **kwargs):
text = self._last_user_text(dialogue)
session = self._get_session(session_id)
try:
turn_id = self._submit_turn(session["session_id"], text)
except ZgcApiError as error:
if error.status_code != 404:
raise
session = self._get_session(session_id, force_new=True)
turn_id = self._submit_turn(session["session_id"], text)
completed = False
try:
yield from self._stream_turn(session_id, session, turn_id)
completed = True
finally:
if not completed:
self._cancel_turn(session["session_id"], turn_id)
class ZgcApiError(RuntimeError):
def __init__(self, status_code, code, message):
super().__init__(f"ZGC API error {status_code} {code}: {message}")
self.status_code = status_code
self.code = code

View file

@ -55,6 +55,7 @@ class DeviceMCPExecutor(ToolExecutor):
):
return ActionResponse(
action=Action[resultJson["action"]],
result=result,
response=resultJson.get("response", ""),
)

View file

@ -1,5 +1,6 @@
import openai
import json
import re
from config.logger import setup_logging
from core.utils.util import check_model_key
from core.providers.vllm.base import VLLMProviderBase
@ -7,6 +8,21 @@ from core.providers.vllm.base import VLLMProviderBase
TAG = __name__
logger = setup_logging()
VISION_RESPONSE_INSTRUCTION = (
"\n请只用中文一到两句话回答,最多80个汉字;"
"不要使用标题、列表、Markdown,也不要补充与画面无关的信息。"
)
def limit_vision_response(text, max_chars=80):
normalized = re.sub(r"\s+", " ", text or "").strip()
normalized = re.sub(r"[*#`]", "", normalized)
sentences = [part for part in re.split(r"(?<=[。!?!?])", normalized) if part]
limited = "".join(sentences[:2]).strip() if sentences else normalized
if len(limited) > max_chars:
limited = limited[: max_chars - 1].rstrip(",,;;、 ") + "。"
return limited
class VLLMProvider(VLLMProviderBase):
def __init__(self, config):
@ -40,7 +56,7 @@ class VLLMProvider(VLLMProviderBase):
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url)
def response(self, question, base64_image):
question = question + "(请使用中文回复)"
question = question + VISION_RESPONSE_INSTRUCTION
try:
messages = [
{
@ -58,10 +74,14 @@ class VLLMProvider(VLLMProviderBase):
]
response = self.client.chat.completions.create(
model=self.model_name, messages=messages, stream=False
model=self.model_name,
messages=messages,
stream=False,
temperature=self.temperature,
top_p=self.top_p,
)
return response.choices[0].message.content
return limit_vision_response(response.choices[0].message.content)
except Exception as e:
logger.bind(tag=TAG).error(f"Error in response generation: {e}")

View file

@ -16,38 +16,39 @@ def initialize_modules(
init_memory=False,
init_intent=False,
) -> Dict[str, Any]:
"""
初始化所有模块组件
Args:
config: 配置字典
Returns:
Dict[str, Any]: 包含所有初始化后的模块的字典
"""
modules = {}
# 初始化TTS模块
if init_tts:
select_tts_module = config["selected_module"]["TTS"]
modules["tts"] = initialize_tts(config)
logger.bind(tag=TAG).info(f"初始化组件: tts成功 {select_tts_module}")
# 初始化LLM模块
if init_llm:
select_llm_module = config["selected_module"]["LLM"]
llm_type = (
select_llm_module
if "type" not in config["LLM"][select_llm_module]
else config["LLM"][select_llm_module]["type"]
)
modules["llm"] = llm.create_instance(
llm_type,
config["LLM"][select_llm_module],
)
selected_config = config["LLM"][select_llm_module].copy()
llm_type = selected_config.get("type", select_llm_module)
if llm_type == "hybrid_router":
for role in ("chat", "tool", "router"):
model_id = selected_config.get(f"{role}_model")
# The manager API returns the selected model and its direct
# dependencies, but may omit a nested hybrid backend. The
# hybrid config carries that backend as a fallback.
model_config = config["LLM"].get(model_id) or selected_config.get(
f"{role}_provider_config"
)
if not model_config:
raise ValueError(
f"Hybrid router is missing a valid {role}_model: {model_id}"
)
selected_config[f"{role}_provider_type"] = selected_config.get(
f"{role}_provider_type", model_config.get("type", model_id)
)
selected_config[f"{role}_provider_config"] = model_config.copy()
modules["llm"] = llm.create_instance(llm_type, selected_config)
logger.bind(tag=TAG).info(f"初始化组件: llm成功 {select_llm_module}")
# 初始化Intent模块
if init_intent:
select_intent_module = config["selected_module"]["Intent"]
intent_type = (
@ -56,12 +57,10 @@ def initialize_modules(
else config["Intent"][select_intent_module]["type"]
)
modules["intent"] = intent.create_instance(
intent_type,
config["Intent"][select_intent_module],
intent_type, config["Intent"][select_intent_module]
)
logger.bind(tag=TAG).info(f"初始化组件: intent成功 {select_intent_module}")
# 初始化Memory模块
if init_memory:
select_memory_module = config["selected_module"]["Memory"]
memory_type = (
@ -74,9 +73,7 @@ def initialize_modules(
config["Memory"][select_memory_module],
config.get("summaryMemory", None),
)
logger.bind(tag=TAG).info(f"初始化组件: memory成功 {select_memory_module}")
# 初始化VAD模块
if init_vad:
select_vad_module = config["selected_module"]["VAD"]
vad_type = (
@ -84,13 +81,8 @@ def initialize_modules(
if "type" not in config["VAD"][select_vad_module]
else config["VAD"][select_vad_module]["type"]
)
modules["vad"] = vad.create_instance(
vad_type,
config["VAD"][select_vad_module],
)
logger.bind(tag=TAG).info(f"初始化组件: vad成功 {select_vad_module}")
modules["vad"] = vad.create_instance(vad_type, config["VAD"][select_vad_module])
# 初始化ASR模块
if init_asr:
select_asr_module = config["selected_module"]["ASR"]
modules["asr"] = initialize_asr(config)
@ -102,29 +94,21 @@ def initialize_tts(config):
select_tts_module = config["selected_module"]["TTS"]
tts_config = config["TTS"][select_tts_module].copy()
tts_config.setdefault("tts_timeout", config.get("tts_timeout", 15))
tts_type = (
select_tts_module
if "type" not in tts_config
else tts_config["type"]
)
new_tts = tts.create_instance(
tts_type = tts_config.get("type", select_tts_module)
return tts.create_instance(
tts_type,
tts_config,
str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"),
)
return new_tts
def initialize_asr(config):
select_asr_module = config["selected_module"]["ASR"]
asr_type = (
select_asr_module
if "type" not in config["ASR"][select_asr_module]
else config["ASR"][select_asr_module]["type"]
)
asr_config = config["ASR"][select_asr_module]
asr_type = asr_config.get("type", select_asr_module)
new_asr = asr.create_instance(
asr_type,
config["ASR"][select_asr_module],
asr_config,
str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"),
)
logger.bind(tag=TAG).info("ASR模块初始化完成")
@ -132,21 +116,17 @@ def initialize_asr(config):
def initialize_voiceprint(asr_instance, config):
"""初始化声纹识别功能"""
voiceprint_config = config.get("voiceprint")
if not voiceprint_config:
return False
# 应用配置
return False
if not voiceprint_config.get("url") or not voiceprint_config.get("speakers"):
logger.bind(tag=TAG).warning("声纹识别配置不完整")
return False
try:
asr_instance.init_voiceprint(voiceprint_config)
logger.bind(tag=TAG).info("ASR模块声纹识别功能已动态启用")
logger.bind(tag=TAG).info(f"配置说话人数量: {len(voiceprint_config['speakers'])}")
return True
except Exception as e:
logger.bind(tag=TAG).error(f"动态初始化声纹识别功能失败: {str(e)}")
except Exception as error:
logger.bind(tag=TAG).error(f"动态初始化声纹识别功能失败: {str(error)}")
return False