Loading...
  • Разработка
  • Администрирование
  • Модели и цены
  • Клиентские SDK
  • Справочник API
Search...
⌘K
Log in
Использование Messages API
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
Разработка/Разработка с Claude

Использование Messages API

Практические паттерны и примеры эффективного использования Messages API

Anthropic offers two ways to build with Claude, each suited to different use cases:

Messages APIClaude Managed Agents
What it isDirect model prompting accessPre-built, configurable agent harness that runs in managed infrastructure
Best forCustom agent loops and fine-grained controlLong-running tasks and asynchronous work
Learn moreMessages API docsClaude Managed Agents docs

Это руководство охватывает распространённые паттерны работы с Messages API, включая базовые запросы, многоходовые диалоги, техники предзаполнения и возможности работы с изображениями. Полные спецификации API см. в справочнике Messages API.

This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.

Базовый запрос и ответ

message = anthropic.Anthropic().messages.create(
    model="claude-opus-4-7",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message)
Output
{
  "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hello!"
    }
  ],
  "model": "claude-opus-4-7",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 12,
    "output_tokens": 6
  }
}

Несколько ходов диалога

Messages API не сохраняет состояние, что означает, что вы всегда отправляете полную историю диалога в API. Вы можете использовать этот паттерн для построения диалога со временем. Более ранние ходы диалога не обязательно должны исходить от Claude. Вы можете использовать синтетические сообщения assistant.

message = anthropic.Anthropic().messages.create(
    model="claude-opus-4-7",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Hello, Claude"},
        {"role": "assistant", "content": "Hello!"},
        {"role": "user", "content": "Can you describe LLMs to me?"},
    ],
)
print(message)
Output
{
  "id": "msg_018gCsTGsXkYJVqYPxTgDHBU",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Sure, I'd be happy to provide..."
    }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 30,
    "output_tokens": 309
  }
}

Вкладываем слова в уста Claude

Вы можете предзаполнить часть ответа Claude в последней позиции списка входных сообщений. Это можно использовать для формирования ответа Claude. В примере ниже используется "max_tokens": 1 для получения одного ответа с множественным выбором от Claude.

message = anthropic.Anthropic().messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1,
    messages=[
        {
            "role": "user",
            "content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",
        },
        {"role": "assistant", "content": "The answer is ("},
    ],
)
print(message)
Output
{
  "id": "msg_01Q8Faay6S7QPTvEUUQARt7h",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "C"
    }
  ],
  "model": "claude-sonnet-4-5",
  "stop_reason": "max_tokens",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 42,
    "output_tokens": 1
  }
}

Предзаполнение не поддерживается на Claude Mythos Preview, Claude Opus 4.7, Claude Opus 4.6 и Claude Sonnet 4.6. Запросы с использованием предзаполнения с этими моделями возвращают ошибку 400. Используйте вместо этого структурированные выходы или инструкции в системном приглашении. См. руководство по миграции для паттернов миграции.

Зрение

Claude может читать как текст, так и изображения в запросах. Изображения можно предоставлять, используя типы источников base64, url или file. Тип источника file ссылается на изображение, загруженное через Files API. Поддерживаемые типы медиа: image/jpeg, image/png, image/gif и image/webp. Дополнительные сведения см. в руководстве по зрению.

import base64
import httpx

# Option 1: Base64-encoded image
image_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx.get(image_url).content).decode("utf-8")

message = anthropic.Anthropic().messages.create(
    model="claude-opus-4-7",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": image_media_type,
                        "data": image_data,
                    },
                },
                {"type": "text", "text": "What is in the above image?"},
            ],
        }
    ],
)
print(message)

# Option 2: URL-referenced image
message_from_url = anthropic.Anthropic().messages.create(
    model="claude-opus-4-7",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "url",
                        "url": "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg",
                    },
                },
                {"type": "text", "text": "What is in the above image?"},
            ],
        }
    ],
)
print(message_from_url)
Output
{
  "id": "msg_01EcyWo6m4hyW8KHs2y2pei5",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "This image shows an ant, specifically a close-up view of an ant. The ant is shown in detail, with its distinct head, antennae, and legs clearly visible. The image is focused on capturing the intricate details and features of the ant, likely taken with a macro lens to get an extreme close-up perspective."
    }
  ],
  "model": "claude-opus-4-7",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 1551,
    "output_tokens": 71
  }
}

Использование инструментов и компьютерное использование

Примеры использования инструментов с Messages API см. в руководстве по использованию инструментов. Примеры управления окружением рабочего стола см. в руководстве по компьютерному использованию. Для гарантированного вывода JSON см. Структурированные выходные данные.

Was this page helpful?

  • Базовый запрос и ответ
  • Несколько ходов диалога
  • Вкладываем слова в уста Claude
  • Зрение
  • Использование инструментов и компьютерное использование