Skip to content

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
class DedentError(StructuredPromptsError):
    """Raised when dedenting configuration is invalid or dedenting fails."""

    def __init__(self, message: str):
        self.message = message
        super().__init__(message)

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
class DuplicateKeyError(StructuredPromptsError):
    """Raised when duplicate keys are found and allow_duplicate_keys=False."""

    def __init__(self, key: str):
        self.key = key
        super().__init__(
            f"Duplicate key '{key}' found. Use allow_duplicate_keys=True to allow duplicates, "
            "or use different format specs to create unique keys."
        )

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
@dataclass(slots=True)
class Element(ABC):
    """
    Base class for all elements in a StructuredPrompt.

    An element can be either a Static text segment or a StructuredInterpolation.

    Attributes
    ----------
    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.
    """

    key: Union[str, int, None] = None  # None for root StructuredPrompts
    parent: Optional["StructuredPrompt"] = None
    index: int = 0
    source_location: Optional[SourceLocation] = None
    id: str = field(default_factory=lambda: str(uuid.uuid4()))
    metadata: dict[str, Any] = field(default_factory=dict)

    # Interpolation fields (None for Static and non-interpolated StructuredPrompts)
    expression: Optional[str] = None
    conversion: Optional[str] = None
    format_spec: Optional[str] = None
    render_hints: Optional[str] = None

    @property
    def is_interpolated(self) -> bool:
        """
        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
        -------
        bool
            True if element has been interpolated, False otherwise.
        """
        return self.expression is not None

    @abstractmethod
    def ir(self, ctx: Optional["RenderContext"] = None) -> "IntermediateRepresentation":
        """
        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
        ----------
        ctx : RenderContext | None, optional
            Rendering context with path, header level, etc.
            If None, uses default context (path=(), header_level=1, max_header_level=4).

        Returns
        -------
        IntermediateRepresentation
            IR with chunks for this element.
        """
        pass

    def _base_json_dict(self) -> dict[str, Any]:
        """
        Get base fields common to all elements.

        Returns a dictionary with the base fields that all elements share:
        key, index, source_location, id, parent_id, metadata.

        Returns
        -------
        dict[str, Any]
            Dictionary with base fields (without "type" field).
        """
        return {
            "key": self.key,
            "index": self.index,
            "source_location": self.source_location.toJSON() if self.source_location else None,
            "id": self.id,
            "parent_id": self.parent.id if self.parent else None,
            "metadata": self.metadata,
        }

    def _interpolation_json_dict(
        self,
        expression: str,
        conversion: Optional[str],
        format_spec: str,
        render_hints: str,
    ) -> dict[str, Any]:
        """
        Get fields common to all interpolation types.

        This helper returns the fields shared by TextInterpolation,
        NestedPromptInterpolation, ListInterpolation, and ImageInterpolation.

        Parameters
        ----------
        expression : str
            The original expression text from the t-string.
        conversion : str | None
            The conversion flag if present (!s, !r, !a), or None.
        format_spec : str
            The format specification string.
        render_hints : str
            Rendering hints parsed from format_spec.

        Returns
        -------
        dict[str, Any]
            Dictionary with interpolation fields.
        """
        return {
            "expression": expression,
            "conversion": conversion,
            "format_spec": format_spec,
            "render_hints": render_hints,
        }

    @abstractmethod
    def toJSON(self) -> dict[str, Any]:
        """
        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
        -------
        dict[str, Any]
            JSON-serializable dictionary representing this element.
        """
        pass

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
@abstractmethod
def ir(self, ctx: Optional["RenderContext"] = None) -> "IntermediateRepresentation":
    """
    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
    ----------
    ctx : RenderContext | None, optional
        Rendering context with path, header level, etc.
        If None, uses default context (path=(), header_level=1, max_header_level=4).

    Returns
    -------
    IntermediateRepresentation
        IR with chunks for this element.
    """
    pass

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
@abstractmethod
def toJSON(self) -> dict[str, Any]:
    """
    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
    -------
    dict[str, Any]
        JSON-serializable dictionary representing this element.
    """
    pass

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
class EmptyExpressionError(StructuredPromptsError):
    """Raised when an empty expression {} is encountered."""

    def __init__(self):
        super().__init__(
            "Empty expression {{}} is not allowed. All interpolations must have a valid expression or format spec."
        )

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
@dataclass(frozen=True, slots=True)
class ImageChunk:
    """
    An image chunk in the rendered output.

    Each chunk maps to exactly one source element.

    Attributes
    ----------
    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.
    """

    image: Any
    element_id: str
    id: str = field(default_factory=lambda: str(uuid.uuid4()))
    metadata: dict[str, Any] = field(default_factory=dict)

    @property
    def text(self) -> str:
        """
        Return a text placeholder for this image.

        Returns a bracketed description with format, dimensions, and mode.
        Example: [Image: PNG 1024x768 RGB]

        Returns
        -------
        str
            Text placeholder describing the image.
        """
        try:
            width, height = self.image.size
            mode = self.image.mode
            fmt = self.image.format or "Unknown"
            return f"[Image: {fmt} {width}x{height} {mode}]"
        except (AttributeError, Exception):
            return "[Image]"

    def toJSON(self) -> dict[str, Any]:
        """
        Convert ImageChunk to JSON-serializable dictionary.

        The image is serialized to base64 with metadata.

        Returns
        -------
        dict[str, Any]
            Dictionary with type, image (as base64 dict), element_id, id, metadata.
        """
        # Import here to avoid circular dependency and optional PIL dependency
        from .element import _serialize_image

        return {
            "type": "ImageChunk",
            "image": _serialize_image(self.image),
            "element_id": self.element_id,
            "id": self.id,
            "metadata": self.metadata,
        }

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
def toJSON(self) -> dict[str, Any]:
    """
    Convert ImageChunk to JSON-serializable dictionary.

    The image is serialized to base64 with metadata.

    Returns
    -------
    dict[str, Any]
        Dictionary with type, image (as base64 dict), element_id, id, metadata.
    """
    # Import here to avoid circular dependency and optional PIL dependency
    from .element import _serialize_image

    return {
        "type": "ImageChunk",
        "image": _serialize_image(self.image),
        "element_id": self.element_id,
        "id": self.id,
        "metadata": self.metadata,
    }

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
@dataclass(slots=True)
class ImageInterpolation(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
    ----------
    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).
    """

    # Inherited from Element: expression, conversion, format_spec, render_hints
    value: Any = None  # PIL Image type

    def ir(self, ctx: Optional["RenderContext"] = None) -> "IntermediateRepresentation":
        """
        Convert image to an IntermediateRepresentation with an ImageChunk.

        Parameters
        ----------
        ctx : RenderContext | None, optional
            Rendering context. If None, uses default context.

        Returns
        -------
        IntermediateRepresentation
            IR with a single ImageChunk.
        """
        from .ir import IntermediateRepresentation, RenderContext

        if ctx is None:
            ctx = RenderContext(path=(), header_level=1, max_header_level=4)

        # Use from_image factory method for images
        return IntermediateRepresentation.from_image(self.value, self.id)

    def __repr__(self) -> str:
        """Return a helpful debug representation."""
        return (
            f"ImageInterpolation(key={self.key!r}, expression={self.expression!r}, "
            f"value=<PIL.Image>, index={self.index})"
        )

    def toJSON(self) -> dict[str, Any]:
        """
        Convert ImageInterpolation to JSON-serializable dictionary.

        The PIL Image value is serialized using _serialize_image to include
        base64 data and metadata.

        Returns
        -------
        dict[str, Any]
            Dictionary with type, key, index, source_location, id, expression,
            conversion, format_spec, render_hints, value, parent_id, metadata.
        """
        return {
            "type": "ImageInterpolation",
            **self._base_json_dict(),
            **self._interpolation_json_dict(self.expression, self.conversion, self.format_spec, self.render_hints),
            "value": _serialize_image(self.value),
        }

__repr__()

Return a helpful debug representation.

Source code in src/t_prompts/element.py
657
658
659
660
661
662
def __repr__(self) -> str:
    """Return a helpful debug representation."""
    return (
        f"ImageInterpolation(key={self.key!r}, expression={self.expression!r}, "
        f"value=<PIL.Image>, index={self.index})"
    )

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
def ir(self, ctx: Optional["RenderContext"] = None) -> "IntermediateRepresentation":
    """
    Convert image to an IntermediateRepresentation with an ImageChunk.

    Parameters
    ----------
    ctx : RenderContext | None, optional
        Rendering context. If None, uses default context.

    Returns
    -------
    IntermediateRepresentation
        IR with a single ImageChunk.
    """
    from .ir import IntermediateRepresentation, RenderContext

    if ctx is None:
        ctx = RenderContext(path=(), header_level=1, max_header_level=4)

    # Use from_image factory method for images
    return IntermediateRepresentation.from_image(self.value, self.id)

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
def toJSON(self) -> dict[str, Any]:
    """
    Convert ImageInterpolation to JSON-serializable dictionary.

    The PIL Image value is serialized using _serialize_image to include
    base64 data and metadata.

    Returns
    -------
    dict[str, Any]
        Dictionary with type, key, index, source_location, id, expression,
        conversion, format_spec, render_hints, value, parent_id, metadata.
    """
    return {
        "type": "ImageInterpolation",
        **self._base_json_dict(),
        **self._interpolation_json_dict(self.expression, self.conversion, self.format_spec, self.render_hints),
        "value": _serialize_image(self.value),
    }

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
class ImageRenderError(StructuredPromptsError):
    """Raised when attempting to render a prompt containing images to text."""

    def __init__(self):
        super().__init__(
            "Cannot render prompt containing images to text. "
            "Prompts with images can only be accessed through the prompt structure. "
            "Use p['image_key'].value to access the PIL Image object directly."
        )

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
class 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
    ----------
    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.
    """

    def __init__(
        self,
        chunks: list[Union[TextChunk, ImageChunk]],
        source_prompt: Optional["StructuredPrompt"] = None,
        metadata: Optional[dict[str, Any]] = 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
        ----------
        chunks : list[TextChunk | ImageChunk]
            The output chunks (text or image).
            Each chunk must have an element_id.
        source_prompt : StructuredPrompt | None, optional
            The source prompt that produced this IR (None for intermediate IRs).
        metadata : dict[str, Any] | None, optional
            Metadata dictionary for storing analysis results. If None, creates empty dict.
        """
        self._id = str(uuid.uuid4())
        self._chunks = chunks
        self._source_prompt = source_prompt
        self._metadata = metadata if metadata is not None else {}

    @classmethod
    def empty(cls) -> "IntermediateRepresentation":
        """
        Create an empty IntermediateRepresentation.

        Returns
        -------
        IntermediateRepresentation
            Empty IR with no chunks, no source prompt.
        """
        return cls(chunks=[], source_prompt=None)

    @classmethod
    def from_text(cls, text: str, element_id: str) -> "IntermediateRepresentation":
        """
        Create an IR from a single text string.

        Parameters
        ----------
        text : str
            The text content.
        element_id : str
            UUID of the element that produced this text.

        Returns
        -------
        IntermediateRepresentation
            IR with a single TextChunk.
        """
        chunk = TextChunk(text=text, element_id=element_id)
        return cls(chunks=[chunk], source_prompt=None)

    @classmethod
    def from_image(cls, image: Any, element_id: str) -> "IntermediateRepresentation":
        """
        Create an IR from a single image.

        Parameters
        ----------
        image : Any
            PIL Image object.
        element_id : str
            UUID of the element that produced this image.

        Returns
        -------
        IntermediateRepresentation
            IR with a single ImageChunk.
        """
        chunk = ImageChunk(image=image, element_id=element_id)
        return cls(chunks=[chunk], source_prompt=None)

    def wrap(
        self, prefix: str, suffix: str, wrapper_element_id: str, escape_wrappers: bool = False
    ) -> "IntermediateRepresentation":
        """
        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
        ----------
        prefix : str
            Text to prepend (creates new chunk if non-empty).
        suffix : str
            Text to append (creates new chunk if non-empty).
        wrapper_element_id : str
            Element ID for the prefix/suffix chunks (e.g., element with render hints).
        escape_wrappers : bool, optional
            If True, mark prefix/suffix chunks with needs_html_escape=True.
            Used for XML wrapper tags that should be escaped in markdown rendering.

        Returns
        -------
        IntermediateRepresentation
            New IR with wrapper chunks added.
        """
        if not self._chunks:
            # Empty IR: just create a text chunk with prefix+suffix
            if prefix or suffix:
                chunk = TextChunk(
                    text=prefix + suffix, element_id=wrapper_element_id, needs_html_escape=escape_wrappers
                )
                return IntermediateRepresentation(chunks=[chunk], source_prompt=None)
            return self

        new_chunks = list(self._chunks)

        # Always insert new chunks for prefix/suffix (never modify existing)
        if prefix:
            prefix_chunk = TextChunk(text=prefix, element_id=wrapper_element_id, needs_html_escape=escape_wrappers)
            new_chunks.insert(0, prefix_chunk)

        if suffix:
            suffix_chunk = TextChunk(text=suffix, element_id=wrapper_element_id, needs_html_escape=escape_wrappers)
            new_chunks.append(suffix_chunk)

        return IntermediateRepresentation(
            chunks=new_chunks,
            source_prompt=self._source_prompt,
            metadata=self._metadata,
        )

    @classmethod
    def merge(
        cls,
        irs: list["IntermediateRepresentation"],
        separator: str = "",
        separator_element_id: str = "",
    ) -> "IntermediateRepresentation":
        """
        Merge multiple IRs into a single IR.

        Reuses existing chunks - no recreation needed!
        Inserts separator as TextChunk between IRs (if non-empty).

        Parameters
        ----------
        irs : list[IntermediateRepresentation]
            List of IRs to merge.
        separator : str, optional
            Separator to insert between IRs (default: "").
        separator_element_id : str, optional
            Element ID for separator chunks (e.g., ListInterpolation that wants this separator).

        Returns
        -------
        IntermediateRepresentation
            Merged IR with concatenated chunks.
        """
        if not irs:
            return cls.empty()

        if len(irs) == 1:
            return irs[0]

        all_chunks: list[Union[TextChunk, ImageChunk]] = []

        for i, ir in enumerate(irs):
            # Add separator before all IRs except the first
            if i > 0 and separator:
                sep_chunk = TextChunk(text=separator, element_id=separator_element_id)
                all_chunks.append(sep_chunk)

            # Just append existing chunks - no recreation!
            all_chunks.extend(ir.chunks)

        return cls(chunks=all_chunks, source_prompt=None)

    @property
    def chunks(self) -> list[Union[TextChunk, ImageChunk]]:
        """Return the list of output chunks."""
        return self._chunks

    @property
    def source_prompt(self) -> Optional["StructuredPrompt"]:
        """Return the source StructuredPrompt (None for intermediate IRs)."""
        return self._source_prompt

    @property
    def id(self) -> str:
        """Return the unique identifier for this IntermediateRepresentation."""
        return self._id

    @property
    def metadata(self) -> dict[str, Any]:
        """Return the metadata dictionary for this IntermediateRepresentation."""
        return self._metadata

    @property
    def text(self) -> str:
        """
        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
        -------
        str
            Concatenated text from all chunks.
        """
        return "".join(chunk.text for chunk in self._chunks)

    def compile(self) -> "CompiledIR":
        """
        Compile this IR to build efficient indexes for queries.

        This is an expensive operation - only call when you need query methods.

        Returns
        -------
        CompiledIR
            Compiled IR with indexes for fast lookups.
        """
        return CompiledIR(self)

    def toJSON(self) -> dict[str, Any]:
        """
        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
        -------
        dict[str, Any]
            Dictionary with chunks (as list of chunk JSON dicts), source_prompt_id, id, metadata.
        """
        return {
            "chunks": [chunk.toJSON() for chunk in self._chunks],
            "source_prompt_id": self._source_prompt.id if self._source_prompt else None,
            "id": self._id,
            "metadata": self._metadata,
        }

    def __repr__(self) -> str:
        """Return a helpful debug representation."""
        return f"IntermediateRepresentation(chunks={len(self._chunks)})"

    def widget(self, config: Optional["WidgetConfig"] = None) -> "Widget":
        """
        Create a Widget for Jupyter notebook display.

        This compiles the IR first, then delegates to CompiledIR.widget().

        Parameters
        ----------
        config : WidgetConfig | None, optional
            Widget configuration. If None, uses the package default config.

        Returns
        -------
        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))
        """
        compiled = self.compile()
        return compiled.widget(config)

    def _repr_html_(self) -> str:
        """
        Return HTML representation for Jupyter notebook display.

        This method is automatically called by Jupyter/IPython when displaying
        an IntermediateRepresentation in a notebook cell.

        Returns
        -------
        str
            HTML string with widget visualization.
        """
        return self.widget()._repr_html_()

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
def __init__(
    self,
    chunks: list[Union[TextChunk, ImageChunk]],
    source_prompt: Optional["StructuredPrompt"] = None,
    metadata: Optional[dict[str, Any]] = 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
    ----------
    chunks : list[TextChunk | ImageChunk]
        The output chunks (text or image).
        Each chunk must have an element_id.
    source_prompt : StructuredPrompt | None, optional
        The source prompt that produced this IR (None for intermediate IRs).
    metadata : dict[str, Any] | None, optional
        Metadata dictionary for storing analysis results. If None, creates empty dict.
    """
    self._id = str(uuid.uuid4())
    self._chunks = chunks
    self._source_prompt = source_prompt
    self._metadata = metadata if metadata is not None else {}

