Skip to content

Instantly share code, notes, and snippets.

@raunakdoesdev
Created November 10, 2024 05:34
Show Gist options
  • Save raunakdoesdev/497bc874137a66cdefb20d6a8c3a10d0 to your computer and use it in GitHub Desktop.
Save raunakdoesdev/497bc874137a66cdefb20d6a8c3a10d0 to your computer and use it in GitHub Desktop.
Force claude to output JSON by pre-filling the response with ```json
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
temperature=0,
system="Always respond in JSON.",
messages=[
{"role": "user", "content": [{"type": "text", "text": "Please write a poem."}]},
{"role": "assistant", "content": [{"type": "text", "text": "```json"}]},
],
stop_sequences=["```"],
)
assert message.content[0].type == "text"
print(message.content[0].text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment