API Reference
Structured prompts using template strings
DedentError
Bases: StructuredPromptsError
Raised when dedenting configuration is invalid or dedenting fails.
Source code in src/t_prompts/exceptions.py
61 62 63 64 65 66 | |
DuplicateKeyError
Bases: StructuredPromptsError
Raised when duplicate keys are found and allow_duplicate_keys=False.
Source code in src/t_prompts/exceptions.py
21 22 23 24 25 26 27 28 29 | |
Element
dataclass
Bases: ABC
Base class for all elements in a StructuredPrompt.
An element can be either a Static text segment or a StructuredInterpolation.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
Union[str, int]
|
Identifier for this element. For interpolations: string key from format_spec. For static segments: integer index in the strings tuple. |
parent |
StructuredPrompt | None
|
The parent StructuredPrompt that contains this element. |
index |
int
|
The position of this element in the overall element sequence. |
source_location |
SourceLocation | None
|
Source code location information for this element (if available). |
id |
str
|
Unique identifier for this element (UUID4 string). |
metadata |
dict[str, Any]
|
Metadata dictionary for storing analysis results and other information. |
Source code in src/t_prompts/element.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
is_interpolated
property
Check if this element has been interpolated into a parent prompt.
Returns True if the element has interpolation metadata (expression is not None). For Static elements and non-interpolated StructuredPrompts, returns False.
Returns:
| Type | Description |
|---|---|
bool
|
True if element has been interpolated, False otherwise. |
ir(ctx=None)
abstractmethod
Convert this element to an IntermediateRepresentation.
Each element type knows how to convert itself to IR, including applying render hints, conversions, and handling nested structures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
RenderContext | None
|
Rendering context with path, header level, etc. If None, uses default context (path=(), header_level=1, max_header_level=4). |
None
|
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
IR with chunks for this element. |
Source code in src/t_prompts/element.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
toJSON()
abstractmethod
Convert this element to a JSON-serializable dictionary.
Each element type implements its own serialization logic. References to objects with IDs (e.g., StructuredPrompt) are serialized as just the ID string. The full object dictionaries are stored elsewhere in the JSON structure.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
JSON-serializable dictionary representing this element. |
Source code in src/t_prompts/element.py
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
EmptyExpressionError
Bases: StructuredPromptsError
Raised when an empty expression {} is encountered.
Source code in src/t_prompts/exceptions.py
52 53 54 55 56 57 58 | |
ImageChunk
dataclass
An image chunk in the rendered output.
Each chunk maps to exactly one source element.
Attributes:
| Name | Type | Description |
|---|---|---|
image |
Any
|
The PIL Image object (typed as Any to avoid hard dependency on PIL). |
element_id |
str
|
UUID of the source element that produced this chunk. |
id |
str
|
Unique identifier for this chunk (UUID4 string). |
metadata |
dict[str, Any]
|
Metadata dictionary for storing analysis results and other information. |
Source code in src/t_prompts/ir.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
text
property
Return a text placeholder for this image.
Returns a bracketed description with format, dimensions, and mode. Example: [Image: PNG 1024x768 RGB]
Returns:
| Type | Description |
|---|---|
str
|
Text placeholder describing the image. |
toJSON()
Convert ImageChunk to JSON-serializable dictionary.
The image is serialized to base64 with metadata.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with type, image (as base64 dict), element_id, id, metadata. |
Source code in src/t_prompts/ir.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
ImageInterpolation
dataclass
Bases: Element
Immutable record of an image interpolation in a StructuredPrompt.
Represents interpolations where the value is a PIL Image object. Cannot be rendered to text - raises ImageRenderError when attempting to render.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
The key used for dict-like access (parsed from format_spec or expression). |
parent |
StructuredPrompt | None
|
The parent StructuredPrompt that contains this interpolation. |
index |
int
|
The position of this element in the overall element sequence. |
source_location |
SourceLocation | None
|
Source code location information for this element (if available). |
expression |
str
|
The original expression text from the t-string (what was inside {}). |
conversion |
str | None
|
The conversion flag if present (!s, !r, !a), or None. |
format_spec |
str
|
The format specification string (everything after :), or empty string. |
render_hints |
str
|
Rendering hints parsed from format_spec (everything after first colon in format spec). |
value |
Any
|
The PIL Image object (typed as Any to avoid hard dependency on PIL). |
Source code in src/t_prompts/element.py
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 | |
__repr__()
Return a helpful debug representation.
Source code in src/t_prompts/element.py
657 658 659 660 661 662 | |
ir(ctx=None)
Convert image to an IntermediateRepresentation with an ImageChunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
RenderContext | None
|
Rendering context. If None, uses default context. |
None
|
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
IR with a single ImageChunk. |
Source code in src/t_prompts/element.py
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 | |
toJSON()
Convert ImageInterpolation to JSON-serializable dictionary.
The PIL Image value is serialized using _serialize_image to include base64 data and metadata.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with type, key, index, source_location, id, expression, conversion, format_spec, render_hints, value, parent_id, metadata. |
Source code in src/t_prompts/element.py
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 | |
ImageRenderError
Bases: StructuredPromptsError
Raised when attempting to render a prompt containing images to text.
Source code in src/t_prompts/exceptions.py
69 70 71 72 73 74 75 76 77 | |
IntermediateRepresentation
Lightweight intermediate representation with multi-modal chunks.
This class is a data container for rendered output with chunk-based operations. Each chunk contains an element_id that maps it directly to its source element. Query methods and indexes are provided by CompiledIR (created via compile()).
Operations: - empty() - create empty IR - from_text(text, element_id) - create IR from text string - from_image(image, element_id) - create IR from PIL Image - wrap(prefix, suffix, wrapper_element_id) - wrap with additional text - merge(irs, separator, separator_element_id) - concatenate multiple IRs
Attributes:
| Name | Type | Description |
|---|---|---|
chunks |
list[TextChunk | ImageChunk]
|
Ordered list of output chunks (text or image). Each chunk has an element_id that maps it to its source element. |
source_prompt |
StructuredPrompt | None
|
The source prompt (None for intermediate IRs). |
id |
str
|
Unique identifier for this IR. |
metadata |
dict[str, Any]
|
Metadata dictionary for storing analysis results and other information. |
Source code in src/t_prompts/ir.py
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
chunks
property
Return the list of output chunks.
id
property
Return the unique identifier for this IntermediateRepresentation.
metadata
property
Return the metadata dictionary for this IntermediateRepresentation.
source_prompt
property
Return the source StructuredPrompt (None for intermediate IRs).
text
property
Return the text representation of this IR.
Concatenates the text of all chunks. For TextChunks, uses the text field. For ImageChunks, uses the placeholder text from ImageChunk.text property.
Returns:
| Type | Description |
|---|---|
str
|
Concatenated text from all chunks. |
__init__(chunks, source_prompt=None, metadata=None)
Create an IntermediateRepresentation from chunks.
This is a minimal constructor that just stores data. Rendering logic lives in StructuredPrompt.ir() and Element.ir() methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
list[TextChunk | ImageChunk]
|
The output chunks (text or image). Each chunk must have an element_id. |
required |
source_prompt
|
StructuredPrompt | None
|
The source prompt that produced this IR (None for intermediate IRs). |
None
|
metadata
|
dict[str, Any] | None
|
Metadata dictionary for storing analysis results. If None, creates empty dict. |
None
|
Source code in src/t_prompts/ir.py
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
__repr__()
Return a helpful debug representation.
Source code in src/t_prompts/ir.py
421 422 423 | |
compile()
Compile this IR to build efficient indexes for queries.
This is an expensive operation - only call when you need query methods.
Returns:
| Type | Description |
|---|---|
CompiledIR
|
Compiled IR with indexes for fast lookups. |
Source code in src/t_prompts/ir.py
389 390 391 392 393 394 395 396 397 398 399 400 | |
empty()
classmethod
Create an empty IntermediateRepresentation.
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
Empty IR with no chunks, no source prompt. |
Source code in src/t_prompts/ir.py
204 205 206 207 208 209 210 211 212 213 214 | |
from_image(image, element_id)
classmethod
Create an IR from a single image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Any
|
PIL Image object. |
required |
element_id
|
str
|
UUID of the element that produced this image. |
required |
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
IR with a single ImageChunk. |
Source code in src/t_prompts/ir.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
from_text(text, element_id)
classmethod
Create an IR from a single text string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text content. |
required |
element_id
|
str
|
UUID of the element that produced this text. |
required |
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
IR with a single TextChunk. |
Source code in src/t_prompts/ir.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
merge(irs, separator='', separator_element_id='')
classmethod
Merge multiple IRs into a single IR.
Reuses existing chunks - no recreation needed! Inserts separator as TextChunk between IRs (if non-empty).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
irs
|
list[IntermediateRepresentation]
|
List of IRs to merge. |
required |
separator
|
str
|
Separator to insert between IRs (default: ""). |
''
|
separator_element_id
|
str
|
Element ID for separator chunks (e.g., ListInterpolation that wants this separator). |
''
|
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
Merged IR with concatenated chunks. |
Source code in src/t_prompts/ir.py
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | |
toJSON()
Convert IntermediateRepresentation to JSON-serializable dictionary.
Chunks are serialized fully. The source_prompt is serialized as just its ID since the full StructuredPrompt object will be stored elsewhere.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with chunks (as list of chunk JSON dicts), source_prompt_id, id, metadata. |
Source code in src/t_prompts/ir.py
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | |
widget(config=None)
Create a Widget for Jupyter notebook display.
This compiles the IR first, then delegates to CompiledIR.widget().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
WidgetConfig | None
|
Widget configuration. If None, uses the package default config. |
None
|
Returns:
| Type | Description |
|---|---|
Widget
|
Widget instance with rendered HTML. |
Examples:
>>> p = prompt(t"Hello {name}")
>>> ir = p.ir()
>>> widget = ir.widget()
>>> # Or with custom config
>>> from t_prompts import WidgetConfig
>>> widget = ir.widget(WidgetConfig(wrapping=False))
Source code in src/t_prompts/ir.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 | |
wrap(prefix, suffix, wrapper_element_id, escape_wrappers=False)
Wrap this IR by prepending/appending text chunks.
Creates new chunks for prefix/suffix rather than modifying existing chunks. This maintains the immutability of chunks and simplifies source mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Text to prepend (creates new chunk if non-empty). |
required |
suffix
|
str
|
Text to append (creates new chunk if non-empty). |
required |
wrapper_element_id
|
str
|
Element ID for the prefix/suffix chunks (e.g., element with render hints). |
required |
escape_wrappers
|
bool
|
If True, mark prefix/suffix chunks with needs_html_escape=True. Used for XML wrapper tags that should be escaped in markdown rendering. |
False
|
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
New IR with wrapper chunks added. |
Source code in src/t_prompts/ir.py
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | |
ListInterpolation
dataclass
Bases: Element
Immutable record of a list interpolation in a StructuredPrompt.
Represents interpolations where the value is a list of StructuredPrompts.
Stores the separator as a field for proper handling during rendering.
Attributes
Attributes
key : str
The key used for dict-like access (parsed from format_spec or expression).
parent : StructuredPrompt | None
The parent StructuredPrompt that contains this interpolation.
index : int
The position of this element in the overall element sequence.
source_location : SourceLocation | None
Source code location information for this element (if available).
expression : str
The original expression text from the t-string (what was inside {}).
conversion : str | None
The conversion flag if present (!s, !r, !a), or None.
format_spec : str
The format specification string (everything after :), or empty string.
render_hints : str
Rendering hints parsed from format_spec (everything after first colon in format spec).
separator : str
The separator to use when joining items (parsed from render_hints, default "
"). item_elements : list[StructuredPrompt] The list items stored directly (attached in post_init). Each item is attached to the parent StructuredPrompt with an integer key. Iterate over this to access items directly.
Source code in src/t_prompts/element.py
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 | |
__getitem__(idx)
Access list items by index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int
|
The index of the item to access. |
required |
Returns:
| Type | Description |
|---|---|
StructuredPrompt
|
The item at the given index. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the index is out of bounds. |
Source code in src/t_prompts/element.py
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | |
__iter__()
Iterate over the list items directly.
Source code in src/t_prompts/element.py
530 531 532 | |
__len__()
Return the number of items in the list.
Source code in src/t_prompts/element.py
526 527 528 | |
__post_init__()
Attach list items directly without wrappers.
Source code in src/t_prompts/element.py
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 | |
__repr__()
Return a helpful debug representation.
Source code in src/t_prompts/element.py
573 574 575 576 577 578 | |
ir(ctx=None, base_indent='')
Convert list interpolation to IR with separator, base_indent, and render hints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
RenderContext | None
|
Rendering context. If None, uses default context. |
None
|
base_indent
|
str
|
Base indentation to add after separator for items after the first. Extracted by IR from preceding text. NOTE: base_indent support will be added in a future refactor. |
''
|
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
IR with flattened chunks from all items, with wrappers applied. |
Source code in src/t_prompts/element.py
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 | |
toJSON()
Convert ListInterpolation to JSON-serializable dictionary.
The list of StructuredPrompt items is serialized as a list of ID strings. The full StructuredPrompt objects will be stored elsewhere in the JSON structure.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with type, key, index, source_location, id, expression, conversion, format_spec, render_hints, item_ids, separator, parent_id, metadata. |
Source code in src/t_prompts/element.py
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 | |
MissingKeyError
Bases: StructuredPromptsError, KeyError
Raised when a key is not found during dict-like access.
Source code in src/t_prompts/exceptions.py
32 33 34 35 36 37 38 | |
NotANestedPromptError
Bases: StructuredPromptsError
Raised when attempting to index into a non-nested interpolation.
Source code in src/t_prompts/exceptions.py
41 42 43 44 45 46 47 48 49 | |
PromptReuseError
Bases: StructuredPromptsError
Raised when attempting to nest a StructuredPrompt in multiple locations.
Source code in src/t_prompts/exceptions.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
RenderedPromptDiff
dataclass
Diff between two rendered prompt intermediate representations.
Source code in src/t_prompts/diff.py
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | |
__repr__()
Return string representation.
Source code in src/t_prompts/diff.py
266 267 268 | |
__str__()
Return simple string representation showing chunk operation counts.
Source code in src/t_prompts/diff.py
252 253 254 255 256 257 258 259 260 261 262 263 264 | |
to_widget_data()
Convert diff to widget data for TypeScript rendering.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
JSON-serializable dictionary with diff data. |
Source code in src/t_prompts/diff.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
SourceLocation
dataclass
Source code location information for an Element.
All fields are optional to handle cases where source information is unavailable (e.g., REPL, eval, exec). Use the is_available property to check if location information is present.
This information is captured directly from Python stack frames without reading source files, making it fast and lightweight.
Attributes:
| Name | Type | Description |
|---|---|---|
filename |
str | None
|
Short filename (e.g., 'script.py', ' |
filepath |
str | None
|
Full absolute path to the file. |
line |
int | None
|
Line number where prompt was created (1-indexed). |
Source code in src/t_prompts/source_location.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
is_available
property
Check if source location information is available.
Returns:
| Type | Description |
|---|---|
bool
|
True if location info is present (filename is not None), False otherwise. |
format_location()
Format location as a readable string.
Returns:
| Type | Description |
|---|---|
str
|
Formatted location string (e.g., "script.py:42" or " |
Source code in src/t_prompts/source_location.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
toJSON()
Convert SourceLocation to a JSON-serializable dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with filename, filepath, line. |
Source code in src/t_prompts/source_location.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
Static
dataclass
Bases: Element
Represents a static string segment from the t-string.
Static segments are the literal text between interpolations.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
int
|
The position of this static in the template's strings tuple. |
parent |
StructuredPrompt | None
|
The parent StructuredPrompt that contains this static. |
index |
int
|
The position of this element in the overall element sequence. |
source_location |
SourceLocation | None
|
Source code location information for this element (if available). |
value |
str
|
The static text content. |
Source code in src/t_prompts/element.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
ir(ctx=None)
Convert static text to an IntermediateRepresentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
RenderContext | None
|
Rendering context. If None, uses default context. |
None
|
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
IR with a single TextChunk (if non-empty). |
Source code in src/t_prompts/element.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
toJSON()
Convert Static element to JSON-serializable dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with type, key, index, source_location, id, value, parent_id, metadata. |
Source code in src/t_prompts/element.py
288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
StructuredPrompt
Bases: Element, Mapping[str, InterpolationType]
A provenance-preserving, navigable tree representation of a t-string.
StructuredPrompt wraps a string.templatelib.Template (from a t-string) and provides dict-like access to its interpolations, preserving full provenance information (expression, conversion, format_spec, value).
As an Element, StructuredPrompt can be a root prompt or nested within another prompt. When nested, its parent, key, and interpolation metadata are set.
Attributes:
| Name | Type | Description |
|---|---|---|
metadata |
dict[str, Any]
|
Metadata dictionary for storing analysis results and other information. |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
Template
|
The Template object from a t-string literal. |
required |
allow_duplicate_keys
|
bool
|
If True, allows duplicate keys and provides get_all() for access. If False (default), raises DuplicateKeyError on duplicate keys. |
False
|
Raises:
| Type | Description |
|---|---|
UnsupportedValueTypeError
|
If any interpolation value is not str, StructuredPrompt, or list[StructuredPrompt]. |
DuplicateKeyError
|
If duplicate keys are found and allow_duplicate_keys=False. |
EmptyExpressionError
|
If an empty expression {} is encountered. |
Source code in src/t_prompts/structured_prompt.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 | |
children
property
Return all children (Static and StructuredInterpolation) in order.
creation_location
property
Return the location where this StructuredPrompt was created (via prompt() call).
This is distinct from source_location, which indicates where the prompt was interpolated. For root prompts, creation_location and source_location are the same. For nested prompts, creation_location is where prompt() was called originally, while source_location is where it was interpolated into the parent.
Returns:
| Type | Description |
|---|---|
SourceLocation | None
|
The creation location, or None if not captured. |
interpolations
property
Return all interpolation nodes in order.
strings
property
Return the static string segments from the template.
template
property
Return the original Template object.
__getitem__(key)
Get the interpolation node for the given key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to look up (derived from format_spec or expression). |
required |
Returns:
| Type | Description |
|---|---|
InterpolationType
|
The interpolation node for this key. |
Raises:
| Type | Description |
|---|---|
MissingKeyError
|
If the key is not found. |
ValueError
|
If allow_duplicate_keys=True and the key is ambiguous (use get_all instead). |
Source code in src/t_prompts/structured_prompt.py
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | |
__iter__()
Iterate over keys in insertion order.
Source code in src/t_prompts/structured_prompt.py
278 279 280 281 282 283 284 | |
__len__()
Return the number of unique keys.
Source code in src/t_prompts/structured_prompt.py
286 287 288 | |
__repr__()
Return a helpful debug representation.
Source code in src/t_prompts/structured_prompt.py
557 558 559 560 561 562 | |
__str__()
Render to string (convenience for ir().text).
Source code in src/t_prompts/structured_prompt.py
439 440 441 | |
clone(*, key=None)
Create a deep copy of this prompt with no parent and new source location.
This method allows reusing prompt structure in multiple locations. The cloned prompt will have: - A new unique ID - No parent (can be nested anywhere) - Source location captured at the clone() call site - All nested StructuredPrompts recursively cloned - Optionally a new key
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str | None
|
Optional key for the cloned prompt. If None, uses the original key. |
None
|
Returns:
| Type | Description |
|---|---|
StructuredPrompt
|
A deep copy of this prompt with no parent. |
Examples:
Reuse a template in multiple places:
>>> template = prompt(t"Task: {task}")
>>> instance1 = template.clone()
>>> instance2 = template.clone()
>>> outer = prompt(t"{instance1:i1}\n{instance2:i2}")
Clone with a new key:
>>> footer = prompt(t"--- End ---")
>>> page1_footer = footer.clone(key="page1")
>>> page2_footer = footer.clone(key="page2")
Notes
This method recursively clones all nested StructuredPrompts, ensuring that the entire tree is independent of the original.
Source code in src/t_prompts/structured_prompt.py
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 | |
get_all(key)
Get all interpolation nodes for a given key (for duplicate keys).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to look up. |
required |
Returns:
| Type | Description |
|---|---|
list[InterpolationType]
|
List of all interpolation nodes with this key. |
Raises:
| Type | Description |
|---|---|
MissingKeyError
|
If the key is not found. |
Source code in src/t_prompts/structured_prompt.py
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
ir(ctx=None, _path=(), max_header_level=4, _header_level=1)
Convert this StructuredPrompt to an IntermediateRepresentation with source mapping.
Each chunk contains an element_id that maps it back to its source element. Conversions (!s, !r, !a) are always applied. Format specs are parsed as "key : render_hints".
When this StructuredPrompt has been nested (has render_hints set), the render hints are applied to the output (xml wrapping, header level adjustments, etc.).
The IntermediateRepresentation is ideal for: - Structured optimization when approaching context limits - Debugging and auditing with full provenance - Future multi-modal transformations
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
RenderContext | None
|
Rendering context. If None, uses _path, _header_level, and max_header_level. |
None
|
_path
|
tuple[Union[str, int], ...]
|
Internal parameter for tracking path during recursive rendering. |
()
|
max_header_level
|
int
|
Maximum header level for markdown headers (default: 4). |
4
|
_header_level
|
int
|
Internal parameter for tracking current header nesting level. |
1
|
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
Object containing chunks with source mapping via element_id. |
Source code in src/t_prompts/structured_prompt.py
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
toJSON()
Export complete structured prompt as hierarchical JSON tree.
This method provides a comprehensive JSON representation optimized for analysis and traversal, using a natural tree structure with explicit children arrays and parent references.
The output has a root structure with: 1. prompt_id: UUID of the root StructuredPrompt 2. children: Array of child elements, each with their own children if nested
Each element includes: - parent_id: UUID of the parent element (enables upward traversal) - children: Array of nested elements (for nested_prompt and list types)
Images are serialized as base64-encoded data with metadata (format, size, mode).
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
JSON-serializable dictionary with 'prompt_id' and 'children' keys. |
Examples:
>>> x = "value"
>>> p = prompt(t"{x:x}")
>>> data = p.toJSON()
>>> data.keys()
dict_keys(['prompt_id', 'children'])
>>> len(data['children']) # Static "", interpolation, static ""
3
Source code in src/t_prompts/structured_prompt.py
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 | |
widget(config=None)
Create a Widget for Jupyter notebook display.
This converts to IR, compiles it, then delegates to CompiledIR.widget().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
WidgetConfig | None
|
Widget configuration. If None, uses the package default config. |
None
|
Returns:
| Type | Description |
|---|---|
Widget
|
Widget instance with rendered HTML. |
Examples:
>>> p = prompt(t"Hello {name}")
>>> widget = p.widget()
>>> # Or with custom config
>>> from t_prompts import WidgetConfig
>>> widget = p.widget(WidgetConfig(wrapping=False))
Source code in src/t_prompts/structured_prompt.py
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 | |
StructuredPromptDiff
dataclass
Result of comparing two StructuredPrompt instances.
Source code in src/t_prompts/diff.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
__repr__()
Return string representation.
Source code in src/t_prompts/diff.py
159 160 161 | |
__str__()
Return simple string representation showing diff statistics.
Source code in src/t_prompts/diff.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |
to_widget_data()
Convert diff to widget data for TypeScript rendering.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
JSON-serializable dictionary with diff data. |
Source code in src/t_prompts/diff.py
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
StructuredPromptsError
Bases: Exception
Base exception for all structured-prompts errors.
Source code in src/t_prompts/exceptions.py
4 5 | |
TextChunk
dataclass
A chunk of text in the rendered output.
Each chunk maps to exactly one source element.
Attributes:
| Name | Type | Description |
|---|---|---|
text |
str
|
The text content of this chunk. |
element_id |
str
|
UUID of the source element that produced this chunk. |
id |
str
|
Unique identifier for this chunk (UUID4 string). |
metadata |
dict[str, Any]
|
Metadata dictionary for storing analysis results and other information. |
needs_html_escape |
bool
|
If True, this chunk should be HTML-escaped when rendering as markdown.
Used for XML wrapper tags from render hints (e.g., |
Source code in src/t_prompts/ir.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | |
toJSON()
Convert TextChunk to JSON-serializable dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with type, text, element_id, id, metadata, needs_html_escape. |
Source code in src/t_prompts/ir.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | |
TextInterpolation
dataclass
Bases: Element
Immutable record of a text interpolation in a StructuredPrompt.
Represents interpolations where the value is a string.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
The key used for dict-like access (parsed from format_spec or expression). |
parent |
StructuredPrompt | None
|
The parent StructuredPrompt that contains this interpolation. |
index |
int
|
The position of this element in the overall element sequence. |
source_location |
SourceLocation | None
|
Source code location information for this element (if available). |
expression |
str
|
The original expression text from the t-string (what was inside {}). |
conversion |
str | None
|
The conversion flag if present (!s, !r, !a), or None. |
format_spec |
str
|
The format specification string (everything after :), or empty string. |
render_hints |
str
|
Rendering hints parsed from format_spec (everything after first colon in format spec). |
value |
str
|
The string value. |
Source code in src/t_prompts/element.py
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 | |
__getitem__(key)
Raise NotANestedPromptError since text interpolations cannot be indexed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key attempted to access. |
required |
Raises:
| Type | Description |
|---|---|
NotANestedPromptError
|
Always, since text interpolations don't support indexing. |
Source code in src/t_prompts/element.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | |
__repr__()
Return a helpful debug representation.
Source code in src/t_prompts/element.py
389 390 391 392 393 394 395 | |
ir(ctx=None)
Convert text interpolation to IR with conversions and render hints.
Applies conversions (!s, !r, !a) and render hints (xml, header) to the text value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
RenderContext | None
|
Rendering context. If None, uses default context. |
None
|
Returns:
| Type | Description |
|---|---|
IntermediateRepresentation
|
IR with chunks including any wrappers. |
Source code in src/t_prompts/element.py
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | |
toJSON()
Convert TextInterpolation to JSON-serializable dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with type, key, index, source_location, id, expression, conversion, format_spec, render_hints, value, parent_id, metadata. |
Source code in src/t_prompts/element.py
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 | |
UnsupportedValueTypeError
Bases: StructuredPromptsError
Raised when an interpolation value is neither str nor StructuredPrompt.
Source code in src/t_prompts/exceptions.py
8 9 10 11 12 13 14 15 16 17 18 | |
Widget
Wrapper class for widget HTML content.
This is a simple utility class that holds the rendered HTML string and provides the repr_html() method for Jupyter notebook display.
Attributes:
| Name | Type | Description |
|---|---|---|
html |
str
|
The HTML content to display. |
Source code in src/t_prompts/widgets/widget.py
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | |
__init__(html)
Create a Widget with the given HTML content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
html
|
str
|
The HTML string to display. |
required |
Source code in src/t_prompts/widgets/widget.py
17 18 19 20 21 22 23 24 25 26 | |
WidgetConfig
dataclass
Configuration for widget rendering in Jupyter notebooks.
Attributes:
| Name | Type | Description |
|---|---|---|
wrapping |
bool
|
If True, text wraps in the output container. If False, uses horizontal scroll. Default is True. |
sourcePrefix |
str
|
Path prefix to remove from source locations to create relative paths. Default is current working directory. |
Source code in src/t_prompts/widgets/config.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
__post_init__()
Set sourcePrefix to cwd if empty.
Source code in src/t_prompts/widgets/config.py
26 27 28 29 | |
dedent(template, /, *, trim_leading=True, trim_empty_leading=True, trim_trailing=True, **opts)
Build a StructuredPrompt from a t-string Template with dedenting enabled.
This is a convenience function that forwards to prompt() with dedent=True.
Use this when writing indented multi-line prompts to keep your source code
readable while producing clean output without indentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
Template
|
The Template object from a t-string literal (e.g., t"..."). |
required |
trim_leading
|
bool
|
If True, remove the first line of the first static if it's whitespace-only and ends in a newline. Default is True. |
True
|
trim_empty_leading
|
bool
|
If True, remove empty lines (just newlines) after the first line in the first static. Default is True. |
True
|
trim_trailing
|
bool
|
If True, remove trailing newlines from the last static. Default is True. |
True
|
**opts
|
Additional options passed to StructuredPrompt constructor (e.g., allow_duplicate_keys=True). |
{}
|
Returns:
| Type | Description |
|---|---|
StructuredPrompt
|
The structured prompt object with dedenting applied. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If template is not a Template object. |
DedentError
|
If dedenting fails due to invalid configuration or mixed tabs/spaces. |
Examples:
>>> task = "translate to French"
>>> p = dedent(t"""
... You are a helpful assistant.
... Task: {task:t}
... Please respond.
... """)
>>> print(str(p))
You are a helpful assistant.
Task: translate to French
Please respond.
Source code in src/t_prompts/structured_prompt.py
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 | |
diff_rendered_prompts(before, after)
Compute a diff of the rendered intermediate representations.
Source code in src/t_prompts/diff.py
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | |
diff_structured_prompts(before, after)
Compute a structural diff between two StructuredPrompt trees.
Source code in src/t_prompts/diff.py
271 272 273 274 275 276 277 278 | |
get_default_widget_config()
Get the package-level default widget configuration.
Returns:
| Type | Description |
|---|---|
WidgetConfig
|
The default configuration. If not set, creates a new one with defaults. |
Source code in src/t_prompts/widgets/config.py
36 37 38 39 40 41 42 43 44 45 46 47 48 | |
js_prelude()
Create a script tag containing the widget JavaScript bundle.
This function generates HTML with the widget initialization JavaScript. The script tag includes cache-busting via a hash-based ID, and the auto-initialization machinery will handle deduplication across multiple calls.
Use this function to inject widget JavaScript into web pages, HTML templates, or other contexts where you need explicit control over script loading.
For Jupyter notebooks, use setup_notebook() instead, which wraps this in a displayable Widget.
Returns:
| Type | Description |
|---|---|
str
|
HTML string containing a |