Skip to content

trulens.core.schema.prompt

trulens.core.schema.prompt

Serializable prompt-management classes.

Prompts are reusable, versioned definitions stored in the configured TruLens database. A Prompt is the stable identity, a PromptVersion is one immutable content-addressed revision of it, and a PromptLabel is a mutable pointer from a name such as production to one exact version.

Rendering happens locally and never calls a model.

Attributes

VARIABLE_PATTERN module-attribute

VARIABLE_PATTERN = compile(
    "\\{\\{\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*\\}\\}"
)

Pattern for a simple named variable such as {{question}}.

RESERVED_RENDER_KWARGS module-attribute

RESERVED_RENDER_KWARGS = ('model_overrides', 'strict')

Keyword arguments of the render methods that cannot name a variable.

LATEST_LABEL module-attribute

LATEST_LABEL = 'latest'

Label moved onto every newly created version.

Classes

PromptType

Bases: str, Enum

The kind of content a prompt holds.

Fixed at creation time. A prompt cannot change from text to chat or back.

Attributes
TEXT class-attribute instance-attribute
TEXT = 'text'

One template string.

CHAT class-attribute instance-attribute
CHAT = 'chat'

An ordered list of role-tagged messages.

MessageRole

Bases: str, Enum

Role of a message in a chat prompt.

PromptMessage

Bases: SerialModel

One message of a chat prompt.

Attributes
role instance-attribute

Who the message is attributed to.

content instance-attribute
content: Union[str, List[Dict[str, Any]]]

Message text, or a list of structured content blocks.

Functions
content_variables
content_variables() -> List[str]

Variable names referenced by this message, in order of appearance.

__repr__
__repr__() -> str

Safe repr that handles circular references.

Pydantic's default __repr__ does not guard against circular references among model instances, which leads to RecursionError (see GitHub issue #1862). This override uses the same formatted_objects context-variable that __rich_repr__ uses so that already-visited objects are replaced with a short placeholder instead of recursing infinitely.

__rich_repr__
__rich_repr__() -> Result

Requirement for pretty printing using the rich package.

InvalidTemplateError

Bases: ValueError

Raised when template content uses unsupported syntax.

VariableError

Bases: ValueError

Raised when render values do not match the declared variables.

Prompt

Bases: SerialModel, Hashable

The stable identity of a reusable prompt.

The identifier is derived from the slug so that renaming the prompt or editing its description does not break existing references.

Attributes
prompt_id instance-attribute
prompt_id: PromptID

The unique identifier for the prompt.

slug instance-attribute
slug: str

Short, stable, human-written key such as support-assistant.

name instance-attribute
name: str

Display name.

prompt_type instance-attribute
prompt_type: PromptType

Whether versions of this prompt hold text or chat content.

Immutable once the prompt exists.

description class-attribute instance-attribute
description: Optional[str] = None

Free-text description.

tags class-attribute instance-attribute
tags: List[str] = Field(default_factory=list)

Tags for grouping prompts.

created_at class-attribute instance-attribute
created_at: datetime = Field(
    default_factory=lambda: now(utc)
)

When the prompt was first created.

updated_at class-attribute instance-attribute
updated_at: datetime = Field(
    default_factory=lambda: now(utc)
)

When the prompt metadata last changed.

Functions
__repr__
__repr__() -> str

Safe repr that handles circular references.

Pydantic's default __repr__ does not guard against circular references among model instances, which leads to RecursionError (see GitHub issue #1862). This override uses the same formatted_objects context-variable that __rich_repr__ uses so that already-visited objects are replaced with a short placeholder instead of recursing infinitely.

__rich_repr__
__rich_repr__() -> Result

Requirement for pretty printing using the rich package.

PromptVersion

Bases: SerialModel, Hashable

One immutable revision of a prompt.

The identifier is content-addressed over the prompt identity, the canonical content, the declared variables, the model defaults, and the response format, so creating the same version twice is idempotent.

Attributes
version_id instance-attribute
version_id: PromptVersionID

The unique identifier for this version.

prompt_id instance-attribute
prompt_id: PromptID

The prompt this version belongs to.

prompt_type instance-attribute
prompt_type: PromptType

Matches the type of the owning prompt.

