Swarms Logo

Single-Agent Capabilities

One agent can do far more than answer a prompt. This part upgrades your agent with conversation memory, real-time streaming, schema-enforced JSON, function tools, live web search, MCP connections, and fully autonomous multi-step execution.

90 min · 8 lessons · checkpoint · 6-question quiz

Part 2 progress · 0/8 lessons0 pts · Recruit

You will learn to

  • Build multi-turn conversations with the history field
  • Stream tokens in real time with stream: true
  • Enforce JSON schemas on outputs and attach function tools
  • Connect agents to live data with web search and MCP servers
  • Run autonomous agents with max_loops set to auto
  • Use the OpenAI-compatible endpoint as a drop-in replacement
  • Reuse saved configurations and marketplace prompts across projects

Lesson 2.1

Multi-turn conversations

Agent completions are stateless: each request stands alone. To build a chatbot or research assistant that remembers earlier turns, thread the prior exchange back in through the history field:

conversation.py
payload = {
    "agent_config": {
        "agent_name": "Assistant",
        "system_prompt": "You are a helpful research assistant.",
        "model_name": "gpt-4.1",
        "max_loops": 1,
    },
    "task": "Which of those is most relevant for solar?",
    "history": [
        {"role": "user", "content": "List three energy storage technologies."},
        {"role": "assistant", "content": "1. Lithium-ion batteries ..."},
    ],
}

Your application owns the memory: append each user message and agent reply to a list, and send that list as history on the next call. This gives you full control over how much context to keep and lets you trim or summarize old turns to manage token costs.

Lesson 2.2

Streaming responses

For interactive interfaces, waiting for the full completion feels slow. Set streaming_on: true in the agent config to receive output as server-sent events while the agent generates it:

streaming.py
payload = {
    "agent_config": {
        "agent_name": "Streaming Writer",
        "system_prompt": "You are a concise technical writer.",
        "model_name": "gpt-4.1",
        "streaming_on": True,
    },
    "task": "Explain how multi-agent systems divide work.",
}

with requests.post(
    f"{BASE_URL}/v1/agent/completions",
    headers=headers,
    json=payload,
    stream=True,
) as response:
    for line in response.iter_lines():
        if line:
            print(line.decode("utf-8"))

Note · Streaming works for swarms too

In Part 3 you will see the same flag stream tokens from every agent in a multi-agent workflow, including detecting when parallel agents interleave.

Lesson 2.3

Structured outputs

Free-form text is hard to build on. When the agent's output feeds a database, a UI, or another program, enforce a JSON schema so the response always parses. Describe the schema as a tool in tools_list_dictionary:

structured_output.py
payload = {
    "agent_config": {
        "agent_name": "Data Extractor",
        "system_prompt": "Extract structured company data from text.",
        "model_name": "gpt-4.1",
        "max_loops": 1,
        "tools_list_dictionary": [
            {
                "type": "function",
                "function": {
                    "name": "extract_company",
                    "description": "Extract company facts",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "name": {"type": "string"},
                            "industry": {"type": "string"},
                            "employee_count": {"type": "integer"},
                        },
                        "required": ["name", "industry"],
                    },
                },
            }
        ],
    },
    "task": "Acme Robotics builds warehouse automation and employs 240 people.",
}

The agent responds with a call to your function schema, giving you validated, machine-readable JSON. This same mechanism is how classic function calling works: define one tool per action your application can take, and dispatch on the function name the agent chooses.

Try it: run the extraction below, then change the input text and the schema and run it again.

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

Lesson 2.4

Web search and vision

Models have knowledge cutoffs. For tasks that need current information (prices, news, live documentation), enable web search so the agent can retrieve real-time results before answering. The platform exposes search as a built-in capability; you simply instruct the agent to research and cite:

search_agent.py
payload = {
    "agent_config": {
        "agent_name": "Market Researcher",
        "system_prompt": (
            "You are a market researcher with web search access. "
            "Search for current information before answering and "
            "cite the sources you used."
        ),
        "model_name": "gpt-4.1",
        "max_loops": 1,
    },
    "task": "Summarize this week's developments in solid-state batteries.",
}

Agents can also process images. Pass an image URL in the img field of the request and the agent will analyze it alongside the task, which enables document parsing, chart reading, and visual inspection workflows.

GET/v1/tools/availableLists every built-in tool and capability the API currently supports.

Lesson 2.5

MCP: connect agents to your systems

The Model Context Protocol (MCP) is an open standard for giving agents access to external tools and data sources. Point an agent at any MCP server (Gmail, Notion, your internal APIs) with the mcp_url field, and the agent discovers and calls that server's tools at runtime:

