Skip to content

DynamicPrompt

Base classes

Name Children Inherits
BasePrompt
llmling.prompts.models
Base class for all prompts.

â‹” Inheritance diagram

graph TD
  4272956609["models.DynamicPrompt"]
  3854555607["models.BasePrompt"]
  3879467795["main.BaseModel"]
  2751680898["builtins.object"]
  3854555607 --> 4272956609
  3879467795 --> 3854555607
  2751680898 --> 3879467795

🛈 DocStrings

Bases: BasePrompt

Dynamic prompt loaded from callable.

Source code in src/llmling/prompts/models.py
class DynamicPrompt(BasePrompt):
    """Dynamic prompt loaded from callable."""

    import_path: str | Callable
    """Dotted import path to the callable that generates the prompt."""

    template: str | None = None
    """Optional template string for formatting the callable's output."""

    completions: dict[str, str] | None = None
    """Optional mapping of argument names to completion functions."""

    type: Literal["function"] = Field("function", init=False)
    """Discriminator field identifying this as a function-based prompt."""

    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)

    @property
    def messages(self) -> list[PromptMessage]:
        """Get the template messages for this prompt.

        Note: These are template messages - actual content will be populated
        during format() when the callable is executed.
        """
        template = self.template or "{result}"
        sys_content = MessageContent(type="text", content=f"Content from {self.name}:")
        user_content = MessageContent(type="text", content=template)
        return [
            PromptMessage(role="system", content=sys_content),
            PromptMessage(role="user", content=user_content),
        ]

    def to_fastmcp_prompt(self) -> FunctionPrompt:
        from fastmcp.prompts import FunctionPrompt

        return FunctionPrompt.from_function(
            self.fn,
            title=self.title,
            description=self.description,
            tags=None,
            icons=None,
        )

    @property
    def fn(self) -> Callable[..., Any]:
        if isinstance(self.import_path, str):
            return importing.import_callable(self.import_path)
        return self.import_path

    def get_completion_functions(self) -> dict[str, CompletionFunction]:
        """Resolve completion function import paths and return a completion fn dict."""
        completion_funcs: dict[str, CompletionFunction] = {}
        if not self.completions:
            return {}
        for arg_name, import_path in self.completions.items():
            try:
                func = importing.import_callable(import_path)
                completion_funcs[arg_name] = func
            except ValueError:
                msg = "Failed to import completion function for %s: %s"
                logger.warning(msg, arg_name, import_path)
        return completion_funcs

    async def format(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage]:
        """Format this prompt with given arguments."""
        args = arguments or {}
        self.validate_arguments(args)

        try:
            if isinstance(self.import_path, str):
                result = await calling.execute_callable(self.import_path, **args)
            elif inspect.iscoroutinefunction(self.import_path):
                result = await self.import_path(**args)
            elif inspect.isfunction(self.import_path):
                result = self.import_path(**args)
            else:
                msg = "Invalid result type"
                raise ValueError(msg)  # noqa: TRY301
            # Use result directly in template
            template = self.template or "{result}"
            msg = template.format(result=result)
            content = MessageContent(type="text", content=msg)
            msg = f"Content from {self.name}:"
            sys_content = MessageContent(type="text", content=msg)
            return [
                PromptMessage(role="system", content=sys_content),
                PromptMessage(role="user", content=content),
            ]
        except Exception as exc:
            msg = f"Failed to execute prompt callable: {exc}"
            raise ValueError(msg) from exc

    @classmethod
    def from_callable(
        cls,
        fn: Callable[..., Any] | str,
        *,
        name_override: str | None = None,
        description_override: str | None = None,
        template_override: str | None = None,
        completions: Mapping[str, CompletionFunction] | None = None,
    ) -> DynamicPrompt:
        """Create a prompt from a callable.

        Args:
            fn: Function or import path to create prompt from
            name_override: Optional override for prompt name
            description_override: Optional override for prompt description
            template_override: Optional override for message template
            completions: Optional dict mapping argument names to completion functions

        Returns:
            DynamicPrompt instance

        Raises:
            ValueError: If callable cannot be imported or is invalid
        """
        from docstring_parser import parse as parse_docstring

        completions = completions or {}
        # Import if string path provided
        if isinstance(fn, str):
            fn = importing.import_callable(fn)

        # Get function metadata
        name = name_override or getattr(fn, "__name__", "unknown")
        # FORWARDREF: names imported only under TYPE_CHECKING stay ForwardRefs (-> Any)
        sig = inspect.signature(fn, annotation_format=annotationlib.Format.FORWARDREF)
        hints = get_type_hints(
            fn, include_extras=True, localns=locals(), format=annotationlib.Format.FORWARDREF
        )

        # Parse docstring
        docstring = inspect.getdoc(fn)
        if docstring:
            parsed = parse_docstring(docstring)
            description = description_override or parsed.short_description
            # Create mapping of param names to descriptions
            arg_docs = {
                param.arg_name: param.description
                for param in parsed.params
                if param.arg_name and param.description
            }
        else:
            description = description_override or f"Prompt from {name}"
            arg_docs = {}

        # Create arguments
        arguments = []
        for param_name, param in sig.parameters.items():
            if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
                continue

            type_hint = hints.get(param_name, Any)
            if isinstance(type_hint, ForwardRef):
                type_hint = Any
            required = param.default == param.empty
            arg = PromptParameter(
                name=param_name,
                description=arg_docs.get(param_name),
                required=required,
                type_hint=type_hint,
                default=None if param.default is param.empty else param.default,
                completion_function=completions.get(param_name),
            )
            arguments.append(arg)

        qualname = getattr(fn, "__qualname__", fn.__class__.__qualname__)
        path = f"{fn.__module__}.{qualname}"
        return cls(
            name=name,
            description=description or "",
            arguments=arguments,
            import_path=path,
            template=template_override,
            metadata={"source": "function", "import_path": path},
        )

