> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokenlab.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# 메시지 생성

> Anthropic Messages API 형식을 사용하여 메시지를 생성합니다

## 개요

이 엔드포인트는 Anthropic Messages API와의 네이티브 호환성을 제공합니다. extended thinking과 같은 기능이 있는 Claude 모델에 이것을 사용하세요.

이 엔드포인트는 Anthropic 네이티브 계약을 유지합니다. `messages`는 `user` / `assistant` 메시지 배열이어야 하며, `system`은 최상위 `system` 필드에 두어야 하고 `max_tokens`는 필수입니다. payload가 `messages` 안에서 OpenAI 역할인 `system`, `developer`, `tool`을 사용한다면 `/v1/chat/completions`로 보내세요.

<Note>
  Anthropic SDK의 Base URL: `https://api.tokenlab.sh` (`/v1` 접미사 없음)
</Note>

## 요청 헤더

<ParamField header="x-api-key" type="string" required>
  TokenLab API 키입니다. Bearer token의 대안입니다.
</ParamField>

<ParamField header="anthropic-version" type="string" required>
  Anthropic API 버전입니다. `2023-06-01`을 사용하세요.
</ParamField>

## 요청 본문

<ParamField body="model" type="string" required>
  Claude 모델 ID입니다(예: `claude-sonnet-4-6` 또는 `claude-opus-4-6`).
</ParamField>

<ParamField body="messages" type="array" required>
  `role` 및 `content`를 포함하는 메시지 객체의 배열입니다.
</ParamField>

<ParamField body="max_tokens" type="integer" required>
  생성할 최대 token 수입니다.
</ParamField>

<ParamField body="system" type="string">
  System prompt입니다(messages 배열과 별도).
</ParamField>

<ParamField body="temperature" type="number" default="1">
  Sampling temperature입니다(0-1).
</ParamField>

<ParamField body="stream" type="boolean" default="false">
  스트리밍 응답을 활성화합니다.
</ParamField>

<ParamField body="thinking" type="object">
  Extended thinking 구성입니다(Claude Opus 4.5).

  * `type` (string): 활성화하려면 `"enabled"`
  * `budget_tokens` (integer): thinking을 위한 token 예산
</ParamField>

<ParamField body="tools" type="array">
  모델에서 사용할 수 있는 도구입니다.
</ParamField>

<ParamField body="tool_choice" type="object">
  모델이 도구를 사용하는 방식입니다. 옵션: `auto`, `any`, `tool`(특정 도구).
</ParamField>

<ParamField body="top_p" type="number">
  Nucleus sampling 파라미터입니다. temperature 또는 top\_p 중 하나만 사용하고, 둘 다 사용하지 마세요.
</ParamField>

<ParamField body="top_k" type="integer">
  각 token에 대해 상위 K개 옵션에서만 샘플링합니다.
</ParamField>

<ParamField body="stop_sequences" type="array">
  모델이 생성을 중지하게 하는 사용자 지정 stop sequence입니다.
</ParamField>

<ParamField body="metadata" type="object">
  추적 목적으로 요청에 첨부할 metadata입니다.
</ParamField>

## 응답

<ResponseField name="id" type="string">
  고유한 메시지 식별자입니다.
</ResponseField>

<ResponseField name="type" type="string">
  항상 `message`입니다.
</ResponseField>

<ResponseField name="role" type="string">
  항상 `assistant`입니다.
</ResponseField>

<ResponseField name="content" type="array">
  content block의 배열입니다(text, thinking, tool\_use).
</ResponseField>

<ResponseField name="model" type="string">
  사용된 모델입니다.
</ResponseField>

<ResponseField name="stop_reason" type="string">
  생성이 중지된 이유입니다(`end_turn`, `max_tokens`, `tool_use`).
</ResponseField>

