In this example, we’ll send an image of Hong Kong to an agent and ask “What city is this?”
Step 1: Get Your API Key
Before you can use the Swarms API, you need to obtain an API key.- Visit https://swarms.world/platform/api-keys
- Sign in or create an account
- Generate a new API key
- Copy and save your API key securely
Keep your API key secure and never commit it to version control. Use environment variables to store it.
Step 2: Prepare Your Image (Base64 Encoding)
The Swarms API accepts images as base64-encoded strings. Here’s how to convert an image to base64:- Python
- JavaScript
- Bash/cURL
Step 3: Send the Image to the Agent
Now that you have your API key and base64-encoded image, you can send it to the Swarms API.- Python
- JavaScript
- cURL
Expected Response
Complete Working Example
Here’s a complete Python script you can run:Image Format Support
The API supports common image formats:- JPEG/JPG: Standard photo format
- PNG: Images with transparency
- GIF: Static GIFs (first frame)
- WebP: Modern web image format
Vision-Capable Models
Not all models support vision. Use these models for image analysis:- gpt-4.1: Best for complex visual analysis
- gpt-4.1-mini: Cost-effective for basic vision tasks
- claude-sonnet-4-20250514: High-quality vision understanding
Best Practices
- Image Size: Optimize images before encoding (recommended max: 4096x4096 pixels)
- Compression: Use JPEG for photos, PNG for screenshots/graphics
- Quality: Balance image quality with file size for faster processing
- Specific Questions: Ask clear, specific questions for better results
- Token Usage: Larger/higher resolution images consume more tokens
Cost Considerations
Vision tasks consume additional tokens based on image resolution:Troubleshooting
Common Issues
Issue: “Invalid image format”- Solution: Ensure your image is properly base64-encoded using
base64.b64encode()
- Solution: Resize the image to under 4096x4096 pixels or reduce quality
- Solution: Use gpt-4.1, gpt-4.1-mini, or claude-sonnet-4-20250514
- Solution: Reduce image resolution or use gpt-4.1-mini for basic tasks
Error Handling
Next Steps
- Try analyzing your own images by replacing the image URL
- Experiment with different questions and prompts
- Check out the API Reference for more details