Prompt utils
prompt_utils
AudioContent
dataclass
AudioContent(data, mime_type, source_path=None)
Bases: MediaContent
An audio content block for multi-modal payloads.
Examples::
AudioContent.from_path("recording.wav")
AudioContent.from_bytes(wav_bytes)
from_bytes
classmethod
from_bytes(data)
Create audio from raw bytes.
Source code in llmeter/prompt_utils.py
271 272 273 274 | |
from_path
classmethod
from_path(file_path)
Load audio from a file path.
Source code in llmeter/prompt_utils.py
266 267 268 269 | |
DocumentContent
dataclass
DocumentContent(data, mime_type, source_path=None)
Bases: MediaContent
A document content block for multi-modal payloads.
Examples::
DocumentContent.from_path("report.pdf")
DocumentContent.from_bytes(pdf_bytes)
from_bytes
classmethod
from_bytes(data)
Create a document from raw bytes.
Source code in llmeter/prompt_utils.py
313 314 315 316 | |
from_path
classmethod
from_path(file_path)
Load a document from a file path.
Source code in llmeter/prompt_utils.py
308 309 310 311 | |
ImageContent
dataclass
ImageContent(data, mime_type, source_path=None)
Bases: MediaContent
An image content block for multi-modal payloads.
Examples::
ImageContent.from_path("photo.jpg")
ImageContent.from_bytes(jpeg_bytes)
from_bytes
classmethod
from_bytes(data)
Create an image from raw bytes.
Source code in llmeter/prompt_utils.py
250 251 252 253 | |
from_path
classmethod
from_path(file_path)
Load an image from a file path.
Source code in llmeter/prompt_utils.py
245 246 247 248 | |
MediaContent
dataclass
MediaContent(data, mime_type, source_path=None)
Base for typed multi-modal content blocks.
Subclasses represent specific media types (image, audio, video, document).
Each carries the raw bytes and a detected MIME type so that endpoint
create_payload methods can convert them to the provider-specific format
without re-detecting.
data
instance-attribute
data
Raw binary content.
mime_type
instance-attribute
mime_type
Detected MIME type (e.g. "image/jpeg").
source_path
class-attribute
instance-attribute
source_path = None
Original file path, if the content was loaded from a file.
VideoContent
dataclass
VideoContent(data, mime_type, source_path=None)
Bases: MediaContent
A video content block for multi-modal payloads.
Examples::
VideoContent.from_path("clip.mp4")
VideoContent.from_bytes(mp4_bytes)
from_bytes
classmethod
from_bytes(data)
Create video from raw bytes.
Source code in llmeter/prompt_utils.py
292 293 294 295 | |
from_path
classmethod
from_path(file_path)
Load video from a file path.
Source code in llmeter/prompt_utils.py
287 288 289 290 | |
detect_format
detect_format(content=None, file_path=None)
Detect MIME type from binary content and/or a file path.
Tries content-based detection first (via puremagic, if installed),
then falls back to file-extension detection when a file_path is given.
At least one of content or file_path must be provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes | None
|
Raw bytes to inspect (optional). |
None
|
file_path
|
ReadablePathLike | None
|
A file path whose extension (and, if |
None
|
Returns:
| Type | Description |
|---|---|
str | None
|
The detected MIME type string, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither content nor file_path is provided. |
Examples:
>>> detect_format(content=b"\xff\xd8\xff\xe0")
'image/jpeg'
>>> detect_format(file_path="report.pdf")
'application/pdf'
Source code in llmeter/prompt_utils.py
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 | |
detect_format_from_bytes
detect_format_from_bytes(content)
Detect MIME type from bytes content using puremagic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
Binary content |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: MIME type or None if detection fails or puremagic not available |
Examples:
>>> detect_format_from_bytes(b"\xff\xd8\xff\xe0") # JPEG magic bytes
"image/jpeg"
Source code in llmeter/prompt_utils.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | |
detect_format_from_extension
detect_format_from_extension(file_path)
Detect MIME type from file extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
ReadablePathLike
|
Path to the file |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: MIME type or None if extension not recognized |
Examples:
>>> detect_format_from_extension("image.jpg")
"image/jpeg"
>>> detect_format_from_extension("document.pdf")
"application/pdf"
Source code in llmeter/prompt_utils.py
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 | |
detect_format_from_file
detect_format_from_file(file_path)
Detect MIME type from file using puremagic or extension fallback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
ReadablePathLike
|
Path to the file |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: MIME type or None if format cannot be detected |
Examples:
>>> detect_format_from_file("photo.jpg")
"image/jpeg"
Source code in llmeter/prompt_utils.py
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 | |
load_payloads
load_payloads(file_path)
Load JSON payload(s) from a file or directory with binary content support.
This function reads JSON data from either a single file or multiple files
in a directory. It supports both .json and .jsonl file formats. Binary content
(bytes objects) that were serialized using llmeter_default_serializer are automatically
restored during deserialization.
Binary Content Handling
When loading payloads saved with save_payloads(), marker objects with the key "llmeter_bytes" are automatically detected and converted back to bytes objects. The base64-encoded strings are decoded to restore the original binary data, enabling round-trip preservation of multimodal content like images and video.
The marker object format is: {"llmeter_bytes": "
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Union[UPath, str]
|
Path to a JSON file or a directory containing JSON files. Can be a string or a Path object. |
required |
Yields:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Each JSON object loaded from the file(s). |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified file or directory does not exist. |
JSONDecodeError
|
If there's an error parsing the JSON data. |
ValidationError
|
If the JSON data does not conform to the expected schema. |
IOError
|
If there's an error reading the file. |
Examples:
Load a Bedrock Converse API payload with image content:
>>> # Assuming a file was saved with save_payloads() containing binary data
>>> payloads = list(load_payloads("/tmp/output/payload.jsonl"))
>>> payload = payloads[0]
>>> # Binary content is automatically restored as bytes
>>> image_bytes = payload["messages"][0]["content"][1]["image"]["source"]["bytes"]
>>> isinstance(image_bytes, bytes)
True
>>> # The bytes can be used directly with the API
>>> print(f"Image size: {len(image_bytes)} bytes")
Image size: 52341 bytes
Load multiple payloads with video content:
>>> for payload in load_payloads("/tmp/output/multimodal.jsonl"):
... video_content = payload["messages"][0]["content"][1]
... if "video" in video_content:
... video_bytes = video_content["video"]["source"]["bytes"]
... print(f"Loaded video: {len(video_bytes)} bytes")
Loaded video: 1048576 bytes
Load all payloads from a directory:
>>> # Load all .json and .jsonl files in a directory
>>> all_payloads = list(load_payloads("/tmp/output/"))
>>> print(f"Loaded {len(all_payloads)} payloads")
Loaded 5 payloads
Round-trip example showing binary preservation:
>>> # Original payload with binary data
>>> original = {
... "modelId": "test-model",
... "messages": [{
... "role": "user",
... "content": [
... {"image": {"source": {"bytes": b"\xff\xd8\xff\xe0"}}}
... ]
... }]
... }
>>> # Save and load
>>> save_payloads(original, "/tmp/test")
PosixPath('/tmp/test/payload.jsonl')
>>> loaded = list(load_payloads("/tmp/test/payload.jsonl"))[0]
>>> # Binary data is preserved byte-for-byte
>>> original == loaded
True
Source code in llmeter/prompt_utils.py
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 | |
load_prompts
load_prompts(file_path, create_payload_fn, create_payload_kwargs={}, file_pattern=None)
Load prompts from a file or directory and create payloads.
This function reads prompts from either a single file or multiple files in a directory, and generates payloads using the provided create_payload_fn.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Union[UPath, str]
|
Path to a file or directory containing prompts. |
required |
create_payload_fn
|
Callable
|
Function to create a payload from each prompt. |
required |
create_payload_kwargs
|
Dict
|
Additional keyword arguments for create_payload_fn. Defaults to an empty dictionary. |
{}
|
file_pattern
|
Union[str, None]
|
Glob pattern for matching files in a directory. If None, matches all files. Defaults to None. |
None
|
Yields:
| Name | Type | Description |
|---|---|---|
Dict |
dict
|
Payload created from each prompt. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified file or directory does not exist. |
PermissionError
|
If there's insufficient permission to read the file(s). |
ValueError
|
If create_payload_fn raises a ValueError. |
Source code in llmeter/prompt_utils.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 | |
read_file
read_file(file_path)
Read binary content from a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
ReadablePathLike
|
Path to the file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
File content |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist |
IOError
|
If file cannot be read |
Source code in llmeter/prompt_utils.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
save_payloads
save_payloads(payloads, output_path, output_file='payload.jsonl')
Save payloads to a file with support for binary content.
This function saves payloads to a JSONL file, with automatic handling of binary content (bytes objects) through base64 encoding. Binary data is wrapped in marker objects during serialization to enable round-trip preservation.
Binary Content Handling
When a payload contains bytes objects (e.g., images, video), they are automatically converted to base64-encoded strings and wrapped in a marker object with the key "llmeter_bytes". This approach enables JSON serialization while preserving the ability to restore the original bytes during deserialization with load_payloads().
The marker object format is: {"llmeter_bytes": "
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payloads
|
Union[list[dict], dict]
|
Payload(s) to save. May contain bytes objects at any nesting level. |
required |
output_path
|
Union[UPath, str]
|
The directory path where the output file should be saved. |
required |
output_file
|
str
|
The name of the output file. Defaults to "payload.jsonl". |
'payload.jsonl'
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
UPath
|
The path to the output file. |
Raises:
| Type | Description |
|---|---|
IOError
|
If there's an error writing to the file. |
TypeError
|
If payload contains unserializable types. |
Examples:
Save a Bedrock Converse API payload with image content:
>>> import base64
>>> # Create a payload with binary image data
>>> with open("image.jpg", "rb") as f:
... image_bytes = f.read()
>>> payload = {
... "modelId": "anthropic.claude-3-haiku-20240307-v1:0",
... "messages": [{
... "role": "user",
... "content": [
... {"text": "What is in this image?"},
... {
... "image": {
... "format": "jpeg",
... "source": {"bytes": image_bytes}
... }
... }
... ]
... }]
... }
>>> output_path = save_payloads(payload, "/tmp/output")
>>> print(output_path)
/tmp/output/payload.jsonl
Save multiple payloads with video content:
>>> with open("video.mp4", "rb") as f:
... video_bytes = f.read()
>>> payloads = [
... {
... "modelId": "anthropic.claude-3-sonnet-20240229-v1:0",
... "messages": [{
... "role": "user",
... "content": [
... {"text": "Describe this video"},
... {
... "video": {
... "format": "mp4",
... "source": {"bytes": video_bytes}
... }
... }
... ]
... }]
... }
... ]
>>> save_payloads(payloads, "/tmp/output", "multimodal.jsonl")
PosixPath('/tmp/output/multimodal.jsonl')
The saved JSON file will contain marker objects for binary data:
>>> # Example of what gets written to the file:
>>> # {
>>> # "modelId": "anthropic.claude-3-haiku-20240307-v1:0",
>>> # "messages": [{
>>> # "role": "user",
>>> # "content": [
>>> # {"text": "What is in this image?"},
>>> # {
>>> # "image": {
>>> # "format": "jpeg",
>>> # "source": {
>>> # "bytes": {"__llmeter_bytes__": "/9j/4AAQSkZJRg..."}
>>> # }
>>> # }
>>> # }
>>> # ]
>>> # }]
>>> # }
Source code in llmeter/prompt_utils.py
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 | |