completions class-attribute instance-attribute

completions: dict[str, str] | None = None

Optional mapping of argument names to completion functions.

import_path instance-attribute

import_path: str | Callable

Dotted import path to the callable that generates the prompt.

messages property

messages: list[PromptMessage]

Get the template messages for this prompt.

Note: These are template messages - actual content will be populated during format() when the callable is executed.

template class-attribute instance-attribute

template: str | None = None

Optional template string for formatting the callable's output.

type class-attribute instance-attribute

type: Literal['function'] = Field('function', init=False)

Discriminator field identifying this as a function-based prompt.

format async

format(arguments: dict[str, Any] | None = None) -> list[PromptMessage]

Format this prompt with given arguments.

Source code in src/llmling/prompts/models.py
async def format(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage]:
    """Format this prompt with given arguments."""
    args = arguments or {}
    self.validate_arguments(args)

    try:
        if isinstance(self.import_path, str):
            result = await calling.execute_callable(self.import_path, **args)
        elif inspect.iscoroutinefunction(self.import_path):
            result = await self.import_path(**args)
        elif inspect.isfunction(self.import_path):
            result = self.import_path(**args)
        else:
            msg = "Invalid result type"
            raise ValueError(msg)  # noqa: TRY301
        # Use result directly in template
        template = self.template or "{result}"
        msg = template.format(result=result)
        content = MessageContent(type="text", content=msg)
        msg = f"Content from {self.name}:"
        sys_content = MessageContent(type="text", content=msg)
        return [
            PromptMessage(role="system", content=sys_content),
            PromptMessage(role="user", content=content),
        ]
    except Exception as exc:
        msg = f"Failed to execute prompt callable: {exc}"
        raise ValueError(msg) from exc

from_callable classmethod

from_callable(
    fn: Callable[..., Any] | str,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    template_override: str | None = None,
    completions: Mapping[str, CompletionFunction] | None = None
) -> DynamicPrompt

Create a prompt from a callable.

Parameters:

Name Type Description Default
fn Callable[..., Any] | str

Function or import path to create prompt from

required
name_override str | None

Optional override for prompt name

None
description_override str | None

Optional override for prompt description

None
template_override str | None

Optional override for message template

None
completions Mapping[str, CompletionFunction] | None

Optional dict mapping argument names to completion functions

None

Returns:

Type Description
DynamicPrompt

DynamicPrompt instance

Raises:

Type Description
ValueError

If callable cannot be imported or is invalid

Source code in src/llmling/prompts/models.py
@classmethod
def from_callable(
    cls,
    fn: Callable[..., Any] | str,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    template_override: str | None = None,
    completions: Mapping[str, CompletionFunction] | None = None,
) -> DynamicPrompt:
    """Create a prompt from a callable.

    Args:
        fn: Function or import path to create prompt from
        name_override: Optional override for prompt name
        description_override: Optional override for prompt description
        template_override: Optional override for message template
        completions: Optional dict mapping argument names to completion functions

    Returns:
        DynamicPrompt instance

    Raises:
        ValueError: If callable cannot be imported or is invalid
    """
    from docstring_parser import parse as parse_docstring

    completions = completions or {}
    # Import if string path provided
    if isinstance(fn, str):
        fn = importing.import_callable(fn)

    # Get function metadata
    name = name_override or getattr(fn, "__name__", "unknown")
    # FORWARDREF: names imported only under TYPE_CHECKING stay ForwardRefs (-> Any)
    sig = inspect.signature(fn, annotation_format=annotationlib.Format.FORWARDREF)
    hints = get_type_hints(
        fn, include_extras=True, localns=locals(), format=annotationlib.Format.FORWARDREF
    )

    # Parse docstring
    docstring = inspect.getdoc(fn)
    if docstring:
        parsed = parse_docstring(docstring)
        description = description_override or parsed.short_description
        # Create mapping of param names to descriptions
        arg_docs = {
            param.arg_name: param.description
            for param in parsed.params
            if param.arg_name and param.description
        }
    else:
        description = description_override or f"Prompt from {name}"
        arg_docs = {}

    # Create arguments
    arguments = []
    for param_name, param in sig.parameters.items():
        if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
            continue

        type_hint = hints.get(param_name, Any)
        if isinstance(type_hint, ForwardRef):
            type_hint = Any
        required = param.default == param.empty
        arg = PromptParameter(
            name=param_name,
            description=arg_docs.get(param_name),
            required=required,
            type_hint=type_hint,
            default=None if param.default is param.empty else param.default,
            completion_function=completions.get(param_name),
        )
        arguments.append(arg)

    qualname = getattr(fn, "__qualname__", fn.__class__.__qualname__)
    path = f"{fn.__module__}.{qualname}"
    return cls(
        name=name,
        description=description or "",
        arguments=arguments,
        import_path=path,
        template=template_override,
        metadata={"source": "function", "import_path": path},
    )

get_completion_functions

get_completion_functions() -> dict[str, CompletionFunction]

Resolve completion function import paths and return a completion fn dict.

Source code in src/llmling/prompts/models.py
def get_completion_functions(self) -> dict[str, CompletionFunction]:
    """Resolve completion function import paths and return a completion fn dict."""
    completion_funcs: dict[str, CompletionFunction] = {}
    if not self.completions:
        return {}
    for arg_name, import_path in self.completions.items():
        try:
            func = importing.import_callable(import_path)
            completion_funcs[arg_name] = func
        except ValueError:
            msg = "Failed to import completion function for %s: %s"
            logger.warning(msg, arg_name, import_path)
    return completion_funcs

:fa-brands-github: Show source on GitHub