Messages Structure
Each message is a dictionary with two keys:
messages = [
{"role": "user", "content": "What flavors are used in Dr. Pepper?"}
]
response = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=1000,
messages=messages
)
print(response.content[0].text)
Rules: The list starts with a user message; roles must alternate (user → assistant → user...).
The Message Response Object
# Message(id='msg_01...', content=[TextBlock(text='...', type='text')],
# model='claude-3-haiku-20240307', role='assistant',
# stop_reason='end_turn', usage=Usage(input_tokens=19, output_tokens=8))
print(response.content[0].text) # response text
print(response.stop_reason) # 'end_turn' or 'max_tokens'
print(response.usage.input_tokens, response.usage.output_tokens)
Prefilling Claude's Response
response = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=500,
messages=[
{"role": "user", "content": "Generate a beautiful haiku"},
{"role": "assistant", "content": "calming mountain air"} # Claude will continue from here
]
)
print("calming mountain air" + response.content[0].text)
Few-Shot Prompting Through Message History
response = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=500,
messages=[
{"role": "user", "content": "Unpopular opinion: Pickles are disgusting."},
{"role": "assistant", "content": "NEGATIVE"},
{"role": "user", "content": "I love spicy pickles from @PickleCo!"},
{"role": "assistant", "content": "POSITIVE"},
{"role": "user", "content": "Seriously why would anyone eat a pickle?"},
]
)
# Claude will respond "NEGATIVE" — it understood the pattern from examples
Simple Chatbot
conversation_history = []
while True:
user_input = input("User: ")
if user_input.lower() == "quit":
break
conversation_history.append({"role": "user", "content": user_input})
response = client.messages.create(
model="claude-3-haiku-20240307",
messages=conversation_history,
max_tokens=500
)
assistant_response = response.content[0].text
print(f"Assistant: {assistant_response}")
conversation_history.append({"role": "assistant", "content": assistant_response})