mcp_agent.py
payload = {
    "agent_config": {
        "agent_name": "Ops Assistant",
        "system_prompt": "Use the available tools to complete the task.",
        "model_name": "gpt-4.1",
        "max_loops": 1,
        "mcp_config": {
            "url": "https://your-mcp-server.example.com/mcp",
            "transport": "streamable_http",
            "authorization_token": "your-mcp-token",
            "timeout": 10,
        },
    },
    "task": "Summarize the unread messages in my inbox.",
}

Use mcp_configs (plural) to connect multiple servers to one agent. This is the pattern behind assistants that span Gmail, Calendar, and Notion in a single conversation.

Lesson 2.6

Autonomous agents and sub-agent delegation

Setting max_loops to "auto" turns the agent into an autonomous looper: it plans the task, executes steps one at a time, and decides for itself when the work is done. The platform provides built-in tools for planning, thinking, file operations, and delegation:

autonomous_agent.py
payload = {
    "agent_config": {
        "agent_name": "Autonomous Researcher",
        "system_prompt": (
            "Plan the task, execute each step, and produce a "
            "final summary of your findings."
        ),
        "model_name": "claude-sonnet-4-20250514",
        "max_loops": "auto",
        "selected_tools": ["create_plan", "think", "complete_task"],
    },
    "task": (
        "Research three competing battery chemistries, compare "
        "energy density and cost, and recommend one for grid storage."
    ),
}

Restrict selected_tools to the minimum the task needs; fewer tools means fewer wasted loops. Autonomous agents can also spawn specialists at runtime with create_sub_agent and assign_task, and you can predefine delegation targets with the handoffs field: a list of AgentSpec objects this agent may hand work to.

Warning · Autonomy costs more

Each loop is another model call. Use "auto" when the task genuinely requires multi-step planning, and keep single-pass agents on max_loops: 1.

Lesson 2.7

The OpenAI-compatible endpoint

If you already have code written against the OpenAI SDK, you can route it through Swarms by changing only the base URL and key. The /v1/chat/completions endpoint accepts the standard OpenAI request schema and returns the standard response schema, including streaming:

POST/v1/chat/completions
openai_compatible.py
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("SWARMS_API_KEY"),
    base_url="https://api.swarms.world/v1",
)

response = client.chat.completions.create(
    model="gpt-4.1",
    messages=[{"role": "user", "content": "Hello, Swarms!"}],
)
print(response.choices[0].message.content)

This is the lowest-friction migration path: start with a drop-in swap, then graduate to /v1/agent/completions and /v1/swarm/completions when you want agent configs, tools, and orchestration.

Try it livePOST/v1/chat/completions
The exact OpenAI request schema, served by Swarms.

Lesson 2.8

Reusing configurations and marketplace prompts

As you build, you accumulate agent configurations worth keeping. The platform remembers every distinct configuration you have run and lets you list them for reuse, so your applications can share one library of proven agents instead of duplicating JSON:

GET/v1/agents/list
Try it liveGET/v1/agents/list
Lists agent configurations you have created or used.

You can also skip prompt writing entirely. The Swarms Marketplace hosts production-tested prompts, and any agent can load one by ID with the marketplace_prompt_id field; the platform fetches it and installs it as the system prompt:

marketplace_prompt.py
payload = {
    "agent_config": {
        "agent_name": "Marketplace Agent",
        "marketplace_prompt_id": "prompt-id-from-swarms-world",
        "model_name": "gpt-4.1",
        "max_loops": 1,
    },
    "task": "Analyze this quarter's sales figures.",
}

Tip · Prompts are assets

Treat working system prompts the way you treat working code: version them, reuse them, and consider publishing your best ones to the marketplace, where creators earn on every sale.

Checkpoint · Part 2

Checkpoint project: a structured research assistant

Combine three capabilities from this part into one agent:

  1. Build an agent that researches a product category and returns results as schema-enforced JSON (name, price range, and a one-sentence rationale per item)
  2. Add conversation history so a follow-up question refines the previous answer instead of starting over
  3. Switch the same logic to the OpenAI-compatible endpoint and confirm your existing SDK code works unchanged

The goal is to feel the difference between an agent that chats and an agent that produces data your software can consume.

Knowledge check · Part 2

Test what you remember

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

  1. 1.Agent completions are stateless. How does an agent remember earlier turns of a conversation?

  2. 2.How do you get schema-enforced JSON from an agent?

  3. 3.What does setting max_loops to "auto" do?

  4. 4.Which field connects an agent to several MCP servers at once?

  5. 5.To route existing OpenAI SDK code through Swarms, what do you change?

  6. 6.What does the marketplace_prompt_id field do?

0 of 6 answered