Skip to content

ToPrompt

PyPI License Package status Monthly downloads Distribution format Wheel availability Python version Implementation Releases Github Contributors Github Forks Github Issues Github Issues Github Watchers Github Stars Github Repository size Github last commit Github release date Github language count Github commits this month Package status PyUp

Read the documentation!

Convert Python objects into LLM-friendly text. toprompt provides one async function, to_prompt(), that turns dataclasses, pydantic models, database schemas, CLI apps, FastAPI apps and more into readable descriptions you can drop into a prompt.

Installation

pip install toprompt

Quickstart

import asyncio
from dataclasses import dataclass

from toprompt import Template, to_prompt


@dataclass
class User:
    """A registered user."""

    name: str
    age: int


class Weather:
    def __prompt__(self) -> str:
        return "Sunny, 23 degrees"


async def main() -> None:
    print(await to_prompt(User("Alice", 30)))
    # User:
    # A registered user.
    #
    # - name = 'Alice' (<class 'str'>)
    # - age = 30 (<class 'int'>)

    print(await to_prompt({"user": User("Bob", 25), "weather": Weather()}))

    # Jinja templating (via MiniJinja) is opt-in
    template = Template("Hello {{ agent.name }}!")
    print(await to_prompt(template, template_mode="explicit", name="Bot"))  # Hello Bot!


asyncio.run(main())

Supported objects

  • Strings (returned as-is) and Template strings rendered with MiniJinja (template_mode="explicit", or "all" to template every string)
  • Custom objects implementing __prompt__() or a __prompt_type__() classmethod (sync or async), see the PromptConvertible / PromptTypeConvertible protocols
  • Structured objects via fieldz: dataclasses, pydantic models, attrs classes, msgspec structs, ...
  • SQLModel table classes and instances (table schema plus current values)
  • SQLite connections (sqlite3.Connection): tables, columns, keys and indexes
  • CLI apps: argparse.ArgumentParser, click commands/groups, typer apps, cleo and cappa (via clinspector)
  • FastAPI apps: endpoints, parameters, request and response schemas
  • llmling BasePrompt objects
  • datetime (ISO format) and compiled regex patterns
  • Containers (dict, list, tuple), converted recursively
  • Callables and coroutines: called/awaited, and the result is converted

Framework integrations are optional: toprompt only uses them if they are installed.