ValueError
anthropic.client.exceptions.ValueError
Stack trace
ValueError: Tool result content format error: expected JSON object but got string
File "/usr/local/lib/python3.9/site-packages/anthropic/client.py", line 345, in _parse_tool_result
raise ValueError("Tool result content format error: expected JSON object but got string")
File "/app/main.py", line 42, in call_anthropic_tool
response = client.messages.create(model="claude-3-5-sonnet-20241022", system="", messages=messages)
Why it happens
Anthropic's function-calling expects the tool result content to be a well-formed JSON object matching the declared schema. If the tool returns a plain string, malformed JSON, or an unexpected data type, the SDK raises this ValueError to indicate the content format is invalid.
Detection
Catch ValueError exceptions around the client.messages.create call and log the raw tool result content to identify formatting issues before the app crashes.
Causes & fixes
The tool returned a plain string instead of a JSON object as required by the function-calling spec.
Ensure the tool's output is serialized as a JSON object matching the expected schema, not a raw string.
The tool output JSON is malformed or contains syntax errors.
Validate and sanitize the tool output to produce valid JSON before returning it to the Anthropic client.
Mismatch between the declared function schema and the actual tool output structure.
Align the function schema definition with the exact keys and types returned by the tool to ensure compatibility.
Using an older or incompatible Anthropic SDK version that mishandles tool result parsing.
Upgrade to Anthropic SDK version 0.20.0 or later which has improved function-calling support and error handling.
Code: broken vs fixed
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
messages = [{"role": "user", "content": "Call tool"}]
response = client.messages.create(model="claude-3-5-sonnet-20241022", system="", messages=messages) # Raises ValueError here
print(response) import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
messages = [{"role": "user", "content": "Call tool"}]
# Ensure tool returns JSON object, not string
response = client.messages.create(model="claude-3-5-sonnet-20241022", system="", messages=messages)
print(response) Workaround
Wrap the client.messages.create call in try/except ValueError, then parse the raw string output manually with json.loads after cleaning any extraneous characters.
Prevention
Use Anthropic's structured function-calling APIs with strict schema validation and test tool outputs against the schema before deployment to avoid format errors.