Перевірити рівеньКурсиПрограмиДля командТарифи
RUУвійтиРеєстрація
Перевірити рівеньКурсиПрограмиДля командТарифиТест із ClaudeПромптиБлогПитання та відповідіПошукРеєстраціяRU
AcademlКурсиAPI Fundamentals: Based on Anthropic MaterialsMessages API: Format, Response Object, and Chatbot
Відповідь надходить частинами: кожен рядок довший на одне словоТермінал Claude Code: команда claude -p з дозволеними Read та EditПовторні запити після помилки 429: пауза щоразу вдвічі довша, потім успіх
Курс

API Fundamentals: Based on Anthropic Materials

Модуль 1 · Getting Started with Claude SDK
01First Steps: Installation and Your First Request
Модуль 2 · Messages API Format
02Messages API: Format, Response Object, and Chatbot
Модуль 3 · Claude Models
03Choosing a Model: Speed, Capabilities, Cost
Модуль 4 · Generation Parameters
04max_tokens, stop_sequences, system prompt, and effort
Модуль 5 · Streaming
05Streaming: Real-Time Responses
Модуль 6 · Vision: Working with Images
06Vision: Images in Claude Prompts
API Fundamentals: Based on Anthropic Materials · Урок 2

Messages API: Format, Response Object, and Chatbot

The messages structure with role and content, the Message object (id, stop_reason, usage), reading text from response blocks, response format via structured outputs instead of prefill, few-shot prompting, mid-conversation system messages, and a simple chatbot.

ENМатеріали курсів поки англійською. Інтерфейс, ШІ-наставник і перевірка завдань — українською.

20 хв читанняОновлено 09.11.20263 питання у квізіГотовий промпт включено

Messages Structure

Each message is a dictionary with two keys: role and content.

from anthropic import Anthropic

client = Anthropic()

def text_of(response):
    return "".join(b.text for b in response.content if b.type == "text")

messages = [
    {"role": "user", "content": "What flavors are used in Dr. Pepper?"}
]

response = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=2000,
    messages=messages
)
print(text_of(response))

The response comes back as a list of content blocks. Current Claude models use adaptive thinking, so a thinking block may come before the text. The text_of helper joins the blocks whose type == "text", and every example below uses it. Code like response.content[0].text breaks on such a response.

Rules:

  • The list starts with a user message, then roles alternate (user → assistant → user...).
  • The model is trained on alternating turns. If you send several messages of the same role in a row, the API accepts them and merges them into a single turn.
  • The last message should be from the user (or a system-role message, covered below). A trailing assistant message is a prefill, and current models (Claude 4.6 and later) reject it with a 400 error.

Далі урок відкривається після безкоштовної реєстрації

Реєстрація через email або Google відкриває перші два уроки кожного курсу назавжди і 7 днів повного доступу до всього каталогу. Картка не потрібна.

Зареєструватися безкоштовноАбо пробний урок без реєстрації →
У цьому уроці
Messages StructureThe Message Response ObjectControlling the Response FormatFew-Shot Prompting Through Message HistorySystem Messages Mid-ConversationSimple ChatbotПрактикаГотовий промптКвіз
КурсиКурси з LLMДля командТарифиПитання та відповідіБлогПро насКонфіденційність
© 2026 AcademlРозробка та просування сайтів —MMIX — Marketing Mix
Почати безкоштовно