From 8e105ed3e78327448df634c226930cf41a323bbf Mon Sep 17 00:00:00 2001 From: OhYee Date: Mon, 22 Dec 2025 11:53:09 +0800 Subject: [PATCH 1/4] fix(credential): correct typo in access key secret parameter name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix(agui_protocol): optimize import statements and event handling logic - Move imports to local scope to avoid unnecessary dependencies - Simplify conditional expressions and method calls - Improve type hinting for better code clarity 修复凭据模型中的访问密钥参数拼写错误 优化 AGUI 协议处理器的导入语句和事件处理逻辑: - 将部分导入移至函数内部以减少不必要的依赖 - 简化条件表达式与方法调用 - 改进类型提示以增强代码可读性 Change-Id: I1f4b89fa0a0ceeed09bcf1e6bb03370dfd1547de Signed-off-by: OhYee --- agentrun/credential/model.py | 4 +- agentrun/server/agui_protocol.py | 70 ++++++++++++++++---------------- 2 files changed, 38 insertions(+), 36 deletions(-) diff --git a/agentrun/credential/model.py b/agentrun/credential/model.py index 8413127..63e8097 100644 --- a/agentrun/credential/model.py +++ b/agentrun/credential/model.py @@ -134,7 +134,7 @@ def outbound_tool_ak_sk( cls, provider: str, access_key_id: str, - access_key_secred: str, + access_key_secret: str, account_id: str, ): """配置访问第三方工具的 ak/sk 凭证""" @@ -148,7 +148,7 @@ def outbound_tool_ak_sk( "accountId": account_id, }, }, - credential_secret=access_key_secred, + credential_secret=access_key_secret, ) @classmethod diff --git a/agentrun/server/agui_protocol.py b/agentrun/server/agui_protocol.py index 2d08810..6051265 100644 --- a/agentrun/server/agui_protocol.py +++ b/agentrun/server/agui_protocol.py @@ -19,36 +19,12 @@ ) import uuid -from ag_ui.core import AssistantMessage -from ag_ui.core import CustomEvent as AguiCustomEvent -from ag_ui.core import EventType as AguiEventType -from ag_ui.core import Message as AguiMessage -from ag_ui.core import MessagesSnapshotEvent -from ag_ui.core import RawEvent as AguiRawEvent -from ag_ui.core import ( - RunErrorEvent, - RunFinishedEvent, - RunStartedEvent, - StateDeltaEvent, - StateSnapshotEvent, - StepFinishedEvent, - StepStartedEvent, - SystemMessage, - TextMessageContentEvent, - TextMessageEndEvent, - TextMessageStartEvent, -) -from ag_ui.core import Tool as AguiTool -from ag_ui.core import ToolCall as AguiToolCall -from ag_ui.core import ( - ToolCallArgsEvent, - ToolCallEndEvent, - ToolCallResultEvent, - ToolCallStartEvent, -) -from ag_ui.core import ToolMessage as AguiToolMessage -from ag_ui.core import UserMessage -from ag_ui.encoder import EventEncoder +if TYPE_CHECKING: + from ag_ui.core import ( + Message as AguiMessage, + ) + from ag_ui.encoder import EventEncoder + from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse import pydash @@ -101,8 +77,10 @@ class StreamStateMachine: run_errored: bool = False def end_all_tools( - self, encoder: EventEncoder, exclude: Optional[str] = None + self, encoder: "EventEncoder", exclude: Optional[str] = None ) -> Iterator[str]: + from ag_ui.core import ToolCallEndEvent + for tool_id, state in self.tool_call_states.items(): if exclude and tool_id == exclude: continue @@ -110,7 +88,9 @@ def end_all_tools( yield encoder.encode(ToolCallEndEvent(tool_call_id=tool_id)) state.ended = True - def ensure_text_started(self, encoder: EventEncoder) -> Iterator[str]: + def ensure_text_started(self, encoder: "EventEncoder") -> Iterator[str]: + from ag_ui.core import TextMessageStartEvent + if not self.text.started or self.text.ended: if self.text.ended: self.text = TextState() @@ -123,7 +103,9 @@ def ensure_text_started(self, encoder: EventEncoder) -> Iterator[str]: self.text.started = True self.text.ended = False - def end_text_if_open(self, encoder: EventEncoder) -> Iterator[str]: + def end_text_if_open(self, encoder: "EventEncoder") -> Iterator[str]: + from ag_ui.core import TextMessageEndEvent + if self.text.started and not self.text.ended: yield encoder.encode( TextMessageEndEvent(message_id=self.text.message_id) @@ -168,6 +150,8 @@ class AGUIProtocolHandler(BaseProtocolHandler): name = "ag-ui" def __init__(self, config: Optional[ServerConfig] = None): + from ag_ui.encoder import EventEncoder + self._config = config.agui if config else None self._encoder = EventEncoder() @@ -420,6 +404,18 @@ def _process_event_with_boundaries( """处理事件并注入边界事件""" import json + from ag_ui.core import CustomEvent as AguiCustomEvent + from ag_ui.core import ( + RunErrorEvent, + StateDeltaEvent, + StateSnapshotEvent, + TextMessageContentEvent, + ToolCallArgsEvent, + ToolCallEndEvent, + ToolCallResultEvent, + ToolCallStartEvent, + ) + # RAW 事件直接透传 if event.event == EventType.RAW: raw_data = event.data.get("raw", "") @@ -703,7 +699,7 @@ def _process_event_with_boundaries( def _convert_messages_for_snapshot( self, messages: List[Dict[str, Any]] - ) -> List[AguiMessage]: + ) -> List["AguiMessage"]: """将消息列表转换为 ag-ui-protocol 格式 Args: @@ -712,6 +708,10 @@ def _convert_messages_for_snapshot( Returns: ag-ui-protocol 消息列表 """ + from ag_ui.core import AssistantMessage, SystemMessage + from ag_ui.core import ToolMessage as AguiToolMessage + from ag_ui.core import UserMessage + result = [] for msg in messages: if not isinstance(msg, dict): @@ -779,6 +779,8 @@ async def _error_stream(self, message: str) -> AsyncIterator[str]: Yields: SSE 格式的错误事件 """ + from ag_ui.core import RunErrorEvent, RunStartedEvent + thread_id = str(uuid.uuid4()) run_id = str(uuid.uuid4()) From 4939119c44d01b9cd16c90bdcbe894716ea35b11 Mon Sep 17 00:00:00 2001 From: OhYee Date: Mon, 22 Dec 2025 12:05:55 +0800 Subject: [PATCH 2/4] fix(agui_protocol): import run event classes directly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit the runstartedevent and runfinishedevent classes are now imported directly from ag_ui.core to ensure proper event handling in the sse stream. these events are essential for signaling the start and completion of runs within the agui protocol, improving reliability and maintainability of the streaming mechanism. 修复了 agui 协议中运行事件类的导入问题,确保 SSE 流能够正确处理运行开始和结束事件。此举增强了流机制的可靠性和可维护性。 Change-Id: Ied78843c9533c640a4706b379c8bd9109acc3b0b Signed-off-by: OhYee --- agentrun/model/model.py | 1 + agentrun/server/agui_protocol.py | 2 ++ 2 files changed, 3 insertions(+) diff --git a/agentrun/model/model.py b/agentrun/model/model.py index 73a5e2d..cc6157d 100644 --- a/agentrun/model/model.py +++ b/agentrun/model/model.py @@ -131,6 +131,7 @@ class ProxyConfigTokenRateLimiter(BaseModel): class ProxyConfigAIGuardrailConfig(BaseModel): """AI 防护配置""" + check_request: Optional[bool] = None check_response: Optional[bool] = None diff --git a/agentrun/server/agui_protocol.py b/agentrun/server/agui_protocol.py index 6051265..164dc66 100644 --- a/agentrun/server/agui_protocol.py +++ b/agentrun/server/agui_protocol.py @@ -347,6 +347,8 @@ async def _format_stream( Yields: SSE 格式的字符串 """ + from ag_ui.core import RunFinishedEvent, RunStartedEvent + state = StreamStateMachine() # 发送 RUN_STARTED From 9aa51c802b536cc06817816832a3ad197f7c6f57 Mon Sep 17 00:00:00 2001 From: OhYee Date: Thu, 25 Dec 2025 10:40:48 +0800 Subject: [PATCH 3/4] refactor(core): implement lazy loading for server module to handle optional dependencies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This change introduces a lazy loading mechanism for the server module to avoid import errors when optional dependencies are not installed. The server-related exports are now imported on-demand through __getattr__, with clear error messages when required optional dependencies are missing. The implementation includes: - TYPE_CHECKING import for type hints during development - Delayed imports wrapped in TYPE_CHECKING blocks - __getattr__ function to handle runtime imports - Clear error messages directing users to install optional dependencies - Server exports defined in _SERVER_EXPORTS set for tracking This resolves issues where the package would fail to import when server optional dependencies were not available. refactor(core): 实现服务器模块的延迟加载以处理可选依赖 此更改引入了服务器模块的延迟加载机制,以避免在未安装可选依赖项时出现导入错误。现在通过 __getattr__ 按需导入服务器相关导出,并在缺少必需的可选依赖项时提供清晰的错误消息。 实现包括: - 用于开发期间类型提示的 TYPE_CHECKING 导入 - 包装在 TYPE_CHECKING 块中的延迟导入 - 用于处理运行时导入的 __getattr__ 函数 - 指向用户安装可选依赖项的清晰错误消息 - 定义在 _SERVER_EXPORTS 集合中用于跟踪的服务器导出 这解决了在服务器可选依赖项不可用时包导入失败的问题。 Change-Id: I9d8f7dd8e5c6d34dfd0619714ead5aea22105293 Signed-off-by: OhYee --- agentrun/__init__.py | 149 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 129 insertions(+), 20 deletions(-) diff --git a/agentrun/__init__.py b/agentrun/__init__.py index 1c94f5d..383ef37 100644 --- a/agentrun/__init__.py +++ b/agentrun/__init__.py @@ -16,6 +16,8 @@ - Integration: 框架集成 / Framework integration """ +from typing import TYPE_CHECKING + __version__ = "0.0.8" # Agent Runtime @@ -87,27 +89,50 @@ SandboxClient, Template, ) -# Server -from agentrun.server import ( - AgentRequest, - AgentResult, - AgentRunServer, - AsyncInvokeAgentHandler, - InvokeAgentHandler, - Message, - MessageRole, - OpenAIProtocolHandler, - ProtocolHandler, - SyncInvokeAgentHandler, -) # ToolSet from agentrun.toolset import ToolSet, ToolSetClient +from agentrun.utils.config import Config from agentrun.utils.exception import ( ResourceAlreadyExistError, ResourceNotExistError, ) from agentrun.utils.model import Status +# Server - 延迟导入以避免可选依赖问题 +# Type hints for IDE and type checkers +if TYPE_CHECKING: + from agentrun.server import ( + AgentEvent, + AgentEventItem, + AgentRequest, + AgentResult, + AgentResultItem, + AgentReturnType, + AgentRunServer, + AguiEventNormalizer, + AGUIProtocolConfig, + AGUIProtocolHandler, + AsyncAgentEventGenerator, + AsyncAgentResultGenerator, + AsyncInvokeAgentHandler, + BaseProtocolHandler, + EventType, + InvokeAgentHandler, + MergeOptions, + Message, + MessageRole, + OpenAIProtocolConfig, + OpenAIProtocolHandler, + ProtocolConfig, + ProtocolHandler, + ServerConfig, + SyncAgentEventGenerator, + SyncAgentResultGenerator, + SyncInvokeAgentHandler, + Tool, + ToolCall, + ) + __all__ = [ ######## Agent Runtime ######## # base @@ -185,22 +210,106 @@ ######## ToolSet ######## "ToolSetClient", "ToolSet", - ######## Server ######## + ######## Server (延迟加载) ######## + # Server "AgentRunServer", + # Config + "ServerConfig", + "ProtocolConfig", + "OpenAIProtocolConfig", + "AGUIProtocolConfig", + # Request/Response Models "AgentRequest", - "AgentResponse", + "AgentEvent", "AgentResult", - "AgentStreamResponse", + "Message", + "MessageRole", + "Tool", + "ToolCall", + # Event Types + "EventType", + # Type Aliases + "AgentEventItem", + "AgentResultItem", + "AgentReturnType", + "SyncAgentEventGenerator", + "SyncAgentResultGenerator", + "AsyncAgentEventGenerator", + "AsyncAgentResultGenerator", "InvokeAgentHandler", "AsyncInvokeAgentHandler", "SyncInvokeAgentHandler", - "Message", - "MessageRole", + # Protocol Base "ProtocolHandler", + "BaseProtocolHandler", + # Protocol - OpenAI "OpenAIProtocolHandler", - "AgentStreamIterator", + # Protocol - AG-UI + "AGUIProtocolHandler", + # Event Normalizer + "AguiEventNormalizer", + # Helpers + "MergeOptions", ######## Others ######## - "Status", "ResourceNotExistError", "ResourceAlreadyExistError", + "Config", ] + +# Server 模块的所有导出 +_SERVER_EXPORTS = { + "AgentRunServer", + "ServerConfig", + "ProtocolConfig", + "OpenAIProtocolConfig", + "AGUIProtocolConfig", + "AgentRequest", + "AgentEvent", + "AgentResult", + "Message", + "MessageRole", + "Tool", + "ToolCall", + "EventType", + "AgentEventItem", + "AgentResultItem", + "AgentReturnType", + "SyncAgentEventGenerator", + "SyncAgentResultGenerator", + "AsyncAgentEventGenerator", + "AsyncAgentResultGenerator", + "InvokeAgentHandler", + "AsyncInvokeAgentHandler", + "SyncInvokeAgentHandler", + "ProtocolHandler", + "BaseProtocolHandler", + "OpenAIProtocolHandler", + "AGUIProtocolHandler", + "AguiEventNormalizer", + "MergeOptions", +} + + +def __getattr__(name: str): + """延迟加载 server 模块的导出,避免可选依赖导致导入失败 + + 当用户访问 server 相关的类时,才尝试导入 server 模块。 + 如果 server 可选依赖未安装,会抛出清晰的错误提示。 + """ + if name in _SERVER_EXPORTS: + try: + from agentrun import server + + return getattr(server, name) + except ImportError as e: + # 检查是否是缺少可选依赖导致的错误 + if "fastapi" in str(e) or "uvicorn" in str(e): + raise ImportError( + f"'{name}' requires the 'server' optional dependencies. " + "Install with: pip install agentrun-sdk[server]\n" + f"Original error: {e}" + ) from e + # 其他导入错误继续抛出 + raise + + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") From b3ff8fade25a0ec85909f689e8694047ff9c5223 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 25 Dec 2025 12:19:37 +0800 Subject: [PATCH 4/4] refactor(core): use generic package mapping for optional dependency checks (#25) * Initial plan * fix(core): add 'ag_ui' to optional dependency error check Add "ag_ui" to the error message checking logic in __getattr__ to properly handle import errors when ag-ui-protocol is not installed. This ensures users get helpful error messages when trying to use AGUIProtocolHandler or other AG-UI related components without the server optional dependencies installed. Addresses feedback from PR #23 review comment. Co-authored-by: OhYee <13498329+OhYee@users.noreply.github.com> * refactor(core): use generic package mapping for optional dependency checks Refactor the import error handling to use a more maintainable and scalable approach with a package mapping structure instead of hardcoded string checks. Changes: - Added _OPTIONAL_PACKAGES list with (import_name, install_name) tuples - Refactored __getattr__ to iterate through the package mapping - Now easier to add new optional dependencies in the future - All three server optional dependencies (fastapi, uvicorn, ag_ui) registered This makes the codebase more maintainable when adding new optional dependencies in the future. Addresses feedback from @OhYee on PR #23. Co-authored-by: OhYee <13498329+OhYee@users.noreply.github.com> * fix(core): restore specificity in error message and add clarifying comment Address code review feedback: - Restored "server" context in error message for better clarity - Added comment clarifying that all entries are for server-related dependencies - Maintains generic approach while preserving helpful context for users This ensures users get clear, specific error messages while keeping the code maintainable for future extensions. Co-authored-by: OhYee <13498329+OhYee@users.noreply.github.com> * refactor(core): use constant for server install command to reduce duplication Extract the repeated install command string into a constant _SERVER_INSTALL_CMD to make the code more maintainable and easier to update in the future. This addresses code review feedback about reducing duplication in the package mapping structure. Co-authored-by: OhYee <13498329+OhYee@users.noreply.github.com> * refactor(core): group packages by install command in _OPTIONAL_PACKAGES Refactor _OPTIONAL_PACKAGES from a list of tuples to a dictionary that groups packages by their installation command. This provides better organization when multiple packages share the same installation command. Changes: - Changed from list of (package, install_cmd) tuples to dict of {install_cmd: [packages]} - Removed _SERVER_INSTALL_CMD constant (now a dict key) - Updated iteration logic to handle nested structure - All three server packages (fastapi, uvicorn, ag_ui) grouped together Benefits: - Clearer relationship: install command -> packages it provides - More compact when packages share the same install command - Easier to see all packages for a given installation - Scalable for future optional dependency groups Addresses feedback from @OhYee about merging packages with the same command. Co-authored-by: OhYee <13498329+OhYee@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: OhYee <13498329+OhYee@users.noreply.github.com> --- agentrun/__init__.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/agentrun/__init__.py b/agentrun/__init__.py index 383ef37..bf93517 100644 --- a/agentrun/__init__.py +++ b/agentrun/__init__.py @@ -289,6 +289,13 @@ "MergeOptions", } +# 可选依赖包映射:安装命令 -> 导入错误的包名列表 +# Optional dependency mapping: installation command -> list of import error package names +# 将使用相同安装命令的包合并到一起 / Group packages with the same installation command +_OPTIONAL_PACKAGES = { + "agentrun-sdk[server]": ["fastapi", "uvicorn", "ag_ui"], +} + def __getattr__(name: str): """延迟加载 server 模块的导出,避免可选依赖导致导入失败 @@ -303,12 +310,15 @@ def __getattr__(name: str): return getattr(server, name) except ImportError as e: # 检查是否是缺少可选依赖导致的错误 - if "fastapi" in str(e) or "uvicorn" in str(e): - raise ImportError( - f"'{name}' requires the 'server' optional dependencies. " - "Install with: pip install agentrun-sdk[server]\n" - f"Original error: {e}" - ) from e + error_str = str(e) + for install_cmd, package_names in _OPTIONAL_PACKAGES.items(): + for package_name in package_names: + if package_name in error_str: + raise ImportError( + f"'{name}' requires the 'server' optional dependencies. " + f"Install with: pip install {install_cmd}\n" + f"Original error: {e}" + ) from e # 其他导入错误继续抛出 raise