__repr__()

Return a helpful debug representation.

Source code in src/t_prompts/ir.py
421
422
423
def __repr__(self) -> str:
    """Return a helpful debug representation."""
    return f"IntermediateRepresentation(chunks={len(self._chunks)})"

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
def compile(self) -> "CompiledIR":
    """
    Compile this IR to build efficient indexes for queries.

    This is an expensive operation - only call when you need query methods.

    Returns
    -------
    CompiledIR
        Compiled IR with indexes for fast lookups.
    """
    return CompiledIR(self)

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
@classmethod
def empty(cls) -> "IntermediateRepresentation":
    """
    Create an empty IntermediateRepresentation.

    Returns
    -------
    IntermediateRepresentation
        Empty IR with no chunks, no source prompt.
    """
    return cls(chunks=[], source_prompt=None)

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
@classmethod
def from_image(cls, image: Any, element_id: str) -> "IntermediateRepresentation":
    """
    Create an IR from a single image.

    Parameters
    ----------
    image : Any
        PIL Image object.
    element_id : str
        UUID of the element that produced this image.

    Returns
    -------
    IntermediateRepresentation
        IR with a single ImageChunk.
    """
    chunk = ImageChunk(image=image, element_id=element_id)
    return cls(chunks=[chunk], source_prompt=None)

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
@classmethod
def from_text(cls, text: str, element_id: str) -> "IntermediateRepresentation":
    """
    Create an IR from a single text string.

    Parameters
    ----------
    text : str
        The text content.
    element_id : str
        UUID of the element that produced this text.

    Returns
    -------
    IntermediateRepresentation
        IR with a single TextChunk.
    """
    chunk = TextChunk(text=text, element_id=element_id)
    return cls(chunks=[chunk], source_prompt=None)

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
@classmethod
def merge(
    cls,
    irs: list["IntermediateRepresentation"],
    separator: str = "",
    separator_element_id: str = "",
) -> "IntermediateRepresentation":
    """
    Merge multiple IRs into a single IR.

    Reuses existing chunks - no recreation needed!
    Inserts separator as TextChunk between IRs (if non-empty).

    Parameters
    ----------
    irs : list[IntermediateRepresentation]
        List of IRs to merge.
    separator : str, optional
        Separator to insert between IRs (default: "").
    separator_element_id : str, optional
        Element ID for separator chunks (e.g., ListInterpolation that wants this separator).

    Returns
    -------
    IntermediateRepresentation
        Merged IR with concatenated chunks.
    """
    if not irs:
        return cls.empty()

    if len(irs) == 1:
        return irs[0]

    all_chunks: list[Union[TextChunk, ImageChunk]] = []

    for i, ir in enumerate(irs):
        # Add separator before all IRs except the first
        if i > 0 and separator:
            sep_chunk = TextChunk(text=separator, element_id=separator_element_id)
            all_chunks.append(sep_chunk)

        # Just append existing chunks - no recreation!
        all_chunks.extend(ir.chunks)

    return cls(chunks=all_chunks, source_prompt=None)

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
def toJSON(self) -> dict[str, Any]:
    """
    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
    -------
    dict[str, Any]
        Dictionary with chunks (as list of chunk JSON dicts), source_prompt_id, id, metadata.
    """
    return {
        "chunks": [chunk.toJSON() for chunk in self._chunks],
        "source_prompt_id": self._source_prompt.id if self._source_prompt else None,
        "id": self._id,
        "metadata": self._metadata,
    }

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
def widget(self, config: Optional["WidgetConfig"] = None) -> "Widget":
    """
    Create a Widget for Jupyter notebook display.

    This compiles the IR first, then delegates to CompiledIR.widget().

    Parameters
    ----------
    config : WidgetConfig | None, optional
        Widget configuration. If None, uses the package default config.

    Returns
    -------
    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))
    """
    compiled = self.compile()
    return compiled.widget(config)

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
def wrap(
    self, prefix: str, suffix: str, wrapper_element_id: str, escape_wrappers: bool = False
) -> "IntermediateRepresentation":
    """
    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
    ----------
    prefix : str
        Text to prepend (creates new chunk if non-empty).
    suffix : str
        Text to append (creates new chunk if non-empty).
    wrapper_element_id : str
        Element ID for the prefix/suffix chunks (e.g., element with render hints).
    escape_wrappers : bool, optional
        If True, mark prefix/suffix chunks with needs_html_escape=True.
        Used for XML wrapper tags that should be escaped in markdown rendering.

    Returns
    -------
    IntermediateRepresentation
        New IR with wrapper chunks added.
    """
    if not self._chunks:
        # Empty IR: just create a text chunk with prefix+suffix
        if prefix or suffix:
            chunk = TextChunk(
                text=prefix + suffix, element_id=wrapper_element_id, needs_html_escape=escape_wrappers
            )
            return IntermediateRepresentation(chunks=[chunk], source_prompt=None)
        return self

    new_chunks = list(self._chunks)

    # Always insert new chunks for prefix/suffix (never modify existing)
    if prefix:
        prefix_chunk = TextChunk(text=prefix, element_id=wrapper_element_id, needs_html_escape=escape_wrappers)
        new_chunks.insert(0, prefix_chunk)

    if suffix:
        suffix_chunk = TextChunk(text=suffix, element_id=wrapper_element_id, needs_html_escape=escape_wrappers)
        new_chunks.append(suffix_chunk)

    return IntermediateRepresentation(
        chunks=new_chunks,
        source_prompt=self._source_prompt,
        metadata=self._metadata,
    )

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
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
@dataclass(slots=True)
class ListInterpolation(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
    ----------
    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 "\n").
    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.
    """

    # Inherited from Element: expression, conversion, format_spec, render_hints
    items: list["StructuredPrompt"] = field(default=None, repr=False)  # type: ignore  # Temporary, used only in __post_init__
    separator: str = "\n"
    item_elements: list["StructuredPrompt"] = field(default_factory=list)

    def __post_init__(self) -> None:
        """Attach list items directly without wrappers."""
        from .exceptions import PromptReuseError

        # Get items from temporary field
        items = object.__getattribute__(self, "items")

        # Check for duplicate prompts (disallow reuse in lists)
        seen_ids = set()
        for item in items:
            if item.id in seen_ids:
                raise PromptReuseError(
                    item,
                    None,  # Don't have reference to first occurrence
                    self,
                    message=f"Cannot reuse StructuredPrompt (id={item.id}) in the same list",
                )
            seen_ids.add(item.id)

        # Attach items directly - no wrappers needed
        attached_items = []
        for idx, item in enumerate(items):
            # Check for reuse (item already attached elsewhere)
            if item.parent is not None:
                # Create temp wrapper-like object for error message
                class _TempWrapper:
                    def __init__(self, parent, key):
                        self.parent = parent
                        self.key = key

                old_parent_element = item.parent[item.key] if item.key in item.parent else None
                new_wrapper = _TempWrapper(self.parent, self.key)
                raise PromptReuseError(item, old_parent_element, new_wrapper)

            # Attach the item directly to the parent StructuredPrompt
            item.key = idx  # List items use integer keys
            item.expression = f"[{idx}]"
            item.conversion = None
            item.format_spec = ""
            item.render_hints = ""
            item.parent = self.parent  # Parent is the StructuredPrompt containing this ListInterpolation
            item.index = self.index  # Items share the list's index in parent's children
            # Set source_location to where the list was interpolated (parent's creation location)
            # item._creation_location remains where the item was originally created
            item.source_location = self.source_location

            attached_items.append(item)

        # Store items directly
        object.__setattr__(self, "item_elements", attached_items)

    def __getitem__(self, idx: int) -> "StructuredPrompt":
        """
        Access list items by index.

        Parameters
        ----------
        idx : int
            The index of the item to access.

        Returns
        -------
        StructuredPrompt
            The item at the given index.

        Raises
        ------
        IndexError
            If the index is out of bounds.
        """
        return self.item_elements[idx]

    def __len__(self) -> int:
        """Return the number of items in the list."""
        return len(self.item_elements)

    def __iter__(self):
        """Iterate over the list items directly."""
        return iter(self.item_elements)

    def ir(self, ctx: Optional["RenderContext"] = None, base_indent: str = "") -> "IntermediateRepresentation":
        """
        Convert list interpolation to IR with separator, base_indent, and render hints.

        Parameters
        ----------
        ctx : RenderContext | None, optional
            Rendering context. If None, uses default context.
        base_indent : str, optional
            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
        -------
        IntermediateRepresentation
            IR with flattened chunks from all items, with wrappers applied.
        """
        from .ir import IntermediateRepresentation, RenderContext
        from .parsing import parse_render_hints

        if ctx is None:
            ctx = RenderContext(path=(), header_level=1, max_header_level=4)

        # Parse render hints
        hints = parse_render_hints(self.render_hints, str(self.key))

        # Render each item directly (items are now StructuredPrompts, not wrappers)
        item_irs = [item.ir(ctx) for item in self.item_elements]

        # Merge items with separator using chunk-based merge operation
        # The separator chunks will have element_id = self.id (the ListInterpolation)
        merged_ir = IntermediateRepresentation.merge(item_irs, separator=self.separator, separator_element_id=self.id)

        # Apply render hints using chunk-based operations
        result_ir = apply_render_hints(merged_ir, hints, ctx.header_level, ctx.max_header_level, self.id)

        return result_ir

    def __repr__(self) -> str:
        """Return a helpful debug representation."""
        return (
            f"ListInterpolation(key={self.key!r}, expression={self.expression!r}, "
            f"separator={self.separator!r}, items={len(self.item_elements)}, index={self.index})"
        )

    def toJSON(self) -> dict[str, Any]:
        """
        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
        -------
        dict[str, Any]
            Dictionary with type, key, index, source_location, id, expression,
            conversion, format_spec, render_hints, item_ids, separator, parent_id, metadata.
        """
        return {
            "type": "ListInterpolation",
            **self._base_json_dict(),
            **self._interpolation_json_dict(self.expression, self.conversion, self.format_spec, self.render_hints),
            "item_ids": [item.id for item in self.item_elements],
            "separator": self.separator,
        }

__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
def __getitem__(self, idx: int) -> "StructuredPrompt":
    """
    Access list items by index.

    Parameters
    ----------
    idx : int
        The index of the item to access.

    Returns
    -------
    StructuredPrompt
        The item at the given index.

    Raises
    ------
    IndexError
        If the index is out of bounds.
    """
    return self.item_elements[idx]

__iter__()

Iterate over the list items directly.

Source code in src/t_prompts/element.py
530
531
532
def __iter__(self):
    """Iterate over the list items directly."""
    return iter(self.item_elements)

__len__()

Return the number of items in the list.

Source code in src/t_prompts/element.py
526
527
528
def __len__(self) -> int:
    """Return the number of items in the list."""
    return len(self.item_elements)

__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
def __post_init__(self) -> None:
    """Attach list items directly without wrappers."""
    from .exceptions import PromptReuseError

    # Get items from temporary field
    items = object.__getattribute__(self, "items")

    # Check for duplicate prompts (disallow reuse in lists)
    seen_ids = set()
    for item in items:
        if item.id in seen_ids:
            raise PromptReuseError(
                item,
                None,  # Don't have reference to first occurrence
                self,
                message=f"Cannot reuse StructuredPrompt (id={item.id}) in the same list",
            )
        seen_ids.add(item.id)

    # Attach items directly - no wrappers needed
    attached_items = []
    for idx, item in enumerate(items):
        # Check for reuse (item already attached elsewhere)
        if item.parent is not None:
            # Create temp wrapper-like object for error message
            class _TempWrapper:
                def __init__(self, parent, key):
                    self.parent = parent
                    self.key = key

            old_parent_element = item.parent[item.key] if item.key in item.parent else None
            new_wrapper = _TempWrapper(self.parent, self.key)
            raise PromptReuseError(item, old_parent_element, new_wrapper)

        # Attach the item directly to the parent StructuredPrompt
        item.key = idx  # List items use integer keys
        item.expression = f"[{idx}]"
        item.conversion = None
        item.format_spec = ""
        item.render_hints = ""
        item.parent = self.parent  # Parent is the StructuredPrompt containing this ListInterpolation
        item.index = self.index  # Items share the list's index in parent's children
        # Set source_location to where the list was interpolated (parent's creation location)
        # item._creation_location remains where the item was originally created
        item.source_location = self.source_location

        attached_items.append(item)

    # Store items directly
    object.__setattr__(self, "item_elements", attached_items)

__repr__()

Return a helpful debug representation.

Source code in src/t_prompts/element.py
573
574
575
576
577
578
def __repr__(self) -> str:
    """Return a helpful debug representation."""
    return (
        f"ListInterpolation(key={self.key!r}, expression={self.expression!r}, "
        f"separator={self.separator!r}, items={len(self.item_elements)}, index={self.index})"
    )

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
def ir(self, ctx: Optional["RenderContext"] = None, base_indent: str = "") -> "IntermediateRepresentation":
    """
    Convert list interpolation to IR with separator, base_indent, and render hints.

    Parameters
    ----------
    ctx : RenderContext | None, optional
        Rendering context. If None, uses default context.
    base_indent : str, optional
        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
    -------
    IntermediateRepresentation
        IR with flattened chunks from all items, with wrappers applied.
    """
    from .ir import IntermediateRepresentation, RenderContext
    from .parsing import parse_render_hints

    if ctx is None:
        ctx = RenderContext(path=(), header_level=1, max_header_level=4)

    # Parse render hints
    hints = parse_render_hints(self.render_hints, str(self.key))

    # Render each item directly (items are now StructuredPrompts, not wrappers)
    item_irs = [item.ir(ctx) for item in self.item_elements]

    # Merge items with separator using chunk-based merge operation
    # The separator chunks will have element_id = self.id (the ListInterpolation)
    merged_ir = IntermediateRepresentation.merge(item_irs, separator=self.separator, separator_element_id=self.id)

    # Apply render hints using chunk-based operations
    result_ir = apply_render_hints(merged_ir, hints, ctx.header_level, ctx.max_header_level, self.id)

    return result_ir

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
def toJSON(self) -> dict[str, Any]:
    """
    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
    -------
    dict[str, Any]
        Dictionary with type, key, index, source_location, id, expression,
        conversion, format_spec, render_hints, item_ids, separator, parent_id, metadata.
    """
    return {
        "type": "ListInterpolation",
        **self._base_json_dict(),
        **self._interpolation_json_dict(self.expression, self.conversion, self.format_spec, self.render_hints),
        "item_ids": [item.id for item in self.item_elements],
        "separator": self.separator,
    }

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
class MissingKeyError(StructuredPromptsError, KeyError):
    """Raised when a key is not found during dict-like access."""

    def __init__(self, key: str, available_keys: list[str]):
        self.key = key
        self.available_keys = available_keys
        super().__init__(f"Key '{key}' not found. Available keys: {', '.join(repr(k) for k in available_keys)}")

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
class NotANestedPromptError(StructuredPromptsError):
    """Raised when attempting to index into a non-nested interpolation."""

    def __init__(self, key: str):
        self.key = key
        super().__init__(
            f"Cannot index into interpolation '{key}': value is not a StructuredPrompt. "
            "Only nested prompts support indexing."
        )

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
class PromptReuseError(StructuredPromptsError):
    """Raised when attempting to nest a StructuredPrompt in multiple locations."""

    def __init__(self, prompt, current_parent, new_parent):
        self.prompt = prompt
        self.current_parent = current_parent
        self.new_parent = new_parent

        # Build helpful error message
        current_desc = self._describe_parent(current_parent)
        new_desc = self._describe_parent(new_parent)

        super().__init__(
            f"Cannot nest StructuredPrompt (id={prompt.id}) in multiple locations. "
            f"Already nested in {current_desc}, cannot also nest in {new_desc}. "
            f"Each StructuredPrompt can only be in one location at a time. "
            f"Create separate prompt instances if you need to reuse content."
        )

    def _describe_parent(self, parent):
        """Create a helpful description of the parent element."""
        from .element import ListInterpolation

        # Handle objects with parent and key attributes (new structure or temp wrappers)
        if hasattr(parent, "parent") and hasattr(parent, "key") and parent.key is not None:
            parent_type = type(parent).__name__
            return f"{parent_type}(key='{parent.key}')"
        elif isinstance(parent, ListInterpolation):
            return f"ListInterpolation(key='{parent.key}')"
        else:
            return f"{type(parent).__name__}"

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
@dataclass(slots=True)
class RenderedPromptDiff:
    """Diff between two rendered prompt intermediate representations."""

    before: StructuredPrompt
    after: StructuredPrompt
    chunk_deltas: list[ChunkDelta]
    per_element: dict[str, ElementRenderChange]
    metrics: RenderedDiffMetrics

    def to_widget_data(self) -> dict[str, Any]:
        """
        Convert diff to widget data for TypeScript rendering.

        Returns
        -------
        dict[str, Any]
            JSON-serializable dictionary with diff data.
        """
        return {
            "diff_type": "rendered",
            "chunk_deltas": [
                {
                    "op": delta.op,
                    "before": (
                        {"text": delta.before.text, "element_id": delta.before.element_id} if delta.before else None
                    ),
                    "after": (
                        {"text": delta.after.text, "element_id": delta.after.element_id} if delta.after else None
                    ),
                }
                for delta in self.chunk_deltas
            ],
            "stats": self.stats(),
            "metrics": {
                "render_token_delta": self.metrics.render_token_delta,
                "render_non_ws_delta": self.metrics.render_non_ws_delta,
                "render_ws_delta": self.metrics.render_ws_delta,
                "render_chunk_drift": self.metrics.render_chunk_drift,
            },
        }

    def stats(self) -> dict[str, int]:
        inserts = sum(1 for delta in self.chunk_deltas if delta.op == "insert")
        deletes = sum(1 for delta in self.chunk_deltas if delta.op == "delete")
        replaces = sum(1 for delta in self.chunk_deltas if delta.op == "replace")
        equals = sum(1 for delta in self.chunk_deltas if delta.op == "equal")
        return {
            "insert": inserts,
            "delete": deletes,
            "replace": replaces,
            "equal": equals,
        }

    def _repr_html_(self) -> str:
        """Return HTML representation for Jupyter notebook display."""
        from .widgets import _render_widget_html

        data = self.to_widget_data()
        return _render_widget_html(data, "tp-rendered-diff-mount")

    def __str__(self) -> str:
        """Return simple string representation showing chunk operation counts."""
        stats = self.stats()
        return (
            f"RenderedPromptDiff("
            f"insert={stats['insert']}, "
            f"delete={stats['delete']}, "
            f"replace={stats['replace']}, "
            f"equal={stats['equal']}, "
            f"render_token_delta={self.metrics.render_token_delta}, "
            f"render_ws_delta={self.metrics.render_ws_delta}, "
            f"render_chunk_drift={self.metrics.render_chunk_drift:.3f})"
        )

    def __repr__(self) -> str:
        """Return string representation."""
        return self.__str__()

__repr__()

Return string representation.

Source code in src/t_prompts/diff.py
266
267
268
def __repr__(self) -> str:
    """Return string representation."""
    return self.__str__()

__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
def __str__(self) -> str:
    """Return simple string representation showing chunk operation counts."""
    stats = self.stats()
    return (
        f"RenderedPromptDiff("
        f"insert={stats['insert']}, "
        f"delete={stats['delete']}, "
        f"replace={stats['replace']}, "
        f"equal={stats['equal']}, "
        f"render_token_delta={self.metrics.render_token_delta}, "
        f"render_ws_delta={self.metrics.render_ws_delta}, "
        f"render_chunk_drift={self.metrics.render_chunk_drift:.3f})"
    )

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
def to_widget_data(self) -> dict[str, Any]:
    """
    Convert diff to widget data for TypeScript rendering.

    Returns
    -------
    dict[str, Any]
        JSON-serializable dictionary with diff data.
    """
    return {
        "diff_type": "rendered",
        "chunk_deltas": [
            {
                "op": delta.op,
                "before": (
                    {"text": delta.before.text, "element_id": delta.before.element_id} if delta.before else None
                ),
                "after": (
                    {"text": delta.after.text, "element_id": delta.after.element_id} if delta.after else None
                ),
            }
            for delta in self.chunk_deltas
        ],
        "stats": self.stats(),
        "metrics": {
            "render_token_delta": self.metrics.render_token_delta,
            "render_non_ws_delta": self.metrics.render_non_ws_delta,
            "render_ws_delta": self.metrics.render_ws_delta,
            "render_chunk_drift": self.metrics.render_chunk_drift,
        },
    }

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
@dataclass(frozen=True, slots=True)
class SourceLocation:
    """
    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
    ----------
    filename : str | None
        Short filename (e.g., 'script.py', '<stdin>', '<string>').
    filepath : str | None
        Full absolute path to the file.
    line : int | None
        Line number where prompt was created (1-indexed).
    """

    filename: Optional[str] = None
    filepath: Optional[str] = None
    line: Optional[int] = None

    @property
    def is_available(self) -> bool:
        """
        Check if source location information is available.

        Returns
        -------
        bool
            True if location info is present (filename is not None), False otherwise.
        """
        return self.filename is not None

    def format_location(self) -> str:
        """
        Format location as a readable string.

        Returns
        -------
        str
            Formatted location string (e.g., "script.py:42" or "<unavailable>").
        """
        if not self.is_available:
            return "<unavailable>"
        parts = [self.filename or "<unknown>"]
        if self.line is not None:
            parts.append(str(self.line))
        return ":".join(parts)

    def toJSON(self) -> dict[str, Any]:
        """
        Convert SourceLocation to a JSON-serializable dictionary.

        Returns
        -------
        dict[str, Any]
            Dictionary with filename, filepath, line.
        """
        return {
            "filename": self.filename,
            "filepath": self.filepath,
            "line": self.line,
        }

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
def format_location(self) -> str:
    """
    Format location as a readable string.

    Returns
    -------
    str
        Formatted location string (e.g., "script.py:42" or "<unavailable>").
    """
    if not self.is_available:
        return "<unavailable>"
    parts = [self.filename or "<unknown>"]
    if self.line is not None:
        parts.append(str(self.line))
    return ":".join(parts)

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
def toJSON(self) -> dict[str, Any]:
    """
    Convert SourceLocation to a JSON-serializable dictionary.

    Returns
    -------
    dict[str, Any]
        Dictionary with filename, filepath, line.
    """
    return {
        "filename": self.filename,
        "filepath": self.filepath,
        "line": self.line,
    }

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
@dataclass(slots=True)
class Static(Element):
    """
    Represents a static string segment from the t-string.

    Static segments are the literal text between interpolations.

    Attributes
    ----------
    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.
    """

    value: str = ""  # Default not used, but required for dataclass field ordering

    def ir(self, ctx: Optional["RenderContext"] = None) -> "IntermediateRepresentation":
        """
        Convert static text to an IntermediateRepresentation.

        Parameters
        ----------
        ctx : RenderContext | None, optional
            Rendering context. If None, uses default context.

        Returns
        -------
        IntermediateRepresentation
            IR with a single TextChunk (if non-empty).
        """
        from .ir import IntermediateRepresentation, RenderContext

        if ctx is None:
            ctx = RenderContext(path=(), header_level=1, max_header_level=4)

        if not self.value:
            # Empty static - return empty IR
            return IntermediateRepresentation.empty()

        # Use from_text factory method for simple text
        return IntermediateRepresentation.from_text(self.value, self.id)

    def toJSON(self) -> dict[str, Any]:
        """
        Convert Static element to JSON-serializable dictionary.

        Returns
        -------
        dict[str, Any]
            Dictionary with type, key, index, source_location, id, value, parent_id, metadata.
        """
        return {
            "type": "Static",
            **self._base_json_dict(),
            "value": self.value,
        }

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
def ir(self, ctx: Optional["RenderContext"] = None) -> "IntermediateRepresentation":
    """
    Convert static text to an IntermediateRepresentation.

    Parameters
    ----------
    ctx : RenderContext | None, optional
        Rendering context. If None, uses default context.

    Returns
    -------
    IntermediateRepresentation
        IR with a single TextChunk (if non-empty).
    """
    from .ir import IntermediateRepresentation, RenderContext

    if ctx is None:
        ctx = RenderContext(path=(), header_level=1, max_header_level=4)

    if not self.value:
        # Empty static - return empty IR
        return IntermediateRepresentation.empty()

    # Use from_text factory method for simple text
    return IntermediateRepresentation.from_text(self.value, self.id)

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
def toJSON(self) -> dict[str, Any]:
    """
    Convert Static element to JSON-serializable dictionary.

    Returns
    -------
    dict[str, Any]
        Dictionary with type, key, index, source_location, id, value, parent_id, metadata.
    """
    return {
        "type": "Static",
        **self._base_json_dict(),
        "value": self.value,
    }

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
class StructuredPrompt(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
    ----------
    metadata : dict[str, Any]
        Metadata dictionary for storing analysis results and other information.

    Parameters
    ----------
    template : Template
        The Template object from a t-string literal.
    allow_duplicate_keys : bool, optional
        If True, allows duplicate keys and provides get_all() for access.
        If False (default), raises DuplicateKeyError on duplicate keys.

    Raises
    ------
    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.
    """

    __slots__ = (
        "_template",
        "_processed_strings",
        "_children",
        "_interps",
        "_allow_duplicates",
        "_index",
        "_creation_location",
    )

    def __init__(
        self,
        template: Template,
        *,
        allow_duplicate_keys: bool = False,
        _processed_strings: Optional[tuple[str, ...]] = None,
        _source_location: Optional[SourceLocation] = None,
    ):
        # Initialize Element fields (for root prompt - unattached state)
        self.key = None  # Will be set when interpolated
        self.parent = None  # Will be set when nested
        self.index = 0  # Will be set when nested
        # NEW: Store where this prompt was created (via prompt() call)
        self._creation_location = _source_location
        # source_location will be updated to interpolation site when nested
        # For root prompts, source_location == creation_location initially
        self.source_location = _source_location
        self.id = str(uuid.uuid4())
        self.metadata = {}
        self.expression = None  # Will be set when interpolated
        self.conversion = None
        self.format_spec = None
        self.render_hints = None

        # StructuredPrompt-specific fields
        self._template = template
        self._processed_strings = _processed_strings  # Dedented/trimmed strings if provided
        # All children (Static, StructuredInterpolation, ListInterpolation, ImageInterpolation)
        self._children: list[Element] = []
        # Only interpolations
        self._interps: list[InterpolationType] = []
        self._allow_duplicates = allow_duplicate_keys

        # Index maps keys to interpolation indices (within _interps list)
        # If allow_duplicates, maps to list of indices; otherwise, maps to single index
        self._index: dict[str, Union[int, list[int]]] = {}

        self._build_nodes()

    def _build_nodes(self) -> None:
        """Build Element nodes (Static and StructuredInterpolation) from the template."""
        # Use processed strings if available (from dedenting), otherwise use original
        strings = self._processed_strings if self._processed_strings is not None else self._template.strings
        interpolations = self._template.interpolations

        element_idx = 0  # Overall position in element sequence
        interp_idx = 0  # Position within interpolations list

        # Interleave statics and interpolations
        for static_key, static_text in enumerate(strings):
            # Add static element
            # Use creation_location for child elements - they're created where parent was defined
            static = Static(
                key=static_key,
                value=static_text,
                parent=self,
                index=element_idx,
                source_location=self._creation_location,
            )
            self._children.append(static)
            element_idx += 1

            # Add interpolation if there's one after this static
            if static_key < len(interpolations):
                itp = interpolations[static_key]

                # Parse format spec to extract key and render hints
                key, render_hints = _parse_format_spec(itp.format_spec, itp.expression)

                # Guard against empty keys
                if not key:
                    raise EmptyExpressionError()

                # Validate and extract value - create appropriate node type
                val = itp.value
                if isinstance(val, list):
                    # Check that all items in the list are StructuredPrompts
                    if not all(isinstance(item, StructuredPrompt) for item in val):
                        raise UnsupportedValueTypeError(key, type(val), itp.expression)

                    # Create ListInterpolation node
                    separator = _parse_separator(render_hints)
                    node = ListInterpolation(
                        key=key,
                        expression=itp.expression,
                        conversion=itp.conversion,
                        format_spec=itp.format_spec,
                        render_hints=render_hints,
                        items=val,
                        separator=separator,
                        parent=self,
                        index=element_idx,
                        source_location=self._creation_location,
                    )
                elif HAS_PIL and PILImage and isinstance(val, PILImage.Image):
                    # Create ImageInterpolation node
                    node = ImageInterpolation(
                        key=key,
                        expression=itp.expression,
                        conversion=itp.conversion,
                        format_spec=itp.format_spec,
                        render_hints=render_hints,
                        value=val,
                        parent=self,
                        index=element_idx,
                        source_location=self._creation_location,
                    )
                elif isinstance(val, StructuredPrompt):
                    # Check for reuse - prompt cannot be nested in multiple locations
                    from .exceptions import PromptReuseError

                    if val.parent is not None:
                        # Already attached elsewhere - find old parent element for error message
                        old_parent_element = val.parent[val.key] if val.key and val.key in val.parent else None

                        # Create a temporary wrapper-like object for error message compatibility
                        # This is needed because PromptReuseError expects elements with parent/key
                        class _TempWrapper:
                            def __init__(self, parent, key):
                                self.parent = parent
                                self.key = key

                        new_wrapper = _TempWrapper(self, key)
                        raise PromptReuseError(val, old_parent_element, new_wrapper)

                    # Attach the nested prompt directly - set interpolation metadata
                    val.key = key
                    val.expression = itp.expression
                    val.conversion = itp.conversion
                    val.format_spec = itp.format_spec
                    val.render_hints = render_hints
                    val.parent = self
                    val.index = element_idx
                    # Set source_location to where it was interpolated (parent's creation location)
                    # val._creation_location remains where the nested prompt was originally created
                    val.source_location = self._creation_location

                    node = val  # The StructuredPrompt itself is the node
                elif isinstance(val, str):
                    # Create TextInterpolation node
                    node = TextInterpolation(
                        key=key,
                        expression=itp.expression,
                        conversion=itp.conversion,
                        format_spec=itp.format_spec,
                        render_hints=render_hints,
                        value=val,
                        parent=self,
                        index=element_idx,
                        source_location=self._creation_location,
                    )
                else:
                    raise UnsupportedValueTypeError(key, type(val), itp.expression)

                self._interps.append(node)
                self._children.append(node)
                element_idx += 1

                # Update index (maps string keys to positions in _interps list)
                if self._allow_duplicates:
                    if key not in self._index:
                        self._index[key] = []
                    self._index[key].append(interp_idx)  # type: ignore
                else:
                    if key in self._index:
                        raise DuplicateKeyError(key)
                    self._index[key] = interp_idx

                interp_idx += 1

    # Mapping protocol implementation

    def __getitem__(self, key: str) -> InterpolationType:
        """
        Get the interpolation node for the given key.

        Parameters
        ----------
        key : str
            The key to look up (derived from format_spec or expression).

        Returns
        -------
        InterpolationType
            The interpolation node for this key.

        Raises
        ------
        MissingKeyError
            If the key is not found.
        ValueError
            If allow_duplicate_keys=True and the key is ambiguous (use get_all instead).
        """
        if key not in self._index:
            raise MissingKeyError(key, list(self._index.keys()))

        idx = self._index[key]
        if isinstance(idx, list):
            if len(idx) > 1:
                raise ValueError(f"Ambiguous key '{key}' with {len(idx)} occurrences. Use get_all('{key}') instead.")
            idx = idx[0]

        return self._interps[idx]

    def __iter__(self) -> Iterable[str]:
        """Iterate over keys in insertion order."""
        seen = set()
        for node in self._interps:
            if node.key not in seen:
                yield node.key
                seen.add(node.key)

    def __len__(self) -> int:
        """Return the number of unique keys."""
        return len(set(node.key for node in self._interps))

    def get_all(self, key: str) -> list[InterpolationType]:
        """
        Get all interpolation nodes for a given key (for duplicate keys).

        Parameters
        ----------
        key : str
            The key to look up.

        Returns
        -------
        list[InterpolationType]
            List of all interpolation nodes with this key.

        Raises
        ------
        MissingKeyError
            If the key is not found.
        """
        if key not in self._index:
            raise MissingKeyError(key, list(self._index.keys()))

        idx = self._index[key]
        if isinstance(idx, list):
            return [self._interps[i] for i in idx]
        else:
            return [self._interps[idx]]

    # Properties for provenance
    # (id is inherited from Element)

    @property
    def template(self) -> Template:
        """Return the original Template object."""
        return self._template

    @property
    def strings(self) -> tuple[str, ...]:
        """Return the static string segments from the template."""
        return self._template.strings

    @property
    def interpolations(self) -> tuple[InterpolationType, ...]:
        """Return all interpolation nodes in order."""
        return tuple(self._interps)

    @property
    def children(self) -> tuple[Element, ...]:
        """Return all children (Static and StructuredInterpolation) in order."""
        return tuple(self._children)

    @property
    def creation_location(self) -> Optional[SourceLocation]:
        """
        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
        -------
        SourceLocation | None
            The creation location, or None if not captured.
        """
        return self._creation_location

    # Rendering

    def ir(
        self,
        ctx: Optional["RenderContext"] = None,
        _path: tuple[Union[str, int], ...] = (),
        max_header_level: int = 4,
        _header_level: int = 1,
    ) -> "IntermediateRepresentation":
        """
        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
        ----------
        ctx : RenderContext | None, optional
            Rendering context. If None, uses _path, _header_level, and max_header_level.
        _path : tuple[Union[str, int], ...]
            Internal parameter for tracking path during recursive rendering.
        max_header_level : int, optional
            Maximum header level for markdown headers (default: 4).
        _header_level : int
            Internal parameter for tracking current header nesting level.

        Returns
        -------
        IntermediateRepresentation
            Object containing chunks with source mapping via element_id.
        """
        from .element import apply_render_hints
        from .ir import IntermediateRepresentation, RenderContext
        from .parsing import parse_render_hints

        # Create render context if not provided
        if ctx is None:
            ctx = RenderContext(path=_path, header_level=_header_level, max_header_level=max_header_level)

        # If this prompt has been nested (has render_hints), parse them and update context
        if self.render_hints:
            hints = parse_render_hints(self.render_hints, str(self.key))
            # Update header level if header hint is present
            next_level = ctx.header_level + 1 if "header" in hints else ctx.header_level
            # Update context for nested rendering
            ctx = RenderContext(
                path=ctx.path + (self.key,) if self.key is not None else ctx.path,
                header_level=next_level,
                max_header_level=ctx.max_header_level,
            )

        # Convert each element to IR
        element_irs = [element.ir(ctx) for element in self._children]

        # Merge all element IRs (no separator - children are already interleaved with statics)
        merged_ir = IntermediateRepresentation.merge(element_irs, separator="")

        # Apply render hints if this prompt has been nested
        if self.render_hints:
            hints = parse_render_hints(self.render_hints, str(self.key))
            # Use parent's header level for hint application (before increment)
            parent_header_level = ctx.header_level - 1 if "header" in hints else ctx.header_level
            merged_ir = apply_render_hints(merged_ir, hints, parent_header_level, ctx.max_header_level, self.id)

        # Create final IR with source_prompt set to self (only for root prompts)
        # Nested prompts don't set source_prompt to avoid confusion
        source_prompt = self if self.parent is None else None
        return IntermediateRepresentation(
            chunks=merged_ir.chunks,
            source_prompt=source_prompt,
        )

    def __str__(self) -> str:
        """Render to string (convenience for ir().text)."""
        return self.ir().text

    def toJSON(self) -> dict[str, Any]:
        """
        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
        -------
        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
        """

        def _build_element_tree(element: Element, parent_id: str) -> dict[str, Any]:
            """Build JSON representation of a single element with its children."""
            from .element import _serialize_image
            from .source_location import _serialize_source_location

            base = {
                "type": "",  # Will be set below
                "id": element.id,
                "parent_id": parent_id,
                "key": element.key,
                "index": element.index,
                "source_location": _serialize_source_location(element.source_location),
            }

            if isinstance(element, Static):
                base["type"] = "static"
                base["value"] = element.value

            elif isinstance(element, StructuredPrompt):
                # StructuredPrompt is now stored directly as a child element
                base["type"] = "nested_prompt"
                base.update(
                    {
                        "expression": element.expression,
                        "conversion": element.conversion,
                        "format_spec": element.format_spec,
                        "render_hints": element.render_hints,
                        "prompt_id": element.id,  # Element itself is the prompt
                        "creation_location": _serialize_source_location(element.creation_location),
                    }
                )
                # Nested prompt - recurse into its children
                base["children"] = _build_children_tree(element, element.id)

            elif isinstance(element, TextInterpolation):
                base["type"] = "interpolation"
                base.update(
                    {
                        "expression": element.expression,
                        "conversion": element.conversion,
                        "format_spec": element.format_spec,
                        "render_hints": element.render_hints,
                        "value": element.value,
                    }
                )

            elif isinstance(element, ListInterpolation):
                base["type"] = "list"
                base.update(
                    {
                        "expression": element.expression,
                        "conversion": element.conversion,
                        "format_spec": element.format_spec,
                        "render_hints": element.render_hints,
                        "separator": element.separator,
                    }
                )
                # Build array of list items (StructuredPrompts now stored directly)
                base["children"] = [_build_element_tree(item, element.id) for item in element.item_elements]

            elif isinstance(element, ImageInterpolation):
                base["type"] = "image"
                base.update(
                    {
                        "expression": element.expression,
                        "conversion": element.conversion,
                        "format_spec": element.format_spec,
                        "render_hints": element.render_hints,
                        "image_data": _serialize_image(element.value),
                    }
                )

            return base

        def _build_children_tree(prompt: "StructuredPrompt", parent_id: str) -> list[dict[str, Any]]:
            """Build children array for a prompt."""
            return [_build_element_tree(elem, parent_id) for elem in prompt.children]

        return {"prompt_id": self.id, "children": _build_children_tree(self, self.id)}

    def __repr__(self) -> str:
        """Return a helpful debug representation."""
        keys = ", ".join(repr(k) for k in list(self)[:3])
        if len(self) > 3:
            keys += ", ..."
        return f"StructuredPrompt(keys=[{keys}], num_interpolations={len(self._interps)})"

    def clone(self, *, key: Optional[str] = None) -> "StructuredPrompt":
        """
        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
        ----------
        key : str | None, optional
            Optional key for the cloned prompt. If None, uses the original key.

        Returns
        -------
        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.
        """
        from string.templatelib import Interpolation, Template

        # Helper to recursively clone values
        def clone_value(value: Any) -> Any:
            if isinstance(value, StructuredPrompt):
                return value.clone()
            elif isinstance(value, list):
                return [clone_value(item) for item in value]
            else:
                # Strings, images, etc. can be reused directly
                return value

        # Clone all interpolation values and create new Interpolation objects
        # Note: Interpolation constructor is (value, expression, conversion, format_spec)
        cloned_interps = []
        for itp in self._template.interpolations:
            cloned_value = clone_value(itp.value)
            cloned_interps.append(
                Interpolation(
                    cloned_value,  # value comes first
                    itp.expression,
                    itp.conversion,
                    itp.format_spec,
                )
            )

        # Build the new Template by interleaving strings and interpolations
        # Template constructor takes: str, Interpolation, str, Interpolation, ..., str
        template_args = []
        for i, string in enumerate(self._template.strings):
            template_args.append(string)
            if i < len(cloned_interps):
                template_args.append(cloned_interps[i])

        new_template = Template(*template_args)

        # Capture source location at clone() call site
        # Skip 2 frames: _capture_source_location + clone
        clone_source_location = _capture_source_location(skip_frames=2)

        # Create new StructuredPrompt with cloned template
        cloned_prompt = StructuredPrompt(
            new_template,
            allow_duplicate_keys=self._allow_duplicates,
            _processed_strings=self._processed_strings,  # Can reuse (immutable tuple)
            _source_location=clone_source_location,
        )

        # Copy metadata (shallow copy is fine for dict)
        cloned_prompt.metadata = self.metadata.copy()

        # Set the key if provided
        if key is not None:
            cloned_prompt.key = key

        return cloned_prompt

    def widget(self, config: Optional["WidgetConfig"] = None) -> "Widget":
        """
        Create a Widget for Jupyter notebook display.

        This converts to IR, compiles it, then delegates to CompiledIR.widget().

        Parameters
        ----------
        config : WidgetConfig | None, optional
            Widget configuration. If None, uses the package default config.

        Returns
        -------
        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))
        """
        ir = self.ir()
        compiled = ir.compile()
        return compiled.widget(config)

    def _repr_html_(self) -> str:
        """
        Return HTML representation for Jupyter notebook display.

        This method is automatically called by Jupyter/IPython when displaying
        a StructuredPrompt in a notebook cell.

        Returns
        -------
        str
            HTML string with widget visualization.
        """
        return self.widget()._repr_html_()

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
def __getitem__(self, key: str) -> InterpolationType:
    """
    Get the interpolation node for the given key.

    Parameters
    ----------
    key : str
        The key to look up (derived from format_spec or expression).

    Returns
    -------
    InterpolationType
        The interpolation node for this key.

    Raises
    ------
    MissingKeyError
        If the key is not found.
    ValueError
        If allow_duplicate_keys=True and the key is ambiguous (use get_all instead).
    """
    if key not in self._index:
        raise MissingKeyError(key, list(self._index.keys()))

    idx = self._index[key]
    if isinstance(idx, list):
        if len(idx) > 1:
            raise ValueError(f"Ambiguous key '{key}' with {len(idx)} occurrences. Use get_all('{key}') instead.")
        idx = idx[0]

    return self._interps[idx]

