You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为装饰器param_type_factory添加封闭类实例的类型提示?

问题描述

我正在设计一个@action装饰器,用来收集类中的特定方法并暴露给后端。核心需求是让方法的参数类型提示能动态反映实例状态——比如在Player类中,被@action装饰的attack_action方法里,param_type_factory中的lambda需要接收Player实例来生成target的Literal类型,但静态类型检查无法识别lambda里的player参数类型。

我想给这个lambda的参数标注为封闭类(比如Player)的类型,或者给param_type_factory标注为接收封闭类实例的Callable类型。目前已经实现了tool_action装饰器(其中param_model_factory的类型提示用了Any,需要修正),还有Player类里的_collect_tools方法,运行时功能正常,但缺乏正确的静态类型提示。另外我考虑过把方法逻辑和元数据分离的模式(见下文),但觉得太繁琐,希望找到更简洁、类型安全的装饰器设计方案。

相关代码示例

Player类使用示例

class Player():
    ...
    def _private_fun(): ...

    @action(
        param_type_factory={
            "target": lambda player: Literal[tuple(player.opponents)]
        }
    )
    def attack_action(self, target):
        ...

当前装饰器实现

def tool_action(
    description: str,
    param_model_factory: Any, #<- 需要修正这个类型提示
):
    def decorator(fn):
        fn._tool_meta = {
            "name": fn.__name__,
            "description": description or fn.__doc__ or "",
            "param_model_factory": param_model_factory,
        }
        return fn

    return decorator

Player类中的_collect_tools方法

def _collect_tools(self) -> List[ActionTool]:
        tools: List[ActionTool] = []
        for attr_name, method in inspect.getmembers(self, predicate=inspect.ismethod):
            meta = getattr(method, "_tool_meta", None)
            if not meta:
                continue
            if callable(meta.get("param_model_factory")):
                new_sig = meta["param_model_factory"](self)
            else:
                new_sig = {}
            tools.append(
                ActionTool(
                    func=method,
                    name=meta["name"],
                    description=meta["description"],
                    signature=new_sig,
                )
            )
        return tools

备选模式示例(过于繁琐)

@action
def attack_action(self):
    return Action(
        attack,
        param_type_factory={
            "target": Tuple[self.opponents]
        }
    )

def attack(self, target):
    ...

内容的提问来源于stack exchange,提问作者ximp_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 16:45:13