Skip to content

FilePrompt

Base classes

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

â‹” Inheritance diagram

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

🛈 DocStrings

Bases: BasePrompt

Prompt loaded from a file.

This type of prompt loads its content from a file, allowing for longer or more complex prompts to be managed in separate files. The file content is loaded and parsed according to the specified format.

Source code in src/llmling/prompts/models.py
class FilePrompt(BasePrompt):
    """Prompt loaded from a file.

    This type of prompt loads its content from a file, allowing for longer or more
    complex prompts to be managed in separate files. The file content is loaded
    and parsed according to the specified format.
    """

    path: str | os.PathLike[str] | upath.UPath
    """Path to the file containing the prompt content."""

    fmt: Literal["text", "markdown", "jinja2"] = Field("text", alias="format")
    """Format of the file content (text, markdown, or jinja2 template)."""

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

    watch: bool = False
    """Whether to watch the file for changes and reload automatically."""

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

    @property
    def messages(self) -> list[PromptMessage]:
        """Get messages from file content."""
        from upathtools import to_upath

        content = to_upath(self.path).read_text("utf-8")

        match self.fmt:
            case "text":
                # Simple text format - whole file as user message
                msg = MessageContent(type="text", content=content)
            case "markdown":
                # TODO: Parse markdown sections into separate messages
                msg = MessageContent(type="text", content=content)
            case "jinja2":
                # Raw template - will be formatted during format()
                msg = MessageContent(type="text", content=content)
            case _:
                msg = f"Unsupported format: {self.fmt}"
                raise ValueError(msg)
        return [PromptMessage(role="user", content=msg)]

    async def format(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage]:
        """Format the file content with arguments."""
        from upathtools import to_upath

        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 ""

        content = to_upath(self.path).read_text("utf-8")

        if self.fmt == "jinja2":
            # Use jinja2 for template formatting
            import jinja2

            env = jinja2.Environment(autoescape=True, enable_async=True)
            template = env.from_string(content)
            content = await template.render_async(**args)
        else:
            # Use simple string formatting
            try:
                content = content.format(**args)
            except KeyError as exc:
                msg = f"Missing argument in template: {exc}"
                raise ValueError(msg) from exc
        msg_content = MessageContent(type="text", content=content)
        return [PromptMessage(role="user", content=msg_content)]

fmt class-attribute instance-attribute

fmt: Literal['text', 'markdown', 'jinja2'] = Field('text', alias='format')

Format of the file content (text, markdown, or jinja2 template).

messages property

messages: list[PromptMessage]

Get messages from file content.

path instance-attribute

path: str | PathLike[str] | UPath

Path to the file containing the prompt content.

type class-attribute instance-attribute

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

Discriminator field identifying this as a file-based prompt.

watch class-attribute instance-attribute

watch: bool = False

Whether to watch the file for changes and reload automatically.

format async

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

Format the file content with arguments.

Source code in src/llmling/prompts/models.py
async def format(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage]:
    """Format the file content with arguments."""
    from upathtools import to_upath

    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 ""

    content = to_upath(self.path).read_text("utf-8")

    if self.fmt == "jinja2":
        # Use jinja2 for template formatting
        import jinja2

        env = jinja2.Environment(autoescape=True, enable_async=True)
        template = env.from_string(content)
        content = await template.render_async(**args)
    else:
        # Use simple string formatting
        try:
            content = content.format(**args)
        except KeyError as exc:
            msg = f"Missing argument in template: {exc}"
            raise ValueError(msg) from exc
    msg_content = MessageContent(type="text", content=content)
    return [PromptMessage(role="user", content=msg_content)]

:fa-brands-github: Show source on GitHub