__iter__()

Iterate over keys in insertion order.

Source code in src/t_prompts/structured_prompt.py
278
279
280
281
282
283
284
def __iter__(self) -> Iterable[str]:
    """Iterate over keys in insertion order."""
    seen = set()
    for node in self._interps:
        if node.key not in seen:
            yield node.key
            seen.add(node.key)

__len__()

Return the number of unique keys.

Source code in src/t_prompts/structured_prompt.py
286
287
288
def __len__(self) -> int:
    """Return the number of unique keys."""
    return len(set(node.key for node in self._interps))

__repr__()

Return a helpful debug representation.

Source code in src/t_prompts/structured_prompt.py
557
558
559
560
561
562
def __repr__(self) -> str:
    """Return a helpful debug representation."""
    keys = ", ".join(repr(k) for k in list(self)[:3])
    if len(self) > 3:
        keys += ", ..."
    return f"StructuredPrompt(keys=[{keys}], num_interpolations={len(self._interps)})"

__str__()

Render to string (convenience for ir().text).

Source code in src/t_prompts/structured_prompt.py
439
440
441
def __str__(self) -> str:
    """Render to string (convenience for ir().text)."""
    return self.ir().text

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
def clone(self, *, key: Optional[str] = None) -> "StructuredPrompt":
    """
    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
    ----------
    key : str | None, optional
        Optional key for the cloned prompt. If None, uses the original key.

    Returns
    -------
    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.
    """
    from string.templatelib import Interpolation, Template

    # Helper to recursively clone values
    def clone_value(value: Any) -> Any:
        if isinstance(value, StructuredPrompt):
            return value.clone()
        elif isinstance(value, list):
            return [clone_value(item) for item in value]
        else:
            # Strings, images, etc. can be reused directly
            return value

    # Clone all interpolation values and create new Interpolation objects
    # Note: Interpolation constructor is (value, expression, conversion, format_spec)
    cloned_interps = []
    for itp in self._template.interpolations:
        cloned_value = clone_value(itp.value)
        cloned_interps.append(
            Interpolation(
                cloned_value,  # value comes first
                itp.expression,
                itp.conversion,
                itp.format_spec,
            )
        )

    # Build the new Template by interleaving strings and interpolations
    # Template constructor takes: str, Interpolation, str, Interpolation, ..., str
    template_args = []
    for i, string in enumerate(self._template.strings):
        template_args.append(string)
        if i < len(cloned_interps):
            template_args.append(cloned_interps[i])

    new_template = Template(*template_args)

    # Capture source location at clone() call site
    # Skip 2 frames: _capture_source_location + clone
    clone_source_location = _capture_source_location(skip_frames=2)

    # Create new StructuredPrompt with cloned template
    cloned_prompt = StructuredPrompt(
        new_template,
        allow_duplicate_keys=self._allow_duplicates,
        _processed_strings=self._processed_strings,  # Can reuse (immutable tuple)
        _source_location=clone_source_location,
    )

    # Copy metadata (shallow copy is fine for dict)
    cloned_prompt.metadata = self.metadata.copy()

    # Set the key if provided
    if key is not None:
        cloned_prompt.key = key

    return cloned_prompt

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
def get_all(self, key: str) -> list[InterpolationType]:
    """
    Get all interpolation nodes for a given key (for duplicate keys).

    Parameters
    ----------
    key : str
        The key to look up.

    Returns
    -------
    list[InterpolationType]
        List of all interpolation nodes with this key.

    Raises
    ------
    MissingKeyError
        If the key is not found.
    """
    if key not in self._index:
        raise MissingKeyError(key, list(self._index.keys()))

    idx = self._index[key]
    if isinstance(idx, list):
        return [self._interps[i] for i in idx]
    else:
        return [self._interps[idx]]

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
def ir(
    self,
    ctx: Optional["RenderContext"] = None,
    _path: tuple[Union[str, int], ...] = (),
    max_header_level: int = 4,
    _header_level: int = 1,
) -> "IntermediateRepresentation":
    """
    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
    ----------
    ctx : RenderContext | None, optional
        Rendering context. If None, uses _path, _header_level, and max_header_level.
    _path : tuple[Union[str, int], ...]
        Internal parameter for tracking path during recursive rendering.
    max_header_level : int, optional
        Maximum header level for markdown headers (default: 4).
    _header_level : int
        Internal parameter for tracking current header nesting level.

    Returns
    -------
    IntermediateRepresentation
        Object containing chunks with source mapping via element_id.
    """
    from .element import apply_render_hints
    from .ir import IntermediateRepresentation, RenderContext
    from .parsing import parse_render_hints

    # Create render context if not provided
    if ctx is None:
        ctx = RenderContext(path=_path, header_level=_header_level, max_header_level=max_header_level)

    # If this prompt has been nested (has render_hints), parse them and update context
    if self.render_hints:
        hints = parse_render_hints(self.render_hints, str(self.key))
        # Update header level if header hint is present
        next_level = ctx.header_level + 1 if "header" in hints else ctx.header_level
        # Update context for nested rendering
        ctx = RenderContext(
            path=ctx.path + (self.key,) if self.key is not None else ctx.path,
            header_level=next_level,
            max_header_level=ctx.max_header_level,
        )

    # Convert each element to IR
    element_irs = [element.ir(ctx) for element in self._children]

    # Merge all element IRs (no separator - children are already interleaved with statics)
    merged_ir = IntermediateRepresentation.merge(element_irs, separator="")

    # Apply render hints if this prompt has been nested
    if self.render_hints:
        hints = parse_render_hints(self.render_hints, str(self.key))
        # Use parent's header level for hint application (before increment)
        parent_header_level = ctx.header_level - 1 if "header" in hints else ctx.header_level
        merged_ir = apply_render_hints(merged_ir, hints, parent_header_level, ctx.max_header_level, self.id)

    # Create final IR with source_prompt set to self (only for root prompts)
    # Nested prompts don't set source_prompt to avoid confusion
    source_prompt = self if self.parent is None else None
    return IntermediateRepresentation(
        chunks=merged_ir.chunks,
        source_prompt=source_prompt,
    )

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
def toJSON(self) -> dict[str, Any]:
    """
    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
    -------
    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
    """

    def _build_element_tree(element: Element, parent_id: str) -> dict[str, Any]:
        """Build JSON representation of a single element with its children."""
        from .element import _serialize_image
        from .source_location import _serialize_source_location

        base = {
            "type": "",  # Will be set below
            "id": element.id,
            "parent_id": parent_id,
            "key": element.key,
            "index": element.index,
            "source_location": _serialize_source_location(element.source_location),
        }

        if isinstance(element, Static):
            base["type"] = "static"
            base["value"] = element.value

        elif isinstance(element, StructuredPrompt):
            # StructuredPrompt is now stored directly as a child element
            base["type"] = "nested_prompt"
            base.update(
                {
                    "expression": element.expression,
                    "conversion": element.conversion,
                    "format_spec": element.format_spec,
                    "render_hints": element.render_hints,
                    "prompt_id": element.id,  # Element itself is the prompt
                    "creation_location": _serialize_source_location(element.creation_location),
                }
            )
            # Nested prompt - recurse into its children
            base["children"] = _build_children_tree(element, element.id)

        elif isinstance(element, TextInterpolation):
            base["type"] = "interpolation"
            base.update(
                {
                    "expression": element.expression,
                    "conversion": element.conversion,
                    "format_spec": element.format_spec,
                    "render_hints": element.render_hints,
                    "value": element.value,
                }
            )

        elif isinstance(element, ListInterpolation):
            base["type"] = "list"
            base.update(
                {
                    "expression": element.expression,
                    "conversion": element.conversion,
                    "format_spec": element.format_spec,
                    "render_hints": element.render_hints,
                    "separator": element.separator,
                }
            )
            # Build array of list items (StructuredPrompts now stored directly)
            base["children"] = [_build_element_tree(item, element.id) for item in element.item_elements]

        elif isinstance(element, ImageInterpolation):
            base["type"] = "image"
            base.update(
                {
                    "expression": element.expression,
                    "conversion": element.conversion,
                    "format_spec": element.format_spec,
                    "render_hints": element.render_hints,
                    "image_data": _serialize_image(element.value),
                }
            )

        return base

    def _build_children_tree(prompt: "StructuredPrompt", parent_id: str) -> list[dict[str, Any]]:
        """Build children array for a prompt."""
        return [_build_element_tree(elem, parent_id) for elem in prompt.children]

    return {"prompt_id": self.id, "children": _build_children_tree(self, self.id)}

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
def widget(self, config: Optional["WidgetConfig"] = None) -> "Widget":
    """
    Create a Widget for Jupyter notebook display.

    This converts to IR, compiles it, then delegates to CompiledIR.widget().

    Parameters
    ----------
    config : WidgetConfig | None, optional
        Widget configuration. If None, uses the package default config.

    Returns
    -------
    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))
    """
    ir = self.ir()
    compiled = ir.compile()
    return compiled.widget(config)

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
@dataclass(slots=True)
class StructuredPromptDiff:
    """Result of comparing two StructuredPrompt instances."""

    before: StructuredPrompt
    after: StructuredPrompt
    root: NodeDelta
    stats: DiffStats
    metrics: StructuralDiffMetrics

    def to_widget_data(self) -> dict[str, Any]:
        """
        Convert diff to widget data for TypeScript rendering.

        Returns
        -------
        dict[str, Any]
            JSON-serializable dictionary with diff data.
        """
        return {
            "diff_type": "structured",
            "root": _serialize_node_delta(self.root),
            "stats": {
                "nodes_added": self.stats.nodes_added,
                "nodes_removed": self.stats.nodes_removed,
                "nodes_modified": self.stats.nodes_modified,
                "nodes_moved": self.stats.nodes_moved,
                "text_added": self.stats.text_added,
                "text_removed": self.stats.text_removed,
            },
            "metrics": {
                "struct_edit_count": self.metrics.struct_edit_count,
                "struct_span_chars": self.metrics.struct_span_chars,
                "struct_char_ratio": self.metrics.struct_char_ratio,
                "struct_order_score": self.metrics.struct_order_score,
            },
        }

    def _repr_html_(self) -> str:
        """Return HTML representation for Jupyter notebook display."""
        from .widgets import _render_widget_html

        data = self.to_widget_data()
        return _render_widget_html(data, "tp-sp-diff-mount")

    def __str__(self) -> str:
        """Return simple string representation showing diff statistics."""
        return (
            f"StructuredPromptDiff("
            f"nodes_added={self.stats.nodes_added}, "
            f"nodes_removed={self.stats.nodes_removed}, "
            f"nodes_modified={self.stats.nodes_modified}, "
            f"nodes_moved={self.stats.nodes_moved}, "
            f"text_added={self.stats.text_added}, "
            f"text_removed={self.stats.text_removed}, "
            f"struct_edit_count={self.metrics.struct_edit_count:.1f}, "
            f"struct_span_chars={self.metrics.struct_span_chars}, "
            f"struct_char_ratio={self.metrics.struct_char_ratio:.3f}, "
            f"struct_order_score={self.metrics.struct_order_score:.3f})"
        )

    def __repr__(self) -> str:
        """Return string representation."""
        return self.__str__()

