Swarms Logo
GuidesEngineering

Deploy AI Agents Without Servers: Scheduled and Event-Driven Agents With One API Call

Run AI agents on a schedule or in response to webhooks from Vercel Cron, AWS Lambda or Cloudflare Workers, with no Python runtime, worker process or queue to maintain. Each agent run is one HTTPS request to the Swarms API. TypeScript code for all three platforms.

Kye Gomez10 min read
Deploy AI Agents Without Servers: Scheduled and Event-Driven Agents With One API Call

Most agent frameworks assume a long-running process. You install a Python package, keep a worker alive, add a queue so jobs survive restarts, and then watch memory on a box that is idle 23 hours a day. That is a lot of infrastructure for an agent that writes a morning brief or triages a support ticket when one arrives.

Serverless platforms already solve scheduling and event handling. What they lack is somewhere to run the agent, and that is what a hosted agent API provides. With the Swarms API, one agent or a whole team of agents is a single POST request: the model calls, tool use, retries across fallback models and token accounting happen on the API side, and your function only sends the request and handles the result.

This guide builds two agents and deploys them three ways:

  • A scheduled agent that searches the web every weekday morning and posts a brief to Slack.
  • An event-driven agent that classifies incoming support tickets from a webhook.

Each one runs on Vercel Cron, AWS Lambda or Cloudflare Workers. The agent code is the same everywhere; only the trigger changes.

The shared client

Every platform below runs JavaScript with fetch built in, so the client is a few lines of TypeScript with no dependencies:

ts
// swarms.ts
const SWARMS_API = "https://api.swarms.world"

export type AgentConfig = {
  agent_name: string
  system_prompt: string
  model_name: string
  max_loops?: number
  max_tokens?: number
  temperature?: number
  fallback_models?: string[]
}

export async function runAgent(
  apiKey: string,
  agent: AgentConfig,
  task: string,
  tools?: ("auto_search" | "web_scraper")[],
): Promise<{ text: string; cost: number; jobId: string }> {
  const res = await fetch(`${SWARMS_API}/v1/agent/completions`, {
    method: "POST",
    headers: { "x-api-key": apiKey, "Content-Type": "application/json" },
    body: JSON.stringify({
      agent_config: { max_loops: 1, max_tokens: 2000, ...agent },
      task,
      ...(tools ? { tools_enabled: tools } : {}),
    }),
  })
  if (!res.ok) throw new Error(`Swarms API ${res.status}: ${await res.text()}`)

  const data = await res.json()
  // `outputs` is a list of {role, content} turns; the answer is the last non-user turn.
  const turns = (data.outputs as { role: string; content: unknown }[]).filter(
    (t) => !["user", "system"].includes(String(t.role).toLowerCase()),
  )
  return { text: String(turns.at(-1)?.content ?? ""), cost: data.usage?.total_cost ?? 0, jobId: data.job_id }
}

The two agents

The morning brief uses tools_enabled: ["auto_search"], which lets the agent run web searches during its run. Search costs $0.04 once per request, however many searches the agent makes.

ts
// agents.ts
import { runAgent } from "./swarms"

export async function morningBrief(apiKey: string, slackWebhook: string) {
  const today = new Date().toISOString().slice(0, 10)
  const { text, cost } = await runAgent(
    apiKey,
    {
      agent_name: "Market Brief",
      model_name: "gpt-5.4",
      fallback_models: ["claude-sonnet-5"],
      system_prompt:
        "You write a short morning brief for a product team. Search the web for news from the last 24 hours " +
        "about the companies and topics in the task. Return at most 6 bullets, each one sentence with the " +
        "source link. Skip anything older than two days. If nothing relevant happened, say so in one line.",
    },
    `Date: ${today}. Topics: AI agent platforms, LLM API pricing changes, our competitors Acme AI and Globex Labs.`,
    ["auto_search"],
  )

  await fetch(slackWebhook, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ text: `*Morning brief, ${today}*\n${text}` }),
  })
  return { cost }
}

The ticket triager returns structured JSON your code can act on: a category, a priority and a draft first reply.

ts
export type Triage = { category: string; priority: "low" | "normal" | "urgent"; summary: string; draft_reply: string }

export async function triageTicket(apiKey: string, ticket: { subject: string; body: string }): Promise<Triage> {
  const { text } = await runAgent(
    apiKey,
    {
      agent_name: "Ticket Triage",
      model_name: "gpt-5.4-mini",
      temperature: 0,
      system_prompt:
        "Classify a support ticket. Categories: billing, bug, account, feature_request, other. " +
        "Priority is urgent only for outages, data loss or payment failures. " +
        'Return only JSON: {"category": "...", "priority": "low" | "normal" | "urgent", ' +
        '"summary": "<one sentence>", "draft_reply": "<two to four sentences>"}',
    },
    `Subject: ${ticket.subject}\n\n${ticket.body}`,
  )
  const match = text.match(/\{[\s\S]*\}/)
  if (!match) throw new Error(`Triage returned no JSON: ${text.slice(0, 200)}`)
  return JSON.parse(match[0]) as Triage
}

