Skip to content

prompts

Class info

Re-exported classes

Class Module Description
BasePrompt llmling.prompts.models Base class for all prompts.
DynamicPrompt llmling.prompts.models Dynamic prompt loaded from callable.
PromptMessage llmling.prompts.models A message in a prompt template.
PromptParameter llmling.prompts.models Prompt argument with validation information.
PromptRegistry llmling.prompts.registry Registry for prompt templates.
StaticPrompt llmling.prompts.models Static prompt defined by message list.

🛈 DocStrings

Prompt classes and registry for defining and managing prompts.

BasePrompt

Bases: BaseModel

Base class for all prompts.

Source code in src/llmling/prompts/models.py
class BasePrompt(BaseModel):
    """Base class for all prompts."""

    name: str | None = Field(None, exclude=True)
    """Technical identifier (automatically set from config key during registration)."""

    description: str
    """Human-readable description of what this prompt does."""

    title: str | None = None
    """Title of the prompt."""

    arguments: list[PromptParameter] = Field(default_factory=list)
    """List of arguments that this prompt accepts."""

    metadata: dict[str, Any] = Field(default_factory=dict)
    """Additional metadata for storing custom prompt information."""
    # messages: list[PromptMessage]

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

    def get_messages(self) -> list[PromptMessage]:
        """Get the messages for this prompt."""
        if not hasattr(self, "messages"):
            msg = f"{self.__class__.__name__} must implement 'messages' attribute"
            raise NotImplementedError(msg)
        return self.messages  # pyright: ignore  # ty: ignore[invalid-explicit-return]

    def validate_arguments(self, provided: dict[str, Any]) -> None:
        """Validate that required arguments are provided."""
        required = {arg.name for arg in self.arguments if arg.required}
        missing = required - set(provided)
        if missing:
            msg = f"Missing required arguments: {', '.join(missing)}"
            raise ValueError(msg)

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

        Args:
            arguments: Optional argument values

        Returns:
            List of formatted messages

        Raises:
            ValueError: If required arguments are missing
        """
        raise NotImplementedError

    def to_mcp_prompt(self) -> MCPPrompt:
        """Convert to MCP Prompt."""
        from mcp.types import Prompt as MCPPrompt

        if self.name is None:
            msg = "Prompt name not set. This should be set during registration."
            raise ValueError(msg)
        args = [arg.to_mcp_argument() for arg in self.arguments]
        return MCPPrompt(name=self.name, description=self.description, arguments=args)

arguments class-attribute instance-attribute

arguments: list[PromptParameter] = Field(default_factory=list)

List of arguments that this prompt accepts.

description instance-attribute

description: str

Human-readable description of what this prompt does.

metadata class-attribute instance-attribute

metadata: dict[str, Any] = Field(default_factory=dict)

Additional metadata for storing custom prompt information.

name class-attribute instance-attribute

name: str | None = Field(None, exclude=True)

Technical identifier (automatically set from config key during registration).

title class-attribute instance-attribute

title: str | None = None

Title of the prompt.

format async

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

Format this prompt with given arguments.

Parameters:

Name Type Description Default
arguments dict[str, Any] | None

Optional argument values

None

Returns:

Type Description
list[PromptMessage]

List of formatted messages

Raises:

Type Description
ValueError

If required arguments are missing

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: Optional argument values

    Returns:
        List of formatted messages

    Raises:
        ValueError: If required arguments are missing
    """
    raise NotImplementedError

get_messages

get_messages() -> list[PromptMessage]

Get the messages for this prompt.

Source code in src/llmling/prompts/models.py
def get_messages(self) -> list[PromptMessage]:
    """Get the messages for this prompt."""
    if not hasattr(self, "messages"):
        msg = f"{self.__class__.__name__} must implement 'messages' attribute"
        raise NotImplementedError(msg)
    return self.messages  # pyright: ignore  # ty: ignore[invalid-explicit-return]

to_mcp_prompt

to_mcp_prompt() -> Prompt

Convert to MCP Prompt.

Source code in src/llmling/prompts/models.py
def to_mcp_prompt(self) -> MCPPrompt:
    """Convert to MCP Prompt."""
    from mcp.types import Prompt as MCPPrompt

    if self.name is None:
        msg = "Prompt name not set. This should be set during registration."
        raise ValueError(msg)
    args = [arg.to_mcp_argument() for arg in self.arguments]
    return MCPPrompt(name=self.name, description=self.description, arguments=args)

validate_arguments

validate_arguments(provided: dict[str, Any]) -> None

Validate that required arguments are provided.