parent_version_id class-attribute instance-attribute
parent_version_id: Optional[PromptVersionID] = None

The version this one was derived from, when known.

text class-attribute instance-attribute
text: Optional[str] = None

Template string. Set for text prompts only.

messages class-attribute instance-attribute
messages: Optional[List[PromptMessage]] = None

Ordered messages. Set for chat prompts only.

variables class-attribute instance-attribute
variables: List[str] = Field(default_factory=list)

Names of the variables this version declares.

model_defaults class-attribute instance-attribute
model_defaults: Dict[str, Any] = Field(default_factory=dict)

Provider-neutral model settings persisted with the version.

Never holds credentials.

response_format class-attribute instance-attribute
response_format: Optional[Dict[str, Any]] = None

Response-format metadata handed to provider adapters.

change_note class-attribute instance-attribute
change_note: Optional[str] = None

Why this version was created.

content_hash class-attribute instance-attribute
content_hash: str = ''

Hash of the canonical content alone.

created_at class-attribute instance-attribute
created_at: datetime = Field(
    default_factory=lambda: now(utc)
)

When the version was created.

created_by class-attribute instance-attribute
created_by: Optional[str] = None

Who created the version, when the caller supplies it.

Functions
__repr__
__repr__() -> str

Safe repr that handles circular references.

Pydantic's default __repr__ does not guard against circular references among model instances, which leads to RecursionError (see GitHub issue #1862). This override uses the same formatted_objects context-variable that __rich_repr__ uses so that already-visited objects are replaced with a short placeholder instead of recursing infinitely.

__rich_repr__
__rich_repr__() -> Result

Requirement for pretty printing using the rich package.

PromptLabel

Bases: SerialModel

A mutable pointer from a label to one exact version.

staging and production are conventions, not hosted environments.

Attributes
prompt_id instance-attribute
prompt_id: PromptID

The prompt this label belongs to.

label instance-attribute
label: str

The label name.

version_id instance-attribute
version_id: PromptVersionID

The exact version the label currently points at.

updated_at class-attribute instance-attribute
updated_at: datetime = Field(
    default_factory=lambda: now(utc)
)

When the pointer last moved.

Functions
__repr__
__repr__() -> str

Safe repr that handles circular references.

Pydantic's default __repr__ does not guard against circular references among model instances, which leads to RecursionError (see GitHub issue #1862). This override uses the same formatted_objects context-variable that __rich_repr__ uses so that already-visited objects are replaced with a short placeholder instead of recursing infinitely.

__rich_repr__
__rich_repr__() -> Result

Requirement for pretty printing using the rich package.

PromptLabelHistory

Bases: SerialModel

One append-only record of a label movement.

Attributes
history_id instance-attribute
history_id: str

The unique identifier for this history entry.

prompt_id instance-attribute
prompt_id: PromptID

The prompt whose label moved.

label instance-attribute
label: str

The label that moved.

previous_version_id class-attribute instance-attribute
previous_version_id: Optional[PromptVersionID] = None

Where the label pointed before, or None on first assignment.

new_version_id instance-attribute
new_version_id: PromptVersionID

Where the label points after the move.

moved_by class-attribute instance-attribute
moved_by: Optional[str] = None

Caller label supplied by whoever moved the pointer.

timestamp class-attribute instance-attribute
timestamp: datetime = Field(
    default_factory=lambda: now(utc)
)

When the move happened.

Functions
__repr__
__repr__() -> str

Safe repr that handles circular references.

Pydantic's default __repr__ does not guard against circular references among model instances, which leads to RecursionError (see GitHub issue #1862). This override uses the same formatted_objects context-variable that __rich_repr__ uses so that already-visited objects are replaced with a short placeholder instead of recursing infinitely.

__rich_repr__
__rich_repr__() -> Result

Requirement for pretty printing using the rich package.

RenderedPrompt

Bases: SerialModel

The local result of rendering one exact version.

No model was called to produce this and no credentials were needed.

Attributes
prompt_id instance-attribute
prompt_id: PromptID

The prompt that was rendered.

slug instance-attribute
slug: str

Slug of the prompt that was rendered.

version_id instance-attribute
version_id: PromptVersionID

The exact version that was rendered.

