Skip to content

guanyang/open-agent-hub / skills/claude-api

claude-api

Unverified

Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).

FileKindSize
LICENSE.txtmarkdown11.1 KB
SKILL.mdskill md102.7 KB
csharp/claude-api.mdmarkdown15.3 KB
csharp/claude-api/README.mdmarkdown18.5 KB
csharp/claude-api/batches.mdmarkdown413 B
csharp/claude-api/files-api.mdmarkdown900 B
csharp/claude-api/streaming.mdmarkdown787 B
csharp/claude-api/tool-use.mdmarkdown7.4 KB
curl/examples.mdmarkdown9.5 KB
curl/managed-agents.mdmarkdown10.5 KB
go/claude-api.mdmarkdown14.4 KB
go/claude-api/README.mdmarkdown8.3 KB
go/claude-api/files-api.mdmarkdown936 B
go/claude-api/streaming.mdmarkdown1.0 KB
go/claude-api/tool-use.mdmarkdown9.8 KB
go/managed-agents/README.mdmarkdown21.9 KB
java/claude-api.mdmarkdown15.5 KB
java/claude-api/README.mdmarkdown11.7 KB
java/claude-api/files-api.mdmarkdown1.2 KB
java/claude-api/streaming.mdmarkdown655 B
java/claude-api/tool-use.mdmarkdown10.9 KB
java/managed-agents/README.mdmarkdown20.0 KB
php/claude-api.mdmarkdown11.5 KB
php/claude-api/README.mdmarkdown6.4 KB
php/claude-api/batches.mdmarkdown447 B
php/claude-api/files-api.mdmarkdown476 B
php/claude-api/streaming.mdmarkdown682 B
php/claude-api/tool-use.mdmarkdown9.5 KB
php/managed-agents/README.mdmarkdown16.2 KB
python/agent-sdk/README.mdmarkdown12.4 KB
python/agent-sdk/patterns.mdmarkdown9.0 KB
python/claude-api/README.mdmarkdown20.1 KB
python/claude-api/batches.mdmarkdown5.6 KB
python/claude-api/files-api.mdmarkdown4.4 KB
python/claude-api/sdk-upgrade.mdmarkdown28.1 KB
python/claude-api/streaming.mdmarkdown11.7 KB
python/claude-api/tool-use.mdmarkdown20.9 KB
python/managed-agents/README.mdmarkdown14.5 KB
ruby/claude-api.mdmarkdown3.4 KB
ruby/claude-api/README.mdmarkdown4.7 KB
ruby/claude-api/streaming.mdmarkdown235 B
ruby/claude-api/tool-use.mdmarkdown2.6 KB
ruby/managed-agents/README.mdmarkdown11.9 KB
shared/admin-api.mdmarkdown11.3 KB
shared/agent-design.mdmarkdown8.5 KB
shared/anthropic-cli.mdmarkdown23.4 KB
shared/claude-platform-on-aws.mdmarkdown4.3 KB
shared/cost-optimization.mdmarkdown57.1 KB
shared/error-codes.mdmarkdown20.3 KB
shared/evals/build-eval.mdmarkdown53.5 KB
shared/evals/cost-hillclimb.mdmarkdown31.0 KB
shared/evals/eval-audit.mdmarkdown27.2 KB
shared/evals/eval-hillclimb.mdmarkdown67.5 KB
shared/evals/report/SCHEMA.mdmarkdown15.7 KB
shared/evals/report/build-report-lite.mjsscript26.7 KB
shared/evals/report/runner-scaffold.mjsscript32.4 KB
shared/live-sources.mdmarkdown17.3 KB
shared/managed-agents-api-reference.mdmarkdown34.5 KB
shared/managed-agents-client-patterns.mdmarkdown11.8 KB
shared/managed-agents-core.mdmarkdown32.7 KB
shared/managed-agents-environments.mdmarkdown13.9 KB
shared/managed-agents-events.mdmarkdown25.4 KB
shared/managed-agents-memory.mdmarkdown11.1 KB
shared/managed-agents-multiagent.mdmarkdown65.1 KB
shared/managed-agents-onboarding-from-quickstart.mdmarkdown19.3 KB
shared/managed-agents-onboarding-from-url.mdmarkdown31.9 KB
shared/managed-agents-onboarding.mdmarkdown16.4 KB
shared/managed-agents-outcomes.mdmarkdown8.8 KB
shared/managed-agents-overview.mdmarkdown14.2 KB
shared/managed-agents-quickstarts/bug-hunter.mdmarkdown7.9 KB
shared/managed-agents-quickstarts/contract-tracker.mdmarkdown1.8 KB
shared/managed-agents-quickstarts/data-analyst.mdmarkdown1.5 KB
shared/managed-agents-quickstarts/deep-researcher.mdmarkdown2.4 KB
shared/managed-agents-quickstarts/explainer-video-maker.mdmarkdown4.8 KB
shared/managed-agents-quickstarts/field-monitor.mdmarkdown2.1 KB
shared/managed-agents-quickstarts/incident-commander.mdmarkdown1.7 KB
shared/managed-agents-quickstarts/performance-tuner.mdmarkdown11.1 KB
shared/managed-agents-quickstarts/sprint-retro-facilitator.mdmarkdown2.0 KB
shared/managed-agents-quickstarts/structured-extractor.mdmarkdown1.5 KB
shared/managed-agents-quickstarts/support-agent.mdmarkdown1.4 KB
shared/managed-agents-quickstarts/support-to-eng-escalator.mdmarkdown1.8 KB
shared/managed-agents-quickstarts/watchlist-scanner.mdmarkdown5.5 KB
shared/managed-agents-scheduled-deployments.mdmarkdown9.3 KB
shared/managed-agents-self-hosted-sandboxes.mdmarkdown27.3 KB
shared/managed-agents-tools.mdmarkdown37.0 KB
shared/managed-agents-webhooks.mdmarkdown11.1 KB
shared/model-migration.mdmarkdown338.1 KB
shared/models.mdmarkdown17.1 KB
shared/platform-availability.mdmarkdown7.2 KB
shared/preserved-thinking-migration.mdmarkdown62.5 KB
shared/preserved-thinking-migration/causes.mdmarkdown38.8 KB
shared/preserved-thinking-migration/drop_block_probe.pyscript65.0 KB
shared/preserved-thinking-migration/prefix_diff.pyscript91.8 KB
shared/prompt-audit.mdmarkdown48.2 KB
shared/prompt-caching.mdmarkdown32.3 KB
shared/token-counting.mdmarkdown1.6 KB
shared/tool-use-concepts.mdmarkdown43.3 KB
typescript/agent-sdk/README.mdmarkdown10.6 KB
typescript/agent-sdk/patterns.mdmarkdown4.6 KB
typescript/claude-api/README.mdmarkdown15.5 KB
typescript/claude-api/batches.mdmarkdown2.5 KB
typescript/claude-api/files-api.mdmarkdown2.3 KB
typescript/claude-api/streaming.mdmarkdown9.3 KB
typescript/claude-api/tool-use.mdmarkdown23.7 KB
typescript/managed-agents/README.mdmarkdown13.7 KB