<ResponseField name="usage" type="object">
  `input_tokens` 및 `output_tokens`를 포함한 token 사용량입니다.
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.tokenlab.sh/v1/messages" \
    -H "x-api-key: sk-your-api-key" \
    -H "anthropic-version: 2023-06-01" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "claude-sonnet-4-6",
      "max_tokens": 1024,
      "system": "You are a helpful assistant.",
      "messages": [
        {"role": "user", "content": "Hello, Claude!"}
      ]
    }'
  ```

  ```python Python theme={null}
  from anthropic import Anthropic

  client = Anthropic(
      api_key="sk-your-api-key",
      base_url="https://api.tokenlab.sh"
  )

  message = client.messages.create(
      model="claude-sonnet-4-6",
      max_tokens=1024,
      system="You are a helpful assistant.",
      messages=[
          {"role": "user", "content": "Hello, Claude!"}
      ]
  )

  print(message.content[0].text)
  ```

  ```javascript JavaScript theme={null}
  import Anthropic from '@anthropic-ai/sdk';

  const client = new Anthropic({
    apiKey: 'sk-your-api-key',
    baseURL: 'https://api.tokenlab.sh'
  });

  const message = await client.messages.create({
    model: 'claude-sonnet-4-6',
    max_tokens: 1024,
    system: 'You are a helpful assistant.',
    messages: [
      { role: 'user', content: 'Hello, Claude!' }
    ]
  });

  console.log(message.content[0].text);
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "io"
      "net/http"
  )

  func main() {
      payload := map[string]interface{}{
          "model":      "claude-sonnet-4-6",
          "max_tokens": 1024,
          "system":     "You are a helpful assistant.",
          "messages": []map[string]string{
              {"role": "user", "content": "Hello, Claude!"},
          },
      }

      jsonData, _ := json.Marshal(payload)
      req, _ := http.NewRequest("POST", "https://api.tokenlab.sh/v1/messages", bytes.NewBuffer(jsonData))
      req.Header.Set("x-api-key", "sk-your-api-key")
      req.Header.Set("anthropic-version", "2023-06-01")
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, _ := client.Do(req)
      defer resp.Body.Close()

      body, _ := io.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```

  ```php PHP theme={null}
  <?php
  $payload = [
      'model' => 'claude-sonnet-4-6',
      'max_tokens' => 1024,
      'system' => 'You are a helpful assistant.',
      'messages' => [
          ['role' => 'user', 'content' => 'Hello, Claude!']
      ]
  ];

  $ch = curl_init('https://api.tokenlab.sh/v1/messages');

  curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_HTTPHEADER => [
          'x-api-key: sk-your-api-key',
          'anthropic-version: 2023-06-01',
          'Content-Type: application/json'
      ],
      CURLOPT_POSTFIELDS => json_encode($payload)
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  $data = json_decode($response, true);
  echo $data['content'][0]['text'];
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "id": "msg_abc123",
    "type": "message",
    "role": "assistant",
    "content": [
      {
        "type": "text",
        "text": "Hello! How can I help you today?"
      }
    ],
    "model": "claude-sonnet-4-6",
    "stop_reason": "end_turn",
    "usage": {
      "input_tokens": 15,
      "output_tokens": 10
    }
  }
  ```
</ResponseExample>

## 비전 입력 예시

비전 지원이 있는 Claude 모델의 경우, 이미지를 구조화된 이미지 블록으로 `messages[].content` 안에 넣으세요.

```json theme={null}
{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Please describe this image."
        },
        {
          "type": "image",
          "source": {
            "type": "url",
            "url": "https://example.com/demo.jpg"
          }
        }
      ]
    }
  ]
}
```

```json theme={null}
{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Please describe this image."
        },
        {
          "type": "image",
          "source": {
            "type": "base64",
            "media_type": "image/jpeg",
            "data": "/9j/4AAQSkZJRgABAQ..."
          }
        }
      ]
    }
  ]
}
```

## Extended Thinking 예시

```python theme={null}
message = client.messages.create(
    model="claude-opus-4-6",
    max_tokens=16000,
    thinking={
        "type": "enabled",
        "budget_tokens": 10000
    },
    messages=[{"role": "user", "content": "Solve this math problem..."}]
)

for block in message.content:
    if block.type == "thinking":
        print(f"Thinking: {block.thinking}")
    elif block.type == "text":
        print(f"Response: {block.text}")
```

## Anthropic Message Batches

TokenLab는 `/v1/messages` 와 함께 Anthropic Message Batches 네이티브 흐름도 제공합니다.

사용 가능한 라우트:

* `POST /v1/messages/batches`
* `GET /v1/messages/batches`
* `GET /v1/messages/batches/:message_batch_id`
* `GET /v1/messages/batches/:message_batch_id/results`
* `POST /v1/messages/batches/:message_batch_id/cancel`
* `DELETE /v1/messages/batches/:message_batch_id`

운영 메모:

* 동일한 TokenLab API key 와 Anthropic 네이티브 헤더를 사용하세요.
* batch item 이 `file_id` 를 참조하는 경우 `anthropic-beta: files-api-2025-04-14` 도 함께 포함하세요.
* Batch job 은 Anthropic 네이티브 요청/응답 형태를 유지하면서, TokenLab 가 내부 정산 수명주기를 추적합니다.
