benefits of an SDKâsuch as structured streaming, tool definitions, and async iterationâwhile routing traffic through the subscription pipeline.
Furthermore, the Agent SDK maintains feature parity with the standard SDK for core interactions. Developers can still access streaming responses, tool use, and message parsing. The only significant constraint is the authentication vector; the SDK does not support hybrid billing. It is imperative to ensure that environment variables do not conflict, as the presence of an API key will silently override the OAuth token, reverting billing to the pay-as-you-go model without warning.
Core Solution
To implement subscription-based billing for your scripts, follow this implementation workflow. This example demonstrates a Python-based setup using the Agent SDK with robust environment validation.
Step 1: Install Dependencies
Install the Claude Code CLI globally to manage token generation, and install the Agent SDK in your project environment.
# Install CLI for token management
npm install -g @anthropic-ai/claude-code
# Install Agent SDK in your project
pip install claude-agent-sdk python-dotenv
Generate a long-lived OAuth token and store it securely in your environment configuration.
# Launch browser authentication flow
claude setup-token
Copy the resulting token and add it to your .env file:
CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-<your_token_here>
Step 3: Implement Subscription-Aware Script
The following Python example demonstrates a safe implementation. It includes a validation step to prevent API key shadowing and utilizes the Agent SDK for streaming responses.
import os
import asyncio
from dotenv import load_dotenv
from claude_agent_sdk import query, ClaudeAgentOptions
from claude_agent_sdk.messages import AssistantMessage, TextBlock
load_dotenv()
def ensure_subscription_auth():
"""Validate that API keys are not shadowing the OAuth token."""
if os.environ.get("ANTHROPIC_API_KEY"):
raise RuntimeError(
"Authentication Conflict: ANTHROPIC_API_KEY is detected. "
"This variable overrides subscription billing. "
"Please unset this variable to use your Pro/Max quota."
)
if not os.environ.get("CLAUDE_CODE_OAUTH_TOKEN"):
raise RuntimeError(
"Missing OAuth Token: CLAUDE_CODE_OAUTH_TOKEN is not set. "
"Run 'claude setup-token' to generate credentials."
)
async def run_subscription_query(prompt: str) -> str:
"""Execute a query against the subscription quota."""
ensure_subscription_auth()
full_response = ""
# Stream response tokens
async for message in query(
prompt=prompt,
options=ClaudeAgentOptions(allowed_tools=[])
):
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, TextBlock):
full_response += block.text
return full_response
async def main():
try:
result = await run_subscription_query("Explain the difference between OAuth and API key authentication in one paragraph.")
print("Response:", result)
except RuntimeError as e:
print(f"Configuration Error: {e}")
if __name__ == "__main__":
asyncio.run(main())
This implementation ensures that your script explicitly checks for authentication conflicts before execution, providing immediate feedback if the environment is misconfigured. The streaming loop captures the response efficiently while billing against your subscription.
Pitfall Guide
-
Silent API Key Shadowing
- Issue: If
ANTHROPIC_API_KEY is present in the environment, the SDK prioritizes it over the OAuth token. This results in API credit consumption without any error message.
- Fix: Always unset
ANTHROPIC_API_KEY in scripts intended for subscription billing. Use the validation function shown in the Core Solution to enforce this.
-
Production Multi-User Deployment
- Issue: Using OAuth tokens in a production application serving multiple users violates Anthropic's Terms of Service and exposes your subscription to abuse.
- Fix: Reserve OAuth tokens for personal, local scripts. For production applications, switch to
ANTHROPIC_API_KEY and implement proper usage metering.
-
Token Expiration Management
- Issue: OAuth tokens generated via
claude setup-token have a limited lifespan (typically one year). Scripts may fail silently or with authentication errors after expiration.
- Fix: Implement token rotation procedures or set calendar reminders to regenerate tokens annually. Monitor authentication errors in logs.
-
Environment Variable Pollution
- Issue: Global environment variables from other projects may leak into your script's context, causing unexpected billing behavior.
- Fix: Use project-specific
.env files and load them explicitly. Avoid exporting credentials in shell profiles unless necessary.
-
Incorrect SDK Selection
- Issue: Developers may install the standard
anthropic package, which does not support OAuth authentication.
- Fix: Ensure you install
claude-agent-sdk (Python) or @anthropic-ai/claude-agent-sdk (TypeScript). Verify the package name in your dependency manager.
-
Rate Limit Violations
- Issue: Subscription quotas have different rate limits compared to API credits. Aggressive looping in scripts may trigger rate limit errors.
- Fix: Implement backoff strategies and throttle request rates in your scripts. Monitor for
429 responses and adjust concurrency accordingly.
-
Security Leakage
- Issue: Committing the OAuth token to version control exposes your subscription to unauthorized access.
- Fix: Add
.env to your .gitignore file. Never hardcode tokens in source files. Use secret management tools for sensitive credentials.
Production Bundle
Action Checklist
Decision Matrix
| Scenario | Recommended Auth | SDK Choice | Notes |
|---|
| Personal Automation Script | OAuth Token | Agent SDK | Cost-effective; Uses subscription quota. |
| Local Prototype / Hackathon | OAuth Token | Agent SDK | Rapid setup; No credit card required. |
| Production Web Application | API Key | Standard SDK | Scalable; Compliant with ToS. |
| CI/CD Pipeline | API Key | Standard SDK | Secure; Isolated from personal quota. |
| Multi-User SaaS | API Key | Standard SDK | Mandatory; OAuth prohibited for multi-tenancy. |
Configuration Template
Create a .env.example file to document required variables:
# Subscription Authentication (Personal Use Only)
# Generate via: claude setup-token
CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-...
# API Authentication (Production Use)
# Generate via: console.anthropic.com
# ANTHROPIC_API_KEY=sk-ant-api03-...
Quick Start Guide
- Initialize: Run
claude setup-token to generate your OAuth credentials.
- Configure: Add the token to your
.env file as CLAUDE_CODE_OAUTH_TOKEN.
- Code: Import
query from claude_agent_sdk and execute your prompt.
- Verify: Ensure
ANTHROPIC_API_KEY is not set to avoid billing conflicts.
- Run: Execute your script; requests will now consume your subscription quota.