ruby/managed-agents/README.md

View on GitHub
# Managed Agents - Ruby

> **Bindings not shown here:** This README covers the most common managed-agents flows for Ruby. If you need a class, method, namespace, field, or behavior that isn't shown, WebFetch the Ruby SDK repo **or the relevant docs page** from `shared/live-sources.md` rather than guess. Do not extrapolate from cURL shapes or another language's SDK.

> **Agents are persistent - create once, reference by ID.** Store the agent ID returned by `client.beta.agents.create` and pass it to every subsequent `client.beta.sessions.create`; do not call `agents.create` in the request path. **Recommended:** define agents and environments as version-controlled files synced with `ant apply` - see `shared/anthropic-cli.md` (its live-docs URL is in `shared/live-sources.md`). The CLI owns the control plane (create/update); your code owns the data plane (sessions with the stored ID). The examples below show in-code creation for when you must provision programmatically; in production the create call belongs in setup, not in the request path.

## Installation

```bash
gem install anthropic
```

## Client Initialization

```ruby
require "anthropic"

# Default (uses ANTHROPIC_API_KEY env var)
client = Anthropic::Client.new

# Explicit API key
client = Anthropic::Client.new(api_key: "your-api-key")
```

> Warning: **Trailing underscores:** The Ruby SDK uses `system_:` and `send_(` (trailing underscore) to avoid shadowing `Kernel#system` and `Kernel#send`. Use these forms throughout managed-agents code.

