agentrun-inner-test 0.0.62__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of agentrun-inner-test might be problematic. Click here for more details.

Files changed (154) hide show
  1. agentrun/__init__.py +358 -0
  2. agentrun/agent_runtime/__client_async_template.py +466 -0
  3. agentrun/agent_runtime/__endpoint_async_template.py +345 -0
  4. agentrun/agent_runtime/__init__.py +53 -0
  5. agentrun/agent_runtime/__runtime_async_template.py +477 -0
  6. agentrun/agent_runtime/api/__data_async_template.py +58 -0
  7. agentrun/agent_runtime/api/__init__.py +6 -0
  8. agentrun/agent_runtime/api/control.py +1362 -0
  9. agentrun/agent_runtime/api/data.py +98 -0
  10. agentrun/agent_runtime/client.py +868 -0
  11. agentrun/agent_runtime/endpoint.py +649 -0
  12. agentrun/agent_runtime/model.py +362 -0
  13. agentrun/agent_runtime/runtime.py +904 -0
  14. agentrun/credential/__client_async_template.py +177 -0
  15. agentrun/credential/__credential_async_template.py +216 -0
  16. agentrun/credential/__init__.py +28 -0
  17. agentrun/credential/api/__init__.py +5 -0
  18. agentrun/credential/api/control.py +606 -0
  19. agentrun/credential/client.py +319 -0
  20. agentrun/credential/credential.py +381 -0
  21. agentrun/credential/model.py +248 -0
  22. agentrun/integration/__init__.py +21 -0
  23. agentrun/integration/agentscope/__init__.py +13 -0
  24. agentrun/integration/agentscope/adapter.py +17 -0
  25. agentrun/integration/agentscope/builtin.py +88 -0
  26. agentrun/integration/agentscope/message_adapter.py +185 -0
  27. agentrun/integration/agentscope/model_adapter.py +60 -0
  28. agentrun/integration/agentscope/tool_adapter.py +59 -0
  29. agentrun/integration/builtin/__init__.py +18 -0
  30. agentrun/integration/builtin/knowledgebase.py +137 -0
  31. agentrun/integration/builtin/model.py +93 -0
  32. agentrun/integration/builtin/sandbox.py +1234 -0
  33. agentrun/integration/builtin/toolset.py +47 -0
  34. agentrun/integration/crewai/__init__.py +13 -0
  35. agentrun/integration/crewai/adapter.py +9 -0
  36. agentrun/integration/crewai/builtin.py +88 -0
  37. agentrun/integration/crewai/model_adapter.py +31 -0
  38. agentrun/integration/crewai/tool_adapter.py +26 -0
  39. agentrun/integration/google_adk/__init__.py +13 -0
  40. agentrun/integration/google_adk/adapter.py +15 -0
  41. agentrun/integration/google_adk/builtin.py +88 -0
  42. agentrun/integration/google_adk/message_adapter.py +144 -0
  43. agentrun/integration/google_adk/model_adapter.py +46 -0
  44. agentrun/integration/google_adk/tool_adapter.py +235 -0
  45. agentrun/integration/langchain/__init__.py +31 -0
  46. agentrun/integration/langchain/adapter.py +15 -0
  47. agentrun/integration/langchain/builtin.py +94 -0
  48. agentrun/integration/langchain/message_adapter.py +141 -0
  49. agentrun/integration/langchain/model_adapter.py +37 -0
  50. agentrun/integration/langchain/tool_adapter.py +50 -0
  51. agentrun/integration/langgraph/__init__.py +36 -0
  52. agentrun/integration/langgraph/adapter.py +20 -0
  53. agentrun/integration/langgraph/agent_converter.py +1073 -0
  54. agentrun/integration/langgraph/builtin.py +88 -0
  55. agentrun/integration/pydantic_ai/__init__.py +13 -0
  56. agentrun/integration/pydantic_ai/adapter.py +13 -0
  57. agentrun/integration/pydantic_ai/builtin.py +88 -0
  58. agentrun/integration/pydantic_ai/model_adapter.py +44 -0
  59. agentrun/integration/pydantic_ai/tool_adapter.py +19 -0
  60. agentrun/integration/utils/__init__.py +112 -0
  61. agentrun/integration/utils/adapter.py +560 -0
  62. agentrun/integration/utils/canonical.py +164 -0
  63. agentrun/integration/utils/converter.py +134 -0
  64. agentrun/integration/utils/model.py +110 -0
  65. agentrun/integration/utils/tool.py +1759 -0
  66. agentrun/knowledgebase/__client_async_template.py +173 -0
  67. agentrun/knowledgebase/__init__.py +53 -0
  68. agentrun/knowledgebase/__knowledgebase_async_template.py +438 -0
  69. agentrun/knowledgebase/api/__data_async_template.py +414 -0
  70. agentrun/knowledgebase/api/__init__.py +19 -0
  71. agentrun/knowledgebase/api/control.py +606 -0
  72. agentrun/knowledgebase/api/data.py +624 -0
  73. agentrun/knowledgebase/client.py +311 -0
  74. agentrun/knowledgebase/knowledgebase.py +748 -0
  75. agentrun/knowledgebase/model.py +270 -0
  76. agentrun/memory_collection/__client_async_template.py +178 -0
  77. agentrun/memory_collection/__init__.py +37 -0
  78. agentrun/memory_collection/__memory_collection_async_template.py +457 -0
  79. agentrun/memory_collection/api/__init__.py +5 -0
  80. agentrun/memory_collection/api/control.py +610 -0
  81. agentrun/memory_collection/client.py +323 -0
  82. agentrun/memory_collection/memory_collection.py +844 -0
  83. agentrun/memory_collection/model.py +162 -0
  84. agentrun/model/__client_async_template.py +357 -0
  85. agentrun/model/__init__.py +57 -0
  86. agentrun/model/__model_proxy_async_template.py +270 -0
  87. agentrun/model/__model_service_async_template.py +267 -0
  88. agentrun/model/api/__init__.py +6 -0
  89. agentrun/model/api/control.py +1173 -0
  90. agentrun/model/api/data.py +196 -0
  91. agentrun/model/client.py +674 -0
  92. agentrun/model/model.py +235 -0
  93. agentrun/model/model_proxy.py +439 -0
  94. agentrun/model/model_service.py +438 -0
  95. agentrun/sandbox/__aio_sandbox_async_template.py +523 -0
  96. agentrun/sandbox/__browser_sandbox_async_template.py +110 -0
  97. agentrun/sandbox/__client_async_template.py +491 -0
  98. agentrun/sandbox/__code_interpreter_sandbox_async_template.py +463 -0
  99. agentrun/sandbox/__init__.py +69 -0
  100. agentrun/sandbox/__sandbox_async_template.py +463 -0
  101. agentrun/sandbox/__template_async_template.py +152 -0
  102. agentrun/sandbox/aio_sandbox.py +912 -0
  103. agentrun/sandbox/api/__aio_data_async_template.py +335 -0
  104. agentrun/sandbox/api/__browser_data_async_template.py +140 -0
  105. agentrun/sandbox/api/__code_interpreter_data_async_template.py +206 -0
  106. agentrun/sandbox/api/__init__.py +19 -0
  107. agentrun/sandbox/api/__sandbox_data_async_template.py +107 -0
  108. agentrun/sandbox/api/aio_data.py +551 -0
  109. agentrun/sandbox/api/browser_data.py +172 -0
  110. agentrun/sandbox/api/code_interpreter_data.py +396 -0
  111. agentrun/sandbox/api/control.py +1051 -0
  112. agentrun/sandbox/api/playwright_async.py +492 -0
  113. agentrun/sandbox/api/playwright_sync.py +492 -0
  114. agentrun/sandbox/api/sandbox_data.py +154 -0
  115. agentrun/sandbox/browser_sandbox.py +185 -0
  116. agentrun/sandbox/client.py +925 -0
  117. agentrun/sandbox/code_interpreter_sandbox.py +823 -0
  118. agentrun/sandbox/model.py +384 -0
  119. agentrun/sandbox/sandbox.py +848 -0
  120. agentrun/sandbox/template.py +217 -0
  121. agentrun/server/__init__.py +191 -0
  122. agentrun/server/agui_normalizer.py +180 -0
  123. agentrun/server/agui_protocol.py +797 -0
  124. agentrun/server/invoker.py +309 -0
  125. agentrun/server/model.py +427 -0
  126. agentrun/server/openai_protocol.py +535 -0
  127. agentrun/server/protocol.py +140 -0
  128. agentrun/server/server.py +208 -0
  129. agentrun/toolset/__client_async_template.py +62 -0
  130. agentrun/toolset/__init__.py +51 -0
  131. agentrun/toolset/__toolset_async_template.py +204 -0
  132. agentrun/toolset/api/__init__.py +17 -0
  133. agentrun/toolset/api/control.py +262 -0
  134. agentrun/toolset/api/mcp.py +100 -0
  135. agentrun/toolset/api/openapi.py +1251 -0
  136. agentrun/toolset/client.py +102 -0
  137. agentrun/toolset/model.py +321 -0
  138. agentrun/toolset/toolset.py +271 -0
  139. agentrun/utils/__data_api_async_template.py +721 -0
  140. agentrun/utils/__init__.py +5 -0
  141. agentrun/utils/__resource_async_template.py +158 -0
  142. agentrun/utils/config.py +270 -0
  143. agentrun/utils/control_api.py +105 -0
  144. agentrun/utils/data_api.py +1121 -0
  145. agentrun/utils/exception.py +151 -0
  146. agentrun/utils/helper.py +108 -0
  147. agentrun/utils/log.py +77 -0
  148. agentrun/utils/model.py +168 -0
  149. agentrun/utils/resource.py +291 -0
  150. agentrun_inner_test-0.0.62.dist-info/METADATA +265 -0
  151. agentrun_inner_test-0.0.62.dist-info/RECORD +154 -0
  152. agentrun_inner_test-0.0.62.dist-info/WHEEL +5 -0
  153. agentrun_inner_test-0.0.62.dist-info/licenses/LICENSE +201 -0
  154. agentrun_inner_test-0.0.62.dist-info/top_level.txt +1 -0
