def appl_execute(
s: Any,
_ctx: PromptContext = PromptContext(),
) -> None:
"""Interact with the prompt context using the given value."""
if s is None:
return
if isinstance(s, str):
add_str = True
if _ctx._is_first_str:
docstring = _ctx._func_docstring
if docstring is not None:
docstring = inspect.cleandoc(docstring)
if _ctx._docstring_as is not None:
if docstring is None:
logger.warning(
f"No docstring found for {_ctx._func_name}, cannot include it."
)
else:
assert s == docstring, f"Docstring mismatch: {s}"
if _ctx._docstring_as == "system":
_ctx.add_message(SystemMessage(s))
add_str = False
elif _ctx._docstring_as != "user":
raise ValueError(
f"Unknown message role for docstring: {_ctx._docstring_as}."
"Only support 'system' and 'user' now."
)
# else: user message, treat as a normal string
elif s == docstring and _ctx._docstring_quote_count != 1:
add_str = False
if global_vars.configs.settings.logging.display.docstring_warning:
logger.warning(
f'The docstring """{s}""" for `{_ctx._func_name}` is excluded from the prompt. '
"To include the docstring, set the message role in `docstring_as` in the @ppl function."
)
# else: single quote string as docstring, treat as a normal string
if add_str:
_ctx.add_string(StringFuture(s))
_ctx._is_first_str = False
elif isinstance(s, StringFuture):
_ctx.add_string(s)
elif isinstance(s, PromptRecords):
_ctx.add_records(s)
elif isinstance(s, BaseMessage):
_ctx.add_message(s)
elif isinstance(s, ContentPart): # Image, Audio, ...
_ctx.add_content_part(s)
elif isinstance(s, ImageFile):
_ctx.add_content_part(Image.from_image(s))
elif isinstance(s, Generation):
appl_execute(s.as_prompt(), _ctx)
elif isinstance(s, Promptable):
# recursively apply
appl_execute(promptify(s), _ctx)
elif isinstance(s, Iterable):
# iterable items, recursively apply
for x in s:
appl_execute(x, _ctx)
elif isinstance(s, Namespace): # for advanced usage only
logger.info(f"updating context variables using the namespace: {s}")
_ctx._set_vars(s)
else:
logger.warning(f"Cannot convert {s} of type {type(s)} to prompt, ignore.")