Source code in src/llmling/prompts/models.py
def validate_arguments(self, provided: dict[str, Any]) -> None:
    """Validate that required arguments are provided."""
    required = {arg.name for arg in self.arguments if arg.required}
    missing = required - set(provided)
    if missing:
        msg = f"Missing required arguments: {', '.join(missing)}"
        raise ValueError(msg)

DynamicPrompt

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

PromptMessage

Bases: BaseModel

A message in a prompt template.

Source code in src/llmling/prompts/models.py
class PromptMessage(BaseModel):
    """A message in a prompt template."""

    role: MessageRole
    content: str | MessageContent | list[MessageContent] = ""

    model_config = ConfigDict(frozen=True)

    def get_text_content(self) -> str:
        """Get text content of message."""
        match self.content:
            case str():
                return self.content
            case MessageContent() if self.content.type == "text":
                return self.content.content
            case list() if self.content:
                # Join text content items with space
                text_items = [
                    item.content
                    for item in self.content
                    if isinstance(item, MessageContent) and item.type == "text"
                ]
                return " ".join(text_items) if text_items else ""
            case _:
                return ""

get_text_content

get_text_content() -> str

Get text content of message.

Source code in src/llmling/prompts/models.py
def get_text_content(self) -> str:
    """Get text content of message."""
    match self.content:
        case str():
            return self.content
        case MessageContent() if self.content.type == "text":
            return self.content.content
        case list() if self.content:
            # Join text content items with space
            text_items = [
                item.content
                for item in self.content
                if isinstance(item, MessageContent) and item.type == "text"
            ]
            return " ".join(text_items) if text_items else ""
        case _:
            return ""

PromptParameter

Bases: BaseModel

Prompt argument with validation information.

Source code in src/llmling/prompts/models.py
class PromptParameter(BaseModel):
    """Prompt argument with validation information."""

    name: str
    """Name of the argument as used in the prompt."""

    description: str | None = None
    """Human-readable description of the argument."""

    required: bool = False
    """Whether this argument must be provided when formatting the prompt."""

    type_hint: ImportString = Field(default="str")
    """Type annotation for the argument, defaults to str."""

    default: Any | None = None
    """Default value if argument is optional."""

    completion_function: ImportString | None = Field(default=None)
    """Optional function to provide argument completions."""

    model_config = ConfigDict(use_attribute_docstrings=True)

    def to_mcp_argument(self) -> PromptArgument:
        """Convert to MCP PromptArgument."""
        from mcp.types import PromptArgument

        return PromptArgument(name=self.name, description=self.description, required=self.required)

completion_function class-attribute instance-attribute

completion_function: ImportString | None = Field(default=None)

Optional function to provide argument completions.

default class-attribute instance-attribute

default: Any | None = None

Default value if argument is optional.

description class-attribute instance-attribute

description: str | None = None

Human-readable description of the argument.

name instance-attribute

name: str

Name of the argument as used in the prompt.

required class-attribute instance-attribute

required: bool = False

Whether this argument must be provided when formatting the prompt.

type_hint class-attribute instance-attribute

type_hint: ImportString = Field(default='str')

Type annotation for the argument, defaults to str.

to_mcp_argument

to_mcp_argument() -> PromptArgument

Convert to MCP PromptArgument.

Source code in src/llmling/prompts/models.py
def to_mcp_argument(self) -> PromptArgument:
    """Convert to MCP PromptArgument."""
    from mcp.types import PromptArgument

    return PromptArgument(name=self.name, description=self.description, required=self.required)

PromptRegistry

Bases: BaseRegistry[str, BasePrompt], CompletionProvider

Registry for prompt templates.

Source code in src/llmling/prompts/registry.py
class PromptRegistry(BaseRegistry[str, BasePrompt], CompletionProvider):
    """Registry for prompt templates."""

    @property
    def _error_class(self) -> type[exceptions.LLMLingError]:
        return exceptions.LLMLingError

    def register(self, key: str, item: BasePrompt, replace: bool = False) -> None:
        """Register prompt with its key as name."""
        # Create copy with name set
        item = item.model_copy(update={"name": key})
        super().register(key, item, replace)

    def _validate_item(self, item: Any) -> BasePrompt:
        """Validate and convert items to BasePrompt instances."""
        return to_prompt(item)

    def register_function(
        self,
        fn: Callable[..., Any] | str,
        name: str | None = None,
        *,
        replace: bool = False,
    ) -> None:
        """Register a function as a prompt."""
        prompt = DynamicPrompt.from_callable(fn, name_override=name)
        assert prompt.name
        self.register(prompt.name, prompt, replace=replace)

    async def get_completions(
        self,
        current_value: str,
        argument_name: str | None = None,
        **options: Any,
    ) -> list[str]:
        """Get completions for a prompt argument."""
        try:
            prompt_name = options.get("prompt_name")
            if not prompt_name or not argument_name:
                return []

            prompt = self[prompt_name]
            arg = next((a for a in prompt.arguments if a.name == argument_name), None)
            if not arg:
                return []
            return get_completion_for_arg(arg, current_value)

        except Exception:
            logger.exception("Completion failed")
            return []

