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
feat:支持 openYuanrong serverless 部署和调用
slichengsong96b6afb2feba
diff --git a/deploy/func/clawee.py b/deploy/func/clawee.pynew file mode 100644index 0000000000..276b33c4a8--- /dev/null+++ b/deploy/func/clawee.py@@ -0,0 +1,113 @@+"""OpenYuanRong 函数入口 - clawee handler."""++import asyncio+import json+from dataclasses import asdict+from typing import Any++from jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk+from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.server.runtime.tenant_agent_pool import TenantAgentPool+++def payload_to_request(request: dict[str, Any]) -> AgentRequest:+ """将函数 payload 转换为 AgentRequest.++ Args:+ request: 函数请求字典++ Returns:+ AgentRequest 对象+ """+ req_method = request.get("req_method")+ if req_method is not None and isinstance(req_method, str):+ req_method = ReqMethod(req_method)++ return AgentRequest(+ request_id=request.get("request_id"),+ channel_id=request.get("channel_id", ""),+ session_id=request.get("session_id"),+ req_method=req_method,+ params=request.get("params", {}),+ is_stream=request.get("is_stream", False),+ timestamp=request.get("timestamp", 0.0),+ metadata=request.get("metadata"),+ )+++def to_json(msg: Any) -> str:+ """将对象转换为 JSON 字符串."""+ if msg:+ return json.dumps(asdict(msg), ensure_ascii=False)+ return ""+++def chunk_to_payload(chunk: AgentResponseChunk) -> str:+ """将 chunk 转换为 payload 字符串."""+ return to_json(chunk)+++def response_to_payload(resp: AgentResponse) -> str:+ """将 response 转换为 payload 字符串."""+ return to_json(resp)+++def init(context):+ """函数初始化."""+ try:+ TenantAgentPool.get_instance()+ except Exception as e:+ import logging+ logger = logging.getLogger(__name__)+ logger.exception("[clawee] Failed to initialize TenantAgentPool")+ raise+++async def ahandler(event, context=None):+ """异步处理函数."""+ try:+ request = payload_to_request(event)+ except Exception as e:+ import logging+ logger = logging.getLogger(__name__)+ logger.exception("[clawee] Failed to parse event")+ return None++ pool = TenantAgentPool.get_instance()++ try:+ if request.is_stream:+ # 流式处理+ async for chunk in pool.process_message_stream(request):+ payload = chunk_to_payload(chunk)+ if context is not None and hasattr(context, "get_stream"):+ context.get_stream().write(payload)+ else:+ # 非流式处理+ resp = await pool.process_message(request)+ return response_to_payload(resp)++ except Exception as e:+ import logging+ logger = logging.getLogger(__name__)+ logger.exception("[clawee] Error during message processing")+ # 构建错误响应+ error_response = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )+ return to_json(error_response)++ return None+++def handler(event, context=None):+ """同步入口."""+ return asyncio.run(ahandler(event, context))+++def pre_stop():+ """函数停止前的清理."""+ passdiff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.pyindex 996388a9db..c2e2deafce 100644--- a/jiuwenswarm/server/runtime/agent_manager.py+++ b/jiuwenswarm/server/runtime/agent_manager.py@@ -426,6 +426,66 @@ class AgentManager:)return existing_modes+ async def process_message(self, request: Any) -> Any:+ """处理非流式请求.++ Args:+ request: AgentRequest 对象++ Returns:+ AgentResponse 对象+ """+ try:+ channel_id = getattr(request, "channel_id", "")+ params = getattr(request, "params", {}) if isinstance(getattr(request, "params", {}), dict) else {}+ mode_full = params.get("mode", "agent.plan")+ mode = str(mode_full).split(".")[0] if mode_full else "agent"+ workspace_dir = params.get("workspace_dir")++ agent = await self.get_agent(+ channel_id=channel_id,+ mode=mode,+ project_dir=workspace_dir,+ )+ if agent is None:+ raise RuntimeError(f"[AgentManager] No agent available for channel {channel_id}")++ return await agent.process_message(request)+ except Exception as e:+ logger.error(f"[AgentManager] Error in process_message: {e}", exc_info=True)+ raise++ async def process_message_stream(self, request: Any):+ """处理流式请求.++ Args:+ request: AgentRequest 对象++ Yields:+ AgentResponseChunk 对象+ """+ try:+ channel_id = getattr(request, "channel_id", "")+ params = getattr(request, "params", {}) if isinstance(getattr(request, "params", {}), dict) else {}+ mode_full = params.get("mode", "agent.plan")+ mode = str(mode_full).split(".")[0] if mode_full else "agent"+ workspace_dir = params.get("workspace_dir")++ agent = await self.get_agent(+ channel_id=channel_id,+ mode=mode,+ project_dir=workspace_dir,+ )+ if agent is None:+ raise RuntimeError(f"[AgentManager] No agent available for channel {channel_id}")++ # 流式处理+ async for chunk in agent.process_message_stream(request):+ yield chunk+ except Exception as e:+ logger.error(f"[AgentManager] Error in process_message_stream: {e}", exc_info=True)+ raise+async def cleanup(self) -> None:"""清理所有 agent 实例."""for key, agents in list(self.agents.items()):diff --git a/jiuwenswarm/server/runtime/tenant_agent_pool.py b/jiuwenswarm/server/runtime/tenant_agent_pool.pynew file mode 100644index 0000000000..b50add6a65--- /dev/null+++ b/jiuwenswarm/server/runtime/tenant_agent_pool.py@@ -0,0 +1,89 @@+from __future__ import annotations++import logging+from typing import Any, ClassVar++from jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse+from jiuwenswarm.server.runtime.agent_manager import AgentManager++logger = logging.getLogger(__name__)+++class TenantAgentPool:+ """AgentManager 管理器(单例).++ 职责:+ 1. 管理 AgentManager 实例的创建和生命周期+ 2. 提供统一的函数调用接口+ 3. 调用 AgentManager 的方法(简单分发)+ """++ _instance: ClassVar[TenantAgentPool | None] = None++ def __init__(self) -> None:+ # 单个 AgentManager 实例+ self._agent_manager = AgentManager()+ logger.info("[TenantAgentPool] Initialized with AgentManager")++ @classmethod+ def get_instance(cls) -> "TenantAgentPool":+ """获取单例实例."""+ if cls._instance is None:+ cls._instance = cls()+ logger.info("[TenantAgentPool] Created singleton instance")+ return cls._instance++ @classmethod+ def reset_instance(cls) -> None:+ """重置单例(仅用于测试)."""+ if cls._instance is not None:+ logger.info("[TenantAgentPool] Resetting singleton instance")+ cls._instance = None++ async def process_message(self, request: AgentRequest) -> AgentResponse:+ """处理非流式请求(简单分发到 AgentManager).++ Args:+ request: AgentRequest 对象++ Returns:+ AgentResponse 对象+ """+ try:+ logger.info(+ "[TenantAgentPool] process_message called | request_id=%s | channel_id=%s",+ request.request_id,+ request.channel_id,+ )+ return await self._agent_manager.process_message(request)+ except Exception as e:+ logger.error(f"[TenantAgentPool] Error in process_message: {e}", exc_info=True)+ # 可以选择返回错误响应或重新抛出异常+ raise++ async def process_message_stream(self, request: AgentRequest):+ """处理流式请求(简单分发到 AgentManager).++ Args:+ request: AgentRequest 对象++ Yields:+ AgentResponseChunk 对象+ """+ try:+ logger.info(+ "[TenantAgentPool] process_message_stream called | request_id=%s | channel_id=%s",+ request.request_id,+ request.channel_id,+ )+ async for chunk in self._agent_manager.process_message_stream(request):+ yield chunk+ except Exception as e:+ logger.error(f"[TenantAgentPool] Error in process_message_stream: {e}", exc_info=True)+ raise++ async def cleanup(self) -> None:+ """清理资源."""+ logger.info("[TenantAgentPool] Cleaning up...")+ await self._agent_manager.cleanup()+ logger.info("[TenantAgentPool] Cleanup complete")