### Quickstart Setup Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/sentry/README.md Commands to initialize the environment and begin the interactive setup process with Claude. ```bash cd managed_agents/sentry uv sync claude "walk me through setting this up." ``` -------------------------------- ### Quickstart Installation and Execution Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/cma-mcp/README.md Installs dependencies and starts the CMA-MCP server. After running, ask Claude to 'walk me through setting this up.' ```bash cd managed_agents/cma-mcp bun install claude ``` -------------------------------- ### Quickstart Installation and Execution Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/linear/README.md Steps to install dependencies and run the Linear Managed Agent locally. Assumes you have Bun installed. ```bash cd managed_agents/linear bun install claude ``` -------------------------------- ### Initialize and Run the Roadtrip Planner Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/roadtrip_planner/README.md Commands to install dependencies, configure environment variables, and start the development server. ```bash cd managed_agents/roadtrip_planner npm install cp .env.example .env.local # fill in the three keys npm run setup # environment + 2 agents + vault + 2 credentials, ids -> .env.local npm run dev # http://localhost:3000 ``` -------------------------------- ### Install Modal CLI Source: https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb Initial setup for the Modal environment in the terminal. ```bash pip install modal modal setup ``` -------------------------------- ### Setup Virtual Environment and Dependencies Source: https://github.com/anthropics/claude-cookbooks/blob/main/tool_use/memory_cookbook.ipynb Commands to initialize a Python virtual environment and install project requirements. ```bash # 1. Create virtual environment python -m venv .venv # 2. Activate it source .venv/bin/activate # macOS/Linux # or: .venv\Scripts\activate # Windows # 3. Install dependencies pip install -r requirements.txt # 4. In VSCode: Select .venv as kernel (top right) ``` -------------------------------- ### Install Dependencies and Run Webhook Server Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/self_hosted_sandboxes/daytona/README.md Install the required Python packages and start the FastAPI server with the necessary environment variables. ```sh # standardwebhooks backs `client.beta.webhooks.unwrap()` — only the orchestrator # host needs it; the inner Daytona sandbox never sees raw webhook deliveries. pip install fastapi uvicorn daytona-sdk standardwebhooks anthropic export DAYTONA_API_KEY=... DAYTONA_API_URL=... export ANTHROPIC_WEBHOOK_SECRET=... \ ANTHROPIC_ENVIRONMENT_ID=env_... ANTHROPIC_ENVIRONMENT_KEY=sk-ant-oat... uvicorn daytona_webhook:app --host 0.0.0.0 --port 8080 ``` -------------------------------- ### Provision Agent Environment Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/roadtrip_planner/skill.md Install dependencies and run the setup script to configure the agent, vault, and environment variables. ```bash npm install npm run setup ``` -------------------------------- ### Install Libraries and Set Up Claude Client Source: https://github.com/anthropics/claude-cookbooks/blob/main/multimodal/using_sub_agents.ipynb Installs necessary Python libraries and initializes the Anthropic Claude API client. Ensure you have the libraries installed before running the client setup. ```python %pip install anthropic IPython PyMuPDF matplotlib ``` ```python # Import the required libraries import base64 import io import os from concurrent.futures import ThreadPoolExecutor import fitz import requests from anthropic import Anthropic from PIL import Image # Set up the Claude API client client = Anthropic() MODEL_NAME = "claude-haiku-4-5" ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/00_The_one_liner_research_agent.ipynb Install the necessary SDK and environment management packages. ```python %%capture %pip install -U claude-agent-sdk python-dotenv ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/05_Building_a_session_browser.ipynb Install the required SDK and utility packages for session management. ```python %%capture %pip install -U "claude-agent-sdk>=0.1.51" python-dotenv pandas ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/CMA_coordinate_specialist_team.ipynb Installs the necessary Anthropic SDK and dotenv library. Use this at the beginning of your project setup. ```python %%capture %pip install -q anthropic python-dotenv ``` -------------------------------- ### Set up development environment Source: https://github.com/anthropics/claude-cookbooks/blob/main/CONTRIBUTING.md Commands to create a virtual environment and install dependencies. ```bash # Create virtual environment and install dependencies uv sync --all-extras # Or with pip: pip install -e ".[dev]" ``` -------------------------------- ### Deploying the Kubernetes Quickstart Source: https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb Executes the local Kubernetes quickstart script to set up the agent environment with the required API key. ```bash cd hosting/kubernetes ANTHROPIC_API_KEY=sk-ant-... ./kind-quickstart.sh ``` -------------------------------- ### Set up Python Virtual Environment and Install Dependencies Source: https://github.com/anthropics/claude-cookbooks/blob/main/skills/CLAUDE.md Create and activate a virtual environment, then install project dependencies including the Anthropic SDK. Ensure you use the local wheel file for Skills support. ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -r requirements.txt ``` -------------------------------- ### Start Self-hosted Worker (using environment variables) Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/self_hosted_sandboxes/docs/usage-guide.md Start the 'ant' worker using environment variables for configuration. This is useful for systemd or compose setups. ```bash ANTHROPIC_ENVIRONMENT_ID=env_01... \ ANTHROPIC_ENVIRONMENT_KEY=sk-ant-oat01-... \ ant beta:worker poll --workdir /workspace ``` -------------------------------- ### Initialize Database and Run Evaluations Source: https://github.com/anthropics/claude-cookbooks/blob/main/capabilities/retrieval_augmented_generation/guide.ipynb Setup the summary-indexed database and execute retrieval and end-to-end evaluation pipelines. ```python # Initialize the SummaryIndexedVectorDB level_two_db = SummaryIndexedVectorDB("anthropic_docs_v2") level_two_db.load_data("data/anthropic_summary_indexed_docs.json") import pandas as pd # Run the evaluations avg_precision, avg_recall, avg_mrr, f1, precisions, recalls, mrrs = evaluate_retrieval( retrieve_level_two, eval_data, level_two_db ) e2e_accuracy, e2e_results = evaluate_end_to_end(answer_query_level_two, level_two_db, eval_data) # Create a DataFrame df = pd.DataFrame( { "question": [item["question"] for item in eval_data], "retrieval_precision": precisions, "retrieval_recall": recalls, "retrieval_mrr": mrrs, "e2e_correct": e2e_results, } ) # Save to CSV df.to_csv("evaluation/csvs/evaluation_results_detailed_level_two.csv", index=False) print("Detailed results saved to evaluation_results_detailed.csv") # Print the results print(f"Average Precision: {avg_precision:.4f}") print(f"Average Recall: {avg_recall:.4f}") print(f"Average MRR: {avg_mrr:.4f}") print(f"Average F1: {f1:.4f}") print(f"End-to-End Accuracy: {e2e_accuracy:.4f}") # Save the results to a file with open("evaluation/json_results/evaluation_results_level_two.json", "w") as f: json.dump( { "name": "Summary Indexing", "average_precision": avg_precision, "average_recall": avg_recall, "average_f1": f1, "average_mrr": avg_mrr, "end_to_end_accuracy": e2e_accuracy, }, f, indent=2, ) print( "Evaluation complete. Results saved to evaluation_results_level_two.json, evaluation_results_detailed_level_two.csv" ) ``` -------------------------------- ### Install Dependencies and Configure Environment Source: https://github.com/anthropics/claude-cookbooks/blob/main/capabilities/knowledge_graph/evaluation/README.md Prepare the environment by installing project dependencies and setting the required API key. ```bash uv sync --all-extras cp .env.example .env # then edit .env to add ANTHROPIC_API_KEY ``` -------------------------------- ### Initialize Environment Variables Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/roadtrip_planner/skill.md Copy the example environment file to a local configuration file to store API keys. ```bash cp .env.example .env.local # then fill in the three keys ``` -------------------------------- ### Start Development Server Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/roadtrip_planner/skill.md Command to launch the local development environment. ```bash npm run dev ``` -------------------------------- ### Iterative Coding Loop Setup Source: https://github.com/anthropics/claude-cookbooks/blob/main/patterns/agents/evaluator_optimizer.ipynb Sets up the prompts for code generation and evaluation, and initiates the iterative loop. This is the starting point for the code generation process. ```python evaluator_prompt = """ Evaluate this following code implementation for: 1. code correctness 2. time complexity 3. style and best practices You should be evaluating only and not attemping to solve the task. Only output "PASS" if all criteria are met and you have no further suggestions for improvements. Output your evaluation concisely in the following format. PASS, NEEDS_IMPROVEMENT, or FAIL What needs improvement and why. " generator_prompt = """ Your goal is to complete the task based on . If there are feedback from your previous generations, you should reflect on them to improve your solution Output your answer concisely in the following format: [Your understanding of the task and feedback and how you plan to improve] [Your code implementation here] " task = """ Implement a Stack with: 1. push(x) 2. pop() 3. getMin() All operations should be O(1). " loop(task, evaluator_prompt, generator_prompt) ``` -------------------------------- ### Define Get Team Members Tool Source: https://github.com/anthropics/claude-cookbooks/blob/main/tool_use/programmatic_tool_calling_ptc.ipynb Defines the 'get_team_members' tool, which retrieves a list of team members for a specified department. It includes schema for input and example calls. ```python { "name": "get_team_members", "description": 'Returns a list of team members for a given department. Each team member includes their ID, name, role, level (junior, mid, senior, staff, principal), and contact information. Use this to get a list of people whose expenses you want to analyze. Available departments are: engineering, sales, and marketing.\n\nRETURN FORMAT: Returns a JSON string containing an ARRAY of team member objects (not wrapped in an outer object). Parse with json.loads() to get a list. Example: [{"id": "ENG001", "name": "Alice", ...}, {"id": "ENG002", ...}]', "input_schema": { "type": "object", "properties": { "department": { "type": "string", "description": "The department name. Case-insensitive." } }, "required": ["department"] }, "input_examples": [ {"department": "engineering"}, {"department": "sales"}, {"department": "marketing"} ] } ``` -------------------------------- ### Initialize Project Environment Source: https://github.com/anthropics/claude-cookbooks/blob/main/CLAUDE.md Commands to install dependencies, pre-commit hooks, and configure the API key environment. ```bash # Install dependencies uv sync --all-extras # Install pre-commit hooks uv run pre-commit install # Set up API key cp .env.example .env # Edit .env and add your ANTHROPIC_API_KEY ``` -------------------------------- ### Get Test Data Source: https://github.com/anthropics/claude-cookbooks/blob/main/misc/generate_test_cases.ipynb Generates test data using a prompt template, user examples, and planning text. This function is central to the test case generation process. ```python result = get_test_data(prompt_template, USER_EXAMPLES, planning_text) ``` -------------------------------- ### Define Get Expenses Tool Source: https://github.com/anthropics/claude-cookbooks/blob/main/tool_use/programmatic_tool_calling_ptc.ipynb Defines the 'get_expenses' tool for fetching approved expense line items for an employee in a specific quarter. It details the schema and provides example queries. ```python { "name": "get_expenses", "description": "Returns all expense line items for a given employee in a specific quarter. Each expense includes extensive metadata: date, category, description, amount (in USD), currency, status (approved, pending, rejected), receipt URL, approval chain, merchant name and location, payment method, and project codes. An employee may have 20-50+ expense line items per quarter, and each line item contains substantial metadata for audit and compliance purposes. Categories include: 'travel' (flights, trains, rental cars, taxis, parking), 'lodging' (hotels, airbnb), 'meals', 'software', 'equipment', 'conference', 'office', and 'internet'. IMPORTANT: Only expenses with status='approved' should be counted toward budget limits.\n\nRETURN FORMAT: Returns a JSON string containing an ARRAY of expense objects (not wrapped in an outer object with an 'expenses' key). Parse with json.loads() to get a list directly. Example: [{"expense_id": "ENG001_Q3_001", "amount": 1250.50, "category": "travel", ...}, {...}]", "input_schema": { "type": "object", "properties": { "employee_id": { "type": "string", "description": "The unique employee identifier" }, "quarter": { "type": "string", "description": "Quarter identifier: 'Q1', 'Q2', 'Q3', or 'Q4'" } }, "required": ["employee_id", "quarter"] }, "input_examples": [ {"employee_id": "ENG001", "quarter": "Q3"}, {"employee_id": "SAL002", "quarter": "Q1"}, {"employee_id": "MKT001", "quarter": "Q4"} ] } ``` -------------------------------- ### Slack Managed Agents Quickstart Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/slack/README.md Commands to set up and run the Slack Managed Agents integration locally. Requires Node.js and the Anthropic SDK. ```bash cd managed_agents/slack bun install claude ``` -------------------------------- ### Define Get Custom Budget Tool Source: https://github.com/anthropics/claude-cookbooks/blob/main/tool_use/programmatic_tool_calling_ptc.ipynb Defines the 'get_custom_budget' tool to check for custom quarterly travel budgets for employees. It specifies the input schema and provides example user IDs. ```python { "name": "get_custom_budget", "description": 'Get the custom quarterly travel budget for a specific employee. Most employees have a standard $5,000 quarterly travel budget. However, some employees have custom budget exceptions based on their role requirements. This function checks if a specific employee has a custom budget assigned.\n\nRETURN FORMAT: Returns a JSON string containing a SINGLE OBJECT (not an array). Parse with json.loads() to get a dict. Example: {"user_id": "ENG001", "has_custom_budget": false, "travel_budget": 5000, "reason": "Standard", "currency": "USD"}', "input_schema": { "type": "object", "properties": { "user_id": { "type": "string", "description": "The unique employee identifier" } }, "required": ["user_id"] }, "input_examples": [ {"user_id": "ENG001"}, {"user_id": "SAL002"}, {"user_id": "MKT001"} ] } ``` -------------------------------- ### Canary C Code Example Source: https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/06_The_vulnerability_detection_agent.ipynb This C code contains three deliberately planted memory-safety bugs: a heap buffer overflow, a stack buffer overflow, and a use-after-free. Each bug is reachable through a different 'magic byte' at the start of the input. ```c // canary.c // Entry: ./canary #include #include #include static void parse_alpha(const unsigned char *data, size_t len) { unsigned char *buf = malloc(32); memcpy(buf, data, len); printf("alpha: %02x\n", buf[0]); free(buf); } static void parse_bravo(const unsigned char *data, size_t len) { char name[16]; memcpy(name, data, len); name[15] = 0; printf("bravo: %s\n", name); } static void parse_charlie(const unsigned char *data, size_t len) { char *p = malloc(64); if (len > 0 && data[0] == 0xff) { free(p); } memcpy(p, data, len < 64 ? len : 64); printf("charlie: %p\n", (void *)p); } int main(int argc, char **argv) { if (argc < 2) return 1; FILE *f = fopen(argv[1], "rb"); if (!f) return 1; unsigned char buf[4096]; size_t n = fread(buf, 1, sizeof buf, f); fclose(f); if (n < 1) return 1; switch (buf[0]) { case 'A': parse_alpha(buf + 1, n - 1); break; case 'B': parse_bravo(buf + 1, n - 1); break; case 'C': parse_charlie(buf + 1, n - 1); break; default: printf("unknown format\n"); } return 0; } ``` -------------------------------- ### Deploy to local kind cluster Source: https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/hosting/kubernetes/README.md Initializes the environment, builds images, and starts the gateway service. ```bash cd hosting/kubernetes export ANTHROPIC_API_KEY=sk-ant-... ./kind-quickstart.sh ``` -------------------------------- ### Example Usage of Guided Legal Summary Source: https://github.com/anthropics/claude-cookbooks/blob/main/capabilities/summarization/guide.ipynb This Python code snippet demonstrates how to call the 'guided_legal_summary' function with a 'text' variable and print the resulting summary. Ensure the 'text' variable is defined and populated with the legal document content before execution. ```python # Example usage legal_summary = guided_legal_summary(text) print(legal_summary) ``` -------------------------------- ### Python Function for Multishot Summarization Source: https://github.com/anthropics/claude-cookbooks/blob/main/capabilities/summarization/guide.ipynb This Python function utilizes few-shot learning to summarize text. It takes the text to be summarized and an optional max_tokens parameter. The function constructs a prompt that includes the text and several examples of original documents paired with their summaries to guide the model's output. ```python from data.multiple_subleases import document1, document2, document3, sample1, sample2, sample3 def basic_summarize_multishot(text, max_tokens=1000): # Prompt the model to summarize the text prompt = f"""Summarize the following text in bullet points. Focus on the main ideas and key details: {text} Do not preamble. Use these examples for guidance in summarizing: {document1} {sample1} {document2} {sample2} {document3} {sample3} """ response = client.messages.create( model="claude-sonnet-4-6", max_tokens=max_tokens, system="You are a legal analyst known for highly accurate and detailed summaries of legal documents.", messages=[ {"role": "user", "content": prompt}, { "role": "assistant", "content": "Here is the summary of the legal document: ", }, ], stop_sequences=[""], ) return response.content[0].text ``` ```python basic_multishot_response = basic_summarize_multishot(text, max_tokens=1000) print(basic_multishot_response) ``` -------------------------------- ### Deploy to E2B Source: https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb Initialize a sandbox from a pre-built template and run the entrypoint script in the background. ```python from e2b import Sandbox sbx = Sandbox(template="research-agent") # template built from hosting/Dockerfile sbx.commands.run("./hosting/entrypoint.sh serve", background=True) url = sbx.get_host(8000) ``` -------------------------------- ### Environment Setup and Library Imports Source: https://github.com/anthropics/claude-cookbooks/blob/main/skills/notebooks/03_skills_custom_development.ipynb Sets up the Python environment by importing necessary libraries, configuring API keys, and initializing the Anthropic client with the Skills beta. Ensure your ANTHROPIC_API_KEY is set in your .env file. ```python import os import sys from pathlib import Path from typing import Any # Add parent directory for imports sys.path.insert(0, str(Path.cwd().parent)) from anthropic import Anthropic from anthropic.lib import files_from_dir from dotenv import load_dotenv # Import our utilities from file_utils import ( download_all_files, extract_file_ids, print_download_summary, ) # We'll create skill_utils later in this notebook # from skill_utils import ( # create_skill, # list_skills, # delete_skill, # test_skill # ) # Load environment variables load_dotenv(Path.cwd().parent / ".env") API_KEY = os.getenv("ANTHROPIC_API_KEY") MODEL = os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-6") if not API_KEY: raise ValueError( "ANTHROPIC_API_KEY not found. Copy ../.env.example to ../.env and add your API key." ) # Initialize client with Skills beta client = Anthropic(api_key=API_KEY, default_headers={"anthropic-beta": "skills-2025-10-02"}) # Setup directories SKILLS_DIR = Path.cwd().parent / "custom_skills" OUTPUT_DIR = Path.cwd().parent / "outputs" OUTPUT_DIR.mkdir(exist_ok=True) print("✓ API key loaded") print(f"✓ Using model: {MODEL}") print(f"✓ Custom skills directory: {SKILLS_DIR}") print(f"✓ Output directory: {OUTPUT_DIR}") print("\n📝 Skills beta header configured for skill management") ``` -------------------------------- ### Query Claude with Custom Documents and User Question Source: https://github.com/anthropics/claude-cookbooks/blob/main/misc/using_citations.ipynb This Python code snippet demonstrates how to use the Anthropic API to get a response from Claude. It sends custom documents and a user question to the API, then prints the raw and formatted responses, including citations. Ensure you have the 'anthropic' library installed and your API key configured. ```python import anthropic QUESTION = "I just checked out, where is my order tracking number? Track package is not available on the website yet for my order." client = anthropic.Anthropic() custom_content_response = client.messages.create( model="claude-sonnet-4-6", temperature=0.0, max_tokens=1024, system="You are a customer support bot working for PetWorld. Your task is to provide short, helpful answers to user questions. Since you are in a chat interface avoid providing extra details. You will be given access to PetWorld's help center articles to help you answer questions.", messages=[ {"role": "user", "content": documents}, { "role": "user", "content": [{"type": "text", "text": f"Here is the user's question: {QUESTION}"}] }, ], ) print(visualize_raw_response(custom_content_response)) print(visualize_citations(custom_content_response)) ``` -------------------------------- ### Initialize client and helper functions Source: https://github.com/anthropics/claude-cookbooks/blob/main/multimodal/best_practices_for_vision.ipynb Setup the Anthropic client and a helper function to convert local image files into base64 encoded strings. ```python import base64 from anthropic import Anthropic from IPython.display import Image client = Anthropic() MODEL_NAME = "claude-opus-4-1" def get_base64_encoded_image(image_path): with open(image_path, "rb") as image_file: binary_data = image_file.read() base_64_encoded_data = base64.b64encode(binary_data) base64_string = base_64_encoded_data.decode("utf-8") return base64_string ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-cookbooks/blob/main/capabilities/text_to_sql/guide.ipynb Installs necessary Python libraries for the project. Restart the kernel if prompted after installation. ```python %pip install -q anthropic pandas voyageai matplotlib seaborn ``` -------------------------------- ### Configure Agent, Environment, and Session Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/CMA_explore_unfamiliar_codebase.ipynb Creates the agent with exploration instructions, sets up a cloud environment, and initializes a session with the repository resource mounted. ```python agent = client.beta.agents.create( name="cookbook-explore", model=MODEL, system=( "You are onboarding to an unfamiliar codebase. Explore before " "answering, docs can be stale. Verify what you read against " "actual code structure. Write notes to /tmp/NOTES.md as you go." ), tools=[ { "type": "agent_toolset_20260401", "default_config": { "enabled": True, "permission_policy": {"type": "always_allow"}, }, } ], ) env = client.beta.environments.create( name="cookbook-explore-env", config={"type": "cloud", "networking": {"type": "limited"}}, ) session = client.beta.sessions.create( environment_id=env.id, agent={"type": "agent", "id": agent.id, "version": agent.version}, resources=[{"type": "file", "file_id": fixture_zip.id, "mount_path": "repo.zip"}], title="Onboard to repo", ) print(f"session: {session.id}") ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-cookbooks/blob/main/multimodal/crop_tool.ipynb Installs the necessary libraries: anthropic, pillow, and datasets. A kernel restart might be required after installation. ```python %pip install -q anthropic pillow datasets ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/README.md Installs the uv package manager using a curl script. Ensure Node.js is installed separately. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Python: Before - Webhook Example Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/self_hosted_sandboxes/docs/upgrade-guide.md Shows the previous method for handling webhooks using `client.beta.environments.work.poller` and manually spawning sandbox processes. ```python # BEFORE client = anthropic.AsyncAnthropic(auth_token=os.environ["ANTHROPIC_ENV_KEY"]) async for work, secret in client.beta.environments.work.poller( environment_id=os.environ["ANTHROPIC_ENVIRONMENT_ID"], service_key=os.environ["ANTHROPIC_ENV_KEY"], block_ms=None, reclaim_older_than_ms=2000, drain=True, auto_stop=False, ): if work.data.type != "session": continue spawned.append(spawn_sandbox( session_id=work.data.id, work_id=work.id, environment_id=work.environment_id, sessions_token=secret.sessions_token, )) ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-cookbooks/blob/main/tool_use/memory_cookbook.ipynb Installs necessary Python packages for using the Anthropic API and environment variables. Use requirements.txt for a pre-defined list or install directly. ```python %%capture # Install required packages # Option 1: From requirements.txt # %pip install -q -r requirements.txt # Option 2: Direct install %pip install -q anthropic python-dotenv ipykernel ``` -------------------------------- ### Environment and Deployment Commands Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/sentry/skill.md Commands for setting up the environment, deploying the agent, and executing manual runs. ```bash cp .env.example .env ``` ```bash uv run python setup_agent.py ``` ```bash uv run python deploy.py ``` ```bash uv run python run_now.py ``` ```bash uv run python runs.py ``` ```bash uv run python update_agent.py ``` ```bash uv run python teardown.py ``` -------------------------------- ### Run Infrastructure Setup Script Source: https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/03_The_site_reliability_agent.ipynb Executes the infra_setup.py script to generate the local environment. Ensure the script is in the same directory as the notebook. ```python assert os.path.exists("infra_setup.py"), \ ("infra_setup.py not found — ensure both setup scripts are in the same directory as this notebook.") subprocess.run([sys.executable, "infra_setup.py"], check=True) ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-cookbooks/blob/main/third_party/ElevenLabs/low_latency_stt_claude_tts.ipynb Install the necessary Python packages for the project. ```python %pip install --upgrade pip ``` ```python %pip install -r requirements.txt ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-cookbooks/blob/main/managed_agents/CMA_prompt_versioning_and_rollback.ipynb Install the required Python packages for the cookbook. ```python %%capture %pip install -q "anthropic>=0.91.0" python-dotenv ``` -------------------------------- ### Install Anthropic Library Source: https://github.com/anthropics/claude-cookbooks/blob/main/misc/read_web_pages_with_haiku.ipynb Install the required Anthropic Python library. ```python # Install the necessary libraries %pip install anthropic ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/anthropics/claude-cookbooks/blob/main/tool_use/memory_cookbook.ipynb Sets up the .env file by copying the example and adding your Anthropic API key. This is crucial for authenticating API requests. ```bash # Copy .env.example to .env and add your API key cp .env.example .env ``` -------------------------------- ### Initialize Environment and Client Source: https://github.com/anthropics/claude-cookbooks/blob/main/tool_use/context_engineering/context_engineering_tools.ipynb Load environment variables, verify the corpus file, and initialize the Anthropic client. ```python import json import os import tempfile from collections import namedtuple from pathlib import Path import anthropic import matplotlib.pyplot as plt from dotenv import load_dotenv load_dotenv() if not os.environ.get("ANTHROPIC_API_KEY"): raise ValueError("ANTHROPIC_API_KEY not set. Add it to a .env file or export it.") CORPUS_PATH = Path("research_corpus.py") assert CORPUS_PATH.exists(), ( f"research_corpus.py not found in {Path.cwd()}. It should be alongside this notebook." ) client = anthropic.Anthropic() MODEL = "claude-sonnet-4-6" print(f"anthropic SDK {anthropic.__version__}, model {MODEL}") ```