Skip to content

toprompt

Class info

Re-exported classes

Class Module Description
PromptConvertible toprompt.to_prompt Protocol for instances that can be converted to prompts.
PromptTypeConvertible toprompt.to_prompt Protocol for types that can be converted to prompts.
Template toprompt.to_prompt Marker class for strings that should be templated.

🛈 DocStrings

ToPrompt: main package.

Convert python objects to LLM-friendly descriptions.

PromptConvertible

Bases: Protocol

Protocol for instances that can be converted to prompts.

Source code in src/toprompt/to_prompt.py
class PromptConvertible(Protocol):
    """Protocol for instances that can be converted to prompts."""

    def __prompt__(self) -> str | Awaitable[str]: ...

PromptTypeConvertible

Bases: Protocol

Protocol for types that can be converted to prompts.

Source code in src/toprompt/to_prompt.py
class PromptTypeConvertible(Protocol):
    """Protocol for types that can be converted to prompts."""

    @classmethod
    def __prompt_type__(cls) -> str | Awaitable[str]: ...

Template

Bases: str

Marker class for strings that should be templated.

Source code in src/toprompt/to_prompt.py
class Template(str):  # noqa: SLOT000
    """Marker class for strings that should be templated."""

render_prompt

render_prompt(template: str, agent_context: dict[str, Any]) -> str

Render a Jinja prompt template using MiniJinja.

The context is exposed to the template as agent, e.g. render_prompt("Hi {{ agent.name }}", {"name": "Bot"}) returns "Hi Bot".

Parameters:

Name Type Description Default
template str

Jinja template string

required
agent_context dict[str, Any]

Variables available as agent.<key> in the template

required

Returns:

Type Description
str

The rendered string

Source code in src/toprompt/to_prompt.py
def render_prompt(
    template: str,
    agent_context: dict[str, Any],
) -> str:
    """Render a Jinja prompt template using MiniJinja.

    The context is exposed to the template as ``agent``, e.g.
    ``render_prompt("Hi {{ agent.name }}", {"name": "Bot"})`` returns ``"Hi Bot"``.

    Args:
        template: Jinja template string
        agent_context: Variables available as ``agent.<key>`` in the template

    Returns:
        The rendered string
    """
    return _jinja_env().render_str(template, agent=agent_context)