ToPrompt¶
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¶
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
Templatestrings 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 thePromptConvertible/PromptTypeConvertibleprotocols - 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
BasePromptobjects 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.