__repr__()

Return string representation.

Source code in src/t_prompts/diff.py
159
160
161
def __repr__(self) -> str:
    """Return string representation."""
    return self.__str__()

__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
def __str__(self) -> str:
    """Return simple string representation showing diff statistics."""
    return (
        f"StructuredPromptDiff("
        f"nodes_added={self.stats.nodes_added}, "
        f"nodes_removed={self.stats.nodes_removed}, "
        f"nodes_modified={self.stats.nodes_modified}, "
        f"nodes_moved={self.stats.nodes_moved}, "
        f"text_added={self.stats.text_added}, "
        f"text_removed={self.stats.text_removed}, "
        f"struct_edit_count={self.metrics.struct_edit_count:.1f}, "
        f"struct_span_chars={self.metrics.struct_span_chars}, "
        f"struct_char_ratio={self.metrics.struct_char_ratio:.3f}, "
        f"struct_order_score={self.metrics.struct_order_score:.3f})"
    )

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
def to_widget_data(self) -> dict[str, Any]:
    """
    Convert diff to widget data for TypeScript rendering.

    Returns
    -------
    dict[str, Any]
        JSON-serializable dictionary with diff data.
    """
    return {
        "diff_type": "structured",
        "root": _serialize_node_delta(self.root),
        "stats": {
            "nodes_added": self.stats.nodes_added,
            "nodes_removed": self.stats.nodes_removed,
            "nodes_modified": self.stats.nodes_modified,
            "nodes_moved": self.stats.nodes_moved,
            "text_added": self.stats.text_added,
            "text_removed": self.stats.text_removed,
        },
        "metrics": {
            "struct_edit_count": self.metrics.struct_edit_count,
            "struct_span_chars": self.metrics.struct_span_chars,
            "struct_char_ratio": self.metrics.struct_char_ratio,
            "struct_order_score": self.metrics.struct_order_score,
        },
    }