The brief uses a stronger model because it has to judge relevance across many search results. Triage is a short classification, so a small model is fast and inexpensive.

Option 1: Vercel Cron and route handlers

On Vercel, a cron job is an HTTP request to one of your routes on a schedule. Declare it in vercel.json:

JSON
{
  "crons": [{ "path": "/api/cron/morning-brief", "schedule": "0 8 * * 1-5" }]
}

Schedules are in UTC. Then the route. Vercel sends Authorization: Bearer <CRON_SECRET> on cron requests when you set a CRON_SECRET environment variable, which stops anyone else from triggering the job (and spending your credits) by calling the URL:

ts
// app/api/cron/morning-brief/route.ts
import { morningBrief } from "@/lib/agents"

export const maxDuration = 300 // seconds; agent runs with web search can take a minute or more

export async function GET(request: Request) {
  if (request.headers.get("authorization") !== `Bearer ${process.env.CRON_SECRET}`) {
    return new Response("Unauthorized", { status: 401 })
  }
  const { cost } = await morningBrief(process.env.SWARMS_API_KEY!, process.env.SLACK_WEBHOOK_URL!)
  return Response.json({ ok: true, cost })
}

The webhook route for tickets lives next to it. Verify whatever signature your helpdesk sends before running the agent:

ts
// app/api/webhooks/ticket/route.ts
import { triageTicket } from "@/lib/agents"

export const maxDuration = 60

export async function POST(request: Request) {
  if (request.headers.get("x-webhook-secret") !== process.env.TICKET_WEBHOOK_SECRET) {
    return new Response("Unauthorized", { status: 401 })
  }
  const ticket = (await request.json()) as { id: string; subject: string; body: string }
  const triage = await triageTicket(process.env.SWARMS_API_KEY!, ticket)
  // Write back to your helpdesk here: set the tag, priority and an internal note with the draft.
  return Response.json({ id: ticket.id, ...triage })
}

Add SWARMS_API_KEY, CRON_SECRET, SLACK_WEBHOOK_URL and TICKET_WEBHOOK_SECRET under Settings → Environment Variables and deploy. The maximum maxDuration and how often cron jobs may run depend on your Vercel plan; on the Hobby plan, cron jobs run at most once a day.

Option 2: AWS Lambda with EventBridge Scheduler

On AWS, the same code runs as a Lambda function on the Node.js 22 runtime, which has fetch built in. One handler can serve both triggers: EventBridge Scheduler invokes it on a schedule, and a Lambda function URL or API Gateway route sends it webhooks.

ts
// handler.ts
import { morningBrief, triageTicket } from "./agents"

const KEY = process.env.SWARMS_API_KEY!

export const handler = async (event: any) => {
  // EventBridge Scheduler: invoked with the input you configure, e.g. {"job": "morning-brief"}
  if (event.job === "morning-brief") {
    return morningBrief(KEY, process.env.SLACK_WEBHOOK_URL!)
  }

  // Function URL / API Gateway: an HTTP request carrying the ticket
  if (event.requestContext?.http) {
    if (event.headers?.["x-webhook-secret"] !== process.env.TICKET_WEBHOOK_SECRET) {
      return { statusCode: 401, body: "Unauthorized" }
    }
    const ticket = JSON.parse(event.body ?? "{}")
    return { statusCode: 200, body: JSON.stringify(await triageTicket(KEY, ticket)) }
  }

  return { statusCode: 400, body: "Unknown event" }
}

Create the schedule with the AWS CLI (replace the ARNs with your function and an IAM role that may invoke it):

Shell
aws scheduler create-schedule \
  --name morning-brief \
  --schedule-expression "cron(0 8 ? * MON-FRI *)" \
  --schedule-expression-timezone "America/New_York" \
  --flexible-time-window '{"Mode": "OFF"}' \
  --target '{"Arn": "arn:aws:lambda:us-east-1:123456789012:function:agents", "RoleArn": "arn:aws:iam::123456789012:role/scheduler-invoke", "Input": "{\"job\": \"morning-brief\"}"}'

Set the function timeout to a few minutes (Lambda allows up to 15) and keep the API key in an environment variable encrypted with KMS or in Secrets Manager. EventBridge Scheduler supports time zones directly, which saves converting your 8 a.m. to UTC.

Option 3: Cloudflare Workers with Cron Triggers

A Worker can handle both triggers in one file: scheduled for cron and fetch for webhooks.

ts
// src/index.ts
import { morningBrief, triageTicket } from "./agents"

export interface Env {
  SWARMS_API_KEY: string
  SLACK_WEBHOOK_URL: string
  TICKET_WEBHOOK_SECRET: string
}

