Created
November 10, 2024 05:34
-
-
Save raunakdoesdev/497bc874137a66cdefb20d6a8c3a10d0 to your computer and use it in GitHub Desktop.
Force claude to output JSON by pre-filling the response with ```json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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