StructuredPromptsError

Bases: Exception

Base exception for all structured-prompts errors.

Source code in src/t_prompts/exceptions.py
4
5
class StructuredPromptsError(Exception):
    """Base exception for all structured-prompts errors."""

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
@dataclass(frozen=True, slots=True)
class TextChunk:
    """
    A chunk of text in the rendered output.

    Each chunk maps to exactly one source element.

    Attributes
    ----------
    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., <system>, </system>).
    """

    text: str
    element_id: str
    id: str = field(default_factory=lambda: str(uuid.uuid4()))
    metadata: dict[str, Any] = field(default_factory=dict)
    needs_html_escape: bool = False

    def toJSON(self) -> dict[str, Any]:
        """
        Convert TextChunk to JSON-serializable dictionary.

        Returns
        -------
        dict[str, Any]
            Dictionary with type, text, element_id, id, metadata, needs_html_escape.
        """
        return {
            "type": "TextChunk",
            "text": self.text,
            "element_id": self.element_id,
            "id": self.id,
            "metadata": self.metadata,
            "needs_html_escape": self.needs_html_escape,
        }

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
def toJSON(self) -> dict[str, Any]:
    """
    Convert TextChunk to JSON-serializable dictionary.

    Returns
    -------
    dict[str, Any]
        Dictionary with type, text, element_id, id, metadata, needs_html_escape.
    """
    return {
        "type": "TextChunk",
        "text": self.text,
        "element_id": self.element_id,
        "id": self.id,
        "metadata": self.metadata,
        "needs_html_escape": self.needs_html_escape,
    }

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
@dataclass(slots=True)
class TextInterpolation(Element):
    """
    Immutable record of a text interpolation in a StructuredPrompt.

    Represents interpolations where the value is a string.

    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).
    value : str
        The string value.
    """

    # Inherited from Element: expression, conversion, format_spec, render_hints
    value: str = ""

    def __getitem__(self, key: str) -> InterpolationType:
        """
        Raise NotANestedPromptError since text interpolations cannot be indexed.

        Parameters
        ----------
        key : str
            The key attempted to access.

        Raises
        ------
        NotANestedPromptError
            Always, since text interpolations don't support indexing.
        """
        raise NotANestedPromptError(str(self.key))

    def ir(self, ctx: Optional["RenderContext"] = None) -> "IntermediateRepresentation":
        """
        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
        ----------
        ctx : RenderContext | None, optional
            Rendering context. If None, uses default context.

        Returns
        -------
        IntermediateRepresentation
            IR with chunks including any wrappers.
        """
        from .ir import IntermediateRepresentation, RenderContext
        from .parsing import parse_render_hints

        if ctx is None:
            ctx = RenderContext(path=(), header_level=1, max_header_level=4)

        # Parse render hints
        hints = parse_render_hints(self.render_hints, str(self.key))

        # String value - apply conversion if needed
        text = self.value
        if self.conversion:
            conv: Literal["r", "s", "a"] = self.conversion  # type: ignore
            text = convert(text, conv)
        result_ir = IntermediateRepresentation.from_text(text, self.id)

        # Apply render hints using chunk-based operations
        result_ir = apply_render_hints(result_ir, hints, ctx.header_level, ctx.max_header_level, self.id)

        return result_ir

    def __repr__(self) -> str:
        """Return a helpful debug representation."""
        return (
            f"TextInterpolation(key={self.key!r}, expression={self.expression!r}, "
            f"conversion={self.conversion!r}, format_spec={self.format_spec!r}, "
            f"render_hints={self.render_hints!r}, value={self.value!r}, index={self.index})"
        )

    def toJSON(self) -> dict[str, Any]:
        """
        Convert TextInterpolation to JSON-serializable dictionary.

        Returns
        -------
        dict[str, Any]
            Dictionary with type, key, index, source_location, id, expression,
            conversion, format_spec, render_hints, value, parent_id, metadata.
        """
        return {
            "type": "TextInterpolation",
            **self._base_json_dict(),
            **self._interpolation_json_dict(self.expression, self.conversion, self.format_spec, self.render_hints),
            "value": self.value,
        }

__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
def __getitem__(self, key: str) -> InterpolationType:
    """
    Raise NotANestedPromptError since text interpolations cannot be indexed.

    Parameters
    ----------
    key : str
        The key attempted to access.

    Raises
    ------
    NotANestedPromptError
        Always, since text interpolations don't support indexing.
    """
    raise NotANestedPromptError(str(self.key))

__repr__()

Return a helpful debug representation.

Source code in src/t_prompts/element.py
389
390
391
392
393
394
395
def __repr__(self) -> str:
    """Return a helpful debug representation."""
    return (
        f"TextInterpolation(key={self.key!r}, expression={self.expression!r}, "
        f"conversion={self.conversion!r}, format_spec={self.format_spec!r}, "
        f"render_hints={self.render_hints!r}, value={self.value!r}, index={self.index})"
    )

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
def ir(self, ctx: Optional["RenderContext"] = None) -> "IntermediateRepresentation":
    """
    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
    ----------
    ctx : RenderContext | None, optional
        Rendering context. If None, uses default context.

    Returns
    -------
    IntermediateRepresentation
        IR with chunks including any wrappers.
    """
    from .ir import IntermediateRepresentation, RenderContext
    from .parsing import parse_render_hints

    if ctx is None:
        ctx = RenderContext(path=(), header_level=1, max_header_level=4)

    # Parse render hints
    hints = parse_render_hints(self.render_hints, str(self.key))

    # String value - apply conversion if needed
    text = self.value
    if self.conversion:
        conv: Literal["r", "s", "a"] = self.conversion  # type: ignore
        text = convert(text, conv)
    result_ir = IntermediateRepresentation.from_text(text, self.id)

    # Apply render hints using chunk-based operations
    result_ir = apply_render_hints(result_ir, hints, ctx.header_level, ctx.max_header_level, self.id)

    return result_ir

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
def toJSON(self) -> dict[str, Any]:
    """
    Convert TextInterpolation to JSON-serializable dictionary.

    Returns
    -------
    dict[str, Any]
        Dictionary with type, key, index, source_location, id, expression,
        conversion, format_spec, render_hints, value, parent_id, metadata.
    """
    return {
        "type": "TextInterpolation",
        **self._base_json_dict(),
        **self._interpolation_json_dict(self.expression, self.conversion, self.format_spec, self.render_hints),
        "value": self.value,
    }

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
class UnsupportedValueTypeError(StructuredPromptsError):
    """Raised when an interpolation value is neither str nor StructuredPrompt."""

    def __init__(self, key: str, value_type: type, expression: str):
        self.key = key
        self.value_type = value_type
        self.expression = expression
        super().__init__(
            f"Unsupported value type for interpolation '{expression}' (key='{key}'): "
            f"expected str or StructuredPrompt, got {value_type.__name__}"
        )

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
class 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
    ----------
    html : str
        The HTML content to display.
    """

    def __init__(self, html: str):
        """
        Create a Widget with the given HTML content.

        Parameters
        ----------
        html : str
            The HTML string to display.
        """
        self.html = html

    def _repr_html_(self) -> str:
        """
        Return HTML representation for Jupyter notebook display.

        This method is automatically called by Jupyter/IPython when displaying
        a Widget in a notebook cell.

        Returns
        -------
        str
            The HTML content.
        """
        return self.html

__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
def __init__(self, html: str):
    """
    Create a Widget with the given HTML content.

    Parameters
    ----------
    html : str
        The HTML string to display.
    """
    self.html = html

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
@dataclass
class WidgetConfig:
    """
    Configuration for widget rendering in Jupyter notebooks.

    Attributes
    ----------
    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.
    """

    wrapping: bool = True
    sourcePrefix: str = ""

    def __post_init__(self):
        """Set sourcePrefix to cwd if empty."""
        if not self.sourcePrefix:
            self.sourcePrefix = os.getcwd()

__post_init__()

Set sourcePrefix to cwd if empty.

Source code in src/t_prompts/widgets/config.py
26
27
28
29
def __post_init__(self):
    """Set sourcePrefix to cwd if empty."""
    if not self.sourcePrefix:
        self.sourcePrefix = os.getcwd()

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
def dedent(
    template: Template,
    /,
    *,
    trim_leading: bool = True,
    trim_empty_leading: bool = True,
    trim_trailing: bool = True,
    **opts,
) -> StructuredPrompt:
    """
    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
    ----------
    template : Template
        The Template object from a t-string literal (e.g., t"...").
    trim_leading : bool, optional
        If True, remove the first line of the first static if it's whitespace-only
        and ends in a newline. Default is True.
    trim_empty_leading : bool, optional
        If True, remove empty lines (just newlines) after the first line in the
        first static. Default is True.
    trim_trailing : bool, optional
        If True, remove trailing newlines from the last static. Default is True.
    **opts
        Additional options passed to StructuredPrompt constructor
        (e.g., allow_duplicate_keys=True).

    Returns
    -------
    StructuredPrompt
        The structured prompt object with dedenting applied.

    Raises
    ------
    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.
    """
    # Capture source location here (caller of dedent) if not explicitly disabled
    capture = opts.get("capture_source_location", True)
    if capture:
        # Skip 2 frames: _capture_source_location + dedent
        source_loc = _capture_source_location(skip_frames=2)
        opts["_source_location"] = source_loc

    return prompt(
        template,
        dedent=True,
        trim_leading=trim_leading,
        trim_empty_leading=trim_empty_leading,
        trim_trailing=trim_trailing,
        **opts,
    )

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
def diff_rendered_prompts(before: StructuredPrompt, after: StructuredPrompt) -> RenderedPromptDiff:
    """Compute a diff of the rendered intermediate representations."""

    before_chunks = before.ir().chunks
    after_chunks = after.ir().chunks
    before_signatures = _build_element_signature_map(before)
    after_signatures = _build_element_signature_map(after)
    deltas = _diff_chunks(before_chunks, after_chunks, before_signatures, after_signatures)
    per_element: dict[str, ElementRenderChange] = {}
    for delta in deltas:
        element_id = _chunk_element(delta)
        if not element_id:
            continue
        summary = per_element.setdefault(element_id, ElementRenderChange(element_id))
        if delta.op == "equal":
            summary.equals += 1
        elif delta.op == "insert":
            summary.inserts += 1
        elif delta.op == "delete":
            summary.deletes += 1
        elif delta.op == "replace":
            summary.replaces += 1
        added, removed = delta.text_delta()
        summary.text_added += added
        summary.text_removed += removed
    metrics = _compute_rendered_metrics(before_chunks, after_chunks, before_signatures, after_signatures)
    return RenderedPromptDiff(
        before=before,
        after=after,
        chunk_deltas=deltas,
        per_element=per_element,
        metrics=metrics,
    )

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
def diff_structured_prompts(before: StructuredPrompt, after: StructuredPrompt) -> StructuredPromptDiff:
    """Compute a structural diff between two StructuredPrompt trees."""

    root = _align_nodes(before, after)
    stats = DiffStats()
    _collect_stats(root, stats)
    metrics = _compute_structural_metrics(before, root)
    return StructuredPromptDiff(before=before, after=after, root=root, stats=stats, metrics=metrics)

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
def get_default_widget_config() -> WidgetConfig:
    """
    Get the package-level default widget configuration.

    Returns
    -------
    WidgetConfig
        The default configuration. If not set, creates a new one with defaults.
    """
    global _default_config
    if _default_config is None:
        _default_config = WidgetConfig()
    return _default_config

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