ValueError
anthropic.client.exceptions.ValueError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
response = client.messages.create(model="claude-3-5-sonnet-20241022", system="", messages=messages)
File "/usr/local/lib/python3.9/site-packages/anthropic/client.py", line 210, in create
raise ValueError(f"Invalid JSON schema: {e}")
ValueError: Invalid JSON schema: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) Why it happens
Anthropic's tool use expects the LLM to return a JSON object strictly matching the provided JSON schema. If the LLM outputs extra text, uses single quotes, or returns malformed JSON, the schema validation fails and raises this error. This often happens when the prompt does not clearly instruct the model to return raw JSON or when the model is not instruction-tuned for strict JSON output.
Detection
Monitor for ValueError exceptions during client.messages.create calls and log the raw LLM output to detect schema mismatches before the error propagates.
Causes & fixes
LLM returns JSON with single quotes or extra text outside the JSON object
Update the prompt to explicitly instruct the model to return only raw JSON with double quotes and no extra text.
The JSON schema provided to Anthropic's tool use is malformed or uses incorrect syntax
Validate and correct the JSON schema syntax to conform to standard JSON Schema specifications before passing it to the API.
Using a base model that does not reliably follow JSON schema format instructions
Switch to an instruction-tuned Anthropic model like claude-3-5-sonnet-20241022 that better respects JSON schema output requirements.
Code: broken vs fixed
import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
messages = [
{"role": "user", "content": "Please provide the data in JSON format."}
]
# This line raises ValueError due to invalid JSON schema in response
response = client.messages.create(model="claude-3-5-sonnet-20241022", system="", messages=messages)
print(response) import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
messages = [
{"role": "user", "content": "Return ONLY raw JSON matching the schema with double quotes, no extra text."}
]
# Fixed: prompt instructs raw JSON output, reducing schema validation errors
response = client.messages.create(model="claude-3-5-sonnet-20241022", system="", messages=messages)
print(response) Workaround
Catch the ValueError exception, extract the JSON substring from the raw LLM output using regex, and parse it manually with json.loads() as a fallback.
Prevention
Use Anthropic's structured tool use with strict JSON schema validation and instruction-tuned models, and always include clear prompt instructions to return raw JSON without extra formatting.