JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
创建文件和回传
xiaoxiawang11da53e17b61
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex b20b2ed4db..32314ae166 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -22,6 +22,7 @@ from openjiuwen.core.session.checkpointer.persistence import PersistenceCheckpoifrom jiuwenclaw.agentserver.prompt_builder import build_system_promptfrom jiuwenclaw.agentserver.tools.multi_session_toolkits import MultiSessionToolkit+from jiuwenclaw.agentserver.tools import SendFileToolkitfrom jiuwenclaw.agentserver.prompt_builder import build_system_prompt, build_user_promptfrom jiuwenclaw.gateway.cron import CronController, CronTargetChannelfrom jiuwenclaw.utils import (@@ -132,6 +133,7 @@ class JiuWenClaw:self._memory_tools_registered: bool = Falseself._mcp_tools_registered: bool = Falseself._video_tool_registered: bool = False+ self._send_file_tool_registered: bool = Falseself._todo_tool_sessions_registered: set[str] = set()self._sysop_card_id: str | None = None@@ -449,6 +451,18 @@ class JiuWenClaw:for tool in session_toolkits.get_tools():Runner.resource_mgr.add_tool(tool)self._instance.ability_manager.add(tool.card)++ # Register send file toolkit+ if not self._send_file_tool_registered:+ send_file_toolkit = SendFileToolkit(+ request_id=request_id,+ session_id=effective_session_id,+ channel_id=channel_id,+ )+ for tool in send_file_toolkit.get_tools():+ Runner.resource_mgr.add_tool(tool)+ self._instance.ability_manager.add(tool.card)+ self._send_file_tool_registered = True# tool_list = self._instance.ability_manager.list()# for tool in tool_list:# if isinstance(tool, ToolCard):diff --git a/jiuwenclaw/agentserver/tools/__init__.py b/jiuwenclaw/agentserver/tools/__init__.pyindex 53ef779105..7379bdfe51 100644--- a/jiuwenclaw/agentserver/tools/__init__.py+++ b/jiuwenclaw/agentserver/tools/__init__.py@@ -13,6 +13,10 @@ from .memory_tools import (read_memory,)+from .send_file_to_user import (+ SendFileToolkit,+)+__all__ = ["set_global_memory_manager","init_memory_manager_async",@@ -22,4 +26,5 @@ __all__ = ["write_memory","edit_memory","read_memory",+ "SendFileToolkit",]diff --git a/jiuwenclaw/agentserver/tools/send_file_to_user.py b/jiuwenclaw/agentserver/tools/send_file_to_user.pynew file mode 100644index 0000000000..5b8eb7fb1f--- /dev/null+++ b/jiuwenclaw/agentserver/tools/send_file_to_user.py@@ -0,0 +1,126 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Send File Toolkit++提供发送文件到用户的工具。支持发送一个或多个文件。++使用方式:+1. 创建 SendFileToolkit 实例+2. 调用 get_tools() 获取工具列表+3. 工具会自动注册到 Runner 中+"""++from __future__ import annotations++from typing import List++from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard++from jiuwenclaw.agentserver.agent_ws_server import AgentWebSocketServer+from jiuwenclaw.utils import logger+++class SendFileToolkit:+ """Toolkit for sending files to users."""++ def __init__(self, request_id: str, session_id: str, channel_id: str) -> None:+ """Initialize SendFileToolkit.++ Args:+ request_id: Request identifier for message routing.+ session_id: Session identifier for message routing.+ channel_id: Channel identifier for message routing.+ """+ self.request_id = request_id+ self.session_id = session_id+ self.channel_id = channel_id+ logger.debug(+ "[SendFileToolkit] 初始化 request_id=%s session_id=%s channel_id=%s",+ request_id,+ session_id,+ channel_id,+ )++ async def send_file(self, abs_file_path_list: List[str]) -> str:+ """Send files to user.++ Args:+ abs_file_path_list: List of absolute file paths to send.++ Returns:+ Success message or error description.+ """+ logger.info(+ "[SendFileToolkit] send_file 开始 session_id=%s 文件数=%d",+ self.session_id,+ len(abs_file_path_list),+ )++ try:+ server = AgentWebSocketServer.get_instance()+ msg = {+ "request_id": self.request_id,+ "channel_id": self.channel_id,+ "payload": {+ "event_type": "chat.file",+ "files": abs_file_path_list,+ },+ "is_complete": False,+ }+ await server.send_push(msg)+ logger.info(+ "[SendFileToolkit] send_file 完成 session_id=%s",+ self.session_id,+ )+ return f"成功发送 {len(abs_file_path_list)} 个文件"+ except Exception as e:+ logger.exception(+ "[SendFileToolkit] send_file 失败 session_id=%s error=%s",+ self.session_id,+ str(e),+ )+ return f"发送文件失败: {str(e)}"++ def get_tools(self) -> List[Tool]:+ """Return tools for registration in Runner.++ Returns:+ List of tools for sending files.+ """+ session_id = self.session_id++ def make_tool(+ name: str,+ description: str,+ input_params: dict,+ func,+ ) -> Tool:+ card = ToolCard(+ id=f"{name}_{session_id}_{self.request_id}",+ name=name,+ description=description,+ input_params=input_params,+ )+ return LocalFunction(card=card, func=func)++ return [+ make_tool(+ name="send_file_to_user",+ description=(+ "发送文件给用户。支持发送一个或多个文件。"+ "需要提供文件的绝对路径列表。"+ ),+ input_params={+ "type": "object",+ "properties": {+ "abs_file_path_list": {+ "type": "array",+ "items": {"type": "string"},+ "description": "要发送的文件绝对路径列表",+ }+ },+ "required": ["abs_file_path_list"],+ },+ func=self.send_file,+ ),+ ]diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.pyindex 8b95cfe74b..790cdc2efc 100644--- a/jiuwenclaw/app.py+++ b/jiuwenclaw/app.py@@ -310,7 +310,9 @@ def _register_web_handlers(val = params[param_key]if param_key.endswith("_provider") and val and val not in available_model_providers:await channel.send_response(- ws, req_id, ok=False, error=f"Model provider must in: {available_model_providers} ", code="BAD_REQUEST"+ ws, req_id, ok=False,+ error=f"Model provider must in: {available_model_providers} ",+ code="BAD_REQUEST")returnif val is None:diff --git a/jiuwenclaw/channel/xiaoyi_channel.py b/jiuwenclaw/channel/xiaoyi_channel.pyindex 4c2986ff93..525e311dcb 100644--- a/jiuwenclaw/channel/xiaoyi_channel.py+++ b/jiuwenclaw/channel/xiaoyi_channel.py@@ -10,12 +10,15 @@ import hmacimport hashlibimport inspectimport json-import time+import osimport ssl+import timefrom dataclasses import dataclass-from typing import Any, Callable+from typing import Any, Callable, Optionalfrom urllib.parse import urlparse+import aiohttp+from jiuwenclaw.utils import loggerfrom jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenclaw.schema.message import EventType, Message, ReqMethod@@ -45,6 +48,10 @@ class XiaoyiChannelConfig:task_timeout_ms: int = 3600000# Session cleanup timeout in milliseconds (default: 1 hour)session_cleanup_timeout_ms: int = 3600000+ # File upload service configuration+ file_upload_base_url: str = ""+ file_upload_api_key: str = ""+ file_upload_uid: str = ""def _generate_signature(sk: str, timestamp: str) -> str:@@ -57,6 +64,99 @@ def _generate_signature(sk: str, timestamp: str) -> str:return base64.b64encode(h.digest()).decode("utf-8")+class XYFileUploadService:+ def __init__(self, base_url: str, api_key: str, uid: str):+ self.base_url = base_url.rstrip('/')+ self.api_key = api_key+ self.uid = uid+ self.session = None++ async def __aenter__(self):+ self.session = aiohttp.ClientSession()+ return self++ async def __aexit__(self, exc_type, exc_val, exc_tb):+ await self.session.close()++ async def upload_file(self, file_path: str, object_type: str = "TEMPORARY_MATERIAL_DOC") -> Optional[str]:+ try:+ with open(file_path, 'rb') as f:+ file_content = f.read()++ file_name = os.path.basename(file_path)+ file_size = len(file_content)+ file_sha256 = hashlib.sha256(file_content).hexdigest()++ prepare_url = f"{self.base_url}/osms/v1/file/manager/prepare"+ prepare_data = {+ "objectType": object_type,+ "fileName": file_name,+ "fileSha256": file_sha256,+ "fileSize": file_size,+ "fileOwnerInfo": {+ "uid": self.uid,+ "teamId": self.uid,+ },+ "useEdge": False,+ }++ headers = {+ "Content-Type": "application/json",+ "x-uid": self.uid,+ "x-api-key": self.api_key,+ "x-request-from": "openclaw",+ }++ async with self.session.post(prepare_url, json=prepare_data, headers=headers) as resp:+ if not resp.ok:+ raise Exception(f"Prepare failed: HTTP {resp.status}")++ prepare_resp = await resp.json()+ if prepare_resp.get("code") != "0":+ raise Exception(f"Prepare failed: {prepare_resp.get('desc', 'Unknown error')}")++ object_id = prepare_resp.get("objectId")+ draft_id = prepare_resp.get("draftId")+ upload_infos = prepare_resp.get("uploadInfos", [])++ if not upload_infos:+ raise Exception("No upload information returned")++ upload_info = upload_infos[0]+ upload_url = upload_info.get("url")+ upload_method = upload_info.get("method", "PUT")+ upload_headers = upload_info.get("headers", {})++ async with self.session.request(+ upload_method,+ upload_url,+ data=file_content,+ headers=upload_headers+ ) as resp:+ if not resp.ok:+ raise Exception(f"Upload failed: HTTP {resp.status}")++ complete_url = f"{self.base_url}/osms/v1/file/manager/complete"+ complete_data = {+ "objectId": object_id,+ "draftId": draft_id,+ }++ async with self.session.post(complete_url, json=complete_data, headers=headers) as resp:+ if not resp.ok:+ raise Exception(f"Complete failed: HTTP {resp.status}")++ complete_resp = await resp.json()+ if complete_resp.get("code") != "0":+ raise Exception(f"Complete failed: {complete_resp.get('desc', 'Unknown error')}")++ return object_id++ except Exception as e:+ logger.error(f"[XY File Upload] Error: {e}")+ return None++def _generate_auth_headers(config: XiaoyiChannelConfig) -> dict[str, str]:"""生成鉴权 Header."""if config.mode == "xiaoyi_claw":@@ -103,6 +203,15 @@ class XiaoyiChannel(BaseChannel):self._sessions_waiting_for_push: dict[str, str] = {} # {session: task} waiting for push# Session cleanup managementself._sessions_marked_for_cleanup: dict[str, dict[str, Any]] = {} # Session cleanup state+ # File upload service configuration+ self.file_upload_config = {+ "baseUrl": config.file_upload_base_url,+ "apiKey": config.file_upload_api_key,+ "uid": config.file_upload_uid,+ }+ # Save additional configuration fields+ self.api_id = config.api_id+ self.push_id = config.push_idself._accumulated_texts: dict[str, str] = {} # Accumulated text per session for push notification@property@@ -204,6 +313,30 @@ class XiaoyiChannel(BaseChannel):if not self._ws_connections:returnsession_id, task_id = self._extract_platform_receive_info(msg)++ # Handle chat.file event+ if msg.event_type == EventType.CHAT_FILE:+ files = msg.payload.get("files", []) if isinstance(msg.payload, dict) else []+ if files:+ for file_info in files:+ # Convert file path to file info dict if it's a string+ if isinstance(file_info, str):+ file_info = {+ "success": True,+ "result_type": "file_created",+ "fullPath": file_info,+ "path": os.path.basename(file_info),+ "fileName": os.path.basename(file_info)+ }++ # Send file response+ for url_key, ws in self._ws_connections.items():+ if ws:+ try:+ await self._send_file_response(session_id, task_id, file_info, url_key)+ except Exception as e:+ logger.warning(f"XiaoyiChannel 发送文件响应失败 ({url_key}): {e}")+ returnlogger.info(f"XiaoyiChannel 发送消息: {msg}")content = ""@@ -788,6 +921,189 @@ class XiaoyiChannel(BaseChannel):except Exception as e:logger.warning(f"XiaoyiChannel 发送响应失败 ({url_key}): {e}")+ async def _send_file_response_base64(self, session_id: str, task_id: str, file_info: dict, url_key: str) -> None:+ """发送文件响应(Base64 格式)到指定通道."""+ try:+ file_name = file_info.get("fileName", os.path.basename(file_info.get("path", "file.txt")))+ file_path = file_info.get("fullPath", file_info.get("path", file_name))++ # Check if file exists+ if not os.path.exists(file_path):+ logger.error(f"XiaoyiChannel 文件不存在: {file_path}")+ return++ # Check file size (limit to 20MB for Base64)+ file_size = os.path.getsize(file_path)+ if file_size > 20 * 1024 * 1024: # 20MB limit+ logger.error(f"XiaoyiChannel 文件过大,使用OSMS上传: {file_path}")+ # Use OSMS upload for large files+ base_url = self.file_upload_config.get("baseUrl")+ api_key = self.file_upload_config.get("apiKey")+ uid = self.file_upload_config.get("uid")++ if not all([base_url, api_key, uid]):+ logger.error("XiaoyiChannel OSMS配置不完整,无法上传大文件")+ return++ async with XYFileUploadService(base_url, api_key, uid) as upload_service:+ object_id = await upload_service.upload_file(file_path)+ if object_id:+ # Send file reference response+ response = {+ "jsonrpc": "2.0",+ "id": f"msg_{int(time.time() * 1000)}",+ "result": {+ "taskId": task_id,+ "kind": "artifact-update",+ "append": False,+ "lastChunk": True,+ "isFinal": True,+ "artifact": {+ "artifactId": f"artifact_{int(time.time() * 1000)}",+ "parts": [+ {+ "kind": "artifact",+ "artifact": {+ "kind": "file",+ "file": {+ "objectId": object_id,+ "fileName": file_name,+ "contentType": "application/octet-stream"+ }+ }+ }+ ],+ },+ },+ }+ await self._safe_ws_send(url_key, response)+ return++ # Read file content as Base64+ with open(file_path, "rb") as f:+ file_content = f.read()++ base64_content = base64.b64encode(file_content).decode("utf-8")++ # Guess content type+ import mimetypes+ content_type, _ = mimetypes.guess_type(file_name)+ if not content_type:+ content_type = "application/octet-stream"++ # Send file response+ response = {+ "jsonrpc": "2.0",+ "id": f"msg_{int(time.time() * 1000)}",+ "result": {+ "taskId": task_id,+ "kind": "artifact-update",+ "append": False,+ "lastChunk": True,+ "isFinal": True,+ "artifact": {+ "artifactId": f"artifact_{int(time.time() * 1000)}",+ "parts": [+ {+ "kind": "file",+ "file": {+ "name": file_name,+ "contentType": content_type,+ "data": base64_content+ }+ }+ ],+ },+ },+ }+ await self._safe_ws_send(url_key, response)+ except Exception as e:+ logger.error(f"XiaoyiChannel 发送文件响应失败: {e}")++ async def _send_file_response(self, session_id: str, task_id: str, file_info: dict, url_key: str) -> None:+ """发送文件响应到指定通道."""+ try:+ # Check if file info has content (Base64)+ if file_info.get("content") and isinstance(file_info["content"], str):+ # This is a file with Base64 content+ file_name = file_info.get("fileName", "file.txt")+ content_type = file_info.get("contentType", "application/octet-stream")+ base64_content = file_info["content"]++ # Send file response with Base64 content+ response = {+ "jsonrpc": "2.0",+ "id": f"msg_{int(time.time() * 1000)}",+ "result": {+ "taskId": task_id,+ "kind": "artifact-update",+ "append": False,+ "lastChunk": True,+ "isFinal": True,+ "artifact": {+ "artifactId": f"artifact_{int(time.time() * 1000)}",+ "parts": [+ {+ "kind": "file",+ "file": {+ "name": file_name,+ "contentType": content_type,+ "data": base64_content+ }+ }+ ],+ },+ },+ }+ await self._safe_ws_send(url_key, response)+ return++ # If file is available locally, send as Base64+ if file_info.get("fullPath") or file_info.get("path"):+ await self._send_file_response_base64(session_id, task_id, file_info, url_key)+ return++ # If file is already uploaded to OSMS+ if file_info.get("objectId"):+ file_name = file_info.get("fileName", "file.txt")+ content_type = file_info.get("contentType", "application/octet-stream")+ object_id = file_info["objectId"]++ # Send file reference response+ response = {+ "jsonrpc": "2.0",+ "id": f"msg_{int(time.time() * 1000)}",+ "result": {+ "taskId": task_id,+ "kind": "artifact-update",+ "append": False,+ "lastChunk": True,+ "isFinal": True,+ "artifact": {+ "artifactId": f"artifact_{int(time.time() * 1000)}",+ "parts": [+ {+ "kind": "artifact",+ "artifact": {+ "kind": "file",+ "file": {+ "objectId": object_id,+ "fileName": file_name,+ "contentType": content_type+ }+ }+ }+ ],+ },+ },+ }+ await self._safe_ws_send(url_key, response)+ return++ logger.error(f"XiaoyiChannel 无法发送文件:无效的文件信息")+ except Exception as e:+ logger.error(f"XiaoyiChannel 发送文件响应失败: {e}")+async def _safe_ws_send(self, url_key: str, payload: dict[str, Any]) -> None:ws = self._ws_connections.get(url_key)if not ws:diff --git a/jiuwenclaw/schema/message.py b/jiuwenclaw/schema/message.pyindex eeba55c6d4..7ab429c198 100644--- a/jiuwenclaw/schema/message.py+++ b/jiuwenclaw/schema/message.py@@ -69,6 +69,7 @@ class EventType(Enum):CHAT_DELTA = "chat.delta"CHAT_FINAL = "chat.final"CHAT_MEDIA = "chat.media"+ CHAT_FILE = "chat.file"CHAT_TOOL_CALL = "chat.tool_call"CHAT_TOOL_RESULT = "chat.tool_result"CONTEXT_COMPRESSED = "context.compressed"