### Run Node.js quickstart script Source: https://platform.claude.com/docs/en/get-started This command executes the Node.js quickstart script using `tsx`. Ensure you have Node.js and `tsx` installed. The script will send a request to the Anthropic API and print the response to your terminal. ```bash npx tsx quickstart.ts ``` -------------------------------- ### Install Python Agent SDK with pip Source: https://platform.claude.com/docs/en/agent-sdk/quickstart Installs the Claude Agent SDK for Python using pip. This involves creating a virtual environment first and then activating it before installing the package. ```bash python3 -m venv .venv && source .venv/bin/activate pip3 install claude-agent-sdk ``` -------------------------------- ### Assign Custom System Prompt to Claude Agent Source: https://platform.claude.com/docs/en/agent-sdk/quickstart This code shows how to provide a custom system prompt to your Claude agent, guiding its persona and behavior. The example sets the agent to act as a senior Python developer and adhere to PEP 8 guidelines, while also enabling specific tools and an edit permission mode. ```python options=ClaudeAgentOptions( allowed_tools=["Read", "Edit", "Glob"], permission_mode="acceptEdits", system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines." ) ``` ```typescript options: { allowedTools: ["Read", "Edit", "Glob"], permissionMode: "acceptEdits", systemPrompt: "You are a senior Python developer. Always follow PEP 8 style guidelines." } ``` -------------------------------- ### Provide Example Interactions for AI Guidance (Python) Source: https://platform.claude.com/docs/en/about-claude/use-case-guides/customer-support-chat Includes sample customer-AI interactions to guide the AI's response patterns. These examples demonstrate desired conversational flows, including handling inquiries outside the AI's scope, such as commercial insurance. ```python 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. ``` -------------------------------- ### Install Python Agent SDK with uv Source: https://platform.claude.com/docs/en/agent-sdk/quickstart Initializes a Python project with uv and adds the Claude Agent SDK package. uv handles virtual environments automatically, simplifying Python package management. ```bash uv init && uv add claude-agent-sdk ``` -------------------------------- ### Messages API - Quick Start Source: https://platform.claude.com/docs/en/build-with-claude/structured-outputs This section provides examples of how to use the Messages API with tools in various programming languages. ```APIDOC ## POST /v1/messages ### Description This endpoint allows you to send messages to the Claude API and receive responses, including tool calls. ### Method POST ### Endpoint /v1/messages ### Parameters #### Query Parameters - **model** (string) - Required - The model to use for generation. - **max_tokens** (integer) - Required - The maximum number of tokens to generate. - **messages** (array) - Required - An array of message objects representing the conversation history. - **tools** (array) - Optional - An array of tool definitions that the model can use. #### Request Body ```json { "model": "claude-opus-4-6", "max_tokens": 1024, "messages": [ {"role": "user", "content": "What is the weather in San Francisco?"} ], "tools": [ { "name": "get_weather", "description": "Get the current weather in a given location", "strict": true, "input_schema": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"], "additionalProperties": false } } ] } ``` ### Response #### Success Response (200) - **content** (array) - The content of the response, which may include tool use blocks. #### Response Example ```json { "type": "tool_use", "name": "get_weather", "input": { "location": "San Francisco, CA" } } ``` ### How it works 1. **Define your tool schema**: Create a JSON schema for your tool's `input_schema`. 2. **Add strict: true**: Set `"strict": true` in your tool definition to ensure the tool input strictly follows the schema. 3. **Handle tool calls**: When Claude uses the tool, the `input` field in the `tool_use` block will strictly follow your `input_schema`, and the `name` will always be valid. ``` -------------------------------- ### Quickstart: Semantic Search Example Source: https://platform.claude.com/docs/en/build-with-claude/embeddings A practical example demonstrating how to use Voyage embeddings for semantic search. It covers embedding a corpus of documents, embedding a query, and finding the most relevant document using cosine similarity. ```APIDOC ## Quickstart: Semantic Search ### Description This example demonstrates how to perform semantic search using Voyage embeddings. It involves embedding multiple documents, embedding a query, and then finding the document most similar to the query. ### Method Uses `voyageai.Client().embed()` for both documents and queries. ### Endpoint N/A (Client-side Python SDK usage) ### Parameters - **documents** (list of strings) - The corpus of documents to embed. - **query** (string) - The search query. - **model** (string) - The embedding model to use (e.g., "voyage-3.5"). - **input_type** (string) - "document" for documents, "query" for the query. ### Request Example ```python import voyageai import numpy as np documents = [ "The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.", "Photosynthesis in plants converts light energy into glucose and produces essential oxygen.", "20th-century innovations, from radios to smartphones, centered on electronic advancements.", "Rivers provide water, irrigation, and habitat for aquatic species, vital for ecosystems.", "Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.", "Shakespeare's works, like 'Hamlet' and 'A Midsummer Night's Dream,' endure in literature." ] vo = voyageai.Client() # Embed the documents doc_embds = vo.embed( documents, model="voyage-3.5", input_type="document" ).embeddings query = "When is Apple's conference call scheduled?" # Embed the query query_embd = vo.embed( [query], model="voyage-3.5", input_type="query" ).embeddings[0] # Compute the similarity (dot product for normalized embeddings) similarities = np.dot(doc_embds, query_embd) retrieved_id = np.argmax(similarities) print(documents[retrieved_id]) ``` ### Response #### Success Response Prints the most relevant document from the corpus based on semantic similarity. #### Response Example ``` Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET. ``` ``` -------------------------------- ### Installing and Using pypdf Library in Python Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices Provides an example of explicitly stating dependencies and then using a library. This good practice ensures that Claude knows which packages need to be installed before executing Python code. ```python Install required package: `pip install pypdf` Then use it: ```python from pypdf import PdfReader reader = PdfReader("file.pdf") ``` ``` -------------------------------- ### Install Go Claude SDK Source: https://platform.claude.com/docs/en/api/client-sdks Installs the Anthropic Go client library using the go get command. Requires Go 1.22+. ```bash go get -u 'github.com/anthropics/anthropic-sdk-go@v1.17.0' ``` -------------------------------- ### Create Project Directory Source: https://platform.claude.com/docs/en/agent-sdk/quickstart Creates a new directory for the quickstart project and navigates into it. This is the initial step for setting up any new project using the Agent SDK. ```bash mkdir my-agent && cd my-agent ``` -------------------------------- ### Guiding Claude's Thinking Process After Tool Use Source: https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices This example prompt guides Claude to reflect on tool results, evaluate their quality, and determine optimal next steps before proceeding. It encourages using its thinking capabilities for planning and iteration based on new information. ```text After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action. ``` -------------------------------- ### Create Word Document using Anthropic API Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/quickstart These examples demonstrate how to generate a Word document with a report on renewable energy benefits using the Anthropic API and the 'docx' skill. Similar to the spreadsheet example, it leverages the code execution tool and requires API key authentication. The request specifies the model, max tokens, and the 'docx' skill. ```python response = client.beta.messages.create( model="claude-opus-4-6", max_tokens=4096, betas=["code-execution-2025-08-25", "skills-2025-10-02"], container={ "skills": [ { "type": "anthropic", "skill_id": "docx", "version": "latest" } ] }, messages=[{ "role": "user", "content": "Write a 2-page report on the benefits of renewable energy" }], tools=[{ "type": "code_execution_20250825", "name": "code_execution" }] ) ``` ```typescript const response = await client.beta.messages.create({ model: 'claude-opus-4-6', max_tokens: 4096, betas: ['code-execution-2025-08-25', 'skills-2025-10-02'], container: { skills: [ { type: 'anthropic', skill_id: 'docx', version: 'latest' } ] }, messages: [{ role: 'user', content: 'Write a 2-page report on the benefits of renewable energy' }], tools: [{ type: 'code_execution_20250825', name: 'code_execution' }] }); ``` ```bash curl https://api.anthropic.com/v1/messages \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "anthropic-beta: code-execution-2025-08-25,skills-2025-10-02" \ -H "content-type: application/json" \ -d '{ "model": "claude-opus-4-6", "max_tokens": 4096, "container": { "skills": [ { "type": "anthropic", "skill_id": "docx", "version": "latest" } ] }, "messages": [{ "role": "user", "content": "Write a 2-page report on the benefits of renewable energy" }], "tools": [{ "type": "code_execution_20250825", "name": "code_execution" }] }' ``` -------------------------------- ### Example: Setting Up Sandbox for Project Build in Python Source: https://platform.claude.com/docs/en/agent-sdk/python Demonstrates how to use the SandboxSettings to enable sandboxing and auto-allow bash commands for building and testing a project. This example shows the integration with the `query` function and `ClaudeAgentOptions`. ```python from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings sandbox_settings: SandboxSettings = { "enabled": True, "autoAllowBashIfSandboxed": True, "network": { "allowLocalBinding": True } } async for message in query( prompt="Build and test my project", options=ClaudeAgentOptions(sandbox=sandbox_settings) ): print(message) ``` -------------------------------- ### Guiding Claude's Memory Writes Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool This example shows how to guide Claude on what information to write to the memory system, specifying that only information relevant to a particular topic should be stored. ```text Only write down information relevant to in your memory system. ``` -------------------------------- ### Java Example: Tool Use for Weather Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview Demonstrates how to configure and use tools for getting user location and weather information using the Java client library. ```APIDOC ## POST /v1/messages ### Description This endpoint allows for message creation with tool use capabilities. It's used here to demonstrate how to get user location and then weather information using Java. ### Method POST ### Endpoint /v1/messages ### Parameters #### Query Parameters None #### Request Body ```json { "model": "claude-opus-4-0", "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?" } ] } ``` ### Request Example ```java import java.util.List; import java.util.Map; import com.anthropic.client.AnthropicClient; import com.anthropic.client.okhttp.AnthropicOkHttpClient; import com.anthropic.core.JsonValue; import com.anthropic.models.messages.Message; import com.anthropic.models.messages.MessageCreateParams; import com.anthropic.models.messages.Model; import com.anthropic.models.messages.Tool; import com.anthropic.models.messages.Tool.InputSchema; public class EmptySchemaToolExample { public static void main(String[] args) { AnthropicClient client = AnthropicOkHttpClient.fromEnv(); // Empty schema for location tool InputSchema locationSchema = InputSchema.builder() .properties(JsonValue.from(Map.of())) .build(); // Weather tool schema InputSchema weatherSchema = InputSchema.builder() .properties(JsonValue.from(Map.of( "location", Map.of( "type", "string", "description", "The city and state, e.g. San Francisco, CA" ), "unit", Map.of( "type", "string", "enum", List.of("celsius", "fahrenheit"), "description", "The unit of temperature, either \"celsius\" or \"fahrenheit\"" ) ))) .putAdditionalProperty("required", JsonValue.from(List.of("location"))) .build(); MessageCreateParams params = MessageCreateParams.builder() .model(Model.CLAUDE_OPUS_4_0) .maxTokens(1024) .addTool(Tool.builder() .name("get_location") .description("Get the current user location based on their IP address. This tool has no parameters or arguments.") .inputSchema(locationSchema) .build()) .addTool(Tool.builder() .name("get_weather") .description("Get the current weather in a given location") .inputSchema(weatherSchema) .build()) .addUserMessage("What is the weather like where I am?") .build(); Message message = client.messages().create(params); System.out.println(message); } } ``` ### Response #### Success Response (200) - **content** (list) - The response content, which may include tool use or text. - **role** (string) - The role of the message sender ('assistant'). - **model** (string) - The model used for the response. - **stop_reason** (string) - The reason the model stopped generating tokens. - **stop_sequence** (string) - The stop sequence that was triggered, if any. - **usage** (object) - Usage statistics for the request. #### Response Example ```json { "content": [ { "type": "tool_use", "id": "toolu_0123456789abcdef", "name": "get_location", "input": {} } ], "role": "assistant", "model": "claude-opus-4-0", "stop_reason": "tool_use", "stop_sequence": null, "usage": { "input_tokens": 100, "output_tokens": 50 } } ``` ``` -------------------------------- ### Enable Terminal Command Execution in Claude Agent Source: https://platform.claude.com/docs/en/agent-sdk/quickstart This example illustrates how to grant your Claude agent the ability to execute commands in the terminal by including 'Bash' in the `allowed_tools`. This is useful for automating tasks like running tests and fixing failures. The `permission_mode` is set to 'acceptEdits'. ```python options=ClaudeAgentOptions( allowed_tools=["Read", "Edit", "Glob", "Bash"], permission_mode="acceptEdits" ) ``` ```typescript options: { allowedTools: ["Read", "Edit", "Glob", "Bash"], permissionMode: "acceptEdits" } ``` -------------------------------- ### Python Example: Tool Use for Weather Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview Demonstrates how to configure and use tools for getting user location and weather information using the Python client library. ```APIDOC ## POST /v1/messages ### Description This endpoint allows for message creation with tool use capabilities. It's used here to demonstrate how to get user location and then weather information. ### Method POST ### Endpoint /v1/messages ### Parameters #### Query Parameters None #### Request Body ```json { "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's the weather like where I am?" } ] } ``` ### Request Example ```python response = client.messages.create( 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's the weather like where I am?" } ] ) ``` ### Response #### Success Response (200) - **content** (list) - The response content, which may include tool use or text. - **role** (string) - The role of the message sender ('assistant'). - **model** (string) - The model used for the response. - **stop_reason** (string) - The reason the model stopped generating tokens. - **stop_sequence** (string) - The stop sequence that was triggered, if any. - **usage** (object) - Usage statistics for the request. #### Response Example ```json { "content": [ { "type": "tool_use", "id": "toolu_0123456789abcdef", "name": "get_location", "input": {} } ], "role": "assistant", "model": "claude-opus-4-6", "stop_reason": "tool_use", "stop_sequence": null, "usage": { "input_tokens": 100, "output_tokens": 50 } } ``` ``` -------------------------------- ### Example Plugin Configuration in Python Source: https://platform.claude.com/docs/en/agent-sdk/python Provides an example of how to configure plugins for the SDK using a list of SdkPluginConfig dictionaries. It shows both relative and absolute paths. ```python # Assuming SdkPluginConfig is defined as: # class SdkPluginConfig(TypedDict): # type: Literal["local"] # path: str plugins = [ {"type": "local", "path": "./my-plugin"}, {"type": "local", "path": "/absolute/path/to/plugin"} ] ``` -------------------------------- ### Quickstart: Connect to Claude Code Docs MCP Server (HTTP) Source: https://platform.claude.com/docs/en/agent-sdk/mcp This example demonstrates connecting to the Claude Code documentation MCP server using HTTP transport. It utilizes the 'allowedTools' option with a wildcard to permit all tools from the specified server, allowing the agent to query the documentation. ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; for await (const message of query({ prompt: "Use the docs MCP server to explain what hooks are in Claude Code", options: { mcpServers: { "claude-code-docs": { type: "http", url: "https://code.claude.com/docs/mcp" } }, allowedTools: ["mcp__claude-code-docs__*"] } })) { if (message.type === "result" && message.subtype === "success") { console.log(message.result); } } ``` ```python import asyncio from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage async def main(): options = ClaudeAgentOptions( mcp_servers={ "claude-code-docs": { "type": "http", "url": "https://code.claude.com/docs/mcp" } }, allowed_tools=["mcp__claude-code-docs__*"] ) async for message in query(prompt="Use the docs MCP server to explain what hooks are in Claude Code", options=options): if isinstance(message, ResultMessage) and message.subtype == "success": print(message.result) asyncio.run(main()) ``` -------------------------------- ### Multi-step Automation with Bash Tool (Python) Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool Provides a Python example demonstrating multi-step automation using the bash tool. It shows how Claude can chain commands to install a package, create a Python script, and then execute it, leveraging the persistent session state. ```python # 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"} ``` -------------------------------- ### Create Presentation using PowerPoint Skill Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/quickstart Demonstrates how to use the PowerPoint Skill via the Messages API to generate a presentation. ```APIDOC ## POST /v1/messages (with Skill usage) ### Description Creates a presentation using the PowerPoint Skill by specifying it in the `container` parameter of the Messages API. ### Method POST ### Endpoint /v1/messages ### Request Body - **model** (string) - Required - The model to use for the request (e.g., 'claude-3-opus-20240229'). - **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) - The role of the message sender ('user' or 'assistant'). - **content** (string) - The content of the message. - **container** (object) - Required - Specifies the Skill to use for the request. - **tool_code** (string) - The tool code for the desired skill (e.g., 'pptx'). ### Request Example ```python import anthropic client = anthropic.Anthropic() response = client.messages.create( model="claude-3-opus-20240229", max_tokens=1024, messages=[ { "role": "user", "content": "Create a presentation about renewable energy." } ], container={"tool_code": "pptx"} ) print(response.content) ``` ### Response #### Success Response (200) - **content** (array) - The response content, which may include information about the generated file or status. #### Response Example (Response content will vary based on the generated presentation and API output. It might contain URLs to the generated file or status messages.) ```json [ { "type": "text", "text": "Your presentation on renewable energy has been generated. You can access it at [link_to_presentation.pptx]." } ] ``` ``` -------------------------------- ### POST /v1/messages - Pre-filling Response Example Source: https://platform.claude.com/docs/en/build-with-claude/working-with-messages This example demonstrates how to pre-fill Claude's response by including an 'assistant' message in the `messages` list. This can be used to guide Claude's output, for instance, to get a single multiple-choice answer by setting `max_tokens` to 1. ```APIDOC ## POST /v1/messages ### Description Pre-fills part of Claude's response by including an 'assistant' message in the `messages` list. This can be used to shape Claude's output, for example, to get a single multiple-choice answer by setting `max_tokens` to 1. ### Method POST ### Endpoint /v1/messages ### Parameters #### Query Parameters None #### Request Body - **model** (string) - Required - The model to use for the request. - **max_tokens** (integer) - Required - The maximum number of tokens to generate. - **messages** (array) - Required - A list of messages representing the conversation history. Each message should have a `role` (user or assistant) and `content`. - **role** (string) - Required - The role of the message sender ('user' or 'assistant'). - **content** (string) - Required - The content of the message. ### Request Example ```json { "model": "claude-opus-4-6", "max_tokens": 1, "messages": [ {"role": "user", "content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"}, {"role": "assistant", "content": "The answer is ("} ] } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the message. - **type** (string) - The type of the response ('message'). - **role** (string) - The role of the sender ('assistant'). - **content** (array) - The content of the message. - **type** (string) - The type of content ('text'). - **text** (string) - The text content of the message. - **model** (string) - The model used for the response. - **stop_reason** (string) - The reason the response stopped (e.g., 'max_tokens'). - **stop_sequence** (null) - The stop sequence, if any. - **usage** (object) - Token usage information. - **input_tokens** (integer) - The number of input tokens. - **output_tokens** (integer) - The number of output tokens. #### Response Example ```json { "id": "msg_01Q8Faay6S7QPTvEUUQARt7h", "type": "message", "role": "assistant", "content": [ { "type": "text", "text": "C" } ], "model": "claude-opus-4-6", "stop_reason": "max_tokens", "stop_sequence": null, "usage": { "input_tokens": 42, "output_tokens": 1 } } ``` ### Warning Prefilling is deprecated and not supported on Claude Opus 4.6 and Claude Sonnet 4.5. Use [structured outputs](/docs/en/build-with-claude/structured-outputs) or system prompt instructions instead. ``` -------------------------------- ### Compile and run Java quickstart program Source: https://platform.claude.com/docs/en/get-started These commands first compile the `QuickStart.java` file using `javac` and then run the compiled Java program using `java`. This executes the code that interacts with the Anthropic API and prints the response. ```bash javac QuickStart.java java QuickStart ``` -------------------------------- ### POST /v1/messages (Generate PDF) Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/quickstart This endpoint allows you to generate PDF documents by specifying the 'pdf' skill in the container configuration. The example demonstrates how to prompt the model to create a PDF invoice template. ```APIDOC ## POST /v1/messages ### Description Generates a PDF document using the 'pdf' Agent Skill. This endpoint is useful for creating various types of PDF content, such as templates or reports, by interacting with the Claude API. ### Method POST ### Endpoint /v1/messages ### Parameters #### Query Parameters None #### Request Body - **model** (string) - Required - The model to use for generation (e.g., "claude-opus-4-6"). - **max_tokens** (integer) - Required - The maximum number of tokens to generate. - **betas** (array of strings) - Optional - Beta features to enable (e.g., ["code-execution-2025-08-25", "skills-2025-10-02"]). - **container** (object) - Required - Configuration for skills. - **skills** (array of objects) - Required - List of skills to use. - **type** (string) - Required - The type of skill (e.g., "anthropic"). - **skill_id** (string) - Required - The identifier for the skill (e.g., "pdf"). - **version** (string) - Optional - The version of the skill (e.g., "latest"). - **messages** (array of objects) - Required - The conversation history. - **role** (string) - Required - The role of the message sender (e.g., "user"). - **content** (string) - Required - The content of the message (e.g., "Generate a PDF invoice template"). - **tools** (array of objects) - Optional - Tools to use for the request. - **type** (string) - Required - The type of tool (e.g., "code_execution_20250825"). - **name** (string) - Required - The name of the tool (e.g., "code_execution"). ### Request Example ```json { "model": "claude-opus-4-6", "max_tokens": 4096, "betas": ["code-execution-2025-08-25", "skills-2025-10-02"], "container": { "skills": [ { "type": "anthropic", "skill_id": "pdf", "version": "latest" } ] }, "messages": [ { "role": "user", "content": "Generate a PDF invoice template" } ], "tools": [ { "type": "code_execution_20250825", "name": "code_execution" } ] } ``` ### Response #### Success Response (200) - **content** (array) - Description of the generated content, which may include references to the generated PDF. - **role** (string) - The role of the assistant. - **model** (string) - The model used for the response. - **stop_reason** (string) - The reason the generation stopped. - **stop_sequence** (string) - The stop sequence, if any. #### Response Example ```json { "content": [ { "type": "text", "text": "I have generated a PDF invoice template. You can access it via the provided link or download it directly." } ], "role": "assistant", "model": "claude-opus-4-6", "stop_reason": "end_turn", "stop_sequence": null } ``` ``` -------------------------------- ### Install SDKs Source: https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai Instructions for installing the necessary client SDKs for Python and TypeScript to interact with Claude on Vertex AI. ```APIDOC ## Install SDKs ### Python ```python pip install -U google-cloud-aiplatform "anthropic[vertex]" ``` ### TypeScript ```typescript npm install @anthropic-ai/vertex-sdk ``` ``` -------------------------------- ### Make API Request to Claude (Python & TypeScript) Source: https://platform.claude.com/docs/en/resources/prompt-library/idiom-illuminator Examples for making API requests to the Claude model. These snippets demonstrate initializing the client, setting model parameters like `model`, `max_tokens`, `temperature`, `system` prompt, and `messages`. The Python example uses the `anthropic` library, while the TypeScript example uses `@anthropic-ai/sdk`. Both examples show how to print or log the response. ```Python import anthropic client = anthropic.Anthropic( # defaults to os.environ.get("ANTHROPIC_API_KEY") api_key="my_api_key", ) message = client.messages.create( model="claude-opus-4-6", max_tokens=1000, temperature=1, system="Your task is to provide a clear explanation of the meaning and origin of an idioms and proverb that the user gives you. Offer a concise interpretation of its figurative meaning and how it is typically used in conversation or writing. Next, delve into the origin of the phrase, providing historical context, cultural references, or etymological information that explains how the idiom or proverb came to be. If there are any interesting stories, anecdotes, or theories associated with the origin, include those as well. Aim to provide a comprehensive understanding of both the meaning and the background of the idiom or proverb.", messages=[{"role": "user", "content": [{"type": "text", "text": "Break a leg"}]}], ) print(message.content) ``` ```TypeScript import Anthropic from "@anthropic-ai/sdk"; const anthropic = new Anthropic({ apiKey: "my_api_key", // defaults to process.env["ANTHROPIC_API_KEY"] }); const msg = await anthropic.messages.create({ model: "claude-opus-4-6", max_tokens: 1000, temperature: 1, system: "Your task is to provide a clear explanation of the meaning and origin of an idioms and proverb that the user gives you. Offer a concise interpretation of its figurative meaning and how it is typically used in conversation or writing. Next, delve into the origin of the phrase, providing historical context, cultural references, or etymological information that explains how the idiom or proverb came to be. If there are any interesting stories, anecdotes, or theories associated with the origin, include those as well. Aim to provide a comprehensive understanding of both the meaning and the background of the idiom or proverb.", messages: [ { "role": "user", "content": [ { "type": "text", "text": "Break a leg" } ] } ] }); console.log(msg); ``` -------------------------------- ### Call Claude API using TypeScript SDK Source: https://platform.claude.com/docs/en/get-started This snippet demonstrates how to use the Anthropic TypeScript SDK to interact with the Claude API. It requires installing the SDK via npm. The code initializes the Anthropic client and prepares to make a call to the messages endpoint. This example focuses on the setup and the beginning of the API call structure. ```bash export ANTHROPIC_API_KEY='your-api-key-here' npm install @anthropic-ai/sdk ``` ```typescript import Anthropic from "@anthropic-ai/sdk"; async function main() { const anthropic = new Anthropic(); const msg = await anthropic.messages.create({ ``` -------------------------------- ### Deferred Tool Loading Example (JSON) Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool Demonstrates how to mark a tool for deferred loading by setting 'defer_loading' to true. This ensures the tool is only loaded into context when Claude discovers it via search, optimizing performance. ```json { "name": "get_weather", "description": "Get current weather for a location", "input_schema": { "type": "object", "properties": { "location": { "type": "string" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] }, "defer_loading": true } ``` -------------------------------- ### Create Spreadsheet using Anthropic API Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/quickstart These examples show how to create a quarterly sales tracking spreadsheet using the Anthropic API with the 'xlsx' skill. It utilizes the code execution tool and requires authentication with an API key. The request specifies the model, max tokens, and the skill to be used. ```python response = client.beta.messages.create( model="claude-opus-4-6", max_tokens=4096, betas=["code-execution-2025-08-25", "skills-2025-10-02"], container={ "skills": [ { "type": "anthropic", "skill_id": "xlsx", "version": "latest" } ] }, messages=[{ "role": "user", "content": "Create a quarterly sales tracking spreadsheet with sample data" }], tools=[{ "type": "code_execution_20250825", "name": "code_execution" }] ) ``` ```typescript const response = await client.beta.messages.create({ model: 'claude-opus-4-6', max_tokens: 4096, betas: ['code-execution-2025-08-25', 'skills-2025-10-02'], container: { skills: [ { type: 'anthropic', skill_id: 'xlsx', version: 'latest' } ] }, messages: [{ role: 'user', content: 'Create a quarterly sales tracking spreadsheet with sample data' }], tools: [{ type: 'code_execution_20250825', name: 'code_execution' }] }); ``` ```bash curl https://api.anthropic.com/v1/messages \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "anthropic-beta: code-execution-2025-08-25,skills-2025-10-02" \ -H "content-type: application/json" \ -d '{ "model": "claude-opus-4-6", "max_tokens": 4096, "container": { "skills": [ { "type": "anthropic", "skill_id": "xlsx", "version": "latest" } ] }, "messages": [{ "role": "user", "content": "Create a quarterly sales tracking spreadsheet with sample data" }], "tools": [{ "type": "code_execution_20250825", "name": "code_execution" }] }' ``` -------------------------------- ### Go Example: Create Text Completion with Anthropic SDK Source: https://platform.claude.com/docs/en/api/go/completions/create Demonstrates how to create a text completion using the Anthropic SDK for Go. It shows client initialization with an API key, calling the New completion method with parameters like MaxTokensToSample, Model, and Prompt, and handling potential errors. The example prints the ID of the generated completion. ```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"), ) completion, err := client.Completions.New(context.TODO(), anthropic.CompletionNewParams{ MaxTokensToSample: 256, Model: anthropic.ModelClaudeOpus4_6, Prompt: "\n\nHuman: Hello, world!\n\nAssistant:", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", completion.ID) } ``` -------------------------------- ### Web Fetch Tool Usage Example (JSON) Source: https://platform.claude.com/docs/en/about-claude/pricing This JSON example demonstrates the usage statistics when employing the web fetch tool. It highlights token counts for input and output, cache operations, and records one web fetch request. Notably, web fetch incurs no additional charges beyond standard token costs. ```json { "usage": { "input_tokens": 25039, "output_tokens": 931, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0, "server_tool_use": { "web_fetch_requests": 1 } } } ```