label class-attribute instance-attribute
label: Optional[str] = None

The label that was asked for, when the version came from one.

prompt_type instance-attribute
prompt_type: PromptType

Whether this holds text or messages.

text class-attribute instance-attribute
text: Optional[str] = None

Rendered text. Set for text prompts only.

messages class-attribute instance-attribute
messages: Optional[List[Dict[str, Any]]] = None

Rendered provider-neutral message dictionaries. Chat prompts only.

model_args class-attribute instance-attribute
model_args: Dict[str, Any] = Field(default_factory=dict)

Persisted model defaults merged with the caller's overrides.

response_format class-attribute instance-attribute
response_format: Optional[Dict[str, Any]] = None

Response-format metadata, kept out of model_args on purpose.

rendered_content_hash instance-attribute
rendered_content_hash: str

Hash of the rendered content.

Functions
__repr__
__repr__() -> str

Safe repr that handles circular references.

Pydantic's default __repr__ does not guard against circular references among model instances, which leads to RecursionError (see GitHub issue #1862). This override uses the same formatted_objects context-variable that __rich_repr__ uses so that already-visited objects are replaced with a short placeholder instead of recursing infinitely.

__rich_repr__
__rich_repr__() -> Result

Requirement for pretty printing using the rich package.

ResolvedPrompt

Bases: SerialModel

One exact prompt version, plus strict local rendering.

Attributes
prompt instance-attribute
prompt: Prompt

The prompt identity.

version instance-attribute
version: PromptVersion

The exact version that was resolved.

label class-attribute instance-attribute
label: Optional[str] = None

The label that was requested, when a label was used.

version_id property
version_id: PromptVersionID

The exact version identifier.

Functions
model_args
model_args(
    model_overrides: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]

Persisted model defaults merged with model_overrides.

Neither the stored defaults nor the supplied overrides are mutated.

PARAMETER DESCRIPTION
model_overrides

Caller settings that win over the defaults.

TYPE: Optional[Dict[str, Any]] DEFAULT: None

RETURNS DESCRIPTION
Dict[str, Any]

A new dictionary.

render
render(
    model_overrides: Optional[Dict[str, Any]] = None,
    strict: bool = True,
    **values: Any
) -> RenderedPrompt

Render this version locally.

PARAMETER DESCRIPTION
model_overrides

Model settings that win over the persisted defaults.

TYPE: Optional[Dict[str, Any]] DEFAULT: None

strict

When true, values that no declared variable uses are an error rather than being dropped. Missing values are always an error.

TYPE: bool DEFAULT: True

**values

One entry per declared variable.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
RenderedPrompt
RenderedPrompt

text or ordered message dictionaries, the merged model arguments,

RenderedPrompt

and the response format kept separate.

RAISES DESCRIPTION
VariableError

If the supplied values do not match the declared variables.

build
build(
    model_overrides: Optional[Dict[str, Any]] = None,
    strict: bool = True,
    **values: Any
) -> List[Dict[str, Any]]

Render a chat version straight to message dictionaries.

PARAMETER DESCRIPTION
model_overrides

Model settings that win over the persisted defaults. Accepted so that the signature matches render.

TYPE: Optional[Dict[str, Any]] DEFAULT: None

strict

See render.

TYPE: bool DEFAULT: True

**values

One entry per declared variable.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
List[Dict[str, Any]]

Ordered provider-neutral message dictionaries.

RAISES DESCRIPTION
ValueError

If this is a text prompt.

__repr__
__repr__() -> str

Safe repr that handles circular references.

Pydantic's default __repr__ does not guard against circular references among model instances, which leads to RecursionError (see GitHub issue #1862). This override uses the same formatted_objects context-variable that __rich_repr__ uses so that already-visited objects are replaced with a short placeholder instead of recursing infinitely.

__rich_repr__
__rich_repr__() -> Result

Requirement for pretty printing using the rich package.

Functions

validate_template

validate_template(strings: Sequence[str]) -> None

Reject template syntax beyond simple named variables.

PARAMETER DESCRIPTION
strings

Template strings to check.

TYPE: Sequence[str]

RAISES DESCRIPTION
InvalidTemplateError

If a statement tag is present or a {{ ... }} span is not a bare variable name.