---
title: Ruby SDK
url: https://platform.claude.com/docs/ko/cli-sdks-libraries/sdks/ruby
description: Sorbet 타입, 스트리밍 헬퍼, 커넥션 풀링을 갖춘 Anthropic Ruby SDK를 설치하고 구성합니다
---

Anthropic Ruby 라이브러리는 Ruby 3.2.0 이상의 모든 애플리케이션에서 Claude API에 편리하게 접근할 수 있도록 해 줍니다. YARD, RBS, RBI 형식의 포괄적인 타입과 docstring이 함께 제공됩니다. HTTP 전송 계층으로는 표준 라이브러리의 `net/http`를 사용하며, `connection_pool` gem을 통해 "connection pooling"(커넥션 풀링)을 지원합니다.

<Info>
  코드 예제가 포함된 API 기능 문서는 [API 레퍼런스](https://platform.claude.com/docs/ko/api/overview)를 참조하세요. 이 페이지는 Ruby 전용 SDK 기능과 구성을 다룹니다.
</Info>

## 설치

Bundler를 사용하여 애플리케이션의 `Gemfile`에 gem을 추가하세요:

```bash
bundle add anthropic
```

## 요구 사항

Ruby 3.2.0 이상.

## 사용법

```ruby
anthropic = Anthropic::Client.new(
  api_key: ENV["ANTHROPIC_API_KEY"] # This is the default and can be omitted
)

message = anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5"
)

message.content.each do |block|
  puts block.text if block.type == :text
end
```

Workload Identity Federation을 포함한 인증 옵션에 대해서는 [인증](https://platform.claude.com/docs/ko/manage-claude/authentication)을 참조하세요. API 키가 여러 워크스페이스에 액세스할 수 있는 [개인 또는 서비스 계정 키](https://platform.claude.com/docs/ko/manage-claude/authentication#key-types)인 경우, `anthropic-workspace-id` 요청 헤더에 워크스페이스 ID를 설정하세요. [워크스페이스 선택](https://platform.claude.com/docs/ko/manage-claude/authentication#select-a-workspace)에서 이 SDK에 대한 요청별 옵션을 확인할 수 있습니다.

## 스트리밍

SDK는 Server-Sent Events(SSE)를 사용한 "streaming"(스트리밍) 응답을 지원합니다.

```ruby
anthropic = Anthropic::Client.new
stream = anthropic.messages.stream(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5"
)

stream.each do |message|
  puts(message.type)
end
```

### 스트리밍 헬퍼

이 라이브러리는 메시지 스트리밍을 위한 여러 편의 기능을 제공합니다. 예를 들면 다음과 같습니다:

```ruby
anthropic = Anthropic::Client.new
stream = anthropic.messages.stream(
  max_tokens: 1024,
  messages: [{role: :user, content: "Say hello there!"}],
  model: :"claude-opus-5-5"
)

stream.text.each do |text|
  print(text)
end
```

`anthropic.messages.stream(...)`을 사용한 스트리밍은 누적(accumulation) 및 SDK 전용 이벤트를 포함한 다양한 헬퍼를 제공합니다.

## 입력 스키마와 도구 호출

SDK는 도구를 위한 구조화된 데이터 클래스를 정의하고 Claude가 이를 자동으로 실행하도록 하는 헬퍼 메커니즘을 제공합니다. 도구 러너를 포함한 "tool use"(도구 사용) 패턴에 대한 자세한 문서는 [도구 러너 (SDK)](https://platform.claude.com/docs/ko/agents-and-tools/tool-use/tool-runner)를 참조하세요.

```ruby
anthropic = Anthropic::Client.new
class CalculatorInput < Anthropic::BaseModel
  required :lhs, Float
  required :rhs, Float
  required :operator, Anthropic::InputSchema::EnumOf[:+, :-, :*, :/]
end

class Calculator < Anthropic::BaseTool
  input_schema CalculatorInput

  def call(expr)
    expr.lhs.public_send(expr.operator, expr.rhs)
  end
end

# 도구 실행 루프를 자동으로 처리합니다
anthropic.beta.messages.tool_runner(
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [{role: "user", content: "What's 15 * 7?"}],
  tools: [Calculator.new]
).each_message { |message| puts message.content }
```

## 구조화된 출력

Ruby 예제를 포함한 전체 구조화된 출력 문서는 [구조화된 출력](https://platform.claude.com/docs/ko/build-with-claude/structured-outputs)을 참조하세요.

## 오류 처리

라이브러리가 API에 연결할 수 없거나 API가 성공이 아닌 상태 코드(즉, 4xx 또는 5xx 응답)를 반환하면 `Anthropic::Errors::APIError`의 하위 클래스가 발생합니다:

```ruby
anthropic = Anthropic::Client.new
begin
  message = anthropic.messages.create(
    max_tokens: 1024,
    messages: [{role: "user", content: "Hello, Claude"}],
    model: :"claude-opus-5-5"
  )
rescue Anthropic::Errors::APIConnectionError => e
  puts("The server could not be reached")
  puts(e.cause)  # an underlying Exception, likely raised within `net/http`
rescue Anthropic::Errors::RateLimitError => e
  puts("A 429 status code was received; we should back off a bit.")
rescue Anthropic::Errors::APIStatusError => e
  puts("Another non-200-range status code was received")
  puts(e.status)
end
```

오류 코드는 다음과 같습니다:

| 원인          | 오류 타입                      |
| ----------- | -------------------------- |
| HTTP 400    | `BadRequestError`          |
| HTTP 401    | `AuthenticationError`      |
| HTTP 403    | `PermissionDeniedError`    |
| HTTP 404    | `NotFoundError`            |
| HTTP 409    | `ConflictError`            |
| HTTP 422    | `UnprocessableEntityError` |
| HTTP 429    | `RateLimitError`           |
| HTTP >= 500 | `InternalServerError`      |
| 기타 HTTP 오류  | `APIStatusError`           |
| 타임아웃        | `APITimeoutError`          |
| 네트워크 오류     | `APIConnectionError`       |

## 재시도

특정 오류는 기본적으로 짧은 지수 백오프와 함께 2회 자동으로 재시도됩니다.

연결 오류(예: 네트워크 연결 문제로 인한 오류), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 내부 오류, 그리고 타임아웃은 모두 기본적으로 재시도됩니다.

`max_retries` 옵션을 사용하여 이를 구성하거나 비활성화할 수 있습니다:

```ruby
# 모든 요청의 기본값을 구성합니다:
anthropic = Anthropic::Client.new(
  max_retries: 0 # default is 2
)

# 또는 요청별로 구성합니다:
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5",
  request_options: {max_retries: 5}
)
```

## 타임아웃

기본적으로 요청은 10분 후에 타임아웃됩니다. `timeout` 옵션을 사용하여 이를 구성할 수 있습니다:

```ruby
# 모든 요청의 기본값을 구성합니다:
anthropic = Anthropic::Client.new(
  timeout: 20 # 20 seconds (default is 10 minutes)
)

# 또는 요청별로 구성합니다:
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5",
  request_options: {timeout: 5}
)
```

타임아웃 시 `Anthropic::Errors::APITimeoutError`가 발생합니다.

타임아웃된 요청은 기본적으로 재시도된다는 점에 유의하세요.

## 페이지네이션

Claude API의 목록 메서드는 페이지네이션됩니다.

이 라이브러리는 각 목록 응답과 함께 자동 페이지네이션 이터레이터를 제공하므로, 후속 페이지를 수동으로 요청할 필요가 없습니다:

```ruby
anthropic = Anthropic::Client.new
page = anthropic.messages.batches.list(limit: 20)

# 페이지에서 단일 항목을 가져옵니다.
batch = page.data[0]
puts(batch.id)

# 필요에 따라 추가 페이지를 자동으로 가져옵니다.
page.auto_paging_each do |batch|
  puts(batch.id)
end
```

또는 `#next_page?` 및 `#next_page` 메서드를 사용하여 페이지를 보다 세밀하게 제어할 수 있습니다.

```ruby
anthropic = Anthropic::Client.new
page = anthropic.messages.batches.list(limit: 20)
loop do
  page.data&.each { |batch| puts(batch.id) }
  break unless page.next_page?
  page = page.next_page
end
```

## 파일 업로드

파일 업로드에 해당하는 요청 매개변수는 원시 콘텐츠, [`Pathname`](https://rubyapi.org/3.2/o/pathname) 인스턴스, [`StringIO`](https://rubyapi.org/3.2/o/stringio) 등으로 전달할 수 있습니다.

```ruby
anthropic = Anthropic::Client.new
require "pathname"

# `Pathname`을 사용하여 파일 이름을 전송하거나 큰 파일을 메모리에 페이징하지 않도록 합니다:
file_metadata = anthropic.files.upload(file: Pathname("/path/to/file"))

# 또는 파일 내용이나 `StringIO`를 직접 전달합니다:
file_metadata = anthropic.files.upload(file: File.read("/path/to/file"))

# 또는 파일 이름 및/또는 콘텐츠 유형을 제어하려면:
file = Anthropic::FilePart.new(File.read("/path/to/file"), filename: "/path/to/file", content_type: "...")
file_metadata = anthropic.files.upload(file: file)

puts(file_metadata.id)
```

원시 `IO` 디스크립터를 전달할 수도 있지만, 이 경우 라이브러리가 해당 디스크립터가 파일인지 (되감을 수 없는) 파이프인지 확신할 수 없으므로 재시도가 비활성화된다는 점에 유의하세요.

## Sorbet

이 라이브러리는 포괄적인 [RBI](https://sorbet.org/docs/rbi) 정의를 제공하며, sorbet-runtime에 대한 의존성이 없습니다.

다음과 같이 타입 안전한 요청 매개변수를 제공할 수 있습니다:

```ruby
anthropic = Anthropic::Client.new
anthropic.messages.create(
  max_tokens: 1024,
  messages: [Anthropic::MessageParam.new(role: "user", content: "Hello, Claude")],
  model: :"claude-opus-5-5"
)
```

또는 동일하게 다음과 같이 할 수 있습니다:

```ruby
anthropic = Anthropic::Client.new
# 해시도 사용할 수 있지만 타입 안전하지 않습니다:
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5"
)

# 전체 Params 클래스를 splat할 수도 있습니다:
params = Anthropic::MessageCreateParams.new(
  max_tokens: 1024,
  messages: [Anthropic::MessageParam.new(role: "user", content: "Hello, Claude")],
  model: :"claude-opus-5-5"
)
anthropic.messages.create(**params)
```

### Enum

이 라이브러리는 `sorbet-runtime`에 의존하지 않으므로 [`T::Enum`](https://sorbet.org/docs/tenum) 인스턴스를 제공할 수 없습니다. 대신 SDK는 런타임에 항상 원시 값인 "tagged symbols"(태그된 심볼)를 제공합니다:

```ruby
# :auto
puts(Anthropic::MessageCreateParams::ServiceTier::AUTO)

# 표시된 타입: `T.all(Anthropic::MessageCreateParams::ServiceTier, Symbol)`
T.reveal_type(Anthropic::MessageCreateParams::ServiceTier::AUTO)
```

Enum 매개변수는 "완화된(relaxed)" 타입을 가지므로, enum 상수 또는 그 리터럴 값을 전달할 수 있습니다:

```ruby
anthropic = Anthropic::Client.new
# enum 상수를 사용하면 태그된 타입 정보가 유지됩니다:
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: Anthropic::Model::CLAUDE_OPUS_5_5,
  service_tier: Anthropic::MessageCreateParams::ServiceTier::AUTO
)

# 리터럴 값도 허용됩니다:
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5",
  service_tier: :auto
)
```

## BaseModel

모든 매개변수 및 응답 객체는 `Anthropic::Internal::Type::BaseModel`을 상속하며, 이는 다음을 포함한 여러 편의 기능을 제공합니다:

1. 알 수 없는 필드를 포함한 모든 필드는 `obj[:prop]` 구문으로 접근할 수 있으며, `obj => {prop: prop}` 또는 패턴 매칭 구문으로 구조 분해할 수 있습니다.

2. 동등성 비교에 구조적 동등성을 사용합니다. 두 API 호출이 동일한 값을 반환하면 ==로 응답을 비교했을 때 true가 반환됩니다.

3. 인스턴스와 클래스 자체 모두 pretty-print할 수 있습니다.

4. `#to_h`, `#deep_to_h`, `#to_json`, `#to_yaml`과 같은 헬퍼를 제공합니다.

## 동시성과 커넥션 풀링

`Anthropic::Client` 인스턴스는 스레드 안전하지만, 진행 중인 HTTP 요청이 없을 때에만 fork 안전합니다.

각 `Anthropic::Client` 인스턴스는 기본 크기가 99인 자체 HTTP 커넥션 풀을 가집니다. 따라서 대부분의 환경에서는 애플리케이션당 클라이언트를 한 번만 생성하는 것을 권장합니다.

풀에서 사용 가능한 모든 커넥션이 체크아웃되면, 요청은 새 커넥션이 사용 가능해질 때까지 대기하며, 대기 시간은 요청 타임아웃에 포함됩니다.

별도로 명시되지 않는 한, SDK의 다른 클래스들은 내부 데이터 구조를 보호하는 락을 가지고 있지 않습니다.

## 커스텀 또는 문서화되지 않은 요청 보내기

### 문서화되지 않은 속성

다음과 같이 모든 엔드포인트에 문서화되지 않은 매개변수를 보내고, 문서화되지 않은 응답 속성을 읽을 수 있습니다:

<Warning>
  동일한 이름의 `extra_` 매개변수는 문서화된 매개변수를 덮어씁니다. 보안상의 이유로, 이러한 메서드는 신뢰할 수 있는 입력 데이터에만 사용하도록 하세요.
</Warning>

```ruby
anthropic = Anthropic::Client.new
value = "example"
message =
  anthropic.messages.create(
    max_tokens: 1024,
    messages: [{role: "user", content: "Hello, Claude"}],
    model: :"claude-opus-5-5",
    request_options: {
      extra_query: {my_query_parameter: value},
      extra_body: {my_body_parameter: value},
      extra_headers: {"my-header": value}
    }
  )

puts(message[:my_undocumented_property])
```

### 문서화되지 않은 요청 매개변수

추가 매개변수를 명시적으로 보내려면, 앞의 예제에서 본 것처럼 요청 시 `request_options:` 매개변수 아래의 `extra_query`, `extra_body`, `extra_headers`를 사용하면 됩니다.

### 문서화되지 않은 엔드포인트

인증, 재시도 등의 이점을 유지하면서 문서화되지 않은 엔드포인트에 요청하려면, 다음과 같이 `anthropic.request`를 사용하여 요청할 수 있습니다:

```ruby
response = anthropic.request(
  method: :post,
  path: '/undocumented/endpoint',
  query: {"dog": "woof"},
  headers: {"useful-header": "interesting-value"},
  body: {"hello": "world"}
)
```

## 플랫폼 통합

<Note>
  코드 예제가 포함된 자세한 플랫폼 설정 가이드는 다음을 참조하세요:

  * [Amazon Bedrock](https://platform.claude.com/docs/ko/build-with-claude/claude-in-amazon-bedrock)
  * [Amazon Bedrock (Opus 4.6 및 이전 버전)](https://platform.claude.com/docs/ko/build-with-claude/claude-on-amazon-bedrock-legacy)
  * [Claude Platform on AWS](https://platform.claude.com/docs/ko/build-with-claude/claude-platform-on-aws)
  * [Google Cloud](https://platform.claude.com/docs/ko/build-with-claude/claude-on-vertex-ai)
</Note>

Ruby SDK는 다음 플랫폼을 지원합니다:

* **Agent Platform:** `Anthropic::VertexClient`. `googleauth` gem이 필요합니다.
* **Bedrock:** `Anthropic::BedrockMantleClient`, 또는 `bedrock-runtime` 경로의 경우 `Anthropic::BedrockClient`. `Anthropic::BedrockMantleClient`는 `aws-sdk-core` gem이 필요하며, `Anthropic::BedrockClient`는 `aws-sdk-bedrockruntime` gem이 필요합니다.
* **Claude Platform on AWS:** 메인 `anthropic` gem의 일부입니다(`aws-sdk-core` gem 필요). `Anthropic::AWSClient`를 제공합니다. 생성자에 `workspace_id:`를 전달하거나 `ANTHROPIC_AWS_WORKSPACE_ID` 환경 변수를 설정하세요([Workspaces](https://platform.claude.com/docs/ko/build-with-claude/claude-platform-on-aws#workspaces) 참조). 베타로 제공됩니다.
* **Foundry:** 현재 Ruby SDK에서는 지원되지 않습니다. 지원되는 SDK는 [Claude in Microsoft Foundry](https://platform.claude.com/docs/ko/build-with-claude/claude-in-microsoft-foundry)를 참조하세요.

새 프로젝트에는 `Anthropic::BedrockMantleClient`를 사용하세요. `Anthropic::BedrockClient`는 Bedrock `InvokeModel` API를 사용하는 기존 애플리케이션을 위해 유지됩니다.

## 시맨틱 버저닝

이 패키지는 [SemVer](https://semver.org/spec/v2.0.0.html) 규칙을 따릅니다.

이 패키지는 (런타임이 아닌) `*.rbi` 및 `*.rbs` 타입 정의의 개선을 호환성을 깨지 않는 변경으로 간주합니다.

## 추가 리소스

* [GitHub 저장소](https://github.com/anthropics/anthropic-sdk-ruby)
* [YARD 문서](https://gemdocs.org/gems/anthropic)
* [API 레퍼런스](https://platform.claude.com/docs/ko/api/overview)
* [메시지 스트리밍](https://platform.claude.com/docs/ko/build-with-claude/streaming)
