В библиотеке Outlines есть такой класс подсказок
@dataclass
class Prompt:
"""Represents a prompt function.
We return a `Prompt` class instead of a simple function so the
template defined in prompt functions can be accessed.
"""
template: str
signature: inspect.Signature
def __post_init__(self):
self.parameters: List[str] = list(self.signature.parameters.keys())
def __call__(self, *args, **kwargs) -> str:
"""Render and return the template.
Returns
-------
The rendered template as a Python ``str``.
"""
bound_arguments = self.signature.bind(*args, **kwargs)
bound_arguments.apply_defaults()
return render(self.template, **bound_arguments.arguments)
def __str__(self):
return self.template
У него есть такой декоратор
def prompt(fn: Callable) -> Prompt:
signature = inspect.signature(fn)
# The docstring contains the template that will be rendered to be used
# as a prompt to the language model.
docstring = fn.__doc__
if docstring is None:
raise TypeError("Could not find a template in the function's docstring.")
template = cast(str, docstring)
return Prompt(template, signature)
Кажется, это сильно отличается от декораторов, которые я видел с вложенными функциями декоратора и оболочки.
Если я попытаюсь использовать эту подсказку, например
@prompt
def my_system_prompt():
"""This is system prompt."""
system_prompt = query_gen_system_prompt()
Похоже, что Pyright определяет тип system_prompt как str вместо Prompt (вероятно, из-за вызова?), что вызывает проблемы.
Как мне это решить?
Если вы уменьшите проблему, вы увидите, что Пайрайт прав:
class Thing:
def __call__(self):
return 'hello, world'
def deco(fn):
return Thing()
@deco
def f():
return 'world, hello'
# returns the value for Thing.__call__
f()
hello, world
Это потому, что в декораторе вы возвращаете свой класс, который можно вызвать. Затем класс вызывается, когда вы вызываете функцию, возвращая значение __call__
, то есть str
.
Prompt
в данном случае является вложенной оберткой, поскольку технически это вызываемый объект, как и def wrapper(*args, **kwargs)
в более традиционном декораторе.