---

## Create an Environment

```ruby
environment = client.beta.environments.create(
  name: "my-dev-env",
  config: {
    type: "cloud",
    networking: {type: "limited", allow_package_managers: true, allow_mcp_servers: true}
  }
)
puts "Environment ID: #{environment.id}" # env_...
```

---

## Create an Agent (required first step)

> Warning: **There is no inline agent config.** `model`/`system_`/`tools` live on the agent object, not the session. Always start with `client.beta.agents.create()` - the session takes either `agent: agent.id` or the typed hash form `agent: {type: "agent", id: agent.id, version: agent.version}`.

### Minimal

The examples on this page turn both web tools off. Set `enabled` to true on `web_fetch` / `web_search` only when the job as described needs the web (a general-purpose or open-ended job stays off; tell the user how to switch it on) - see `shared/managed-agents-tools.md` § Agent Toolset. They also set the `auto` permission policy, under which a call can pause for your approval - the event loop under Stream Events answers it. When nobody is watching the run, answer `deny`; never answer `allow` to every paused call.

```ruby
# 1. Create the agent (reusable, versioned)
agent = client.beta.agents.create(
  name: "Coding Assistant",
  model: :"claude-opus-5-5",
  system_: "You are a helpful coding assistant.",
  tools: [
    {
      type: "agent_toolset_20260401",
      default_config: {permission_policy: {type: "auto"}},
      configs: [
        {name: "web_fetch", enabled: false},
        {name: "web_search", enabled: false}
      ]
    }
  ]
)

# 2. Start a session
session = client.beta.sessions.create(
  agent: {type: "agent", id: agent.id, version: agent.version},
  environment_id: environment.id,
  title: "Quickstart session"
)
puts "Session ID: #{session.id}"
puts "Trace: https://platform.claude.com/workspaces/default/sessions/#{session.id}"  # swap 'default' for your workspace ID if the API key is not in the Default workspace
```

### Updating an Agent

Updates create new versions; the agent object is immutable per version.

```ruby
updated_agent = client.beta.agents.update(
  agent.id,
  version: agent.version,
  system_: "You are a helpful coding agent. Always write tests."
)
puts "New version: #{updated_agent.version}"

# List all versions
client.beta.agents.versions.list(agent.id).auto_paging_each do |version|
  puts "Version #{version.version}: #{version.updated_at.iso8601}"
end

# Archive the agent
archived = client.beta.agents.archive(agent.id)
puts "Archived at: #{archived.archived_at.iso8601}"
```

---

## Send a User Message

```ruby
client.beta.sessions.events.send_(
  session.id,
  events: [{
    type: "user.message",
    content: [{type: "text", text: "Review the auth module"}]
  }]
)
```

> Tip: **Stream-first:** Open the stream *before* (or concurrently with) sending the message. The stream only delivers events that occur after it opens - stream-after-send means early events arrive buffered in one batch. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).

---

## Stream Events (SSE)

