### Run Quickstart Example
Source: https://docs.claude.com/en/docs/initial-setup
Execute the Python quickstart script to see an example of the LLM in action. This command initiates the script that interacts with the Claude LLM.
```bash
python quickstart.py
```
--------------------------------
### Run the Quickstart Script
Source: https://docs.claude.com/en/docs/initial-setup
Execute the quickstart script using npx and tsx. Ensure you have Node.js and TypeScript installed.
```bash
npx tsx quickstart.ts
```
--------------------------------
### Example Output from Quickstart
Source: https://docs.claude.com/en/docs/initial-setup
This is the expected JSON output when running the quickstart script. It includes message details, content, and usage statistics.
```json
{
id: "msg_01ThFHzad6Bh4TpQ6cHux9t8",
type: "message",
role: "assistant",
model: "claude-opus-4-7",
content: [
{
type: "text",
text:
"Here are some effective search strategies to find the latest renewable energy developments:\n\n## Search Terms to Use:\n" +
'- "renewable energy news 2024"\n' +
'- "clean energy breakthroughs"\n' +
'- "solar wind technology advances"\n' +
'- "energy storage innovations"\n' +
'- "green hydrogen developments"\n' +
'- "offshore wind projects"\n' +
'- "battery technology renewable"\n\n' +
'## Best Sources to Check:\n\n**News & Industry Sites:**\n' +
'- Renewable Energy World\n' +
'- CleanTechnica\n' +
'- GreenTech Media (now Wood Mackenzie)\n' +
'- Energy Storage News\n' +
'- PV Magazine (for solar)...\n'
}
],
stop_reason: "end_turn",
usage: {
input_tokens: 21,
output_tokens: 302
}
}
```
--------------------------------
### Quickstart Script Output Example
Source: https://platform.claude.com/docs/en/get-started
This is an example of the JSON output produced by the `quickstart.py` script. It details message properties such as ID, type, role, model, and content.
```json
{
"id": "msg_01ThFHzad6Bh4TpQ6cHux9t8",
"type": "message",
"role": "assistant",
"model": "claude-opus-4-7",
"content": [
{
"type": "text",
"text": "Here are some effective search strategies to find the latest renewable energy developments:\n\n"}
]
}
```
--------------------------------
### Creating Setup Scripts
Source: https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices
Employ shell scripts to automate setup tasks like starting servers or running linters. This ensures consistency when resuming work from a new context window.
```shell
init.sh
```
--------------------------------
### MDX Component Rendering (Get Started Paragraph)
Source: https://code.claude.com/docs/en/overview
Renders a paragraph for the 'Get started' section, guiding users to choose their environment and mentioning requirements like a Claude subscription or Anthropic Console account.
```javascript
span\",\n strong: \
```
--------------------------------
### LLM Response Handling
Source: https://platform.claude.com/docs/en/build-with-claude/context-editing
Example of awaiting a response from the LLM. This snippet demonstrates the start of an asynchronous operation to get a response.
```javascript
var response = await
```
--------------------------------
### Setup Script to Install gh CLI
Source: https://code.claude.com/docs/en/claude-code-on-the-web
This Bash script installs the 'gh' CLI using apt. It runs at the start of a new cloud session. Append '|| true' to non-critical commands to prevent session failure on intermittent errors.
```bash
#!/bin/bash
apt update && apt install -y gh
```
--------------------------------
### Set up quality of life tools
Source: https://docs.claude.com/en/docs/system-prompts
Encourage Claude to create setup scripts, such as `init.sh`, to automate starting servers, running test suites, and linters. This prevents repetitive work when continuing from a fresh context window.
```text
Set up quality of life tools: Encourage Claude to create setup scripts (e.g., "init.sh") to gracefully start servers, run test suites, and linters. This prevents repeated work when continuing from a fresh context window.
```
--------------------------------
### Install gh CLI in Setup Script
Source: https://code.claude.com/docs/en/claude-code-on-the-web
To use `gh` commands not covered by built-in tools, install it in your setup script. Ensure a `GH_TOKEN` environment variable is provided for authentication.
```bash
apt update && apt install -y gh
```
--------------------------------
### Initialize Client and Create Message in Go
Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool
Demonstrates client instantiation and a beta message creation call in Go.
```go
client := anthropic.NewClient()
response, err := client.Beta.Messages.Create(
```
--------------------------------
### Handoff Component for Alternative Installations
Source: https://code.claude.com/docs/en/overview
This component displays information and actions for alternative installation methods, including a direct install link, a guide link, and an alternative command with a copy button.
```javascript
alt && _jsxs(_components.div, {
className: "cc-ic-handoff",
children: [
_jsxs(_components.div, {
className: "cc-ic-handoff-title",
children: ["Claude Code for ", alt.name]
}),
_jsx(_components.div, {
className: "cc-ic-handoff-sub",
children: alt.tagline
}),
_jsxs(_components.div, {
className: "cc-ic-handoff-actions",
children: [
_jsxs(_components.a, {
href: alt.installHref,
className: "cc-ic-btn-clay",
...alt.installHref.startsWith('http') ? {
target: '_blank',
rel: 'noopener'
} : {},
children: [alt.installLabel, " ", iconArrowUpRight(13)]
}),
_jsxs(_components.a, {
href: alt.guideHref,
className: "cc-ic-btn-ghost",
children: [alt.name, " guide ", iconArrowRight(12)]
})
]
}),
alt.altCmd && _jsxs(_components.div, {
className: "cc-ic-handoff-alt",
children: ["or run ", _jsx(_components.code, {
children: alt.altCmd
}), _jsx(_components.button, {
type: "button",
className: 'cc-ic-copy-sm' + (copied === 'alt' ? ' cc-ic-copied' : ''),
onClick: () => handleCopy(alt.altCmd, 'alt'),
"aria-label": "Copy command",
children: copied === 'alt' ? iconCheck(11) : iconCopy(11)
})]
})
]
})
]
```
--------------------------------
### Initialize Client and Create Message in Go
Source: https://platform.claude.com/docs/en/build-with-claude/fast-mode
Demonstrates client initialization and the start of a message creation call in Go.
```go
client := anthropic.NewClient()
response, err := client.Beta.Messages.Messages.N
```
--------------------------------
### Create a Beta Environment
Source: https://platform.claude.com/docs/en/managed-agents/quickstart
Examples for creating a new beta environment with specific configuration settings.
```csharp
var environment = await client.Beta.Environments.Create(new()
{
Name = "quickstart-env",
Config = new() { Networking = new UnrestrictedNetwork() },
});
Console.WriteLine($"Environment ID: {environment.ID}");
```
```go
environment, err := client.Beta.Environments.New(ctx, anthropic.BetaEnvironmentNewParams{
Name: "quickstart-env",
Config: anthropic.BetaCloudConfigParams{
Networking: anthropic.
```
--------------------------------
### Initialize Anthropic Client and Tool
Source: https://platform.claude.com/docs/en/build-with-claude/search-results
Setup the client and define a tool parameter for knowledge base queries.
```go
client := anthropic.NewClient()
knowledgeBaseTool := anthropic.ToolUnionParam{
OfTool: &anthropic.ToolParam{
Name: "s
```
--------------------------------
### Claude API Streaming Event Examples
Source: https://platform.claude.com/docs/en/build-with-claude/streaming
These snippets demonstrate the structure of message start and content block start events in the API stream.
```json
"message_start", "message": {"id": "msg_01...", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-7", "stop_reason": null, "stop_sequence": null}
```
```json
event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking":
```
--------------------------------
### Server Tool Use Example (SSE)
Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool
This Server-Sent Events (SSE) example demonstrates a server-side tool use scenario. It shows the start of a tool use block, a delta for the input JSON (search query), and the start of a tool result block with references to available tools.
```sse
event: content_block_start
data: { "type": "content_block_start", "index": 1, "content_block": { "type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "tool_search_tool_regex" }}
// Search query streamed
event: content_block_delta
data: { "type": "content_block_delta", "index": 1, "delta": { "type": "input_json_delta", "partial_json": "{"query":"weather"}" }}
// Pause while search executes
// Search results streamed
event: content_block_start
data: { "type": "content_block_start", "index": 2, "content_block": { "type": "tool_search_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": { "type": "tool_search_tool_search_result", "tool_references": [{"type": "tool_reference", "tool_name": "get_weather"}] } }}
// Claude continues with discovered tools
```
--------------------------------
### Initialize Anthropic Client and Configure Beta Context
Source: https://platform.claude.com/docs/en/build-with-claude/compaction
Demonstrates how to instantiate the Anthropic client and define a beta context management configuration with compact edits.
```go
client := anthropic.NewClient()
messages := []anthropic.BetaMessageParam{
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Help me build a web scraper")),
}
compactEdit := anthropic.BetaContextManagementConfigParam{
Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
{
OfCompact20260112: &anthropic.BetaCompact20260112EditParam{},
},
},
}
```
--------------------------------
### Initialize and Use Beta Features in PHP
Source: https://platform.claude.com/docs/en/build-with-claude/context-editing
Shows how to instantiate the client using an API key from environment variables and execute a beta message creation request.
```php
$client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));
$response = $client->beta()->messages()->create(
```
--------------------------------
### Start Claude Code in a Project
Source: https://code.claude.com/docs
After installation, navigate to your project directory and run this command to start Claude Code. You will be prompted to log in on the first use.
```bash
cd your-project
claude
```
--------------------------------
### List Files with Anthropic Go SDK
Source: https://platform.claude.com/docs/en/build-with-claude/files
Demonstrates how to initialize the client and list files using the Beta API. Ensure the appropriate beta header is configured in the parameters.
```go
client := anthropic.NewClient()
files, err := client.Beta.Files.List(context.TODO(), anthropic.BetaFileListParams{
Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaFilesAPI2025_04_14},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(files)
```
--------------------------------
### Alternative Target Configurations
Source: https://code.claude.com/docs/en/overview
Configuration for alternative installation targets like Desktop, VS Code, and JetBrains, including install links and guide references.
```javascript
const ALT_TARGETS = {
desktop: {
name: 'Desktop',
tagline: 'The full agent in a native app for macOS and Windows.',
installLabel: 'Download the app',
installHref: 'https://claude.com/download?utm_source=claude_code&utm_medium=docs&utm_content=configurator_desktop_download',
guideHref: '/en/desktop-quickstart'
},
vscode: {
name: 'VS Code',
tagline: 'Review diffs, manage context, and chat without leaving your editor.',
installLabel: 'Install from Marketplace',
installHref: 'https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code',
altCmd: 'code --install-extension anthropic.claude-code',
guideHref: '/en/vs-code'
},
jetbrains: {
name: 'JetBrains',
tagline: 'Native plugin for IntelliJ, PyCharm, WebStorm, and other JetBrains IDEs.',
installLabel: 'Install from Marketplace',
installHref: 'https://plugins.jetbrains.com/plugin/27310-claude-code-beta-',
guideHref: '/en/jetbrains'
}
};
```
--------------------------------
### Initialize Client and Create Message in PHP
Source: https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool
Demonstrates client instantiation using an API key from environment variables and the structure for creating a message.
```php
$client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));
$message = $client->messages()->create(
maxTokens: 1024,
messages: [
```
--------------------------------
### Install and Authenticate gh CLI
Source: https://code.claude.com/docs/en/claude-code-on-the-web
Install the 'gh' CLI in your setup script and provide a GH_TOKEN for automatic authentication. This avoids the need for 'gh auth login'.
```shellscript
apt update && apt install -y gh
```
```shellscript
GH_TOKEN
```
```shellscript
gh auth login
```
--------------------------------
### Configure and Use Web Search Tool in Go
Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools
This example shows how to define the Web Search tool, initiate a message request, and handle a pause turn to continue the conversation with the tool's output.
```go
webSearchTool := []anthropic.ToolUnionParam{
{OfWebSearchTool20250305: &anthropic.WebSearchTool20250305Param{
MaxUses: anthropic.Int(10),
}},
}
response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus4_7,
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("Search for comprehensive information about quantum computing breakthroughs in 2025")),
},
Tools: webSearchTool,
})
if err != nil {
log.Fatal(err)
}
if response.StopReason == "pause_turn" {
// Convert response content to param types for the assistant message
var contentParams []anthropic.ContentBlockParamUnion
for _, block := range response.Content {
contentParams = append(contentParams, block.ToParam())
}
continuation, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus4_7,
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("Search for comprehensive information about quantum computing breakthroughs in 2025")),
anthropic.NewAssistantMessage(contentParams...),
},
Tools: webSearchTool,
})
if err != nil {
log.Fatal(err)
}
fmt.Println(continuation)
} else {
fmt.Println(response)
}
```
--------------------------------
### Compile and Run Java Code
Source: https://docs.claude.com/en/docs/initial-setup
These bash commands show how to compile the QuickStart.java file and then run the compiled Java code. This is necessary to execute the Anthropic client example.
```bash
javac QuickStart.java
java QuickStart
```
--------------------------------
### Example SSE Output for Streaming Thinking
Source: https://docs.claude.com/en/docs/build-with-claude/extended-thinking
This example demonstrates the sequence of Server-Sent Events (SSE) received when streaming extended thinking. It includes message start, content block start for thinking, thinking deltas, signature deltas, content block stop, and subsequent text block events.
```text
event: message_start
data: {"type": "message_start", "message": {"id": "msg_01...", "type": "message", "role": "assistant", "content": [], "model": "claude-sonnet-4-6", "stop_reason": null, "stop_sequence": null}}
event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": "", "signature": ""}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "I need to find the GCD of 1071 and 462 using the Euclidean algorithm.\n\n1071 = 2 \u00d7 462 + 147"}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "\n462 = 3 \u00d7 147 + 21\n147 = 7 \u00d7 21 + 0\n\nSo GCD(1071, 462) = 21"}}
// Additional thinking deltas...
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds..."}}
event: content_block_stop
data: {"type": "content_block_stop", "index": 0}
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "The greatest common divisor of 1071 and 462 is **21**."}}
// Additional text deltas...
event: content_block_stop
data: {"type": "content_block_stop", "index": 1}
event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}}
event: message_stop
data: {"type": "message_stop"}
```
--------------------------------
### Initialize Client and Send Messages in Go
Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool
Demonstrates client instantiation and the structure for calling beta message endpoints in Go.
```go
client := anthropic.NewClient()
response, err := client.Beta.Messages
```
--------------------------------
### Agent Code Example
Source: https://platform.claude.com/docs/en/managed-agents/skills
This is a basic example of an agent's code, likely for interacting with an LLM. The specific functionality is not detailed, but it shows a starting point for agent implementation.
```javascript
agent
```
--------------------------------
### Claude GitHub App Installation Prompt
Source: https://code.claude.com/docs/en/routines
The trigger setup process will prompt users to install the Claude GitHub App if it's not already present on the target repository.
```text
/web-setup
```
--------------------------------
### Initialize Beta Client in Go
Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool
Demonstrates the initialization of the Anthropic client and the creation of a new message request within a Go context.
```go
client := anthropic.NewClient()
response, err := client.Beta.Messages.New(context
```
--------------------------------
### Run First Agent Example
Source: https://code.claude.com/docs/en/agent-sdk/overview
This Python example demonstrates creating an agent that lists files in the current directory using built-in tools.
```python
from anthropic import Claude, AnthropicBedrock
from anthropic.types import ToolParam
# Initialize the client
client = Claude(
# api_key="my-api-key", # Defaults to ANTHROPIC_API_KEY environment variable
)
# Define tools for the agent
agent_tools = [
ToolParam(
name="list_files",
description="Lists files in the current directory.",
input_schema={
"type": "object",
"properties": {
"directory": {
"type": "string",
"description": "The directory to list files from.",
}
},
"required": ["directory"],
},
)
]
# Create the agent
response = client.agents.create(
name="File Lister Agent",
description="An agent that lists files in a directory.",
tools=agent_tools,
metadata={"user_id": "123"},
)
print(response.id)
```
--------------------------------
### Example Output from Anthropic Client
Source: https://docs.claude.com/en/docs/initial-setup
This is an example of the text output you might receive from the Anthropic client after running the QuickStart code. The actual content will vary based on the model and the prompt.
```text
[ContentBlock{text=TextBlock{text=Here are so
```
--------------------------------
### Install Anthropic SDK for Go
Source: https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock
Use the go get command to install the Anthropic SDK for Go, specifically for integration with Amazon Bedrock. Ensure your Go environment is configured.
```bash
go get github.com/anthropics/anthropic-sdk-go/bedrock
```
--------------------------------
### Initialize environment client in Go
Source: https://platform.claude.com/docs/en/managed-agents/environments
Demonstrates the syntax for assigning the environment client response in Go.
```go
environment, err := client.
```
--------------------------------
### Example: Formatting Preferences
Source: https://docs.claude.com/en/docs/system-prompts
Demonstrates how to specify formatting preferences by providing clear 'less effective' and 'more effective' examples. Use this to guide Claude's output style.
```text
NEVER use ellipses
```
```text
Your response will be read aloud by a text-to-speech engine, so never use ellipses since the text-to-speech engine will not know how to pronounce them.
```
--------------------------------
### Initialize and Send Message with PHP
Source: https://docs.claude.com/en/api/prompt-validation
Demonstrates client initialization using an environment variable and a message creation request with an array-based structure.
```php
$client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));
$message = $client->messages->create(
maxTokens: 1,
messages: [
['role' => 'user', 'content' => 'What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae'],
['role' =>
```
--------------------------------
### Streaming Response Example
Source: https://docs.claude.com/en/api/streaming
This example shows the event stream format for a streaming response from the Claude API, including message start, content block deltas, and message stop events.
```text
event: message_start
data: { "type": "message_start", "message": { "id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-7", "stop_reason": null, "stop_sequence": null, "usage": { "input_tokens": 25, "output_tokens": 1 }}}
event: content_block_start
data: { "type": "content_block_start", "index": 0, "content_block": { "type": "text", "text": ""}}
event: ping
data: { "type": "ping"}
event: content_block_delta
data: { "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "Hello"}}
event: content_block_delta
data: { "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "!"}}
event: content_block_stop
data: { "type": "content_block_stop", "index": 0}
event: message_delta
data: { "type": "message_delta", "delta": { "stop_reason": "end_turn", "stop_sequence":null}, "usage": { "output_tokens": 15}}
event: message_stop
data: { "type": "message_stop"}
```
--------------------------------
### Full Streaming Response Example (SSE)
Source: https://platform.claude.com/docs/en/build-with-claude/streaming
This Server-Sent Events (SSE) example demonstrates a complete streaming interaction, from message start to message stop, including content block deltas.
```sse
event: message_start
data: {"type": "message_start", "message": {"id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-7", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 25, "output_tokens": 1}}}
event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
event: ping
data: {"type": "ping"}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "!"}}
event: content_block_stop
data: {"type": "content_block_stop", "index": 0}
event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null}, "usage": {"output_tokens": 15}}
event: message_stop
data: {"type": "message_stop"}
```
--------------------------------
### Create Message with Tools in Go
Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool
Shows how to initialize a client and create a message with tool definitions in Go.
```go
client := anthropic.NewClient()
response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus4_7,
MaxTokens: 2048,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("What is the weather in San Francisco?")),
},
Tools: []anthropic.ToolUnionParam{
{OfToolSearchToolRegex20251119: &anthropic.ToolSearchToolRegex20251119Param{
Type: anthropic.ToolSearchToolRegex20251119TypeToolSearchToolRegex20251119,
}},
{OfTool: &anthropic.ToolParam{
Name: "get_weather",
Description: anthropic.String("Get the weather at a specific location"),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: map[string]any{
"location": map[string]any{"type": "string"},
"unit": map[string]any{
"type": "string",
"enum": []string{"celsius", "fahrenheit"},
},
},
Required: []string{"location"},
},
DeferLoading: anthropic.Bool(true),
}},
{OfTool: &anthropic.ToolParam{
Name: "search_files",
Description: anthropic.String("Search through files in the worksp
```
--------------------------------
### Messages API - cURL Example
Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool
This example demonstrates how to send a request to the Anthropic Messages API using cURL to get a response from the claude-opus-4-7 model, including a web search tool.
```APIDOC
## POST /v1/messages
### Description
Sends a message to the Anthropic API to generate a response. This example includes a tool definition for web search.
### Method
POST
### Endpoint
https://api.anthropic.com/v1/messages
### Headers
- **x-api-key** (string) - Required - Your Anthropic API key.
- **anthropic-version** (string) - Required - The API version to use (e.g., "2023-06-01").
- **content-type** (string) - Required - Set to "application/json".
### Request Body
- **model** (string) - Required - The model to use (e.g., "claude-opus-4-7").
- **max_tokens** (integer) - Required - The maximum number of tokens to generate.
- **messages** (array) - Required - An array of message objects representing the conversation history.
- **role** (string) - Required - The role of the message sender ("user" or "assistant").
- **content** (string) - Required - The content of the message.
- **tools** (array) - Optional - A list of tools the model can use.
- **type** (string) - Required - The type of tool (e.g., "web_search_20250305").
- **name** (string) - Required - The name of the tool (e.g., "web_search").
- **max_uses** (integer) - Optional - The maximum number of times the tool can be used.
### Request Example
```json
{
"model": "claude-opus-4-7",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "What is the weather in NYC?"
}
],
"tools": [{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 5
}]
}
```
### Response
#### Success Response (200)
- **content** (array) - The response content from the model.
- **role** (string) - The role of the sender (e.g., "assistant").
- **stop_reason** (string) - The reason the model stopped generating text.
- **type** (string) - The type of response.
#### Response Example
```json
{
"content": [
{
"type": "tool_use",
"tool_name": "web_search",
"tool_input": {
"query": "weather in NYC"
}
}
],
"role": "assistant",
"stop_reason": "tool_use",
"type": "content_block"
}
```
```
--------------------------------
### PHP Session Creation Example
Source: https://platform.claude.com/docs/en/managed-agents/files
This code demonstrates how to initiate a session with the client's beta sessions API. It includes agent ID, environment ID, and a file resource with a specified mount path.
```php
session = client.beta.sessions.create(
agent: agent.id,
environment_id: environment.id,
resources: [
{
type: "file",
file_id: file.id,
mountPath: '/workspace/data.csv',
},
]
)
```
--------------------------------
### Create Messages with Context Management in Go
Source: https://platform.claude.com/docs/en/build-with-claude/compaction
Demonstrates initializing a client and creating messages with context management configuration. This example includes handling compaction stop reasons.
```go
client := anthropic.NewClient()
messages := []anthropic.BetaMessageParam{anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude"))}
compactEdit := anthropic.BetaContextManagementConfigParam{
Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{
PauseAfterCompaction: anthropic.Bool(true),
}},
},
}
response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
Model: anthropic.ModelClaudeOpus4_7,
MaxTokens: 4096,
Messages: messages,
ContextManagement: compactEdit,
Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},
})
if err != nil {
log.Fatal(err)
}
if response.StopReason == "compaction" {
messages = append(messages, response.ToParam())
response, err = client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
Model: anthropic.ModelClaudeOpus4_7,
MaxTokens: 4096,
Messages: messages,
ContextManagement: anthropic.BetaContextManagementConfigParam{
Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
{OfCompact20260112: &anthropic.BetaCompact20260112EditParam{}},
},
},
Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},
})
if err != nil {
log.Fatal(err)
}
}
fmt.Println(response)
```
```go
client := anthropic.NewClient()
messages := []anthropic.BetaMessageParam{anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude"))}
```
--------------------------------
### Initialize Client with PHP
Source: https://docs.claude.com/en/api/messages-examples
Instantiates the client using an API key retrieved from environment variables.
```php
$client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));
```
--------------------------------
### PHP Example for API Key Authentication
Source: https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry
This PHP code snippet shows how to authenticate with your Foundry Claude deployment using an API key. The example assumes the Anthropic PHP SDK is installed.
```php
messages->create([
'model' => 'claude-sonnet-4-6',
'max_tokens' => 1024,
'messages' => [
['role' => 'user', 'content' => 'Hello, world!']
]
]);
echo $response->content[0]->text;
```
--------------------------------
### Initialize Client in Go
Source: https://platform.claude.com/docs/en/build-with-claude/batch-processing
Demonstrates the syntax for assigning a value to a client variable in Go.
```go
client :=
```
--------------------------------
### API Request Example: Get Weather
Source: https://platform.claude.com/docs/en/build-with-claude/tool-use
A cURL command demonstrating how to call the Anthropic Messages API to get weather information, including defining available tools and providing a user message.
```APIDOC
## Get Weather Information via API
### Description
This example shows how to use the Anthropic Messages API to retrieve weather information. It defines two tools: `get_location` and `get_weather`, and makes a request to find out the weather based on the user's current location.
### Method
`POST`
### Endpoint
`https://api.anthropic.com/v1/messages`
### Parameters
#### Headers
- **x-api-key** (string) - Required - Your Anthropic API key.
- **anthropic-version** (string) - Required - API version, e.g., `2023-06-01`.
- **content-type** (string) - Required - Set to `application/json`.
#### Request Body
- **model** (string) - Required - The model to use, e.g., `claude-opus-4-6`.
- **max_tokens** (integer) - Required - The maximum number of tokens to generate.
- **tools** (array) - Required - A list of tool definitions.
- **name** (string) - Required - The name of the tool.
- **description** (string) - Required - A description of what the tool does.
- **input_schema** (object) - Required - The schema for the tool's input.
- **type** (string) - Required - Must be `object`.
- **properties** (object) - Required - Defines the properties of the input.
- **location** (string) - Optional - The city and state, e.g. San Francisco, CA.
- **unit** (string) - Optional - The unit of temperature, enum: `celsius`, `fahrenheit`.
- **required** (array) - Optional - List of required input fields.
- **messages** (array) - Required - A list of message objects.
- **role** (string) - Required - Role of the message sender (`user` or `assistant`).
- **content** (string) - Required - The content of the message.
### Request Example
```bash
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data \
'{
"model": "claude-opus-4-6",
"max_tokens": 1024,
"tools": [
{
"name": "get_location",
"description": "Get the current user location based on their IP address. This tool has no parameters or arguments.",
"input_schema": {
"type": "object",
"properties": {}
}
},
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
}
},
"required": ["location"]
}
}
],
"messages": [{"role": "user", "content": "What is the weather like where I am?"}]
}'
```
### Response
#### Success Response (200)
- **content** (array) - The response from the model, which may include tool use requests.
- **type** (string) - Type of content, e.g., `tool_use`.
- **id** (string) - Unique identifier for the tool use.
- **name** (string) - The name of the tool to be called.
- **input** (object) - The input parameters for the tool.
#### Response Example
```json
{
"content": [
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "get_location",
"input": {}
}
]
}
```
```
--------------------------------
### Initialize and Send Message in PHP
Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool
Demonstrates how to instantiate the client using an environment variable and send a message request.
```PHP
$client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));
$response = $client->beta()->messages()->create(
maxTokens: 1024,
messages: [
['role' => 'user', 'content' => 'Save a picture of a cat to my desktop.'],
],
model: 'claude-opus-4-7'
```
--------------------------------
### Full Message Exchange Example
Source: https://docs.claude.com/en/api/messages-streaming
This example demonstrates a complete message exchange using Server-Sent Events (SSE), from message start to message stop, including content block updates and usage statistics.
```sse
event: message_start
data: { "type": "message_start", "message": { "id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-7", "stop_reason": null, "stop_sequence": null, "usage": { "input_tokens": 25, "output_tokens": 1 }}}
event: content_block_start
data: { "type": "content_block_start", "index": 0, "content_block": { "type": "text", "text": ""}}
event: ping
data: { "type": "ping"}
event: content_block_delta
data: { "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "Hello"}}
event: content_block_delta
data: { "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "!"}}
event: content_block_stop
data: { "type": "content_block_stop", "index": 0}
event: message_delta
data: { "type": "message_delta", "delta": { "stop_reason": "end_turn", "stop_sequence":null}, "usage": { "output_tokens": 15}}
event: message_stop
data: { "type": "message_stop"}
```
--------------------------------
### Configure SessionStart Hook for Dependency Installation
Source: https://code.claude.com/docs/en/claude-code-on-the-web
Use a SessionStart hook in your repository's .claude/settings.json to install dependencies specifically in cloud sessions. This ensures that necessary packages are available when the cloud environment starts.
```json
{
"hooks": {
"SessionStart": [
{
"matcher": ".*",
"run": "npm install"
}
]
}
}
```
--------------------------------
### Configure Tool Use and Streaming in Java
Source: https://platform.claude.com/docs/en/build-with-claude/streaming
This example shows how to initialize the Anthropic client, define a tool with an input schema, and stream the response content.
```java
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_7)
.maxTokens(1024L)
.addTool(Tool.builder()
.name("get_weather")
.description("Get the current weather in a given location")
.inputSchema(Tool.InputSchema.builder()
.properties(JsonValue.from(Map.of(
"location", Map.of(
"type", "string",
"description", "The city and state, e.g. San Francisco, CA"
)
)))
.putAdditionalProperty("required", JsonValue.from(List.of("location")))
.build())
.build())
.toolChoice(ToolChoice.ofAny(ToolChoiceAny.builder().build()))
.addUserMessage("What is the weather like in San Francisco?")
.build();
try (var streamResponse = client.messages().createStreaming(params)) {
streamResponse.stream().forEach(event -> {
event.contentBlockDelta().ifPresent(deltaEvent ->
deltaEvent.delta().text().ifPresent(td ->
System.out.print(td.text())
)
);
});
}
```
--------------------------------
### Create an environment with pre-installed packages
Source: https://platform.claude.com/docs/en/managed-agents/environments
This example demonstrates creating an environment with specific packages pre-installed for Python (pandas, numpy, scikit-learn) and Node.js (express). Packages are installed by their respective managers and cached across sessions. Package managers run in alphabetical order.
```yaml
name: data-analysis
config:
type: cloud
packages:
pip:
- pandas
- numpy
- scikit-learn
npm:
- express
networking:
type: unrestricted
```
--------------------------------
### Python: Example of str_replace Tool Usage
Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool
This example shows how to use the text_editor_20250728 tool to replace a specific string in a file. It includes the client setup, tool definition, and message structure for the API call.
```python
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=1024,
tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],
messages=[
# Previous messages...
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you.",
},
{
"type": "tool_use",
"id": "toolu_01PqRsTuVwXyZAbCdEfGh",
"name": "str_replace_based_edit_tool",
"input": {
"command": "str_replace",
"path": "primes.py",
"old_str": " for num in range(2, limit + 1)",
"new_str": " for num in range(2, limit + 1):",
},
},
],
},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01PqRsTuVwXyZAbCdEfGh",
"content": "Successfully replaced text at exactly one location.",
}
],
},
],
)
print(response)
```
--------------------------------
### Example Customer Interactions for Claude
Source: https://platform.claude.com/docs/en/about-claude/use-case-guides/customer-support-chat
These examples demonstrate ideal customer interactions for Claude, covering various insurance-related queries. They can be used to guide Claude's responses and include guardrails or tool calls.
```text
EXAMPLES = """
Here are a few examples of how you can interact with customers:
H: Hi, do you offer commercial insurance for small businesses?
A: Ah! Unfortunately, we don't offer commercial insurance at this time.
However, we do provide a range of personal insurance products including car insurance and electric car insurance.
Would you like to know more about these offerings?
H: Hi, what are your business hours?
A: Our business hours are Monday to Friday, 9 AM to 5 PM EST.
If you have any questions or need assistance, feel free to reach out during those times.
How else can I assist you today?
H: I'm shopping for car insurance. What does Acme offer?
A: Great choice! Acme's car insurance policies typically include:
- Liability coverage: Protects you if you're at fault in an accident
- Collision coverage: Pays for damage to your car in an accident
- Comprehensive coverage: Covers non-collision incidents like theft or vandalism
- Medical payments coverage: Pays for medical expenses after an accident
- Uninsured/underinsured motorist coverage: Protects you from drivers with insufficient insurance
We also offer optional coverages like rental car reimbursement, roadside assistance, and new car replacement.
Would you like more details on any of these coverages, or do you have specific questions about insuring your vehicle?
H: I'd like to hear about your electric car insurance.
A: Certainly! Our electric car insurance is specially designed to meet the unique needs of electric vehicle owners.
In addition to all the standard coverages we offer for regular cars, our electric car policies include:
- Battery coverage: Protection against damage or degradation of your vehicle's expensive battery system
- Tech package: Covers repairs or replacement of advanced electronics and onboard computer systems
- Charging station coverage: Protects both home and portable charging equipment
- Cybersecurity protection: Coverage against hacking or digital threats
- Specialized roadside assistance: Includes flatbed towing to protect the vehicle's undercarriage
We cover a wide range of electric vehicles, including popular models from Tesla, Rivian, Nissan, Chevrolet, and more.
Is there a specific electric vehicle you're looking to insure, or would you like more details on any of these coverages?
H: I'd like to get a quote for my car insurance.
A: Certainly! I'd be happy to help you get a quote for your car insurance.
To provide you with an accurate quote, I'll need to collect some information about your vehicle and the primary driver.
Let's start with the basics:
1. What is the make and model of your vehicle?
2. What year was it manufactured?
3. Approximately how many miles have you driven?
4. What is the age of the primary driver?
Once you provide this information, I'll use our quoting tool to generate a personalized insurance quote for you.
"""
```
--------------------------------
### Initialize Anthropic Client and Create Agent
Source: https://platform.claude.com/docs/en/managed-agents/quickstart
Demonstrates how to initialize the Anthropic client and create an agent. Ensure you have the necessary imports.
```go
package main
import (
"context"
"github.com/anthropics/anthropic-sdk-go"
)
func main() {
client := anthropic.NewClient()
ctx := context.Background()
agent, err := client.Beta.Agents.New(ctx)
```
--------------------------------
### Initialize Client and Send Message in PHP
Source: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking
Shows how to instantiate the client using an environment variable for the API key and initiate a message request.
```php
$client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));
$message = $client->messages->
```