What Is the Claude API and Why Should Engineers Use It?
The Claude API gives you programmatic access to Anthropic's Claude language models. Rather than using the Claude.ai chat interface manually, you can integrate Claude directly into your own tools, scripts, and applications. For engineers, this opens up a wide range of automation possibilities:
- Automate repetitive calculations and document generation
- Build internal tools that analyze specifications, drawings, or sensor data
- Generate RFI drafts, submittals, and reports from structured data
- Ask Claude questions about NEC code sections or engineering standards with relevant context
- Analyze electrical schematics, P&IDs, or structural drawings via Claude's vision capabilities
Getting Started: Account, API Key, and Credits
- Visit console.anthropic.com and create an Anthropic account.
- Navigate to the API Keys section and generate a new API key. Store this key securely — treat it like a password. Never commit it to a public repository.
- Add credits to your account or set up billing. Claude API usage is billed per token (see pricing below).
Best practice: store your API key as an environment variable rather than hardcoding it in your scripts:
export ANTHROPIC_API_KEY="your-key-here"
Available Models in 2026
Anthropic offers several Claude models through the API. Choose based on your task complexity and cost requirements:
- claude-sonnet-4-6 — Best balance of speed and intelligence. $3.00 input / $15.00 output per million tokens. Recommended default for most engineering applications. 1M token context window, 64K max output.
- claude-opus-4-8 — Most capable model for demanding reasoning and long-horizon tasks. $5.00 / $25.00 per million tokens. Use when maximum reasoning quality matters. 1M token context window, 128K max output.
- claude-haiku-4-5 — Fastest and cheapest. $1.00 / $5.00 per million tokens. 200K context window. Ideal for high-volume classification, extraction, or simple query tasks where cost matters most.
Installing the Python SDK
pip install anthropic
The official Anthropic Python SDK is the recommended way to make API calls from Python. It handles authentication, request formatting, retries, and error handling automatically.
Your First API Call
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from environment
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "What is the minimum burial depth for a 120V residential circuit in a conduit per NEC 300.5?"}
]
)
print(message.content[0].text)
The response arrives as a Message object. The text content is in message.content[0].text. The max_tokens parameter sets an upper limit on how long the response can be — increase it for longer outputs.
Key API Parameters
- model: The Claude model to use (e.g.,
"claude-sonnet-4-6") - max_tokens: Maximum number of tokens in the response. Set higher for longer outputs — 1,024 for short answers, 4,096–8,192 for detailed explanations or code, up to 64,000 for Sonnet 4.6.
- messages: A list of conversation turns with
role("user" or "assistant") andcontent - system: Optional system prompt that sets the AI's persona and behavioral constraints (see below)
- temperature: Controls randomness.
0gives deterministic, consistent output.1gives more creative, varied output. For engineering tasks, use0for reliable results. Note: temperature is not supported on all models — check documentation for your target model.
System Prompts for Engineering Use
A system prompt defines Claude's role, behavior, and constraints before any user message. For engineering applications, a well-crafted system prompt significantly improves response quality and consistency:
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=2048,
system="""You are an expert electrical engineer specializing in the National Electrical Code (NEC).
When answering questions about code requirements:
1. Always cite the specific NEC article and section
2. Distinguish between requirements (shall) and recommendations (should)
3. Note if requirements vary by occupancy type or installation method
4. Flag when a question may require interpretation by the Authority Having Jurisdiction (AHJ)
Respond in clear, professional language appropriate for a licensed engineer.""",
messages=[
{"role": "user", "content": "What are the requirements for ground fault circuit interrupter (GFCI) protection in a commercial kitchen?"}
]
)
print(message.content[0].text)
Prompt Engineering for Technical Tasks
The quality of Claude's output depends heavily on how you phrase your prompt. For engineering tasks:
- Be specific about format: Ask for "a numbered list of steps" or "a table with columns for load, voltage, ampacity, and wire size"
- Include relevant context: If asking about a calculation, provide the relevant parameters, standards being followed, and jurisdiction
- Reference specific standards: "Per NEC 2023 Article 210..." or "Per ASHRAE 90.1-2022..."
- Specify your audience: "Explain for a PE stamping the design" vs "Explain for a journeyman electrician"
Using Vision: Sending Images to Claude
Claude can analyze images, including engineering drawings, P&IDs, schematics, and photographs of installations. This opens up use cases like reviewing a drawing for obvious errors or extracting data from a diagram.
import anthropic
import base64
client = anthropic.Anthropic()
# Read and encode image as base64
with open("electrical_panel_schedule.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=2048,
messages=[{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": image_data
}
},
{
"type": "text",
"text": "Review this electrical panel schedule. Identify any circuits that appear to exceed standard branch circuit ratings, any unusual load groupings, and confirm the total connected load calculation appears reasonable for the panel rating shown."
}
]
}]
)
print(message.content[0].text)
Claude can also receive images via URL if they are publicly accessible, using "type": "url" and "url": "https://..." instead of the base64 approach.
Document Processing: Analyzing PDFs and Specifications
For longer documents like spec sections or data sheets, paste the relevant text directly into your prompt. Claude's large context window (up to 1M tokens for Sonnet 4.6) means you can include entire document sections:
import anthropic
client = anthropic.Anthropic()
# Read the spec section text from a file
with open("spec_section_16470.txt", "r") as f:
spec_text = f.read()
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=4096,
system="You are an electrical engineer reviewing project specifications. Extract requirements clearly and flag any ambiguities or potential conflicts.",
messages=[{
"role": "user",
"content": f"""Review the following specification section and extract:
1. All submittal requirements with deadlines
2. Equipment standards and listing requirements
3. Testing and commissioning requirements
4. Any requirements that conflict with typical NEC installations
SPECIFICATION TEXT:
{spec_text}"""
}]
)
print(message.content[0].text)
Practical Engineering Use Cases with Code Examples
1. NEC Code Question Answering with Context
import anthropic
client = anthropic.Anthropic()
nec_section = """
NEC 210.12(A) - Dwelling Unit Bedrooms
All branch circuits that supply 120-volt, single-phase, 15- and 20-ampere
outlets installed in dwelling unit bedrooms shall have ground-fault circuit
interrupter protection for personnel.
"""
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{
"role": "user",
"content": f"""Given this NEC code section:
{nec_section}
Question: Does this requirement apply to a 240V dedicated circuit for a window air conditioner installed in a bedroom?"""
}]
)
print(message.content[0].text)
2. Generating a Python Script for Load Calculations
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=4096,
system="You are an expert electrical engineer. Write clean, well-commented Python code.",
messages=[{
"role": "user",
"content": """Write a Python script that calculates the minimum service entrance size for a
single-family dwelling using the NEC 220.82 optional calculation method.
The script should accept inputs for:
- Square footage of conditioned space
- Number of small appliance circuits
- Number of laundry circuits
- List of fixed appliance loads in watts
- Air conditioning load in watts
- Heating load in watts (electric)
And output the calculated demand load in VA and recommended service size in amps."""
}]
)
print(message.content[0].text)
3. Analyzing CSV Sensor Data
import anthropic
import csv
client = anthropic.Anthropic()
# Read sensor data from CSV
sensor_data = []
with open("power_meter_readings.csv", "r") as f:
reader = csv.DictReader(f)
sensor_data = list(reader)
# Format data as text for Claude
data_text = "
".join([f"Timestamp: {row['timestamp']}, kW: {row['demand_kw']}, PF: {row['power_factor']}"
for row in sensor_data[:100]]) # First 100 rows
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=2048,
messages=[{
"role": "user",
"content": f"""Analyze this power meter data from a commercial building:
{data_text}
Identify:
1. Peak demand and when it occurred
2. Average power factor and whether it indicates a problem
3. Any anomalous readings that warrant investigation
4. Recommendations for demand reduction"""
}]
)
print(message.content[0].text)
4. Drafting RFIs from Template Data
import anthropic
client = anthropic.Anthropic()
rfi_data = {
"project": "Riverside Medical Center Expansion",
"spec_section": "16470",
"drawing_ref": "E-201",
"subject": "Panelboard location conflict with mechanical equipment",
"description": "Electrical panelboard LP-2A shown on drawing E-201 conflicts with ductwork shown on M-105. The panelboard requires 36 inches of working clearance per NEC 110.26, but the ductwork as shown would leave only 18 inches.",
"question": "Please confirm revised location for panelboard LP-2A or provide revised mechanical drawings showing ductwork relocation."
}
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
system="You are an electrical project engineer drafting professional RFI documents for construction projects. Write in formal, precise language.",
messages=[{
"role": "user",
"content": f"""Draft a formal RFI (Request for Information) using these details:
Project: {rfi_data['project']}
Spec Section: {rfi_data['spec_section']}
Drawing Reference: {rfi_data['drawing_ref']}
Subject: {rfi_data['subject']}
Issue Description: {rfi_data['description']}
Question: {rfi_data['question']}
Format as a professional RFI document suitable for submission to the Engineer of Record."""
}]
)
print(message.content[0].text)
Token Counting and Cost Estimation
Before running large API calls, you can count tokens to estimate cost:
import anthropic
client = anthropic.Anthropic()
# Count tokens before sending
response = client.messages.count_tokens(
model="claude-sonnet-4-6",
messages=[{"role": "user", "content": your_prompt_text}]
)
input_tokens = response.input_tokens
estimated_input_cost = input_tokens * 0.000003 # $3.00 per million tokens
print(f"Estimated input tokens: {input_tokens}")
print(f"Estimated input cost: ${estimated_input_cost:.4f}")
Streaming Responses for Real-Time Output
For long responses, streaming lets you display text as it is generated rather than waiting for the complete response:
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=8192,
messages=[{"role": "user", "content": "Write a detailed specification section for a 480V switchboard..."}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final_message = stream.get_final_message()
print(f"
Tokens used: {final_message.usage.output_tokens}")
Error Handling and Rate Limits
import anthropic
import time
client = anthropic.Anthropic()
def call_claude_with_retry(prompt, max_retries=3):
for attempt in range(max_retries):
try:
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
return message.content[0].text
except anthropic.RateLimitError as e:
if attempt < max_retries - 1:
wait_time = 60
print(f"Rate limited. Waiting {wait_time}s before retry...")
time.sleep(wait_time)
else:
raise
except anthropic.BadRequestError as e:
print(f"Bad request: {e.message}")
raise
except anthropic.APIConnectionError:
print("Connection error. Check your internet connection.")
raise
The Anthropic SDK automatically retries rate limits and server errors with exponential backoff (up to 2 retries by default). The code above adds a manual retry layer for rate limits that exceed the SDK's built-in handling.
Safety and Data Handling Considerations
- API keys: Never hardcode API keys in source code. Use environment variables or a secrets management system.
- Sensitive project data: Review your organization's policies before sending proprietary project data to any cloud API. Anthropic's API terms govern data handling — review the current privacy policy at anthropic.com.
- Output verification: Always verify AI-generated engineering calculations and code interpretations. Claude can make errors, particularly on edge cases or ambiguous code language. Treat AI output as a knowledgeable assistant, not as a licensed engineer providing professional judgments.
- Version control: Pin to a specific model version in production scripts to avoid unexpected behavior changes when Anthropic releases model updates.
Claude Code CLI for Engineering Workflows
For engineers who write scripts and build tools, the Claude Code CLI (claude) provides a terminal-based interface to Claude that can read files, run code, and assist with software development workflows directly from your command line. Install it via npm:
npm install -g @anthropic-ai/claude-code
Claude Code can assist with engineering Python scripts, review code, help debug analysis tools, and navigate codebases — making it a natural addition to any engineer's development environment.