```ruby
# Open the stream first, then send the user message
stream = client.beta.sessions.events.stream_events(session.id)

client.beta.sessions.events.send_(
  session.id,
  events: [{
    type: "user.message",
    content: [{type: "text", text: "Summarize the repo README"}]
  }]
)

stream.each do |event|
  case event.type
  in :"agent.message"
    event.content.each { |block| print block.text }
  in :"agent.tool_use" | :"agent.mcp_tool_use"
    puts "\n[Using tool: #{event.name}]"
    if event.evaluated_permission == :ask
      # Paused for your decision (always_ask, or auto with no determination)
      client.beta.sessions.events.send_(
        session.id,
        events: [{
          type: "user.tool_confirmation",
          tool_use_id: event.id,
          # you write approve: ask a person or apply your own rule; deny when unattended
          result: approve(event) ? "allow" : "deny"
        }]
      )
    end
  in :"session.status_idle"
    break unless event.stop_reason.type == :requires_action # waiting on you, keep streaming
  in :"session.error"
    puts "\n[Error: #{event.error&.message || "unknown"}]"
    break
  else
    # ignore other event types
  end
end
```

> Note: Event `.type` is a Symbol (compare with `:"agent.message"`, not `"agent.message"`).

### Reconnecting and Tailing

When reconnecting mid-session, list past events first to dedupe, then tail live events. Answer paused calls as in the loop above, including an `ask` in the history that no `user.tool_confirmation` follows.

```ruby
require "set"

stream = client.beta.sessions.events.stream_events(session.id)

# Stream is open and buffering. List history before tailing live.
seen_event_ids = Set.new
client.beta.sessions.events.list(session.id).auto_paging_each { |past| seen_event_ids << past.id }

# Tail live events, skipping anything already seen
stream.each do |event|
  next if seen_event_ids.include?(event.id)
  seen_event_ids << event.id
  case event.type
  in :"agent.message"
    event.content.each { |block| print block.text }
  in :"session.status_idle"
    # requires_action: answer the paused call as under Stream Events, then keep streaming
    break unless event.stop_reason.type == :requires_action
  else
    # ignore other event types
  end
end
```

---

## Provide Custom Tool Result

> Note: The Ruby managed-agents bindings for `user.custom_tool_result` are not yet documented in this skill or in the apps source examples. Refer to `shared/managed-agents-events.md` for the wire format and the `anthropic` Ruby gem repository for the corresponding params.

---

## Poll Events

```ruby
client.beta.sessions.events.list(session.id).auto_paging_each do |event|
  puts "#{event.type}: #{event.id}"
end
```

---

## Upload a File

```ruby
require "pathname"

file = client.beta.files.upload(file: Pathname("data.csv"))
puts "File ID: #{file.id}"

# Mount in a session
session = client.beta.sessions.create(
  agent: agent.id,
  environment_id: environment.id,
  resources: [
    {
      type: "file",
      file_id: file.id,
      mount_path: "/data.csv"
    }
  ]
)
```

### Add and Manage Resources on an Existing Session

```ruby
# Attach an additional file to an open session
resource = client.beta.sessions.resources.add(
  session.id,
  type: "file",
  file_id: file.id
)
puts resource.id # "sesrsc_01ABC..."

# List resources on the session
listed = client.beta.sessions.resources.list(session.id)
listed.data.each { |entry| puts "#{entry.id} #{entry.type}" }

# Detach a resource
client.beta.sessions.resources.delete(resource.id, session_id: session.id)
```

---

## List and Download Session Files

```ruby
files = client.beta.files.list(scope_id: "sesn_abc123", betas: ["managed-agents-2026-04-01"])
content = client.beta.files.download(files.data[0].id)
File.binwrite("output.txt", content.read)
```

---

## Session Management