export default {
  async scheduled(_event: ScheduledController, env: Env, ctx: ExecutionContext) {
    ctx.waitUntil(morningBrief(env.SWARMS_API_KEY, env.SLACK_WEBHOOK_URL))
  },

  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url)
    if (request.method === "POST" && url.pathname === "/webhooks/ticket") {
      if (request.headers.get("x-webhook-secret") !== env.TICKET_WEBHOOK_SECRET) {
        return new Response("Unauthorized", { status: 401 })
      }
      const ticket = (await request.json()) as { subject: string; body: string }
      return Response.json(await triageTicket(env.SWARMS_API_KEY, ticket))
    }
    return new Response("Not found", { status: 404 })
  },
}
TOML
# wrangler.toml
name = "agents"
main = "src/index.ts"
compatibility_date = "2026-11-01"

[triggers]
crons = ["0 8 * * 1-5"]

Store secrets with npx wrangler secret put SWARMS_API_KEY (and the same for the other two), then npx wrangler deploy. Workers bill CPU time, and time spent waiting on the agent's response is not CPU time, so a minute-long agent run costs about the same as a fast one on the Worker side.

From one agent to a team

Both examples use a single agent. When a job needs several steps (research, then analysis, then writing), change the endpoint to /v1/swarm/completions and describe the team. The trigger, secrets and deployment stay exactly the same:

ts
const res = await fetch("https://api.swarms.world/v1/swarm/completions", {
  method: "POST",
  headers: { "x-api-key": apiKey, "Content-Type": "application/json" },
  body: JSON.stringify({
    name: "Weekly Competitor Report",
    swarm_type: "SequentialWorkflow",
    task: "Compare this week's product announcements from Acme AI and Globex Labs.",
    agents: [
      { agent_name: "Researcher", model_name: "gpt-5.4-mini", max_loops: 1,
        system_prompt: "List every announcement with date and one-line description." },
      { agent_name: "Analyst", model_name: "claude-sonnet-5", max_loops: 1,
        system_prompt: "Explain what each announcement means for a company selling an agent platform." },
      { agent_name: "Editor", model_name: "gpt-5.4-mini", max_loops: 1,
        system_prompt: "Turn the analysis into a 200-word report with three recommendations." },
    ],
  }),
})
const data = await res.json()
const report = data.output.at(-1).content // the last agent's message is the final report

Build a Multi-Agent Backend in Node.js and TypeScript has a fully typed client for this endpoint, including streaming.

Production checklist

  • Protect every trigger. A cron route without CRON_SECRET or a webhook without signature checks lets anyone spend your credits.
  • Expect duplicate deliveries. Schedulers and webhook senders retry. Key each run on something stable (the date for a daily brief, the ticket ID for triage) and skip work you have already done.
  • Set timeouts above your slowest run. Agents that search the web or run several steps can take a minute or more. Size maxDuration or the function timeout to match.
  • Add fallback_models. If a provider has an outage, the request is retried on the next model in the list instead of failing your 8 a.m. job.
  • Log the job_id. Every response includes one, and GET /v1/job/{job_id} returns the stored result later, which makes debugging a bad brief from last Tuesday straightforward.
  • Watch spend. Each response carries usage.total_cost, and your Swarms Cloud dashboard shows every request with tokens and cost.

Get started

Create an API key at cloud.swarms.world, copy swarms.ts and agents.ts, and deploy to whichever platform you already use. The Swarms API docs cover every endpoint, and the pricing page shows what each plan includes. When a scheduled job grows into hundreds of runs at once, the batch endpoints on the Pro plan run them in a single request.

More from the blog

Swarms v18 'Collective': Self-Organizing Swarms, A2A, Native Async Agents, Structured Output, and Token Usage on Every Structure
Engineering

Swarms v18 'Collective': Self-Organizing Swarms, A2A, Native Async Agents, Structured Output, and Token Usage on Every Structure

The complete technical changelog for Swarms v18, code-named Collective. SelfOrganizingSwarm runs a leaderless team that coordinates by message, MessageBoard gives agents a forum they work through tools, A2AServer and A2AClient put any agent on the A2A protocol, Agent.arun runs natively on the event loop, output_schema returns a validated Pydantic object, every multi-agent structure reports its token usage, seven structures force the tool call they depend on, images actually reach the model, telemetry is off by default, and importing swarms and building the first Agent takes half the time. Every new feature, improvement, bug fix and removal from November 2 to December 1, 2026, day by day.

The OpenAI Assistants API Has Shut Down: How to Migrate Your Agents to the Swarms API
Guides

The OpenAI Assistants API Has Shut Down: How to Migrate Your Agents to the Swarms API

OpenAI sunset the Assistants API on August 26, 2026. This guide maps assistants, threads, runs, function tools and file search to the Swarms API, with before-and-after Python code, a thread store you own, MCP in place of function calling, and a one-line route for code that already uses the OpenAI SDK.

LLM-as-a-Judge: Build an Evaluation Pipeline With a Panel of Agents
Guides

LLM-as-a-Judge: Build an Evaluation Pipeline With a Panel of Agents

How to grade LLM outputs automatically: write a rubric, score with one judge, then reduce judge bias with a panel of three judges from different model providers, majority voting, and self-consistency sampling for the close calls. Working Python code on the Swarms API.