get_completions async

get_completions(current_value: str, argument_name: str | None = None, **options: Any) -> list[str]

Get completions for a prompt argument.

Source code in src/llmling/prompts/registry.py
async def get_completions(
    self,
    current_value: str,
    argument_name: str | None = None,
    **options: Any,
) -> list[str]:
    """Get completions for a prompt argument."""
    try:
        prompt_name = options.get("prompt_name")
        if not prompt_name or not argument_name:
            return []

        prompt = self[prompt_name]
        arg = next((a for a in prompt.arguments if a.name == argument_name), None)
        if not arg:
            return []
        return get_completion_for_arg(arg, current_value)

    except Exception:
        logger.exception("Completion failed")
        return []

register

register(key: str, item: BasePrompt, replace: bool = False) -> None

Register prompt with its key as name.

Source code in src/llmling/prompts/registry.py
def register(self, key: str, item: BasePrompt, replace: bool = False) -> None:
    """Register prompt with its key as name."""
    # Create copy with name set
    item = item.model_copy(update={"name": key})
    super().register(key, item, replace)

register_function

register_function(
    fn: Callable[..., Any] | str, name: str | None = None, *, replace: bool = False
) -> None

Register a function as a prompt.

Source code in src/llmling/prompts/registry.py
def register_function(
    self,
    fn: Callable[..., Any] | str,
    name: str | None = None,
    *,
    replace: bool = False,
) -> None:
    """Register a function as a prompt."""
    prompt = DynamicPrompt.from_callable(fn, name_override=name)
    assert prompt.name
    self.register(prompt.name, prompt, replace=replace)

StaticPrompt

Bases: BasePrompt

Static prompt defined by message list.

Source code in src/llmling/prompts/models.py
class StaticPrompt(BasePrompt):
    """Static prompt defined by message list."""

    messages: list[PromptMessage]
    """List of messages that make up this prompt."""

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

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

    def to_fastmcp_prompt(self) -> FastMCPPrompt:
        params = [
            FastMCPArgument(name=p.name, description=p.description, required=p.required)
            for p in self.arguments
        ]
        return FastMCPPrompt(
            name=self.name or "",
            title=self.title,
            description=self.description,
            arguments=params,
            icons=None,
            tags=set(),
        )

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

        # Add default values for optional arguments
        for arg in self.arguments:
            if arg.name not in args and not arg.required:
                args[arg.name] = arg.default if arg.default is not None else ""

        # Format all messages
        formatted_messages = []
        for msg in self.messages:
            match msg.content:
                case str():
                    content: MessageContent | list[MessageContent] = MessageContent(
                        type="text", content=msg.content.format(**args)
                    )
                case MessageContent() if msg.content.type == "text":
                    msg_content = msg.content.content.format(**args)
                    content = MessageContent(type="text", content=msg_content)
                case list():
                    content = [
                        MessageContent(
                            type=item.type,
                            content=item.content.format(**args)
                            if item.type == "text"
                            else item.content,
                            alt_text=item.alt_text,
                        )
                        for item in msg.content
                        if isinstance(item, MessageContent)
                    ]
                case _:
                    content = msg.content

            formatted_messages.append(PromptMessage(role=msg.role, content=content))

        return formatted_messages

messages instance-attribute

messages: list[PromptMessage]

List of messages that make up this prompt.

type class-attribute instance-attribute

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

Discriminator field identifying this as a static text prompt.

format async

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

Format static prompt messages with arguments.

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

    # Add default values for optional arguments
    for arg in self.arguments:
        if arg.name not in args and not arg.required:
            args[arg.name] = arg.default if arg.default is not None else ""

    # Format all messages
    formatted_messages = []
    for msg in self.messages:
        match msg.content:
            case str():
                content: MessageContent | list[MessageContent] = MessageContent(
                    type="text", content=msg.content.format(**args)
                )
            case MessageContent() if msg.content.type == "text":
                msg_content = msg.content.content.format(**args)
                content = MessageContent(type="text", content=msg_content)
            case list():
                content = [
                    MessageContent(
                        type=item.type,
                        content=item.content.format(**args)
                        if item.type == "text"
                        else item.content,
                        alt_text=item.alt_text,
                    )
                    for item in msg.content
                    if isinstance(item, MessageContent)
                ]
            case _:
                content = msg.content

        formatted_messages.append(PromptMessage(role=msg.role, content=content))

    return formatted_messages