Swarms Logo

Foundations: Your First Agent

Understand what the Swarms API is, get authenticated, and run a single AI agent end to end. By the end of this part you will have executed your first agent completion and know how to read every field in the response.

60 min · 7 lessons · checkpoint · 6-question quiz

Part 1 progress · 0/7 lessons0 pts · Recruit

You will learn to

  • Understand the Swarms platform architecture: single agents, swarms, and workflows
  • Create an API key and authenticate with the x-api-key header
  • Verify connectivity with the health endpoint
  • Configure an agent with AgentSpec and run POST /v1/agent/completions
  • Discover available models and check your credit balance
  • Read the usage field and handle every common error status

Lesson 1.1

What is the Swarms API?

The Swarms API is a hosted platform for building and orchestrating AI agents. You describe an agent (its name, instructions, and model) in JSON, send it a task over HTTPS, and the platform runs it on managed infrastructure. There is nothing to deploy, no GPU to rent, and no framework to install: every capability is an HTTP endpoint.

The platform is organized in three tiers, and this course follows them in order:

  • Single agents: one agent, one task. The POST /v1/agent/completions endpoint. This is where Part 1 and Part 2 live.
  • Multi-agent swarms: multiple agents collaborating under an orchestration pattern such as SequentialWorkflow, ConcurrentWorkflow, or HierarchicalSwarm. Covered in Part 3.
  • Production operations: batch execution, rate limits, cost controls, and observability. Covered in Part 4.

Everything runs against a single base URL:

Base URL
https://api.swarms.world

Note · You choose the model

Agents can run on models from OpenAI, Anthropic, Groq, and more. You select the model per agent with the model_name field, so a single swarm can mix a frontier model for synthesis with cheaper models for extraction.

Lesson 1.2

Get your API key

Every request is authenticated with an API key. Create one in the Swarms Platform under API Keys at swarms.world/platform/api-keys. Copy the key once it is shown; treat it like a password.

Store the key as an environment variable instead of hardcoding it. Create a .env file in your project:

.env
SWARMS_API_KEY="your-api-key-here"

Then install the two libraries used throughout this course:

Terminal
pip install requests python-dotenv

Warning · Never commit keys

Add .env to your .gitignore. If a key leaks, revoke it on the platform and create a new one. The API also accepts Authorization: Bearer <key> for OpenAI SDK compatibility, but x-api-key is the canonical header.

Lesson 1.3

Your first request: the health check

Before running any agent, confirm that your key and connection work. The health endpoint is free and requires no body:

GET/health
health_check.py
import os
import requests
from dotenv import load_dotenv

load_dotenv()

BASE_URL = "https://api.swarms.world"
headers = {
    "x-api-key": os.getenv("SWARMS_API_KEY"),
    "Content-Type": "application/json",
}

response = requests.get(f"{BASE_URL}/health", headers=headers)
print(response.status_code)  # 200
print(response.json())

A 200 response means you are authenticated and the service is operational. If you get 401, your key is missing or wrong; check that load_dotenv() ran and that the variable name matches your .env file.

You can run this request right here. Paste your API key below (it is stored only in your browser and sent only to api.swarms.world), and every other trial in this course will reuse it:

Try it liveGET/health
Free; consumes no credits.

Lesson 1.4

Anatomy of an agent

An agent is defined by an agent_config object (the AgentSpec schema). It tells the platform who the agent is, how it should behave, and which model to run. These are the fields you will use in almost every request:

FieldTypeDefaultWhat it does
agent_namestring-Identifier for the agent and its role
descriptionstring-What the agent is for; helps coordination in swarms
system_promptstring-The agent's instructions and persona
model_namestringgpt-4.1Which model runs the agent
temperaturenumberprovider defaultRandomness; lower is more deterministic
max_tokensinteger8192Cap on generated output length
max_loopsint | "auto"1How many reasoning iterations the agent may run
rolestringworkerThe agent's role inside a swarm

The system_prompt is the most important field. Be specific about the agent's expertise, the shape of the output you expect, and what it should refuse to guess at. A precise prompt outperforms a clever one.

Tip · Start with max_loops: 1

One loop means one pass over the task: predictable latency and cost. Higher loop counts and "auto" unlock autonomous behavior, which you will meet in Part 2.

Lesson 1.5

Run your first agent completion

Now put it together. An agent completion request has two parts: the agent_config describing the agent, and a task string describing the work:

POST/v1/agent/completions
first_agent.py
import os
import requests
from dotenv import load_dotenv

load_dotenv()

