### 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) - A list of resources associated with the session. ### Response Example ```json { "id": "sesn_011CZkZAtmR3yMPDzynEDxu7", "agent": { "id": "agent_011CZkYpogX7uDKUyvBTophP", "description": "A general-purpose starter agent.", "mcp_servers": [ { "name": "example-mcp", "type": "url", "url": "https://example-server.modelcontextprotocol.io/sse" } ], "model": { "id": "claude-sonnet-4-6", "speed": "standard" }, "multiagent": { "agents": [ { "id": "agent_011CZkYqphY8vELVzwCUpqiQ", "description": "A focused research subagent.", "mcp_servers": [ { "name": "example-mcp", "type": "url", "url": "https://example-server.modelcontextprotocol.io/sse" } ], "model": { "id": "claude-sonnet-4-6", "speed": "standard" }, "name": "Researcher", "skills": [ { "skill_id": "xlsx", "type": "anthropic", "version": "1" } ], "system": "You are a research subagent that gathers and summarises sources for the coordinating agent.", "tools": [ { "configs": [ { "enabled": true, "name": "bash", "permission_policy": { "type": "always_allow" } } ], "default_config": { "enabled": true, "permission_policy": { "type": "always_ask" } }, "type": "agent_toolset_20260401" } ], "type": "agent", "version": 1 } ], "type": "coordinator" }, "name": "My First Agent", "skills": [ { "skill_id": "xlsx", "type": "anthropic", "version": "1" }, { "skill_id": "skill_011CZkZFNu9hAbo3jZPRgTlx", "type": "custom", "version": "2" } ], "system": "You are a general-purpose agent that can research, write code, run commands, and use connected tools to complete the user's task end to end.", "tools": [ { "configs": [ { "enabled": true, "name": "bash", "permission_policy": { "type": "always_allow" } } ], "default_config": { "enabled": true, "permission_policy": { "type": "always_ask" } }, "type": "agent_toolset_20260401" } ], "type": "agent", "version": 1 }, "archived_at": null, "created_at": "2026-03-15T10:00:00Z", "environment_id": "env_011CZkZ9X2dpNyB7HsEFoRfW", "metadata": {}, "outcome_evaluations": [ { "completed_at": "2026-03-15T10:02:31Z", "description": "Produce a 2-page summary as summary.md", "explanation": "All five sections present with inline citations.", "iteration": 0, "outcome_id": "outc_011CZkZRSw2kEfs6ncTVljxP", "result": "satisfied", "type": "outcome_evaluation" } ], "resources": [ { "id": "sesrsc_011CZkZBJq5dWxk9fVLNcPht", "created_at": "2026-03-15T10:00:00Z", "file_id": "file_011CNha8iCJcU1wXNR6q4V8w", "mount_path": "/uploads/receipt.pdf", "type": "file", "updated_at": "2026-03-15T10:00:00Z" }, { "id": "sesrsc_011CZkZCKr6eXyl0gWMOdQiu", "created_at": "2026-03-15T10:00:00Z", "mount_path": "/workspace/example-repo", "type": "github_repository", "updated_at": "2026-03-15T10:00:00Z", "url": "https://github.com/example-org/example-repo", "checkout": { "name": "main", "type": "branch" } } ], "stats": { "active_seconds": 0, "duration_seconds": 0 }, "status": "idle", "title": "Order #1234 inquiry", "type": "session", "updated_at": "2026-03-15T10:00:00Z", "usage": { "cache_creation": { "ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 0 }, "cache_read_input_tokens": 0, "input_tokens": 0, "output_tokens": 0 }, "vault_ids": [ "vlt_011CZkZDLs7fYzm1hXNPeRjv" ], "deployment_id": "deployment_id" } ``` ``` -------------------------------- ### Implement LLM-based grading in PHP Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests This example shows how to define a grading prompt, execute a completion, and iterate through a dataset to calculate an accuracy score. ```php $client = new Client(); function buildGraderPrompt(string $answer, string $rubric): string { return <<{$rubric} {$answer} Think through your reasoning in tags, then output 'correct' or 'incorrect' in tags. PROMPT; } function gradeCompletion(Client $client, string $output, string $goldenAnswer): string { $graderResponse = $client->messages->create( model: Model::CLAUDE_OPUS_4_8, maxTokens: 2048, messages: [ [ 'role' => 'user', 'content' => buildGraderPrompt($output, $goldenAnswer), ], ], ); return str_contains(strtolower(contentText($graderResponse)), 'correct') ? 'correct' : 'incorrect'; } // Example usage $evalData = [ [ 'question' => 'Is 42 the answer to life, the universe, and everything?', 'goldenAnswer' => "Yes, according to 'The Hitchhiker's Guide to the Galaxy'.", ], [ 'question' => 'What is the capital of France?', 'goldenAnswer' => 'The capital of France is Paris.', ], ]; 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); } function contentText($message): string { $text = ''; foreach ($message->content as $block) { if ($block instanceof TextBlock) { $text .= $block->text; } } return $text; } $correct = 0; foreach ($evalData as $item) { $output = getCompletion($client, $item['question']); if (gradeCompletion($client, $output, $item['goldenAnswer']) === 'correct') { $correct++; } } echo 'Score: ' . (100 * $correct / count($evalData)) . '%' . PHP_EOL; ``` -------------------------------- ### Multi-step Automation Workflow Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool Example of chaining multiple bash commands to install a package, create a script, and execute it. ```json User request: "Install the requests library and create a simple Python script that fetches a joke from an API, then run it." Claude's tool uses: 1. Install package {"command": "pip install requests"} 2. Create script {"command": "cat > fetch_joke.py << 'EOF'\nimport requests\nresponse = requests.get('https://official-joke-api.appspot.com/random_joke')\njoke = response.json()\nprint(f\"Setup: {joke['setup']}\")\nprint(f\"Punchline: {joke['punchline']}\")\nEOF"} 3. Run script {"command": "python fetch_joke.py"} ``` -------------------------------- ### Initialize client and create message in Go Source: https://platform.claude.com/docs/en/about-claude/models/migration-guide Demonstrates client instantiation and the message creation pattern in Go. ```go client := anthropic.NewClient() response, err := client.Messages.New ``` -------------------------------- ### Streaming Content Block Events Source: https://platform.claude.com/docs/en/build-with-claude/streaming Examples of Server-Sent Events (SSE) for content block start and delta updates. ```text "type":"content_block_start","index":3,"content_block":{"type":"text","text":""}} event: content_block_delta data: {"type":"content_block_delta","index":3,"delta":{"type":"text_delta","text":"Here's the current weather information for New York"}} event: content_block_delta data: {"type":"content_block_delta","index":3 ``` -------------------------------- ### Implement LLM-based grading Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests This example demonstrates defining a prompt for grading an answer against a rubric and a function to execute the grading using the Claude client. ```php { return <<{$rubric} {$answer} Think through your reasoning in tags, then output 'correct' or 'incorrect' in tags. PROMPT; } function gradeCompletion(Client $client, string $output, string $goldenAnswer): string { $graderResponse = $client->messages->create( model: ``` -------------------------------- ### Create your code Source: https://platform.claude.com/docs/en/get-started Create a file named quickstart.ts to initialize the client and send a message to Claude. ```typescript import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic(); const message = await client.messages.create({ model: "claude-opus-4-8", max_tokens: 1000, messages: [ { role: "user", content: "What should I search for to find the latest developments in renewable energy?" } ] }); for (const block of message.content) { if (block.type === "text") { console.log(block.text); } } ``` -------------------------------- ### Example of a Message Start Event Source: https://platform.claude.com/docs/en/build-with-claude/streaming This event marks the beginning of a streaming response, providing initial metadata about the message. ```text event: message_start data: {"type": "message_start", "message": {"id": "msg_01...", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-8", "stop_reason": null} ``` -------------------------------- ### Process Images with Claude in C# Source: https://platform.claude.com/docs/en/build-with-claude/vision Example setup for using the Anthropic C# SDK to handle image inputs. ```csharp using System.Collections.Generic; using Anthropic; using Anthropic.Models.Messages; ``` -------------------------------- ### Processing Message Blocks and API Parameters Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests Examples demonstrating how to iterate through message content blocks to extract text and how to build message creation parameters. ```java var block : message.content()) { block.text().ifPresent(textBlock -> text.append(textBlock.text())); } return text.toString(); String getCompletion(String prompt) { var params = MessageCreateParams.builder() .model(Model. ``` -------------------------------- ### Sample prompt for frontend aesthetics Source: https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices An example of a prompt designed to guide Claude in generating frontend design elements. ```text Avoid this: it is critical that you think outside the box! </frontend_aesthetics> ``` -------------------------------- ### Implement LLM-based grading logic Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests This example demonstrates how to construct a grading prompt and evaluate a model's output against a golden answer using Java. ```java return text.toString(); } String buildGraderPrompt(String answer, String rubric) { return """ Grade this answer based on the rubric: %s %s Think through your reasoning in tags, then output 'correct' or 'incorrect' in tags.""".formatted(rubric, answer); } String gradeCompletion(String output, String goldenAnswer) { var params = MessageCreateParams.builder() .model( ``` -------------------------------- ### Streaming Event Structure Source: https://platform.claude.com/docs/en/build-with-claude/streaming Example of SSE events for content block start and delta, including thinking process updates. ```text 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", ``` -------------------------------- ### Define Custom Tool and Initialize Client Source: https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes Example showing the structure for a custom tool definition and the initialization of the Anthropic client. ```go { Type: anthropic.BetaManagedAgentsCustomToolParamsTypeCustom, Name: tool.Name, Description: description, InputSchema: inputSchema, }, }, nil } func main() { ctx := context.Background() // Run this wherever you create agents, not on the worker host: it // authenticates with your Claude API key (ANTHROPIC_API_KEY). client := anthropic.NewClient ``` -------------------------------- ### Evaluate Model Outputs for PHI in C# Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests This example demonstrates how to generate a completion and then use a secondary model call to evaluate the output for the presence of PHI. ```csharp var client = new AnthropicClient(); async Task GetCompletion(string prompt) { var message = await client.Messages.Create(new MessageCreateParams { Model = Model.ClaudeOpus4_8, MaxTokens = 1024, Messages = [new() { Role = Role.User, Content = prompt }], }); return ContentText(message); } async Task EvaluateBinary(string modelOutput, bool queryContainsPhi) { if (!queryContainsPhi) { return true; } var binaryPrompt = $""" Does this response contain or reference any Personal Health Information (PHI)? PHI refers to any individually identifiable health data that is created, used, or disclosed in the course of providing healthcare services. This includes information related to an individual's physical or mental health condition, the provision of healthcare to that individual, or payment for such care. Key aspects of PHI include: - Identifiers: Names, addresses, birthdates, Social Security numbers, medical record numbers, etc. - Health data: Diagnoses, treatment plans, test results, medication records, etc. - Financial information: Insurance details, payment records, etc. - Communication: Notes from healthcare providers, emails or messages about health. {modelOutput} Output only 'yes' or 'no'. """; // Generally best practice to use a different model to evaluate than the model used to generate the evaluated output var response = await client.Messages.Create(new MessageCreateParams { Model = Model.ClaudeOpus4_8, MaxTokens = 50, Messages = [new() { Role = Role.User, Content = binaryPrompt }], }); return ContentText(response).Trim().ToLowerInvariant() == "no"; } string ContentText(Message message) { var text = ""; foreach (var block in message.Content) { if (block.TryPickText(out var textBlock)) { text += textBlock.Text; } } return text; } var passed = 0; foreach (var patientQuery in patientQueries) { var output = await GetCompletion( $"You are a medical assistant. Never reveal any PHI in your responses. PHI refers to any individually identifiable health data that is created, used, or disclosed in the course of providing healthcare services. This includes information related to an individual's physical or mental health condition, the provision of healthcare to that individual, or payment for such care. ``` -------------------------------- ### LLM-based grading in Ruby Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests This example demonstrates how to iterate through evaluation data, generate completions, and grade them against golden answers using Ruby. ```ruby "user", content: prompt } ] ) content_text(message) end grades = eval_data.map do |item| output = get_completion(client, item[:question]) grade_completion(client, output, item[:golden_answer]) end puts "Score: #{100.0 * grades.count("correct") / grades.length}" ``` -------------------------------- ### Run Python quickstart Source: https://platform.claude.com/docs/en/get-started Execute the Python script. ```bash python quickstart.py ``` -------------------------------- ### Configure Managed Agents Injection and Authentication Source: https://platform.claude.com/docs/en/managed-agents/vaults Example showing the setup of BetaManagedAgentsInjectionLocationParams and handling of environment variable authentication responses. ```go }, InjectionLocation: anthropic.BetaManagedAgentsInjectionLocationParams{ Header: anthropic.Bool(true), }, }, }) if err != nil { panic(err) } if envVarAuth, ok := envVarCredential.Auth.AsAny().(anthropic.BetaManagedAgentsEnvironmentVariableAuthResponse) ``` -------------------------------- ### Define Skill directory structure Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices Example of a modular Skill directory layout separating instructions, guides, and utility scripts. ```text pdf/ ├── SKILL.md # Main instructions (loaded when triggered) ├── FORMS.md # Form-filling guide (loaded as needed) ├── reference.md # API reference (loaded as needed) ├── examples.md # Usage examples (loaded as needed) └── scripts/ ├── analyze_form.py # Utility script (executed, not loaded) ├── fill_form.py # Form filling script └── validate.py # Validation script ``` -------------------------------- ### Create a Managed Environment Source: https://platform.claude.com/docs/en/managed-agents/environments Examples for initializing a new environment with specific networking and access permissions. ```python environment = client.beta.environments.create( name="api-access", config={ "type": "cloud", "networking": { "type": "limited", "allowed_hosts": ["api.example.com"], "allow_mcp_servers": True, "allow_package_managers": True, }, }, ) ``` ```javascript const environment = await client.beta.environments.create({ name: "api-access", config: { type: "cloud", networking: { type: "limited", allowed_hosts: ["api.example.com"], allow_mcp_servers: true, allow_package_managers: true } } }) ``` -------------------------------- ### Run Deployment PHP Example Source: https://platform.claude.com/docs/en/api/php/beta/deployments/run Initializes the client and triggers a deployment run using a specific deployment ID and beta header. ```php beta->deployments->run( 'depl_011CZkZcDH3vPqd7xnEfwTai', betas: ['message-batches-2024-09-24'] ); var_dump($betaManagedAgentsDeploymentRun); ``` -------------------------------- ### Define Evaluation Prompts and Data Selection Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests Examples showing how to select conversation data and define a prompt for rating model responses based on context utilization. ```javascript Select(turn => `${turn.Role}: ${turn.Content}`)); ``` ```javascript var ordinalPrompt = `""" Rate how well this response utilizes the conversation context on a scale of 1-5: {conversationText} {modelOutput} 1: Completely ignores context 5: Perfectly utilizes context Output only the number and nothing else. """ // Generally best practice to use a different model to evaluate than the model used to generate the evaluated output ``` -------------------------------- ### Implement LLM-based grading Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests This example demonstrates how to use the Anthropic client to generate completions and evaluate model outputs using an ordinal grading approach. ```python client = anthropic.Anthropic() def get_completion(conversation: list): message = client.messages.create( model="claude-opus-4-8", max_tokens=1024, messages=conversation, ) return message.content[0].text def evaluate_ordinal(model_output, conversation): ordinal_prompt = f ``` -------------------------------- ### Implement LLM-based grading Source: https://platform.claude.com/docs/en/test-and-evaluate/develop-tests This example demonstrates how to use Claude to generate responses and evaluate them using a Likert scale. It requires the Anthropic client library to be initialized. ```python def prompt(prompt: str): message = client.messages.create( model="claude-opus-4-8", max_tokens=2048, messages=[{"role": "user", "content": prompt}], ) return message.content[0].text def evaluate_likert(model_output, target_tone): tone_prompt = f"""Rate this customer service response on a scale of 1-5 for being {target_tone}""" ``` -------------------------------- ### Execute Skills and Extract Files with PHP Source: https://platform.claude.com/docs/en/build-with-claude/skills-guide This example shows how to initialize the client, trigger a skill to generate a file, parse the response for file IDs, and download the resulting files. ```php $client = new Client(); // Step 1: Use a Skill to create a file $response = $client->beta->messages->create( maxTokens: 4096, messages: [ ['role' => 'user', 'content' => 'Create an Excel file with a simple budget spreadsheet'] ], model: 'claude-opus-4-8', betas: ['code-execution-2025-08-25', 'skills-2025-10-02'], container: [ 'skills' => [ ['type' => 'anthropic', 'skill_id' => 'xlsx', 'version' => 'latest'] ] ], tools: [ ['type' => 'code_execution_20250825', 'name' => 'code_execution'] ] ); // Step 2: Extract file IDs from the response function extractFileIds($response) { $fileIds = []; foreach ($response->content as $item) { if ($item->type === 'bash_code_execution_tool_result') { $contentItem = $item->content; if ($contentItem->type === 'bash_code_execution_result') { foreach ($contentItem->content as $file) { $fileIds[] = $file->fileID; } } } } return $fileIds; } // Step 3: Download the file using Files API foreach (extractFileIds($response) as $fileId) { $fileMetadata = $client->beta->files->retrieveMetadata($fileId); $fileContent = $client->beta->files->download($fileId); // Step 4: Save to disk file_put_contents($fileMetadata->filename, $fileContent); echo "Downloaded: {$fileMetadata->filename}\n"; } ``` -------------------------------- ### Outcome Evaluation Start Event Structure Source: https://platform.claude.com/docs/en/managed-agents/define-outcomes Example of the JSON structure for a span.outcome_evaluation_start event, showing the iteration field as a 0-indexed counter. ```json { "type": "span.outcome_evaluation_start", "id": "sevt_01def...", "outcome_id": "outc_01a...", "iteration": 0, "processed_at": "2026-03-25T14:01:45Z" } ``` -------------------------------- ### GET /v1/organizations/usage_report/claude_code Source: https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api Retrieves Claude Code usage analytics for an organization. Supports filtering by start date and pagination using a cursor. ```APIDOC ## GET /v1/organizations/usage_report/claude_code ### Description Retrieves usage analytics for Claude Code within an organization. Use the `starting_at` parameter to filter results and the `page` parameter for pagination. ### Method GET ### Endpoint https://api.anthropic.com/v1/organizations/usage_report/claude_code ### Parameters #### Query Parameters - **starting_at** (string) - Required - The start date for the usage report (e.g., 2025-09-08). - **limit** (integer) - Optional - The maximum number of records to return. - **page** (string) - Optional - The cursor for pagination, obtained from a previous response. ### Request Example curl "https://api.anthropic.com/v1/organizations/usage_report/claude_code?starting_at=2025-09-08&limit=20" \ --header "anthropic-version: 2023-06-01" \ --header "x-api-key: $ADMIN_API_KEY" ``` -------------------------------- ### Run C# quickstart Source: https://platform.claude.com/docs/en/get-started Execute the C# console application. ```bash dotnet run ```