@@ -0,0 +1,248 @@
1
+ """Credential 模型定义 / Credential Model Definitions
2
+
3
+ 定义凭证相关的数据模型和枚举。
4
+ Defines data models and enumerations related to credentials.
5
+ """
6
+
7
+ from enum import Enum
8
+ from typing import Any, Dict, List, Optional
9
+
10
+ from agentrun.utils.config import Config
11
+ from agentrun.utils.model import BaseModel, PageableInput
12
+
13
+
14
+ class CredentialAuthType(str, Enum):
15
+ """凭证认证类型 / Credential Authentication Type"""
16
+
17
+ JWT = "jwt"
18
+ API_KEY = "api_key"
19
+ BASIC = "basic"
20
+ AKSK = "ak_sk"
21
+ CUSTOM_HEADER = "custom_header"
22
+
23
+
24
+ class CredentialSourceType(str, Enum):
25
+ """凭证来源类型 / Credential Source Type"""
26
+
27
+ LLM = "external_llm"
28
+ """模型凭证"""
29
+ TOOL = "external_tool"
30
+ """工具凭证"""
31
+ INTERNAL = "internal"
32
+ """自定义凭证"""
33
+
34
+
35
+ class CredentialBasicAuth(BaseModel):
36
+ username: Optional[str]
37
+ password: Optional[str]
38
+
39
+
40
+ class RelatedResource(BaseModel):
41
+ resource_id: Optional[str] = None
42
+ """资源 ID"""
43
+ resource_name: Optional[str] = None
44
+ """资源名称"""
45
+ resource_type: Optional[str] = None
46
+ """资源类型"""
47
+
48
+
49
+ class CredentialConfigInner(BaseModel):
50
+ credential_auth_type: Optional[CredentialAuthType] = None
51
+ """凭证认证类型"""
52
+ credential_source_type: Optional[CredentialSourceType] = None
53
+ """凭证来源类型"""
54
+ credential_public_config: Optional[Dict[str, Any]] = None
55
+ """凭证公共配置"""
56
+ credential_secret: Optional[str] = None
57
+ """凭证密钥"""
58
+
59
+
60
+ class CredentialConfig(CredentialConfigInner):
61
+ """凭证配置"""
62
+
63
+ @classmethod
64
+ def inbound_api_key(cls, api_key: str, header_key: str = "Authorization"):
65
+ """配置访问 AgentRun 的 api key 凭证"""
66
+ return cls(
67
+ credential_source_type=CredentialSourceType.INTERNAL,
68
+ credential_auth_type=CredentialAuthType.API_KEY,
69
+ credential_public_config={"headerKey": header_key},
70
+ credential_secret=api_key,
71
+ )
72
+
73
+ @classmethod
74
+ def inbound_static_jwt(cls, jwks: str):
75
+ """配置访问 AgentRun 的静态 JWKS 凭证"""
76
+ return cls(
77
+ credential_source_type=CredentialSourceType.INTERNAL,
78
+ credential_auth_type=CredentialAuthType.JWT,
79
+ credential_public_config={"authType": "static_jwks", "jwks": jwks},
80
+ credential_secret="",
81
+ )
82
+
83
+ @classmethod
84
+ def inbound_remote_jwt(
85
+ cls, uri: str, timeout: int = 3000, ttl: int = 30000, **kwargs
86
+ ):
87
+ """配置访问 AgentRun 的远程 JWT 凭证"""
88
+ return cls(
89
+ credential_source_type=CredentialSourceType.INTERNAL,
90
+ credential_auth_type=CredentialAuthType.JWT,
91
+ credential_public_config={
92
+ "uri": uri,
93
+ "timeout": timeout,
94
+ "ttl": ttl,
95
+ **kwargs,
96
+ },
97
+ credential_secret="",
98
+ )
99
+
100
+ @classmethod
101
+ def inbound_basic(cls, users: List[CredentialBasicAuth]):
102
+ """配置访问 AgentRun 的 Basic 凭证"""
103
+ return cls(
104
+ credential_source_type=CredentialSourceType.INTERNAL,
105
+ credential_auth_type=CredentialAuthType.BASIC,
106
+ credential_public_config={
107
+ "users": [user.model_dump() for user in users]
108
+ },
109
+ credential_secret="",
110
+ )
111
+
112
+ @classmethod
113
+ def outbound_llm_api_key(cls, api_key: str, provider: str):
114
+ """配置访问第三方模型的 api key 凭证"""
115
+ return cls(
116
+ credential_source_type=CredentialSourceType.LLM,
117
+ credential_auth_type=CredentialAuthType.API_KEY,
118
+ credential_public_config={"provider": provider},
119
+ credential_secret=api_key,
120
+ )
121
+
122
+ @classmethod
123
+ def outbound_tool_api_key(cls, api_key: str):
124
+ """配置访问第三方工具的 api key 凭证"""
125
+ return cls(
126
+ credential_source_type=CredentialSourceType.TOOL,
127
+ credential_auth_type=CredentialAuthType.API_KEY,
128
+ credential_public_config={},
129
+ credential_secret=api_key,
130
+ )
131
+
132
+ @classmethod
133
+ def outbound_tool_ak_sk(
134
+ cls,
135
+ provider: str,
136
+ access_key_id: str,
137
+ access_key_secret: str,
138
+ account_id: str,
139
+ ):
140
+ """配置访问第三方工具的 ak/sk 凭证"""
141
+ return cls(
142
+ credential_source_type=CredentialSourceType.TOOL,
143
+ credential_auth_type=CredentialAuthType.AKSK,
144
+ credential_public_config={
145
+ "provider": provider,
146
+ "authConfig": {
147
+ "accessKey": access_key_id,
148
+ "accountId": account_id,
149
+ },
150
+ },
151
+ credential_secret=access_key_secret,
152
+ )
153
+
154
+ @classmethod
155
+ def outbound_tool_ak_sk_custom(cls, auth_config: Dict[str, str]):
156
+ """配置访问第三方工具的自定义凭证"""
157
+ return cls(
158
+ credential_source_type=CredentialSourceType.TOOL,
159
+ credential_auth_type=CredentialAuthType.AKSK,
160
+ credential_public_config={
161
+ "provider": "custom",
162
+ "authConfig": auth_config,
163
+ },
164
+ credential_secret="",
165
+ )
166
+
167
+ @classmethod
168
+ def outbound_tool_custom_header(cls, headers: Dict[str, str]):
169
+ """配置访问第三方工具的自定义 Header 凭证"""
170
+ return cls(
171
+ credential_source_type=CredentialSourceType.TOOL,
172
+ credential_auth_type=CredentialAuthType.CUSTOM_HEADER,
173
+ credential_public_config={"authConfig": headers},
174
+ credential_secret="",
175
+ )
176
+
177
+
178
+ class CredentialMutableProps(BaseModel):
179
+ """凭证公共配置"""
180
+
181
+ # credential_secret: Optional[str] = None
182
+ """凭证密钥"""
183
+ description: Optional[str] = None
184
+ """描述"""
185
+ enabled: Optional[bool] = None
186
+ """是否启用"""
187
+
188
+
189
+ class CredentialImmutableProps(BaseModel):
190
+ credential_name: Optional[str] = None
191
+ """凭证名称"""
192
+
193
+
194
+ class CredentialSystemProps(CredentialConfigInner):
195
+ credential_id: Optional[str] = None
196
+ """凭证 ID"""
197
+ created_at: Optional[str] = None
198
+ """创建时间"""
199
+ updated_at: Optional[str] = None
200
+ """更新时间"""
201
+ related_resources: Optional[List[RelatedResource]] = None
202
+ """关联资源"""
203
+
204
+
205
+ class CredentialCreateInput(CredentialImmutableProps, CredentialMutableProps):
206
+ """凭证创建输入参数"""
207
+
208
+ credential_config: CredentialConfig
209
+
210
+
211
+ class CredentialUpdateInput(CredentialMutableProps):
212
+ credential_config: Optional[CredentialConfig] = None
213
+
214
+
215
+ class CredentialListInput(PageableInput):
216
+ credential_auth_type: Optional[CredentialAuthType] = None
217
+ """凭证认证类型"""
218
+ credential_name: Optional[str] = None
219
+ """凭证名称"""
220
+ credential_source_type: Optional[CredentialSourceType] = None
221
+ """凭证来源类型(必填)"""
222
+ provider: Optional[str] = None
223
+ """提供商"""
224
+
225
+
226
+ class CredentialListOutput(BaseModel):
227
+ created_at: Optional[str] = None
228
+ credential_auth_type: Optional[str] = None
229
+ credential_id: Optional[str] = None
230
+ credential_name: Optional[str] = None
231
+ credential_source_type: Optional[str] = None
232
+ enabled: Optional[bool] = None
233
+ related_resource_count: Optional[int] = None
234
+ updated_at: Optional[str] = None
235
+
236
+ async def to_credential_async(self, config: Optional[Config] = None):
237
+ from .client import CredentialClient
238
+
239
+ return await CredentialClient(config).get_async(
240
+ self.credential_name or "", config=config
241
+ )
242
+
243
+ def to_credential(self, config: Optional[Config] = None):
244
+ from .client import CredentialClient
245
+
246
+ return CredentialClient(config).get(
247
+ self.credential_name or "", config=config
248
+ )
@@ -0,0 +1,21 @@
1
+ """Integration 模块 / Integration Module
2
+
3
+ 提供与主流 AI 框架的集成适配器。
4
+ Provides integration adapters for mainstream AI frameworks.
5
+
6
+ 支持的框架 / Supported Frameworks:
7
+ - LangChain: 流行的 LLM 应用开发框架 / Popular LLM application development framework
8
+ - LangGraph: LangChain 的图形化工作流扩展 / Graph-based workflow extension for LangChain
9
+ - Google ADK: Google 的 AI Development Kit / Google's AI Development Kit
10
+ - AgentScope: 阿里云的 Agent 开发框架 / Alibaba Cloud's agent development framework
11
+ - PydanticAI: 基于 Pydantic 的 AI 框架 / Pydantic-based AI framework
12
+ - CrewAI: 多 Agent 协作框架 / Multi-agent collaboration framework
13
+
14
+ 使用方法 / Usage:
15
+ >>> from agentrun.integration.langchain import wrap_model, wrap_tools
16
+ >>> # 或 / Or
17
+ >>> from agentrun.integration.utils.model import CommonModel
18
+ >>> from agentrun.integration.utils.tool import CommonToolSet
19
+ """
20
+
21
+ __all__ = []
@@ -0,0 +1,13 @@
1
+ """AgentScope 集成模块。 / AgentScope 集成 Module
2
+
3
+ 提供 AgentRun 模型与沙箱工具的 AgentScope 适配入口。 / 提供 AgentRun 模型with沙箱工具的 AgentScope 适配入口。
4
+ """
5
+
6
+ from .builtin import knowledgebase_toolset, model, sandbox_toolset, toolset
7
+
8
+ __all__ = [
9
+ "model",
10
+ "toolset",
11
+ "sandbox_toolset",
12
+ "knowledgebase_toolset",
13
+ ]
@@ -0,0 +1,17 @@
1
+ """AgentScope 适配器兼容性导出 / AgentScope Adapters Compatibility Exports
2
+
3
+ 提供 AgentScope 框架的所有适配器。
4
+ Provides all adapters for the AgentScope framework.
5
+ """
6
+
7
+ from agentrun.integration.agentscope.message_adapter import (
8
+ AgentScopeMessageAdapter,
9
+ )
10
+ from agentrun.integration.agentscope.model_adapter import AgentScopeModelAdapter
11
+ from agentrun.integration.agentscope.tool_adapter import AgentScopeToolAdapter
12
+
13
+ __all__ = [
14
+ "AgentScopeMessageAdapter",
15
+ "AgentScopeToolAdapter",
16
+ "AgentScopeModelAdapter",
17
+ ]
@@ -0,0 +1,88 @@
1
+ """AgentScope 内置集成函数 / AgentScope Built-in Integration Functions
2
+
3
+ 提供快速创建 AgentScope 兼容模型和工具的便捷函数。
4
+ Provides convenient functions for quickly creating AgentScope-compatible models and tools.
5
+ """
6
+
7
+ from typing import Any, Callable, List, Optional, Union
8
+
9
+ from typing_extensions import Unpack
10
+
11
+ from agentrun.integration.builtin import (
12
+ knowledgebase_toolset as _knowledgebase_toolset,
13
+ )
14
+ from agentrun.integration.builtin import model as _model
15
+ from agentrun.integration.builtin import ModelArgs
16
+ from agentrun.integration.builtin import sandbox_toolset as _sandbox_toolset
17
+ from agentrun.integration.builtin import toolset as _toolset
18
+ from agentrun.integration.utils.tool import Tool
19
+ from agentrun.model import ModelProxy, ModelService
20
+ from agentrun.sandbox import TemplateType
21
+ from agentrun.toolset import ToolSet
22
+ from agentrun.utils.config import Config
23
+
24
+
25
+ def model(
26
+ name: Union[str, ModelProxy, ModelService],
27
+ **kwargs: Unpack[ModelArgs],
28
+ ):
29
+ """获取 AgentRun 模型并转换为 LangChain ``BaseChatModel``。 / AgentScope Built-in Integration Functions"""
30
+
31
+ m = _model(input=name, **kwargs)
32
+ return m.to_agentscope()
33
+
34
+
35
+ def toolset(
36
+ name: Union[str, ToolSet],
37
+ *,
38
+ prefix: Optional[str] = None,
39
+ modify_tool_name: Optional[Callable[[Tool], Tool]] = None,
40
+ filter_tools_by_name: Optional[Callable[[str], bool]] = None,
41
+ config: Optional[Config] = None,
42
+ ) -> List[Any]:
43
+ """将内置工具集封装为 LangChain ``StructuredTool`` 列表。 / AgentScope Built-in Integration Functions"""
44
+
45
+ ts = _toolset(input=name, config=config)
46
+ return ts.to_crewai(
47
+ prefix=prefix,
48
+ modify_tool_name=modify_tool_name,
49
+ filter_tools_by_name=filter_tools_by_name,
50
+ )
51
+
52
+
53
+ def sandbox_toolset(
54
+ template_name: str,
55
+ *,
56
+ template_type: TemplateType = TemplateType.CODE_INTERPRETER,
57
+ config: Optional[Config] = None,
58
+ sandbox_idle_timeout_seconds: int = 600,
59
+ prefix: Optional[str] = None,
60
+ ) -> List[Any]:
61
+ """将沙箱模板封装为 LangChain ``StructuredTool`` 列表。 / AgentScope Built-in Integration Functions"""
62
+
63
+ return _sandbox_toolset(
64
+ template_name=template_name,
65
+ template_type=template_type,
66
+ config=config,
67
+ sandbox_idle_timeout_seconds=sandbox_idle_timeout_seconds,
68
+ ).to_agentscope(prefix=prefix)
69
+
70
+
71
+ def knowledgebase_toolset(
72
+ knowledge_base_names: List[str],
73
+ *,
74
+ prefix: Optional[str] = None,
75
+ modify_tool_name: Optional[Callable[[Tool], Tool]] = None,
76
+ filter_tools_by_name: Optional[Callable[[str], bool]] = None,
77
+ config: Optional[Config] = None,
78
+ ) -> List[Any]:
79
+ """将知识库检索封装为 AgentScope 工具列表。 / AgentScope Built-in Integration Functions"""
80
+
81
+ return _knowledgebase_toolset(
82
+ knowledge_base_names=knowledge_base_names,
83
+ config=config,
84
+ ).to_agentscope(
85
+ prefix=prefix,
86
+ modify_tool_name=modify_tool_name,
87
+ filter_tools_by_name=filter_tools_by_name,
88
+ )
@@ -0,0 +1,185 @@
1
+ """消息适配器,负责 AgentScope <-> CanonicalMessage 的转换。 / AgentScope Message Adapter"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Iterable, List
7
+
8
+ from agentrun.integration.utils.adapter import MessageAdapter
9
+ from agentrun.integration.utils.canonical import (
10
+ CanonicalMessage,
11
+ CanonicalToolCall,
12
+ MessageRole,
13
+ )
14
+
15
+
16
+ def _ensure_agentscope_installed() -> None:
17
+ try:
18
+ import agentscope # noqa: F401
19
+ except ImportError as exc: # pragma: no cover - defensive
20
+ raise ImportError(
21
+ "AgentScope is not installed. Install it with: pip install"
22
+ " agentscope"
23
+ ) from exc
24
+
25
+
26
+ class AgentScopeMessageAdapter(MessageAdapter):
27
+ """AgentScope 消息适配器。 / AgentScope Message Adapter"""
28
+
29
+ def to_canonical(self, messages: Any) -> List[CanonicalMessage]:
30
+ _ensure_agentscope_installed()
31
+
32
+ from agentscope.message import Msg
33
+
34
+ if messages is None:
35
+ return []
36
+
37
+ if isinstance(messages, Msg):
38
+ iterable: Iterable[Any] = [messages]
39
+ elif isinstance(messages, Iterable):
40
+ iterable = messages
41
+ else:
42
+ iterable = [messages]
43
+
44
+ canonical: List[CanonicalMessage] = []
45
+ for item in iterable:
46
+ msg = self._ensure_msg(item)
47
+ text_segments: List[str] = []
48
+ tool_calls: List[CanonicalToolCall] = []
49
+
50
+ blocks = (
51
+ msg.content
52
+ if isinstance(msg.content, list)
53
+ else msg.get_content_blocks()
54
+ ) or []
55
+
56
+ for block in blocks:
57
+ block_type = block.get("type")
58
+ if block_type == "text":
59
+ text = block.get("text")
60
+ if text:
61
+ text_segments.append(str(text))
62
+ elif block_type == "tool_use":
63
+ tool_calls.append(
64
+ CanonicalToolCall(
65
+ id=str(block.get("id", "")),
66
+ name=str(block.get("name", "")),
67
+ arguments=block.get("input", {}) or {},
68
+ )
69
+ )
70
+ elif block_type == "tool_result":
71
+ canonical.append(
72
+ CanonicalMessage(
73
+ role=MessageRole.TOOL,
74
+ content=self._format_tool_result(block),
75
+ tool_call_id=str(block.get("id", "")),
76
+ name=block.get("name"),
77
+ )
78
+ )
79
+
80
+ if text_segments or tool_calls or msg.role:
81
+ canonical.append(
82
+ CanonicalMessage(
83
+ role=self._resolve_role(msg.role),
84
+ content="\n".join(text_segments)
85
+ if text_segments
86
+ else None,
87
+ name=msg.name,
88
+ tool_calls=tool_calls or None,
89
+ )
90
+ )
91
+
92
+ return canonical
93
+
94
+ def from_canonical(self, messages: List[CanonicalMessage]) -> Any:
95
+ _ensure_agentscope_installed()
96
+
97
+ from agentscope.message import (
98
+ Msg,
99
+ TextBlock,
100
+ ToolResultBlock,
101
+ ToolUseBlock,
102
+ )
103
+
104
+ result: List[Msg] = []
105
+ for msg in messages:
106
+ role = msg.role.value
107
+ blocks: List[dict] = []
108
+
109
+ if msg.role == MessageRole.TOOL:
110
+ blocks.append(
111
+ ToolResultBlock(
112
+ type="tool_result",
113
+ id=msg.tool_call_id or "",
114
+ name=msg.name or "",
115
+ output=msg.content or "",
116
+ )
117
+ )
118
+ else:
119
+ if msg.content:
120
+ blocks.append(
121
+ TextBlock(
122
+ type="text",
123
+ text=msg.content,
124
+ )
125
+ )
126
+ for call in msg.tool_calls or []:
127
+ blocks.append(
128
+ ToolUseBlock(
129
+ type="tool_use",
130
+ id=call.id,
131
+ name=call.name,
132
+ input=call.arguments,
133
+ )
134
+ )
135
+
136
+ content: Any
137
+ if len(blocks) == 1 and blocks[0]["type"] == "text":
138
+ content = blocks[0]["text"]
139
+ else:
140
+ content = blocks or ""
141
+
142
+ result.append(
143
+ Msg(
144
+ name=msg.name or role,
145
+ role=role,
146
+ content=content,
147
+ )
148
+ )
149
+
150
+ return result
151
+
152
+ @staticmethod
153
+ def _ensure_msg(message: Any):
154
+ from agentscope.message import Msg
155
+
156
+ if isinstance(message, Msg):
157
+ return message
158
+ if isinstance(message, dict):
159
+ return Msg(
160
+ name=message.get("name", message.get("role", "user")),
161
+ role=message.get("role", "user"),
162
+ content=message.get("content"),
163
+ )
164
+ raise TypeError(f"Unsupported AgentScope message type: {type(message)}")
165
+
166
+ @staticmethod
167
+ def _resolve_role(role: str) -> MessageRole:
168
+ role_lower = (role or "user").lower()
169
+ if role_lower.startswith("system"):
170
+ return MessageRole.SYSTEM
171
+ if role_lower.startswith("assistant"):
172
+ return MessageRole.ASSISTANT
173
+ if role_lower.startswith("tool"):
174
+ return MessageRole.TOOL
175
+ return MessageRole.USER
176
+
177
+ @staticmethod
178
+ def _format_tool_result(block: dict) -> str:
179
+ output = block.get("output")
180
+ if isinstance(output, str):
181
+ return output
182
+ try:
183
+ return json.dumps(output, ensure_ascii=False)
184
+ except (TypeError, ValueError): # pragma: no cover - fallback
185
+ return str(output)
@@ -0,0 +1,60 @@
1
+ """AgentScope 模型适配器 / AgentScope Model Adapter
2
+
3
+ 将 CommonModel 包装为 AgentScope ChatModelBase。"""
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+ from agentrun.integration.agentscope.message_adapter import (
10
+ AgentScopeMessageAdapter,
11
+ )
12
+ from agentrun.integration.utils.adapter import ModelAdapter
13
+ from agentrun.integration.utils.model import CommonModel
14
+
15
+
16
+ def _ensure_agentscope_installed() -> None:
17
+ try:
18
+ import agentscope # noqa: F401
19
+ except ImportError as exc: # pragma: no cover - defensive
20
+ raise ImportError(
21
+ "AgentScope is not installed. Install it with: pip install"
22
+ " agentscope"
23
+ ) from exc
24
+
25
+
26
+ class AgentScopeModelAdapter(ModelAdapter):
27
+ """AgentScope 模型适配器 / AgentScope Model Adapter
28
+
29
+ 将 CommonModel 包装为 AgentScope ChatModelBase。"""
30
+
31
+ def __init__(self):
32
+ """初始化适配器,创建内部的消息适配器 / AgentScope Message Adapter"""
33
+ self._message_adapter = AgentScopeMessageAdapter()
34
+
35
+ def wrap_model(self, common_model: CommonModel) -> Any:
36
+ """包装 CommonModel 为 AgentScope ChatModelBase / AgentScope Model Adapter"""
37
+ _ensure_agentscope_installed()
38
+
39
+ try:
40
+ from agentscope.model import OpenAIChatModel
41
+ except Exception as e:
42
+ raise ImportError(
43
+ "AgentScope is not installed. Install it with: pip install"
44
+ " agentscope"
45
+ ) from e
46
+
47
+ from httpx import AsyncClient
48
+
49
+ info = common_model.get_model_info()
50
+
51
+ return OpenAIChatModel(
52
+ model_name=info.model or "",
53
+ api_key=info.api_key,
54
+ stream=True,
55
+ client_args={
56
+ "base_url": info.base_url,
57
+ "http_client": AsyncClient(headers=info.headers),
58
+ },
59
+ generate_kwargs={"stream_options": {"include_usage": True}},
60
+ )
@@ -0,0 +1,59 @@
1
+ """AgentScope 工具适配器 / AgentScope Tool Adapter
2
+
3
+ 将标准工具定义转换为 AgentScope 工具格式。"""
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ from typing import Any, List
9
+
10
+ from agentscope.message import TextBlock
11
+ from agentscope.tool import ToolResponse
12
+
13
+ from agentrun.integration.utils.adapter import ToolAdapter
14
+ from agentrun.integration.utils.canonical import CanonicalTool
15
+
16
+
17
+ def _ensure_agentscope_installed() -> None:
18
+ try:
19
+ import agentscope # noqa: F401
20
+ except ImportError as exc: # pragma: no cover - defensive
21
+ raise ImportError(
22
+ "AgentScope is not installed. Install it with: pip install"
23
+ " agentscope"
24
+ ) from exc
25
+
26
+
27
+ class AgentScopeToolAdapter(ToolAdapter):
28
+ """AgentScope 工具适配器 / AgentScope Tool Adapter
29
+
30
+ 实现 CanonicalTool → AgentScope 工具格式的转换。"""
31
+
32
+ def _modify_tool(self, tool: CanonicalTool, *args, **kwargs) -> Any:
33
+ """修改工具函数以符合 AgentScope 的要求 / AgentScope Tool Adapter"""
34
+ _ensure_agentscope_installed()
35
+
36
+ if tool.func is None:
37
+ return ToolResponse(
38
+ content=[
39
+ TextBlock(
40
+ type="text",
41
+ text="工具未实现。",
42
+ ),
43
+ ],
44
+ )
45
+
46
+ result = tool.func(*args, **kwargs)
47
+ return ToolResponse(
48
+ content=[
49
+ TextBlock(
50
+ type="text",
51
+ text=result if type(result) is str else json.dumps(result),
52
+ ),
53
+ ],
54
+ )
55
+
56
+ def from_canonical(self, tools: List[CanonicalTool]) -> Any:
57
+ """将标准格式转换为 AgentScope 工具 / AgentScope Tool Adapter"""
58
+
59
+ return self.function_tools(tools, modify_func=self._modify_tool)