```ruby
# List environments
environments = client.beta.environments.list

# Retrieve a specific environment
env = client.beta.environments.retrieve(environment.id)

# Archive an environment (read-only, existing sessions continue)
client.beta.environments.archive(environment.id)

# Delete an environment (only if no sessions reference it)
client.beta.environments.delete(environment.id)

# Delete a session
client.beta.sessions.delete(session.id)
```

---

## MCP Server Integration

```ruby
# Agent declares MCP server (no auth here - auth goes in a vault)
agent = client.beta.agents.create(
  name: "GitHub Assistant",
  model: :"claude-opus-5-5",
  mcp_servers: [
    {
      type: "url",
      name: "github",
      url: "https://api.githubcopilot.com/mcp/"
    }
  ],
  tools: [
    {
      type: "agent_toolset_20260401",
      default_config: {permission_policy: {type: "auto"}},
      configs: [
        {name: "web_fetch", enabled: false},
        {name: "web_search", enabled: false}
      ]
    },
    {type: "mcp_toolset", mcp_server_name: "github"}
  ]
)

# Session attaches vault(s) containing credentials for those MCP server URLs
session = client.beta.sessions.create(
  agent: {type: "agent", id: agent.id, version: agent.version},
  environment_id: environment.id,
  vault_ids: [vault.id]
)
```

See `shared/managed-agents-tools.md` §Vaults for creating vaults and adding credentials.

---

## Vaults

```ruby
# Create a vault
vault = client.beta.vaults.create(
  display_name: "Alice",
  metadata: {external_user_id: "usr_abc123"}
)
puts vault.id # "vlt_01ABC..."

# Add an OAuth credential
credential = client.beta.vaults.credentials.create(
  vault.id,
  display_name: "Alice's Slack",
  auth: {
    type: "mcp_oauth",
    mcp_server_url: "https://mcp.slack.com/mcp",
    access_token: "xoxp-...",
    expires_at: "2026-04-15T00:00:00Z",
    refresh: {
      token_endpoint: "https://slack.com/api/oauth.v2.access",
      client_id: "1234567890.0987654321",
      scope: "channels:read chat:write",
      refresh_token: "xoxe-1-...",
      token_endpoint_auth: {
        type: "client_secret_post",
        client_secret: "abc123..."
      }
    }
  }
)

# Rotate the credential (e.g., after a token refresh)
client.beta.vaults.credentials.update(
  credential.id,
  vault_id: vault.id,
  auth: {
    type: "mcp_oauth",
    access_token: "xoxp-new-...",
    expires_at: "2026-05-15T00:00:00Z",
    refresh: {refresh_token: "xoxe-1-new-..."}
  }
)

# Archive a vault
client.beta.vaults.archive(vault.id)
```

---

## GitHub Repository Integration

Mount a GitHub repository as a session resource (a vault holds the GitHub MCP credential):

```ruby
session = client.beta.sessions.create(
  agent: agent.id,
  environment_id: environment.id,
  vault_ids: [vault.id],
  resources: [
    {
      type: "github_repository",
      url: "https://github.com/org/repo",
      mount_path: "/workspace/repo",
      authorization_token: "ghp_your_github_token"
    }
  ]
)
```

Multiple repositories on the same session:

```ruby
resources = [
  {
    type: "github_repository",
    url: "https://github.com/org/frontend",
    mount_path: "/workspace/frontend",
    authorization_token: "ghp_your_github_token"
  },
  {
    type: "github_repository",
    url: "https://github.com/org/backend",
    mount_path: "/workspace/backend",
    authorization_token: "ghp_your_github_token"
  }
]
```

Rotating a repository's authorization token:

```ruby
listed = client.beta.sessions.resources.list(session.id)
repo_resource_id = listed.data.first.id

client.beta.sessions.resources.update(
  repo_resource_id,
  session_id: session.id,
  authorization_token: "ghp_your_new_github_token"
)
```
rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).Stars: 198kUpdated Claude CodeCodexUnverifiedInstall
doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.Stars: 198kUpdated Claude CodeCodexVerifiedInstall