Messages API: Format, Response Object, and Chatbot
The messages structure with role and content, the Message object (id, stop_reason, usage), prefilling Claude's response with an assistant message, few-shot prompting, and building a simple chatbot.
Write a translate(word, language) function that uses Claude to translate a word and returns only the translated word without preamble. Use few-shot examples with 2-3 pairs in messages.
Copy and adapt to your context. Text in angle brackets should be replaced.
from anthropic import Anthropic
client = Anthropic()
conversation = []
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
break
conversation.append({"role": "user", "content": user_input})
response = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=500,
messages=conversation
)
reply = response.content[0].text
print(f"Claude: {reply}")
conversation.append({"role": "assistant", "content": reply})- Starting messages with an assistant message — the API will return an error.
- Placing two assistant messages in a row without a user message between them — violates the alternation rule.