AI Agent API Keys: Setup, Security, and Best Practices
API keys are the bridge between your AI agent and the language models that power it. They authenticate your agent with model providers like OpenAI, Anthropic, and Google, and they determine how usage is billed back to you.
Getting API keys right is more important than most people realize. A misconfigured key means your agent cannot work. An insecure key could mean unauthorized charges on your account. A poorly managed key makes cost tracking and troubleshooting harder than it needs to be.
This guide covers everything you need to know about API keys for AI agents: how to generate them, how to store them securely, how to manage costs, and how to handle rotation and revocation.
Understanding API Keys
What Is an API Key?
An API key is a string of characters (typically 40-64 characters long) that identifies and authenticates your account with a service. When your OpenClaw agent on EZClaws needs to generate a response, it sends the user's message and your API key to the model provider. The provider:
- Verifies the key is valid and active
- Checks that the key has permission to use the requested model
- Processes the request using the AI model
- Returns the response to your agent
- Bills the token usage to your account
Why You Bring Your Own Key
EZClaws uses a "bring your own key" model for AI model access. This means:
- You control your costs - You pay the model provider directly at their rates with no markup.
- You choose your model - Switch between providers and models without any platform restriction.
- You own the relationship - Your billing, rate limits, and usage data are directly with the provider.
- You maintain security - Your key is your responsibility, and EZClaws encrypts it in storage.
Getting Your API Key
OpenAI API Key
OpenAI provides access to GPT-4, GPT-4o, GPT-4o-mini, and other models.
Step 1: Create an OpenAI Platform account
Go to platform.openai.com and sign up. This is different from a ChatGPT account (though you can use the same email). The platform account gives you API access.
Step 2: Set up billing
Navigate to Settings > Billing and add a payment method. Without billing set up, API requests will fail. OpenAI offers prepaid and pay-as-you-go billing options.
Set a monthly spending limit. This is critical for cost control. Start with a conservative limit (like $20-50/month) and increase as you understand your usage patterns.
Step 3: Generate the key
Go to API Keys and click Create new secret key. Give it a descriptive name like "EZClaws Support Agent" so you know what it is for later.
Copy the key immediately. OpenAI only shows it once. If you lose it, you will need to generate a new one.
Step 4: Understand the rate limits
New OpenAI accounts have rate limits based on your usage tier. As you spend more, your limits increase automatically. Check your current tier in the API settings.
Anthropic API Key
Anthropic provides access to Claude models (Opus, Sonnet, Haiku).
Step 1: Create an Anthropic Console account
Go to console.anthropic.com and sign up.
Step 2: Set up billing
Navigate to the billing section and add a payment method. Anthropic uses a prepaid credit system. You purchase credits in advance.
Set a usage limit to prevent unexpected charges.
Step 3: Generate the key
Go to API Keys and click Create Key. Name it descriptively and copy it immediately.
Step 4: Review rate limits
Anthropic has rate limits based on your account tier. New accounts start with lower limits that increase as you build usage history.
Google AI API Key
Google provides access to Gemini models.
Step 1: Access Google AI Studio
Go to aistudio.google.com and sign in with your Google account.
Step 2: Generate the key
Click Get API key and create a new key. You may need to create or select a Google Cloud project.
Step 3: Set up billing (for production use)
For development and testing, Google offers free API access with usage limits. For production use, you may need to enable billing through Google Cloud Console.
Entering Your Key in EZClaws
Once you have your API key, here is how to use it:
- Log into the EZClaws dashboard.
- Click Create New Agent or go to an existing agent's settings.
- Select your model provider.
- Paste the API key in the API key field.
- Click save or deploy.
EZClaws immediately encrypts the key. After entry, it is shown as masked (sk-...xxxx) and cannot be retrieved. If you need to change it, you enter a new key.
For a full deployment walkthrough, see the deployment tutorial.
Security Best Practices
Never Share API Keys
This seems obvious, but it is the most common security mistake. Never:
- Send your API key over email, Slack, or any messaging platform
- Include it in code that gets pushed to a public repository
- Share it in a support ticket or forum post
- Paste it in a document that others can access
- Screenshot it and send to someone
If someone else needs API access, have them create their own key.
Use Dedicated Keys Per Agent
Create a separate API key for each agent you deploy. This provides:
- Cost tracking - You can see exactly how much each agent costs.
- Access control - If one agent is compromised, revoke only that key.
- Rate limit isolation - One agent's traffic does not affect another's limits.
- Audit trail - You know which agent made which API calls.
Set Spending Limits
Every major model provider lets you set monthly spending limits:
- OpenAI: Settings > Billing > Usage limits
- Anthropic: Console > Billing > Usage limits
- Google: Google Cloud Console > Budgets and alerts
Set limits conservatively, especially when you are still learning your usage patterns. You can always increase them later. It is much better to have your agent hit a spending limit than to receive a surprise bill.
Recommended initial limits:
- Personal or testing use: $10-20/month
- Small business agent: $50-100/month
- Production support agent: $100-500/month
- High-volume deployment: Set based on projected usage with a 50% buffer
Monitor Usage Regularly
Check your model provider's usage dashboard weekly:
- OpenAI: platform.openai.com/usage
- Anthropic: console.anthropic.com/usage
- Google: Google Cloud Console usage metrics
Look for:
- Unexpected usage spikes (could indicate a misconfigured agent or abuse)
- Steady increases that might exceed your limit
- Cost per conversation trends (helps you optimize)
The EZClaws dashboard also shows usage credit consumption, which correlates with API usage.
Rotate Keys Periodically
Even if you do not suspect compromise, rotating API keys every 90 days is good security hygiene:
- Generate a new key in your provider's dashboard.
- Update the key in your EZClaws agent settings.
- Verify the agent still works with the new key.
- Delete the old key from your provider's dashboard.
Do not delete the old key until the new one is confirmed working.
Revoke Compromised Keys Immediately
If you suspect a key has been exposed:
- Immediately revoke it in the provider's dashboard. Do not wait.
- Check the usage logs for any unauthorized activity.
- Generate a new key.
- Update all agents using the compromised key.
- If unauthorized charges occurred, contact the provider's support team.
Speed matters. An exposed key can generate charges within seconds.
Cost Management
Understanding Token Pricing
AI model APIs charge by the token. Here is a simplified breakdown:
| Model | Input (per 1M tokens) | Output (per 1M tokens) | Cost per conversation (est.) |
|---|---|---|---|
| GPT-4o-mini | $0.15 | $0.60 | $0.002 |
| Claude Haiku | $0.25 | $1.25 | $0.003 |
| Gemini Pro | $1.25 | $5.00 | $0.01 |
| Claude Sonnet | $3.00 | $15.00 | $0.02 |
| GPT-4o | $5.00 | $15.00 | $0.03 |
| GPT-4 | $30.00 | $60.00 | $0.20 |
| Claude Opus | $15.00 | $75.00 | $0.15 |
Conversation cost estimates assume a typical 10-exchange conversation with moderate message lengths.
For help choosing a model, see our model comparison guide.
Cost Optimization Strategies
1. Choose the right model for the job
Do not use GPT-4 for a FAQ bot. GPT-4o-mini handles simple queries perfectly well at 1/100th the cost. Reserve expensive models for complex tasks where quality genuinely matters.
2. Limit conversation context
Every previous message included in context costs tokens. Limit the context window to the last 10 messages instead of unlimited. See the configuration guide for details.
3. Write concise system prompts
A 2,000-word system prompt is included with every request. That is thousands of tokens per conversation before the user even speaks. Trim your system prompt to essential instructions only.
4. Set max response tokens
Prevent the agent from writing novels by setting a reasonable max token limit. 256-512 tokens is sufficient for most conversational responses.
5. Enable caching for repeated queries
If your agent handles many identical questions, enable response caching to avoid redundant API calls.
6. Monitor and adjust
Check your usage weekly and look for optimization opportunities. Sometimes a small configuration change (like reducing context window from 20 to 10 messages) can cut costs by 30-40% without noticeable quality impact.
Billing Alerts
Set up billing alerts at multiple thresholds:
- 50% of budget: Information alert. You are on track.
- 80% of budget: Warning. Review usage and consider if adjustments are needed.
- 100% of budget: Action required. Decide whether to increase the limit or optimize usage.
Most providers support email alerts at custom thresholds.
API Key Troubleshooting
"Authentication failed" or "Invalid API key"
Causes:
- The key was entered incorrectly (extra spaces, missing characters)
- The key has been revoked or deleted
- The key is for a different service (e.g., a ChatGPT key instead of an API key)
- Billing is not set up on the provider account
Fix: Re-enter the key carefully. Verify it is active in your provider's dashboard. Confirm billing is enabled.
"Rate limit exceeded"
Causes:
- Your agent is making too many requests too quickly
- Your provider account is on a low usage tier
- Multiple agents sharing the same key exceed combined limits
Fix: Implement rate limiting on your agent (see configuration guide). Wait for the rate limit window to reset (usually 1 minute). Consider using separate keys per agent.
"Insufficient quota" or "Billing limit reached"
Causes:
- You have hit your monthly spending limit
- Your prepaid credits are exhausted (Anthropic)
- Billing payment has failed
Fix: Increase your spending limit, add more prepaid credits, or update your payment method. Then restart your agent.
"Model not found" or "Permission denied for model"
Causes:
- You are requesting a model that does not exist or is deprecated
- Your account does not have access to the requested model (some models require waitlist approval)
- The model name is misspelled in the configuration
Fix: Verify the model name matches your provider's current model list. Check that your account has access to the model.
Multi-Provider Strategy
Advanced users may want to use different providers for different agents:
- Support agent: Claude Sonnet for strong instruction following
- Creative agent: GPT-4 for creative writing strength
- Budget agent: GPT-4o-mini for high-volume, cost-sensitive use
- Fallback: If one provider has an outage, you can quickly switch your agent to a different provider
This strategy requires managing keys for multiple providers but provides flexibility and resilience.
Enterprise Key Management
For larger organizations managing many agents and keys:
- Use a key management service - Tools like HashiCorp Vault or AWS Secrets Manager provide centralized, audited key storage.
- Implement key rotation automation - Script automatic key rotation on a schedule.
- Separate billing accounts - Use different provider accounts for different teams or departments for clean cost allocation.
- Maintain an inventory - Keep a record of which keys are assigned to which agents, when they were created, and when they are due for rotation.
- Conduct regular audits - Monthly review of active keys, their usage, and whether any should be revoked.
Conclusion
API keys are a small but critical part of your AI agent infrastructure. Getting them right means secure, cost-effective, and reliable agent operations. Getting them wrong means unauthorized charges, agent downtime, and debugging headaches.
The key takeaways:
- Generate dedicated keys per agent for clean cost tracking and security isolation.
- Set spending limits before you deploy to prevent surprises.
- Monitor usage weekly to catch anomalies and optimize costs.
- Rotate keys every 90 days as standard security hygiene.
- Revoke compromised keys immediately and generate replacements.
With these practices in place, your API keys become a well-managed asset instead of a source of risk.
Ready to deploy your agent with a properly configured API key? Follow the deployment tutorial to get started, or visit /pricing to choose your EZClaws plan.
Frequently Asked Questions
An API key is a unique credential that authenticates your AI agent with a model provider like OpenAI, Anthropic, or Google. When your agent needs to generate a response, it sends the user's message along with your API key to the model provider. The provider verifies the key, processes the request, and bills your account. Without a valid API key, your agent cannot access any AI models.
Yes. EZClaws encrypts API keys at rest using industry-standard encryption. Your key is never displayed in the dashboard after entry, never included in logs, and never accessible to other users. The key is only used server-side when your agent makes requests to the model provider.
API costs depend on your model choice and usage volume. GPT-4o-mini costs roughly $0.002 per typical conversation. Claude Sonnet costs roughly $0.01-0.03 per conversation. GPT-4 costs roughly $0.15-0.40 per conversation. Set billing alerts with your model provider to avoid surprises.
Immediately revoke the compromised key in your model provider's dashboard (OpenAI, Anthropic, or Google). Generate a new key and update it in your EZClaws agent settings. Check your model provider's usage logs for any unauthorized activity. If charges occurred, contact the provider's support team.
Technically yes, but it is not recommended. Using separate API keys for each agent makes it easier to track per-agent costs, set individual rate limits, and revoke access to a specific agent without affecting others. Most providers allow you to create multiple API keys on a single account.
Your OpenClaw Agent is Waiting for you
Our provisioning engine is standing by to spin up your private OpenClaw instance — dedicated VM, HTTPS endpoint, and full autonomy in under a minute.
