| title | Environment Setup |
|---|---|
| description | Configure API keys, workspace directory, and environment variables for Swarms |
Before you can start using Swarms, you need to configure your environment with the necessary API keys and settings. This guide will walk you through setting up your environment variables and workspace directory.
Swarms supports multiple LLM providers including OpenAI, Anthropic, Groq, and more. You only need to configure the API keys for the providers you plan to use.The fastest way to get started is to create a .env file in your project root:
```bash
touch .env
```
```bash
OPENAI_API_KEY="your-openai-api-key-here"
WORKSPACE_DIR="agent_workspace"
ANTHROPIC_API_KEY="your-anthropic-api-key-here"
GROQ_API_KEY="your-groq-api-key-here"
```
```python
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Verify API keys are loaded
print(f"OpenAI API Key: {os.getenv('OPENAI_API_KEY')[:10]}...")
print(f"Workspace: {os.getenv('WORKSPACE_DIR')}")
```
WORKSPACE_DIR="agent_workspace"Configure the API keys for the LLM providers you want to use:
Your OpenAI API key for using GPT models (gpt-4, gpt-4o-mini, etc.)Get your key: OpenAI API Keys
OPENAI_API_KEY="sk-..."Get your key: Anthropic Console
ANTHROPIC_API_KEY="sk-ant-..."Get your key: Groq Console
GROQ_API_KEY="gsk_..."Here's a complete example of a .env file with all supported providers:
# Core Configuration
WORKSPACE_DIR="agent_workspace"
# OpenAI
OPENAI_API_KEY="sk-proj-..."
# Anthropic
ANTHROPIC_API_KEY="sk-ant-..."
# Groq
GROQ_API_KEY="gsk_..."
# Additional Providers (Optional)
COHERE_API_KEY="your-cohere-key"
DEEPSEEK_API_KEY="your-deepseek-key"
OPENROUTER_API_KEY="your-openrouter-key"
XAI_API_KEY="your-xai-key"
# Workspace Settings (Optional)
LOG_LEVEL="INFO"
MAX_WORKERS="4"
CACHE_ENABLED="true"The workspace directory is where agents store their outputs, logs, and state:
agent_workspace/
├── logs/ # Agent execution logs
├── outputs/ # Agent-generated outputs
├── cache/ # Cached results
└── state/ # Agent state files
You can customize the workspace location:
import os
from swarms import Agent
# Set workspace directory
os.environ["WORKSPACE_DIR"] = "/path/to/custom/workspace"
# Or specify per-agent
agent = Agent(
model_name="gpt-4o-mini",
workspace_dir="./my_agent_workspace"
)There are several ways to load your environment variables:
from dotenv import load_dotenv
import os
# Load from .env file
load_dotenv()
# Access variables
api_key = os.getenv("OPENAI_API_KEY")
workspace = os.getenv("WORKSPACE_DIR", "agent_workspace") # with defaultimport os
# Set environment variables directly
os.environ["OPENAI_API_KEY"] = "your-api-key"
os.environ["WORKSPACE_DIR"] = "agent_workspace"# Reload shell configuration
source ~/.bashrc
```
# Set permanently
[System.Environment]::SetEnvironmentVariable('OPENAI_API_KEY', 'your-api-key', 'User')
```
# Set permanently
setx OPENAI_API_KEY "your-api-key"
```
Here's where to get API keys for each supported provider:
Create an account and generate API keys from the OpenAI platform Sign up for Anthropic Claude and get your API key from the console Register for Groq's fast inference and generate your API key Create a Cohere account and access your API keys Sign up for DeepSeek and generate your API credentials Access multiple models through OpenRouter with a single API keyRun this script to verify your environment is configured correctly:
import os
from dotenv import load_dotenv
from swarms import Agent
# Load environment variables
load_dotenv()
def verify_setup():
"""Verify that the environment is properly configured."""
print("🔍 Verifying Swarms Environment Setup...\n")
# Check workspace directory
workspace = os.getenv("WORKSPACE_DIR", "agent_workspace")
print(f"✓ Workspace Directory: {workspace}")
# Check API keys
providers = {
"OpenAI": "OPENAI_API_KEY",
"Anthropic": "ANTHROPIC_API_KEY",
"Groq": "GROQ_API_KEY",
}
configured_providers = []
for name, env_var in providers.items():
if os.getenv(env_var):
configured_providers.append(name)
print(f"✓ {name} API Key: Configured")
else:
print(f"✗ {name} API Key: Not configured")
print(f"\n✨ Setup complete! {len(configured_providers)} provider(s) configured.")
# Test agent creation
if "OpenAI" in configured_providers:
print("\n🤖 Testing agent creation...")
try:
agent = Agent(
model_name="gpt-4o-mini",
max_loops=1,
)
response = agent.run("Say 'Setup verified!'")
print(f"✓ Agent test successful: {response[:50]}...")
except Exception as e:
print(f"✗ Agent test failed: {str(e)}")
if __name__ == "__main__":
verify_setup()Run the verification script:
python verify_setup.py```
.env.development
.env.production
.env.test
```
Load the appropriate one:
```python
from dotenv import load_dotenv
import os
env = os.getenv("ENV", "development")
load_dotenv(f".env.{env}")
```
```python
import os
required_vars = ["OPENAI_API_KEY", "WORKSPACE_DIR"]
missing_vars = [var for var in required_vars if not os.getenv(var)]
if missing_vars:
raise EnvironmentError(
f"Missing required environment variables: {', '.join(missing_vars)}"
)
```
- **AWS:** AWS Secrets Manager or Parameter Store
- **Azure:** Azure Key Vault
- **GCP:** Google Secret Manager
- **Kubernetes:** Kubernetes Secrets
- **Docker:** Docker Secrets