-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtool.py
More file actions
1899 lines (1604 loc) · 62.5 KB
/
Copy pathtool.py
File metadata and controls
1899 lines (1604 loc) · 62.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""通用工具定义和转换模块
提供跨框架的通用工具定义和转换功能。
支持多种定义方式:
1. 使用 @tool 装饰器 - 最简单,推荐
2. 使用 Pydantic BaseModel - 类型安全
3. 使用 ToolParameter 列表 - 灵活但繁琐
支持转换为以下框架格式:
- OpenAI Function Calling
- Anthropic Claude Tools
- LangChain Tools
- Google ADK Tools
- AgentScope Tools
"""
from __future__ import annotations
from copy import deepcopy
from functools import wraps
import hashlib
import inspect
import json
import re
from typing import (
Any,
Callable,
Dict,
get_args,
get_origin,
get_type_hints,
List,
Optional,
Set,
Tuple,
Type,
TYPE_CHECKING,
)
from pydantic import (
AliasChoices,
BaseModel,
ConfigDict,
create_model,
Field,
ValidationError,
)
if TYPE_CHECKING:
from agentrun.tool.tool import Tool as ToolResource
from agentrun.toolset import ToolSet
from agentrun.utils.log import logger
# Tool name constraints for external providers like OpenAI
MAX_TOOL_NAME_LEN = 64
TOOL_NAME_HEAD_LEN = 32
def normalize_tool_name(name: str) -> str:
"""Normalize a tool name to fit provider limits.
If `name` length is <= MAX_TOOL_NAME_LEN, return it unchanged.
Otherwise, return the first TOOL_NAME_HEAD_LEN characters + md5(full_name)
(32 hex chars), resulting in a 64-char string.
"""
if not isinstance(name, str):
name = str(name)
if len(name) <= MAX_TOOL_NAME_LEN:
return name
digest = hashlib.md5(name.encode("utf-8")).hexdigest()
return name[:TOOL_NAME_HEAD_LEN] + digest
class ToolParameter:
"""工具参数定义
Attributes:
name: 参数名称
param_type: 参数类型(string, integer, number, boolean, array, object)
description: 参数描述
required: 是否必填
default: 默认值
enum: 枚举值列表
items: 数组元素类型(当 param_type 为 array 时使用)
properties: 对象属性(当 param_type 为 object 时使用)
format: 额外的格式限定(如 int32、int64 等)
nullable: 是否允许为空
"""
def __init__(
self,
name: str,
param_type: str,
description: str = "",
required: bool = False,
default: Any = None,
enum: Optional[List[Any]] = None,
items: Optional[Dict[str, Any]] = None,
properties: Optional[Dict[str, Any]] = None,
format: Optional[str] = None,
nullable: bool = False,
):
self.name = name
self.param_type = param_type
self.description = description
self.required = required
self.default = default
self.enum = enum
self.items = items
self.properties = properties
self.format = format
self.nullable = nullable
def to_json_schema(self) -> Dict[str, Any]:
"""转换为 JSON Schema 格式"""
schema: Dict[str, Any] = {
"type": self.param_type,
}
if self.description:
schema["description"] = self.description
if self.default is not None:
schema["default"] = self.default
if self.enum is not None:
schema["enum"] = self.enum
if self.format:
schema["format"] = self.format
if self.nullable:
schema["nullable"] = True
if self.param_type == "array" and self.items:
schema["items"] = deepcopy(self.items)
if self.param_type == "object" and self.properties:
schema["properties"] = deepcopy(self.properties)
return schema
def _merge_schema_dicts(
base: Dict[str, Any], override: Dict[str, Any]
) -> Dict[str, Any]:
"""递归合并 JSON Schema 片段,override 拥有更高优先级"""
if not base:
return deepcopy(override)
if not override:
return deepcopy(base)
merged: Dict[str, Any] = deepcopy(base)
for key, value in override.items():
if (
key in merged
and isinstance(merged[key], dict)
and isinstance(value, dict)
):
merged[key] = _merge_schema_dicts(merged[key], value)
else:
merged[key] = deepcopy(value)
return merged
def _resolve_ref_schema(
ref: Optional[str], root_schema: Dict[str, Any]
) -> Optional[Dict[str, Any]]:
"""解析 $ref 指针"""
if not ref or not isinstance(ref, str) or not ref.startswith("#/"):
return None
target: Any = root_schema
# 处理 JSON Pointer 转义
parts = ref[2:].split("/")
for raw_part in parts:
part = raw_part.replace("~1", "/").replace("~0", "~")
if not isinstance(target, dict) or part not in target:
return None
target = target[part]
if isinstance(target, dict):
return deepcopy(target)
return None
def _extract_core_schema(
field_schema: Dict[str, Any],
root_schema: Dict[str, Any],
seen_refs: Optional[Set[str]] = None,
) -> Tuple[Dict[str, Any], bool]:
"""展开 anyOf/oneOf/allOf/$ref,返回核心 schema 及 nullable 标记"""
schema = deepcopy(field_schema)
nullable = False
if seen_refs is None:
seen_refs = set()
def _pick_from_union(options: List[Dict[str, Any]]) -> Dict[str, Any]:
nonlocal nullable
chosen: Optional[Dict[str, Any]] = None
for option in options:
if not isinstance(option, dict):
continue
if option.get("type") == "null":
nullable = True
continue
resolved, is_nullable = _extract_core_schema(
option, root_schema, seen_refs
)
nullable = nullable or is_nullable
if chosen is None:
chosen = resolved
return chosen or {}
union_key = None
if "anyOf" in schema:
union_key = "anyOf"
elif "oneOf" in schema:
union_key = "oneOf"
if union_key:
options = schema.pop(union_key, [])
schema = _pick_from_union(options)
if "allOf" in schema:
merged: Dict[str, Any] = {}
for option in schema.pop("allOf", []):
if not isinstance(option, dict):
continue
resolved, is_nullable = _extract_core_schema(
option, root_schema, seen_refs
)
nullable = nullable or is_nullable
merged = _merge_schema_dicts(merged, resolved)
schema = _merge_schema_dicts(merged, schema)
ref = schema.get("$ref")
ref_schema = _resolve_ref_schema(ref, root_schema)
if ref_schema and isinstance(ref, str) and ref not in seen_refs:
seen_refs.add(ref)
schema.pop("$ref", None)
resolved, is_nullable = _extract_core_schema(
ref_schema, root_schema, seen_refs
)
seen_refs.discard(ref)
nullable = nullable or is_nullable
schema = _merge_schema_dicts(resolved, schema)
return schema, nullable
class Tool:
"""通用工具定义
支持多种参数定义方式:
1. 使用 parameters 列表(ToolParameter)
2. 使用 args_schema(Pydantic BaseModel)
Attributes:
name: 工具名称
description: 工具描述
parameters: 参数列表(使用 ToolParameter 定义)
args_schema: 参数模型(使用 Pydantic BaseModel 定义)
func: 工具执行函数
"""
def __init__(
self,
name: str,
description: str = "",
parameters: Optional[List[ToolParameter]] = None,
args_schema: Optional[Type[BaseModel]] = None,
func: Optional[Callable] = None,
):
# Normalize tool name to avoid external provider limits (e.g. OpenAI 64 chars)
# If name length > 64, keep first 32 chars and append 32-char md5 sum of full name.
self.name = normalize_tool_name(name)
self.description = description
self.parameters = list(parameters or [])
self.args_schema = args_schema or _build_args_model_from_parameters(
name, self.parameters
)
if self.args_schema is None:
model_name = f"{self.name.title().replace('_', '')}Args"
self.args_schema = create_model(model_name) # type: ignore
elif not self.parameters:
self.parameters = self._generate_parameters_from_schema(
self.args_schema
)
self.func = func
def _generate_parameters_from_schema(
self, schema: Type[BaseModel]
) -> List[ToolParameter]:
"""从 Pydantic schema 生成参数列表"""
parameters = []
json_schema = schema.model_json_schema()
properties = json_schema.get("properties", {})
required_fields = set(json_schema.get("required", []))
for field_name, field_info in properties.items():
normalized_schema, nullable = _extract_core_schema(
field_info, json_schema
)
param_type = normalized_schema.get("type")
if not param_type:
if "properties" in normalized_schema:
param_type = "object"
elif "items" in normalized_schema:
param_type = "array"
elif "enum" in normalized_schema:
param_type = "string"
else:
param_type = field_info.get("type", "string")
description = (
field_info.get("description")
or normalized_schema.get("description")
or ""
)
if "default" in field_info:
default = field_info.get("default")
else:
default = normalized_schema.get("default")
if "enum" in field_info:
enum = field_info.get("enum")
else:
enum = normalized_schema.get("enum")
items = normalized_schema.get("items")
if items is not None:
items = deepcopy(items)
properties_schema = normalized_schema.get("properties")
if properties_schema is not None:
properties_schema = deepcopy(properties_schema)
fmt = normalized_schema.get("format")
if (
not nullable
and field_name not in required_fields
and "default" in field_info
and field_info.get("default") is None
):
nullable = True
parameters.append(
ToolParameter(
name=field_name,
param_type=param_type,
description=description,
required=field_name in required_fields,
default=default,
enum=enum,
items=items,
properties=properties_schema,
format=fmt,
nullable=nullable,
)
)
return parameters
def get_parameters_schema(self) -> Dict[str, Any]:
"""获取参数的 JSON Schema"""
if self.args_schema is None:
return {"type": "object", "properties": {}}
raw_schema = self.args_schema.model_json_schema()
schema = deepcopy(raw_schema)
properties = raw_schema.get("properties")
if not isinstance(properties, dict):
return schema
normalized_properties: Dict[str, Any] = {}
required_fields = set(schema.get("required", []))
meta_keys = (
"default",
"description",
"examples",
"title",
"deprecated",
"enum",
"const",
"format",
)
for field_name, field_schema in properties.items():
normalized, nullable = _extract_core_schema(
field_schema, raw_schema
)
enriched = deepcopy(normalized) if normalized else {}
for meta_key in meta_keys:
if meta_key in field_schema:
enriched[meta_key] = deepcopy(field_schema[meta_key])
# 确保 description 字段总是存在(即使为空字符串)
if "description" not in enriched:
enriched["description"] = ""
default_is_none = (
field_name not in required_fields
and "default" in field_schema
and field_schema.get("default") is None
)
if nullable or field_schema.get("nullable") or default_is_none:
enriched["nullable"] = True
normalized_properties[field_name] = enriched
schema["properties"] = normalized_properties
return schema
def to_openai_function(self) -> Dict[str, Any]:
"""转换为 OpenAI Function Calling 格式"""
return {
"name": self.name,
"description": self.description,
"parameters": self.get_parameters_schema(),
}
def to_anthropic_tool(self) -> Dict[str, Any]:
"""转换为 Anthropic Claude Tools 格式"""
return {
"name": self.name,
"description": self.description,
"input_schema": self.get_parameters_schema(),
}
def to_langchain(self) -> Any:
"""转换为 LangChain Tool 格式
优先使用适配器模式,如果适配器未注册则回退到旧实现。
"""
# 尝试使用适配器模式
try:
from agentrun.integration.utils.canonical import CanonicalTool
from agentrun.integration.utils.converter import get_converter
converter = get_converter()
adapter = converter._tool_adapters.get("langchain")
if adapter is not None:
# 转换为中间格式
canonical_tool = CanonicalTool(
name=self.name,
description=self.description,
parameters=self.get_parameters_schema(),
func=self.func,
)
# 转换为 LangChain 格式
result = adapter.from_canonical([canonical_tool])
return result[0] if result else None
except (ImportError, AttributeError, KeyError):
pass
# 回退到旧实现(保持向后兼容)
try:
from langchain_core.tools import StructuredTool # type: ignore
except ImportError as e:
raise ImportError(
"LangChain is not installed. "
"Install it with: pip install langchain-core"
) from e
return StructuredTool.from_function(
func=self.func,
name=self.name,
description=self.description,
args_schema=self.args_schema,
)
def to_google_adk(self) -> Callable:
"""转换为 Google ADK Tool 格式
优先使用适配器模式,如果适配器未注册则回退到旧实现。
Google ADK 直接使用 Python 函数作为工具。
"""
# 尝试使用适配器模式
try:
from agentrun.integration.utils.canonical import CanonicalTool
from agentrun.integration.utils.converter import get_converter
converter = get_converter()
adapter = converter._tool_adapters.get("google_adk")
if adapter is not None:
# 转换为中间格式
canonical_tool = CanonicalTool(
name=self.name,
description=self.description,
parameters=self.get_parameters_schema(),
func=self.func,
)
# 转换为 Google ADK 格式
result = adapter.from_canonical([canonical_tool])
if result:
return result[0] # type: ignore
except (ImportError, AttributeError, KeyError):
pass
# 回退到旧实现(保持向后兼容)
if self.func is None:
raise ValueError(
f"Tool '{self.name}' has no function implementation"
)
return self.func
def to_agentscope(self) -> Dict[str, Any]:
"""转换为 AgentScope Tool 格式"""
try:
from agentrun.integration.utils.canonical import CanonicalTool
from agentrun.integration.utils.converter import get_converter
converter = get_converter()
adapter = converter._tool_adapters.get("agentscope")
if adapter is not None:
canonical_tool = CanonicalTool(
name=self.name,
description=self.description,
parameters=self.get_parameters_schema(),
func=self.func,
)
result = adapter.from_canonical([canonical_tool])
return result[0] if result else {}
except (ImportError, AttributeError, KeyError):
pass
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.get_parameters_schema(),
},
}
def to_langgraph(self) -> Any:
"""转换为 LangGraph Tool 格式
LangGraph 与 LangChain 完全兼容,因此使用相同的接口。
"""
return self.to_langchain()
def to_crewai(self) -> Any:
"""转换为 CrewAI Tool 格式
CrewAI 内部使用 LangChain,因此使用相同的接口。
"""
return self.to_langchain()
def to_pydanticai(self) -> Any:
"""转换为 PydanticAI Tool 格式"""
# PydanticAI 使用函数装饰器定义工具
# 返回一个包装函数,使其符合 PydanticAI 的工具接口
if self.func is None:
raise ValueError(
f"Tool '{self.name}' has no function implementation"
)
# 创建一个包装函数,添加必要的元数据
func = self.func
# 添加函数文档字符串
if not func.__doc__:
# 使用 setattr 绕过类型检查
object.__setattr__(func, "__doc__", self.description)
# 添加函数名称
if not hasattr(func, "__name__"):
object.__setattr__(func, "__name__", self.name)
# 为 PydanticAI 添加参数 schema 信息
# 使用 setattr 绕过类型检查
object.__setattr__(
func,
"_tool_schema",
{
"name": self.name,
"description": self.description,
"parameters": self.get_parameters_schema(),
},
)
return func
def __get__(self, obj: Any, objtype: Any = None) -> "Tool":
"""实现描述符协议,使 Tool 在类属性访问时自动绑定到实例
这允许在工具方法内部调用其他 @tool 装饰的方法时正常工作。
例如:goto 方法调用 self.browser_navigate() 时,会自动获取绑定版本。
"""
if obj is None:
# 通过类访问(如 BrowserToolSet.browser_navigate),返回未绑定的 Tool
return self
# 通过实例访问,返回绑定到该实例的 Tool
# 使用实例的 __dict__ 作为缓存,避免每次访问都创建新的 Tool 对象
cache_key = f"_bound_tool_{id(self)}"
if cache_key not in obj.__dict__:
obj.__dict__[cache_key] = self.bind(obj)
return obj.__dict__[cache_key]
def bind(self, instance: Any) -> "Tool":
"""绑定工具到实例,便于在类中定义工具方法"""
if self.func is None:
raise ValueError(
f"Tool '{self.name}' has no function implementation"
)
# 复制当前工具的定义,覆写执行函数为绑定后的函数
parameters = deepcopy(self.parameters) if self.parameters else None
original_func = self.func
@wraps(original_func)
def bound(*args, **kwargs):
return original_func(instance, *args, **kwargs)
# 更新函数签名,移除 self 参数
try:
original_sig = inspect.signature(original_func)
params = list(original_sig.parameters.values())
if params and params[0].name == "self":
params = params[1:]
setattr(
bound, "__signature__", original_sig.replace(parameters=params)
)
except (TypeError, ValueError):
# 某些内置函数不支持签名操作,忽略即可
pass
# 清理 self 的注解,确保外部框架解析一致
original_annotations = getattr(original_func, "__annotations__", {})
if original_annotations:
setattr(
bound,
"__annotations__",
{
key: value
for key, value in original_annotations.items()
if key != "self"
},
)
return Tool(
name=self.name,
description=self.description,
parameters=parameters,
args_schema=self.args_schema,
func=bound,
)
def openai(self) -> Dict[str, Any]:
"""to_openai_function 的别名"""
return self.to_openai_function()
def langchain(self) -> Any:
"""to_langchain 的别名"""
return self.to_langchain()
def google_adk(self) -> Callable:
"""to_google_adk 的别名"""
return self.to_google_adk()
def pydanticai(self) -> Any:
"""to_pydanticai 的别名(暂未实现)"""
# TODO: 实现 PydanticAI 转换
raise NotImplementedError("PydanticAI conversion not implemented yet")
def __call__(self, *args, **kwargs) -> Any:
"""直接调用工具函数"""
if self.func is None:
raise ValueError(
f"Tool '{self.name}' has no function implementation"
)
return self.func(*args, **kwargs)
class CommonToolSet:
"""工具集
管理多个工具,提供批量转换和过滤功能。
默认会收集子类中定义的 `Tool` 属性,因此简单的继承即可完成
工具集的声明。也可以通过传入 ``tools_list`` 或调用 ``register``
方法来自定义工具集合。
Attributes:
tools_list: 工具列表
"""
def __init__(self, tools_list: Optional[List[Tool]] = None):
if tools_list is None:
tools_list = self._collect_declared_tools()
self._tools: List[Tool] = list(tools_list)
def _collect_declared_tools(self) -> List[Tool]:
"""收集并绑定子类中定义的 Tool 对象"""
tools: List[Tool] = []
seen: set[str] = set()
for cls in type(self).mro():
if cls in {CommonToolSet, object}:
continue
class_dict = getattr(cls, "__dict__", {})
for attr_name, attr_value in class_dict.items():
if attr_name.startswith("_") or attr_name in seen:
continue
if isinstance(attr_value, Tool):
seen.add(attr_name)
tools.append(attr_value.bind(self))
return tools
# def register(self, *tools: Tool) -> None:
# """动态注册工具"""
# for tool in tools:
# if not isinstance(tool, Tool):
# raise TypeError(
# f"register() 只接受 Tool 实例, 收到类型: {type(tool)!r}"
# )
# self._tools.append(tool)
def tools(
self,
prefix: Optional[str] = None,
modify_tool_name: Optional[Callable[[Tool], Tool]] = None,
filter_tools_by_name: Optional[Callable[[str], bool]] = None,
):
"""获取工具列表
Args:
prefix: 为所有工具名称添加前缀
modify_tool_name: 自定义工具修改函数
filter_tools_by_name: 工具名称过滤函数
Returns:
处理后的工具列表
"""
tools = list(self._tools)
# 应用过滤器
if filter_tools_by_name is not None:
tools = [t for t in tools if filter_tools_by_name(t.name)]
# 应用前缀
if prefix is not None:
tools = [
Tool(
name=f"{prefix}{t.name}",
description=t.description,
parameters=t.parameters,
args_schema=t.args_schema,
func=t.func,
)
for t in tools
]
# 应用自定义修改函数
if modify_tool_name is not None:
tools = [modify_tool_name(t) for t in tools]
from agentrun.integration.utils.canonical import CanonicalTool
return [
CanonicalTool(
name=tool.name,
description=tool.description,
parameters=tool.get_parameters_schema(),
func=tool.func,
)
for tool in tools
]
def __convert_tools(
self,
adapter_name: str,
prefix: Optional[str] = None,
modify_tool_name: Optional[Callable[[Tool], Tool]] = None,
filter_tools_by_name: Optional[Callable[[str], bool]] = None,
):
tools = self.tools(prefix, modify_tool_name, filter_tools_by_name)
# 尝试使用适配器模式进行批量转换
try:
from agentrun.integration.utils.converter import get_converter
converter = get_converter()
adapter = converter._tool_adapters.get(adapter_name)
if adapter is not None:
return adapter.from_canonical(tools)
except (ImportError, AttributeError, KeyError):
pass
logger.warning(
f"adapter {adapter_name} not found, returning empty list"
)
return []
@classmethod
def from_agentrun_toolset(
cls,
toolset: ToolSet,
config: Optional[Any] = None,
refresh: bool = False,
) -> "CommonToolSet":
"""从 AgentRun ToolSet 创建通用工具集
Args:
toolset: agentrun.toolset.toolset.ToolSet 实例
config: 额外的请求配置,调用工具时会自动合并
refresh: 是否先刷新最新信息
Returns:
通用 ToolSet 实例,可直接调用 .to_openai_function()、.to_langchain() 等
Example:
>>> from agentrun.toolset.client import ToolSetClient
>>> from agentrun.integration.common import from_agentrun_toolset
>>>
>>> client = ToolSetClient()
>>> remote_toolset = client.get(name="my-toolset")
>>> common_toolset = from_agentrun_toolset(remote_toolset)
>>>
>>> # 使用已有的转换方法
>>> openai_tools = common_toolset.to_openai_function()
>>> google_adk_tools = common_toolset.to_google_adk()
"""
if refresh:
toolset = toolset.get(config=config)
# 获取所有工具元数据
tools_meta = toolset.list_tools(config=config) or []
integration_tools: List[Tool] = []
seen_names = set()
for meta in tools_meta:
tool = _build_tool_from_meta(toolset, meta, config)
if tool:
# 检测工具名冲突
if tool.name in seen_names:
logger.warning(
f"Duplicate tool name '{tool.name}' detected, "
"second occurrence will be skipped"
)
continue
seen_names.add(tool.name)
integration_tools.append(tool)
return CommonToolSet(integration_tools)
@classmethod
def from_agentrun_tool(
cls,
tool_resource: "ToolResource",
config: Optional[Any] = None,
refresh: bool = False,
) -> "CommonToolSet":
"""从 AgentRun ToolResource 创建通用工具集 / Create CommonToolSet from AgentRun ToolResource
Args:
tool_resource: agentrun.tool.tool.Tool (ToolResource) 实例 / ToolResource instance
config: 额外的请求配置,调用工具时会自动合并 / Extra request config, merged automatically when calling tools
refresh: 是否先刷新最新信息 / Whether to refresh latest info first
Returns:
通用 ToolSet 实例,可直接调用 .to_openai_function()、.to_langchain() 等
CommonToolSet instance, can directly call .to_openai_function(), .to_langchain(), etc.
Example:
>>> from agentrun import ToolResource, ToolResourceClient
>>> from agentrun.integration.utils.tool import CommonToolSet
>>>
>>> client = ToolResourceClient()
>>> tool = client.get(name="my-tool")
>>> common_toolset = CommonToolSet.from_agentrun_tool(tool)
>>>
>>> openai_tools = common_toolset.to_openai_function()
>>> langchain_tools = common_toolset.to_langchain()
"""
if refresh:
tool_resource = tool_resource.get(config=config)
tools_meta = tool_resource.list_tools(config=config) or []
integration_tools: List[Tool] = []
seen_names: set = set()
for meta in tools_meta:
tool = _build_tool_from_meta(tool_resource, meta, config)
if tool:
if tool.name in seen_names:
logger.warning(
f"Duplicate tool name '{tool.name}' detected, "
"second occurrence will be skipped"
)
continue
seen_names.add(tool.name)
integration_tools.append(tool)
return CommonToolSet(integration_tools)
def to_openai_function(
self,
prefix: Optional[str] = None,
modify_tool_name: Optional[Callable[[Tool], Tool]] = None,
filter_tools_by_name: Optional[Callable[[str], bool]] = None,
) -> List[Dict[str, Any]]:
"""批量转换为 OpenAI Function Calling 格式"""
tools = self.tools(prefix, modify_tool_name, filter_tools_by_name)
return [
{
"name": tool.name,
"description": tool.description,
"parameters": tool.parameters,
}
for tool in tools
]
def to_anthropic_tool(
self,
prefix: Optional[str] = None,
modify_tool_name: Optional[Callable[[Tool], Tool]] = None,
filter_tools_by_name: Optional[Callable[[str], bool]] = None,
) -> List[Dict[str, Any]]:
"""批量转换为 Anthropic Claude Tools 格式"""
tools = self.tools(prefix, modify_tool_name, filter_tools_by_name)
return [
{
"name": tool.name,
"description": tool.description,
"input_schema": tool.parameters,
}
for tool in tools
]
def to_langchain(
self,
prefix: Optional[str] = None,
modify_tool_name: Optional[Callable[[Tool], Tool]] = None,
filter_tools_by_name: Optional[Callable[[str], bool]] = None,
) -> List[Any]:
"""批量转换为 LangChain Tool 格式
优先使用适配器模式进行批量转换,提高效率。
"""
return self.__convert_tools(
"langchain", prefix, modify_tool_name, filter_tools_by_name
)
def to_google_adk(
self,
prefix: Optional[str] = None,
modify_tool_name: Optional[Callable[[Tool], Tool]] = None,
filter_tools_by_name: Optional[Callable[[str], bool]] = None,
):
"""批量转换为 Google ADK Tool 格式
优先使用适配器模式进行批量转换,提高效率。
"""
return self.__convert_tools(
"google_adk", prefix, modify_tool_name, filter_tools_by_name
)
def to_agentscope(
self,
prefix: Optional[str] = None,
modify_tool_name: Optional[Callable[[Tool], Tool]] = None,
filter_tools_by_name: Optional[Callable[[str], bool]] = None,
):
"""批量转换为 AgentScope Tool 格式"""
return self.__convert_tools(
"agentscope", prefix, modify_tool_name, filter_tools_by_name
)
def to_langgraph(
self,
prefix: Optional[str] = None,
modify_tool_name: Optional[Callable[[Tool], Tool]] = None,
filter_tools_by_name: Optional[Callable[[str], bool]] = None,
) -> List[Any]:
"""批量转换为 LangGraph Tool 格式
LangGraph 与 LangChain 完全兼容,因此使用相同的接口。
"""
return self.__convert_tools(
"langgraph", prefix, modify_tool_name, filter_tools_by_name
)