Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions pydantic_ai_slim/pydantic_ai/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from dataclasses import KW_ONLY, dataclass, field, replace
from datetime import datetime
from mimetypes import guess_type
from os import PathLike
from pathlib import Path
from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeAlias, cast, overload

import pydantic
Expand Down Expand Up @@ -530,6 +532,25 @@ def from_data_uri(cls, data_uri: str) -> BinaryContent:
media_type, data = data_uri[len(prefix) :].split(';base64,', 1)
return cls.narrow_type(cls(data=base64.b64decode(data), media_type=media_type))

@classmethod
def from_path(cls, path: PathLike[str]) -> BinaryContent:
"""Create a `BinaryContent` from a path.

Defaults to 'application/octet-stream' if the media type cannot be inferred.

Raises:
FileNotFoundError: if the file does not exist.
PermissionError: if the file cannot be read.
"""
path = Path(path)
if not path.exists():
raise FileNotFoundError(f'File not found: {path}')
media_type, _ = guess_type(path)
if media_type is None:
media_type = 'application/octet-stream'

return cls.narrow_type(cls(data=path.read_bytes(), media_type=media_type))

@pydantic.computed_field
@property
def identifier(self) -> str:
Expand Down
35 changes: 35 additions & 0 deletions tests/test_messages.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import sys
from datetime import datetime, timezone
from pathlib import Path

import pytest
from inline_snapshot import snapshot
Expand Down Expand Up @@ -612,3 +613,37 @@ def test_binary_content_validation_with_optional_identifier():
'identifier': 'foo',
}
)


def test_binary_content_from_path(tmp_path: Path):
# test normal file
test_xml_file = tmp_path / 'test.xml'
test_xml_file.write_text('<think>about trains</think>', encoding='utf-8')
binary_content = BinaryContent.from_path(test_xml_file)
assert binary_content == snapshot(BinaryContent(data=b'<think>about trains</think>', media_type='application/xml'))

# test non-existent file
non_existent_file = tmp_path / 'non-existent.txt'
with pytest.raises(FileNotFoundError, match='File not found:'):
BinaryContent.from_path(non_existent_file)

# test file with unknown media type
test_unknown_file = tmp_path / 'test.unknownext'
test_unknown_file.write_text('some content', encoding='utf-8')
binary_content = BinaryContent.from_path(test_unknown_file)
assert binary_content == snapshot(BinaryContent(data=b'some content', media_type='application/octet-stream'))

# test string path
test_txt_file = tmp_path / 'test.txt'
test_txt_file.write_text('just some text', encoding='utf-8')
string_path = test_txt_file.as_posix()
binary_content = BinaryContent.from_path(string_path) # pyright: ignore[reportArgumentType]
assert binary_content == snapshot(BinaryContent(data=b'just some text', media_type='text/plain'))

# test image file
test_jpg_file = tmp_path / 'test.jpg'
test_jpg_file.write_bytes(b'\xff\xd8\xff\xe0' + b'0' * 100) # minimal JPEG header + padding
binary_content = BinaryContent.from_path(test_jpg_file)
assert binary_content == snapshot(
BinaryImage(data=b'\xff\xd8\xff\xe0' + b'0' * 100, media_type='image/jpeg', _identifier='bc8d49')
)