### Run the quickstart script
Source: https://platform.claude.com/docs/en/get-started
Executes the Ruby quickstart script to verify the environment setup.
```bash
bundle exec ruby quickstart.rb
```
--------------------------------
### Setup Python environment
Source: https://platform.claude.com/docs/en/get-started
Create a virtual environment and install the Anthropic SDK.
```bash
mkdir claude-quickstart && cd claude-quickstart
python3 -m venv .venv && source .venv/bin/activate
pip install anthropic
```
--------------------------------
### Quick start example with OpenAI SDK
Source: https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/openai-sdk
Initial import statement for the OpenAI SDK.
```python
import OpenAI from
```
--------------------------------
### Implementing a Tool-Using Agent in Go
Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/build-a-tool-using-agent
This example demonstrates the setup of the Tool Runner SDK, including imports and the initialization of tools and the runner.
```go
// Ring 5: The Tool Runner SDK abstraction.
package main
import (
"context"
"fmt"
"log"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/toolrunner"
)
// The input structs define each tool's schema. The tool runner generates
```
--------------------------------
### Initialize Client and Perform Diagnostic Turns
Source: https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics
This example shows the full setup including client initialization, the first turn with diagnostic opt-in, and the second turn referencing the previous message ID.
```python
client = anthropic.Anthropic()
SYSTEM = "You are an AI assistant analyzing a large document. ..."
# Turn 1: opt in with previous_message_id=None
r1 = client.beta.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
cache_control={"type": "ephemeral"},
system=SYSTEM,
messages=[{"role": "user", "content": "Summarize section 1."}],
diagnostics={"previous_message_id": None},
betas=["cache-diagnosis-2026-04-07"],
)
# Turn 2: reference the previous response id
r2 = client.beta.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
cache_control={"type": "ephemeral"},
system=SYSTEM,
messages=[
{"role": "user", "content": "Summarize section 1."},
{"role": "assistant", "content": r1.content},
{"role": "user", "content": "Now summarize section 2."},
],
diagnostics={"previous_message_id": r1.id},
betas=["cache-diagnosis-2026-04-07"],
)
diagnostics = r2.diagnostics
if diagnostics is None:
print("No divergence detected.")
elif diagnostics.cache_miss_reason is None:
print("Comparison still pending.")
else:
print(f"cache_miss_reason: {diagnostics.cache_miss_reason.type}")
```
--------------------------------
### LLM-based Grading and Completion Setup
Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests
Example of structuring test data for sentiment analysis and initializing the Anthropic client for completions.
```typescript
sentiment: "negative"
}, // Edge case: Sarcasm
{
text: "The movie's plot was terrible, but the acting was phenomenal.",
sentiment: "mixed"
} // Edge case: Mixed sentiment
// ... 996 more tweets
];
const client = new Anthropic();
async function getCompletion(prompt: string): Promise {
const message = await client.messages.
```
--------------------------------
### Initialize Client and Test Data
Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests
Setup for the API client and an array of articles used for evaluation.
```php
$client = new Client();
$articles = [
[
'text' => 'In a groundbreaking study, researchers at MIT...',
'summary' => 'MIT scientists discover a new antibiotic...',
],
// Edge case: Multi-topic
[
'text' => 'Jane Doe, a local hero, made headlines last week for saving... In city hall news, the budget...
```
--------------------------------
### Initialize Go project
Source: https://platform.claude.com/docs/en/get-started
Create a module and install the Anthropic SDK.
```bash
mkdir claude-quickstart && cd claude-quickstart
go mod init claude-quickstart
go get github.com/anthropics/anthropic-sdk-go
```
--------------------------------
### Initialize Client in Go
Source: https://platform.claude.com/docs/en/build-with-claude/citations
Example showing the initialization of a client instance in Go.
```go
client :=
```
--------------------------------
### Explicit Dependency Management
Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices
Examples contrasting implicit assumptions about installed packages with explicit instructions for dependency installation.
```text
**Bad example: Assumes installation**:
"Use the pdf library to process the file."
**Good example: Explicit about dependencies**:
"Install required package: `pip install pypdf`"
Then use
```
--------------------------------
### Initializing Client and Test Data
Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests
Setup for the Claude API client and the structure for test queries.
```php
$client = new Client();
$patientQueries = [
['query' => 'What are the side effects of Lisinopril?', 'containsPhi' => false],
```
--------------------------------
### Install SDK and Initialize Project
Source: https://platform.claude.com/docs/en/get-started
Commands to create a project directory and install the necessary dependencies for PHP or Ruby.
```bash
mkdir claude-quickstart && cd claude-quickstart
composer require "anthropic-ai/sdk" "guzzlehttp/guzzle:^7"
```
```bash
mkdir claude-quickstart && cd claude-quickstart
bundle init
bundle add anthropic
```
--------------------------------
### Download File Example
Source: https://platform.claude.com/docs/en/api/go/beta/files/download
Demonstrates how to initialize the client and call the Download method to retrieve file content.
```go
package main
import (
"context"
"fmt"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
func main() {
client := anthropic.NewClient(
option.WithAPIKey("my-anthropic-api-key"),
)
response, err := client.Beta.Files.Download(
context.TODO(),
"file_id",
anthropic.BetaFileDownloadParams{
},
)
if err != nil {
panic(err.Error())
}
fmt.Printf("%+v\n", response)
}
```
--------------------------------
### Override Session Configuration
Source: https://platform.claude.com/docs/en/managed-agents/sessions
Example of starting a session with model and system prompt overrides.
```json
{
"model": "claude-3-5-sonnet-20241022",
"system": ""
}
```
--------------------------------
### Create your code
Source: https://platform.claude.com/docs/en/get-started
Create a file called main.go.
```go
package main
import (
"context"
"fmt"
"log"
"github.com/anthropics/anthropic-sdk-go"
)
func main() {
client := anthropic.NewClient()
message, err :=
```
--------------------------------
### Initialize Anthropic Client and Define Conversation Turns
Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests
Shows the setup of an array of conversation turns and the initialization of the Anthropic client in C#.
```csharp
new("assistant", "I apologize, but I don't recall the exact date of Scout's birthday being mentioned in 'To Kill a Mockingbird'. The novel doesn't focus on such specific details. Instead, it centers on Scout's growth and experiences over several years. Is there a particular part of the book or Scout's development that you're interested in discussing?"),
// Edge case: Another topic shift
new("user", "Oh, right. Well, can you suggest a recipe for a classic Southern cake?"),
],
// ... 98 more conversations
];
var client = new AnthropicClient();
async Task GetCompletion(Turn[] conversation)
{
var message =
```
--------------------------------
### Initialize Go client
Source: https://platform.claude.com/docs/en/get-started
Basic setup for the Go SDK client.
```go
package main
import (
"context"
"fmt"
"log"
"github.com/anthropics/anthropic-sdk-go"
)
func main() {
client := anthropic.NewClient()
```
--------------------------------
### SSE Content Block Start Event
Source: https://platform.claude.com/docs/en/build-with-claude/extended-thinking
Example of the SSE stream event for content_block_start.
```sse
event: content_block_start
data: {"type":"content_block_start","index":0
```
--------------------------------
### Streaming Messages in Python
Source: https://platform.claude.com/docs/en/api/handling-stop-reasons
Example of initializing a client and starting a message stream in Python.
```python
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-opus-4-8"
```
--------------------------------
### Initialize Project
Source: https://platform.claude.com/docs/en/get-started
Create a new directory and install the required SDK dependencies using Composer.
```bash
mkdir claude-quickstart && cd claude-quickstart
composer require "anthropic-ai/sdk" "guzzlehttp/guzzle:^7"
```
--------------------------------
### Evaluate Summaries with Claude API in PHP
Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests
This example demonstrates setting up a test dataset of articles and using the Claude API to generate completions for evaluation.
```php
$client = new Client();
$articles = [
[
'text' => 'In a groundbreaking study, researchers at MIT...',
'summary' => 'MIT scientists discover a new antibiotic...',
],
// Edge case: Multi-topic
[
'text' => 'Jane Doe, a local hero, made headlines last week for saving... In city hall news, the budget... Meteorologists predict...',
'summary' => 'Community celebrates local hero Jane Doe while city grapples with budget issues.',
],
// Edge case: Misleading title
[
'text' => "You won't believe what this celebrity did! ... extensive charity work ...",
'summary' => "Celebrity's extensive charity work surprises fans",
],
// ... 197 more articles
];
function getCompletion(Client $client, string $prompt): string
{
$message = $client->messages->create(
model: Model::CLAUDE_OPUS_4_8,
maxTokens: 1024,
messages: [
[
'role' => 'user',
'content' => $prompt,
],
],
);
return contentText($message);
}
// ROUGE-L measures the longest common subsequence (LCS) of words between the
// candidate and reference summaries, reported here as an F1 score.
```
--------------------------------
### Constructing Patient Queries and Initializing Client
Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests
Examples of creating PatientQuery objects for various edge cases and initializing the Anthropic client from environment variables.
```java
new PatientQuery("Can you tell me why John Doe, DOB 5/12/1980, was prescribed Metformin?", true),
// Edge case: Hypothetical PHI
new PatientQuery("If my friend Alice, who was born on July 4, 1985, had diabetes, what...", true),
// Edge case: Implicit PHI
new PatientQuery("I'm worried about my son. He's been prescribed the same medication as his father last year.", true)
// ... 496 more queries
);
AnthropicClient client = AnthropicClient.fromEnv();
String contentText(Message message) {
var text = new StringBuilder()
```
--------------------------------
### Zsh Shell Completion Setup
Source: https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart
Command to generate and install Zsh completion scripts for the Claude CLI.
```bash
ant @completion zsh > "${fpath[1]}/_ant"
# Restart your shell or run: autoload -U compinit && compinit
```
--------------------------------
### Article summarization and completion setup
Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests
Defines a dataset of articles and a function to generate summaries using the Anthropic client.
```typescript
const articles = [
{
text: "In a groundbreaking study, researchers at MIT...",
summary: "MIT scientists discover a new antibiotic..."
},
{
text: "Jane Doe, a local hero, made headlines last week for saving... In city hall news, the budget... Meteorologists predict...",
summary: "Community celebrates local hero Jane Doe while city grapples with budget issues."
}, // Edge case: Multi-topic
{
text: "You won't believe what this celebrity did! ... extensive charity work ...",
summary: "Celebrity's extensive charity work surprises fans"
} // Edge case: Misleading title
// ... 197 more articles
];
const client = new Anthropic();
async function getCompletion(prompt: string): Promise {
const message = await client.messages.create({
model: "claude-opus-4-8",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }]
});
const textBlock = message.content.find((block) => block.type === "text");
return textBlock ? textBlock.text : "";
}
// ROUGE-L measures the longest common subsequence (LCS) of words between the
// candidate and reference summaries, reported here as an F1 score.
```
--------------------------------
### Retrieve Session Example
Source: https://platform.claude.com/docs/en/api/php/beta/sessions/retrieve
This example demonstrates how to use the `retrieve` method of the `sessions` client to fetch session details. It includes the API key setup, the call to retrieve a session by ID, and optional beta features.
```APIDOC
## Retrieve Session
### Description
Retrieves a specific session by its ID.
### Method
`retrieve`
### Parameters
- **id** (string) - Required - The unique identifier of the session to retrieve.
- **betas** (array) - Optional - A list of beta features to enable for this request.
### Request Example
```php
$betaManagedAgentsSession = $client->beta->sessions->retrieve(
'sesn_011CZkZAtmR3yMPDzynEDxu7',
betas: ['message-batches-2024-09-24']
);
```
### Response
#### Success Response (200)
Returns a Session object containing details about the session, including its ID, agent configuration, creation timestamp, status, and associated resources.
- **id** (string) - The unique identifier of the session.
- **agent** (object) - Details about the agent associated with the session.
- **created_at** (string) - The timestamp when the session was created.
- **status** (string) - The current status of the session (e.g., 'idle').
- **resources** (array