BASE_URL = "https://api.swarms.world"
headers = {
    "x-api-key": os.getenv("SWARMS_API_KEY"),
    "Content-Type": "application/json",
}

payload = {
    "agent_config": {
        "agent_name": "Research Analyst",
        "description": "Analyzes topics and produces structured summaries",
        "system_prompt": (
            "You are a research analyst. Analyze the given topic, "
            "identify the three most important trends, and present "
            "them as a numbered list with one supporting fact each."
        ),
        "model_name": "claude-sonnet-4-20250514",
        "max_loops": 1,
        "max_tokens": 4096,
        "temperature": 0.7,
    },
    "task": "What are the key trends in renewable energy adoption?",
}

response = requests.post(
    f"{BASE_URL}/v1/agent/completions", headers=headers, json=payload
)
result = response.json()
print(result["outputs"])
print(result["usage"])

The response contains the agent's output plus metadata you should get in the habit of reading:

  • id: unique identifier for this completion, useful when correlating logs
  • outputs: the agent's answer, including the conversation structure
  • usage: token counts for the request; this is what you are billed on
  • name: the agent name you configured, echoed back

Tip · Iterate on the prompt, not the code

Once this script runs, improving output quality is almost always a matter of sharpening system_prompt and task. Keep the plumbing constant and treat prompts as the thing under development.

Run a real agent completion now. The body below is editable: change the task, the system prompt, or the temperature and watch the output change.

Try it livePOST/v1/agent/completions
Runs on your account; costs a small number of credits.

Lesson 1.6

Discover models and check your balance

Two read-only endpoints round out the foundations. First, list every model you can pass as model_name:

GET/v1/models/available
models.py
response = requests.get(
    f"{BASE_URL}/v1/models/available", headers=headers
)
print(response.json())
Try it liveGET/v1/models/available
Free; consumes no credits.

Second, check your credit balance. Completions consume credits based on token usage, so this is the number to watch while you learn:

GET/v1/account/credits
credits.py
response = requests.get(
    f"{BASE_URL}/v1/account/credits", headers=headers
)
print(response.json())  # regular, free, and referral credits
Try it liveGET/v1/account/credits
Free; consumes no credits.

Lesson 1.7

Reading responses and handling failures

Production habits start on day one, so learn to read the whole response now. A successful agent completion contains more than the answer:

FieldWhat to do with it
idLog it; it is how you find this run later in /v1/swarm/logs
outputsThe agent's conversation, including the final answer
usageInput, output, and total token counts; multiply by model price to know cost
temperature / model_nameEcho of the configuration that actually ran

Failures arrive as HTTP status codes, and each one tells you something different:

StatusMeaningFirst thing to check
400Malformed requestJSON syntax and field names in your payload
401Authentication failedThe x-api-key header and the key itself
402Insufficient creditsYour balance at /v1/account/credits
429Rate limit hitYour request frequency; wait and retry
500Server-side errorRetry once; if persistent, check service health
safe_call.py
response = requests.post(
    f"{BASE_URL}/v1/agent/completions", headers=headers, json=payload
)

if response.status_code == 200:
    result = response.json()
    print(result["outputs"])
elif response.status_code == 401:
    raise SystemExit("Check your SWARMS_API_KEY.")
elif response.status_code == 402:
    raise SystemExit("Out of credits: top up at swarms.world.")
else:
    print(response.status_code, response.text)

Note · Part 4 goes deeper

Retries, backoff, and rate-limit headers get a full lesson in Part 4. For now, the habit that matters is reading usage on every run and never ignoring a non-200 status.

Checkpoint · Part 1

Checkpoint project: a working research agent

Before moving to Part 2, build this on your own. It exercises everything in this part:

  1. Write a script that runs the health check and exits with an error message if it fails
  2. Configure an agent with a domain of your choice (finance, medicine, engineering) and a system prompt that demands a specific output format
  3. Run the same task at temperature 0.1 and 1.0 and compare the outputs
  4. Print the token usage of each run, then fetch /v1/account/credits and confirm the balance moved

If you can predict roughly what a run will cost before you send it, you have internalized the core loop of the API.

Knowledge check · Part 1

Test what you remember

6 questions. Answer from memory before checking; look back at the lessons only after you see your score.

  1. 1.Which header authenticates every request to the Swarms API?

  2. 2.What is the base URL for all Swarms API requests?

  3. 3.Which endpoint runs a single agent on a task?

  4. 4.An agent config omits max_loops. How many reasoning iterations does the agent run?

  5. 5.Where do you look to know what a completed run cost you?

  6. 6.A request returns 402. What happened?

0 of 6 answered