Agent 与集成(1/6)

Gather data wherever it lives on the web.

Picking the right tool. Agent is right when you don't know the URLs or need autonomous navigation across the web.

Firecrawl /agent is a magic API that searches, navigates, and gathers data from the widest range of websites, finding data in hard-to-reach places and uncovering data in ways no other API can. It accomplishes in a few minutes what would take a human many hours — end-to-end data collection, without scripts or manual work. Whether you need one data point or entire datasets at scale, Firecrawl /agent works to get your data.

Think of /agent as deep research for data, wherever it is!

Agent builds on everything great about /extract and takes it further:

  • No URLs Required: Just describe what you need via prompt parameter. URLs are optional
  • Deep Web Search: Autonomously searches and navigates deep into sites to find your data
  • Reliable and Accurate: Works with a wide variety of queries and use cases
  • Faster: Processes multiple sources in parallel for quicker results

Test the agent in the interactive playground — no code required.

Using /agent

The only required parameter is prompt. Simply describe what data you want to extract. For structured output, provide a JSON schema. The SDKs support Pydantic (Python) and Zod (Node) for type-safe schema definitions:

from firecrawl import Firecrawl
from pydantic import BaseModel, Field
from typing import List, Optional

app = Firecrawl(api_key="fc-YOUR_API_KEY")

class Founder(BaseModel):
    name: str = Field(description="Full name of the founder")
    role: Optional[str] = Field(None, description="Role or position")
    background: Optional[str] = Field(None, description="Professional background")

class FoundersSchema(BaseModel):
    founders: List[Founder] = Field(description="List of founders")

result = app.agent(
    prompt="Find the founders of Firecrawl",
    schema=FoundersSchema,
    model="spark-2",
    max_credits=100
)

print(result.data)
import { Firecrawl } from 'firecrawl';
import { z } from 'zod';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

const result = await firecrawl.agent({
  prompt: "Find the founders of Firecrawl",
  schema: z.object({
    founders: z.array(z.object({
      name: z.string().describe("Full name of the founder"),
      role: z.string().describe("Role or position").optional(),
      background: z.string().describe("Professional background").optional()
    })).describe("List of founders")
  }),
  model: "spark-2",
  maxCredits: 100
});

console.log(result.data);
curl -X POST "https://api.firecrawl.dev/v2/agent" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Find the founders of Firecrawl",
    "model": "spark-2",
    "maxCredits": 100,
    "schema": {
      "type": "object",
      "properties": {
        "founders": {
          "type": "array",
          "description": "List of founders",
          "items": {
            "type": "object",
            "properties": {
              "name": { "type": "string", "description": "Full name" },
              "role": { "type": "string", "description": "Role or position" },
              "background": { "type": "string", "description": "Professional background" }
            },
            "required": ["name"]
          }
        }
      },
      "required": ["founders"]
    }
  }'

Response

{
  "success": true,
  "status": "completed",
  "data": {
    "founders": [
      {
        "name": "Eric Ciarla",
        "role": "Co-founder",
        "background": "Previously at Mendable"
      },
      {
        "name": "Nicolas Camara",
        "role": "Co-founder",
        "background": "Previously at Mendable"
      },
      {
        "name": "Caleb Peffer",
        "role": "Co-founder",
        "background": "Previously at Mendable"
      }
    ]
  },
  "expiresAt": "2024-12-15T00:00:00.000Z",
  "creditsUsed": 15
}

Providing URLs (Optional)

You can optionally provide URLs to focus the agent on specific pages:

from firecrawl import Firecrawl

app = Firecrawl(api_key="fc-YOUR_API_KEY")

result = app.agent(
    urls=["https://docs.firecrawl.dev", "https://firecrawl.dev/pricing"],
    prompt="Compare the features and pricing information from these pages"
)

print(result.data)
import { Firecrawl } from 'firecrawl';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

const result = await firecrawl.agent({
  urls: ["https://docs.firecrawl.dev", "https://firecrawl.dev/pricing"],
  prompt: "Compare the features and pricing information from these pages"
});

console.log(result.data);
curl -X POST "https://api.firecrawl.dev/v2/agent" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "urls": [
      "https://docs.firecrawl.dev",
      "https://firecrawl.dev/pricing"
    ],
    "prompt": "Compare the features and pricing information from these pages"
  }'

Job Status and Completion

Agent jobs run asynchronously. When you submit a job, you'll receive a Job ID that you can use to check status:

  • Default method: agent() waits and returns final results
  • Start then poll: Use start_agent (Python) or startAgent (Node) to get a Job ID immediately, then poll with get_agent_status / getAgentStatus
  • Push instead of poll: Pass a webhook when you start the job to receive agent events as the run progresses and finishes

Job results are available via the API for 24 hours after completion. After this period, you can still view your agent history and results in the activity logs.

from firecrawl import Firecrawl

app = Firecrawl(api_key="fc-YOUR_API_KEY")

# Start an agent job
agent_job = app.start_agent(
    prompt="Find the founders of Firecrawl"
)

# Check the status
status = app.get_agent_status(agent_job.id)

print(status)
# Example output:
# status='completed'
# success=True
# data={ ... }
# expires_at=datetime.datetime(...)
# credits_used=15
import { Firecrawl } from 'firecrawl';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

// Start an agent job
const started = await firecrawl.startAgent({
  prompt: "Find the founders of Firecrawl"
});

// Check the status
if (started.id) {
  const status = await firecrawl.getAgentStatus(started.id);
  console.log(status.status, status.data);
}
curl -X GET "https://api.firecrawl.dev/v2/agent/<jobId>" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY"

Possible States

Status Description
processing The agent is still working on your request
completed Extraction finished successfully
failed An error occurred during extraction, the run reached its maxCredits limit (see Handling credit-limit stops), or the job was cancelled (cancelled jobs report failed with a cancellation error message)

Cancellation is cooperative. When you call the cancel endpoint, the request is registered immediately, but any step already in flight (an LLM reasoning step, a tool call, or a browser action) runs to a clean stopping point before the job stops. Credits can continue to accrue during that short window, so the final creditsUsed may be higher than the value reported at the moment you clicked cancel. A cancelled job reports status failed when polled and emits an agent.cancelled webhook event.

Pending Example

{
  "success": true,
  "status": "processing",
  "expiresAt": "2024-12-15T00:00:00.000Z"
}

Completed Example

{
  "success": true,
  "status": "completed",
  "data": {
    "founders": [
      {
        "name": "Eric Ciarla",
        "role": "Co-founder"
      },
      {
        "name": "Nicolas Camara",
        "role": "Co-founder"
      },
      {
        "name": "Caleb Peffer",
        "role": "Co-founder"
      }
    ]
  },
  "expiresAt": "2024-12-15T00:00:00.000Z",
  "creditsUsed": 15
}

Handling credit-limit stops

A run that reaches its maxCredits limit stops and reports status: "failed". To tell a credit stop apart from other failures, check stopReason instead of the error text. stopReason is credit_limit_reached when the run ran out of budget.

data is only set on completed runs, never on a failed one. A failed credit-stop run may include what the agent had gathered before it stopped:

Field Type Description
stopReason string Why the run stopped early. Currently only credit_limit_reached.
partial any Best-effort JSON recovered from the incomplete run. It can be missing rows or fields.
partialSchemaValid boolean Only present when the request included a schema. Whether partial validates against it.
message string A short note on what is incomplete, when available.

These fields only appear once a run has failed. While a run is processing, the status response never includes a partial.

Use partial with care. It is incomplete, so don't store it as a finished result, and check partialSchemaValid before you parse it with your schema. Not every credit stop returns a partial, so handle runs that have only stopReason.

To finish the work, continue the run's thread with a follow-up prompt. The previous partial is restored for the agent and labelled incomplete, so the follow-up continues from it instead of starting over. A follow-up inherits the previous turn's schema and urls but not maxCredits, so set a budget for it.

from firecrawl import Firecrawl
from pydantic import BaseModel
from typing import List

app = Firecrawl(api_key="fc-YOUR_API_KEY")

class Company(BaseModel):
    name: str
    website: str

class CompaniesSchema(BaseModel):
    companies: List[Company]

result = app.agent(
    prompt="Find every company in the YC W24 batch that builds developer tools",
    schema=CompaniesSchema,
    max_credits=100
)

if result.status == "completed":
    print(result.data)
elif result.status == "failed" and result.stop_reason == "credit_limit_reached":
    # `data` is never set on a failed run. `partial` is best-effort and may be missing.
    if result.partial is not None:
        if result.partial_schema_valid is not True:
            print("The partial result does not match the schema yet.")
        print(result.message, result.partial)

    # Continue the same thread. The agent picks up from the incomplete result.
    # The follow-up inherits the schema but not max_credits, so set a budget.
    follow_up = app.agent(
        thread_id=result.thread_id,
        prompt="Continue and finish the list.",
        max_credits=200
    )
    print(follow_up.status, follow_up.data)
else:
    print(result.error)
import { Firecrawl } from 'firecrawl';
import { z } from 'zod';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

const result = await firecrawl.agent({
  prompt: "Find every company in the YC W24 batch that builds developer tools",
  schema: z.object({
    companies: z.array(z.object({
      name: z.string(),
      website: z.string()
    }))
  }),
  maxCredits: 100
});

if (result.status === "completed") {
  console.log(result.data);
} else if (result.status === "failed" && result.stopReason === "credit_limit_reached") {
  // `data` is never set on a failed run. `partial` is best-effort and may be missing.
  if (result.partial !== undefined) {
    if (result.partialSchemaValid !== true) {
      console.warn("The partial result does not match the schema yet.");
    }
    console.log(result.message, result.partial);
  }

  // Continue the same thread. The agent picks up from the incomplete result.
  // The follow-up inherits the schema but not maxCredits, so set a budget.
  const followUp = await firecrawl.agent({
    threadId: result.threadId,
    prompt: "Continue and finish the list.",
    maxCredits: 200
  });
  console.log(followUp.status, followUp.data);
} else {
  console.error(result.error);
}
# 1. Poll the run. A credit stop reports "status": "failed" with "stopReason": "credit_limit_reached".
curl -X GET "https://api.firecrawl.dev/v2/agent/<jobId>" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY"

# 2. Continue the same thread to finish the work.
curl -X POST "https://api.firecrawl.dev/v2/agent" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "threadId": "<threadId from the failed run>",
    "prompt": "Continue and finish the list.",
    "maxCredits": 200
  }'

Credit-limit Example

{
  "success": true,
  "status": "failed",
  "error": "Agent reached max credits",
  "stopReason": "credit_limit_reached",
  "partial": {
    "companies": [
      { "name": "Acme", "website": "https://acme.dev" },
      { "name": "Globex" }
    ]
  },
  "partialSchemaValid": false,
  "message": "Credit limit reached; this result is incomplete.",
  "threadId": "0199bbbb-0000-7000-8000-000000000000",
  "threadTurn": 1,
  "expiresAt": "2024-12-15T00:00:00.000Z",
  "creditsUsed": 0
}

When you read a thread with GET /v2/agent/threads/{threadId}?includeData=true (getAgentThread in Node, get_agent_thread in Python), a run that ended with a partial has status: "credit_limit_reached" and reports partial, partialSchemaValid and stopReason instead of data.

If you started the run with a webhook, the agent.failed event carries the same stopReason, and partial, partialSchemaValid and message when they are available.

Listing agent runs

GET /agent lists every agent run your team has made, most recent first — including runs started from the playground or the API. Each entry carries the run's ID, creation time, status, a short target hint, and the options it was started with.

Results are paginated in fixed pages of 20 runs. When more pages exist, the response includes a next URL; pass its before timestamp to fetch the next page. The SDK methods do not auto-paginate, so you stay in control of how far back to go.

from firecrawl import Firecrawl

app = Firecrawl(api_key="fc-YOUR_API_KEY")

# List your most recent agent runs
page = app.list_agents()

for run in page.agents:
    print(run.id, run.status, run.target_hint)

# Fetch the next page using the cursor from `next`
if page.next:
    before = int(page.next.split("before=")[-1])
    older = app.list_agents(before=before)
import { Firecrawl } from 'firecrawl';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

// List your most recent agent runs
const page = await firecrawl.listAgents();

for (const run of page.agents ?? []) {
  console.log(run.id, run.status, run.targetHint);
}

// Fetch the next page using the cursor from `next`
if (page.next) {
  const before = Number(new URL(page.next).searchParams.get("before"));
  const older = await firecrawl.listAgents({ before });
}
curl -X GET "https://api.firecrawl.dev/v2/agent" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY"

# Fetch the next page (unix ms timestamp from the previous page's `next` URL)
curl -X GET "https://api.firecrawl.dev/v2/agent?before=1756600000000" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY"

Following a run in progress

Agent doesn't hold a streamed connection open. There's no server-sent event stream and no websocket, so you follow a run either by polling its trace or by receiving webhooks.

Surface What you get Best for
Trace polling Full detail: every event the run has emitted so far, including tool calls, reasoning summaries, progress phases, and artifact changes Building your own progress UI, or debugging what a run actually did
Webhooks Push delivery, coarse-grained: the five agent lifecycle events (agent.started, agent.action, agent.completed, agent.failed, agent.cancelled). See webhook events Reacting to a run finishing without holding a poll loop open
Live view A human-watchable view of the agent's browser. Request the trace with ?liveView=true and each entry in activeBrowserSessions carries a liveViewUrl Watching a run navigate in real time

When you order trace events yourself, group them by agent.id first: producerSequence is monotonic per emitting agent, so a single global sort interleaves an orchestrator's events with its subagents' incorrectly. Events can also land for a moment after the terminal run.finished event, so keep polling through a short tail window before you render the final state.

import time
from collections import defaultdict

from firecrawl import Firecrawl

app = Firecrawl(api_key="fc-YOUR_API_KEY")

agent_job = app.start_agent(prompt="Find the founders of Firecrawl")
seen = set()
finished = False
quiet_polls = 0

while True:
    trace = app.get_agent_trace(agent_job.id)

    # producer_sequence is monotonic per emitting agent, so group first.
    by_agent = defaultdict(list)
    for event in trace.events or []:
        by_agent[event.agent.id].append(event)

    new_events = 0
    for agent_id, events in by_agent.items():
        for event in sorted(events, key=lambda e: e.producer_sequence):
            if event.event_id not in seen:
                seen.add(event.event_id)
                new_events += 1
                print(agent_id, event.producer_sequence, event.type)

    if not finished:
        finished = app.get_agent_status(agent_job.id).status != "processing"
    elif new_events:
        quiet_polls = 0
    else:
        # Tail window: events can land for a moment after the run finishes.
        quiet_polls += 1
        if quiet_polls == 3:
            break

    time.sleep(5)
import { Firecrawl } from 'firecrawl';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

const started = await firecrawl.startAgent({ prompt: "Find the founders of Firecrawl" });
const seen = new Set();
let finished = false;
let quietPolls = 0;

for (;;) {
  const trace = await firecrawl.getAgentTrace(started.id);

  // producerSequence is monotonic per emitting agent, so group first.
  const byAgent = new Map();
  for (const event of trace.events ?? []) {
    const bucket = byAgent.get(event.agent.id) ?? [];
    bucket.push(event);
    byAgent.set(event.agent.id, bucket);
  }

  let newEvents = 0;
  for (const [agentId, events] of byAgent) {
    for (const event of events.sort((a, b) => a.producerSequence - b.producerSequence)) {
      if (seen.has(event.eventId)) continue;
      seen.add(event.eventId);
      newEvents++;
      console.log(agentId, event.producerSequence, event.type);
    }
  }

  if (!finished) {
    finished = (await firecrawl.getAgentStatus(started.id)).status !== "processing";
  } else if (newEvents) {
    quietPolls = 0;
  } else {
    // Tail window: events can land for a moment after the run finishes.
    if (++quietPolls === 3) break;
  }

  await new Promise((resolve) => setTimeout(resolve, 5000));
}
# Print only the events you haven't seen yet, and keep polling through a short
# tail window after the run finishes.
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
: > "$tmp/seen.txt"
finished=0
quiet=0

while [ "$quiet" -lt 3 ]; do
  curl -s "https://api.firecrawl.dev/v2/agent/JOB_ID/trace" \
    -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
  | jq -r '.events | group_by(.agent.id)[] | sort_by(.producerSequence)[]
           | "\(.eventId) \(.agent.id) \(.producerSequence) \(.type)"' > "$tmp/poll.txt"

  new=$(grep -vxF -f "$tmp/seen.txt" "$tmp/poll.txt")
  [ -n "$new" ] && echo "$new"
  cp "$tmp/poll.txt" "$tmp/seen.txt"

  if [ "$finished" = 0 ]; then
    status=$(curl -s "https://api.firecrawl.dev/v2/agent/JOB_ID" \
      -H "Authorization: Bearer $FIRECRAWL_API_KEY" | jq -r '.status')
    [ "$status" = "processing" ] || finished=1
  elif [ -n "$new" ]; then
    quiet=0
  else
    quiet=$((quiet + 1))
  fi

  sleep 5
done

Execution Traces and Snapshots

Every run records a canonical execution trace — ordered events covering tool calls, reasoning summaries, progress updates, browser sessions, and output artifact changes. Fetch it to debug a run or power a live progress UI:

from firecrawl import Firecrawl

app = Firecrawl(api_key="fc-YOUR_API_KEY")

# Execution trace of a run: ordered events (tool calls, reasoning, artifacts)
trace = app.get_agent_trace("JOB_ID")

for event in trace.events or []:
    print(event.type)

# Include currently active browser sessions while the run is in flight
live = app.get_agent_trace("JOB_ID", live_view=True)
for session in live.active_browser_sessions or []:
    print(session.live_view_url)
import { Firecrawl } from 'firecrawl';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

// Execution trace of a run: ordered events (tool calls, reasoning, artifacts)
const trace = await firecrawl.getAgentTrace("JOB_ID");

for (const event of trace.events ?? []) {
  console.log(event.type);
}

// Include currently active browser sessions while the run is in flight
const live = await firecrawl.getAgentTrace("JOB_ID", { liveView: true });
console.log(live.activeBrowserSessions);
curl "https://api.firecrawl.dev/v2/agent/JOB_ID/trace" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY"

# Include currently active browser sessions while the run is in flight
curl "https://api.firecrawl.dev/v2/agent/JOB_ID/trace?liveView=true" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY"

artifact.updated trace events reference the agent's working output by snapshotId. Fetch the full content of a snapshot with the snapshots endpoint:

from firecrawl import Firecrawl

app = Firecrawl(api_key="fc-YOUR_API_KEY")

# artifact.updated trace events reference snapshot content by snapshotId
snapshot = app.get_agent_snapshot("JOB_ID", "SNAPSHOT_ID")

print(snapshot.snapshot)
import { Firecrawl } from 'firecrawl';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

// artifact.updated trace events reference snapshot content by snapshotId
const snapshot = await firecrawl.getAgentSnapshot("JOB_ID", "SNAPSHOT_ID");

console.log(snapshot.snapshot);
curl "https://api.firecrawl.dev/v2/agent/JOB_ID/snapshots/SNAPSHOT_ID" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY"

Traces and snapshots are recorded on Spark 2 runs, which is every new run; jobs started on Spark 1 models before their retirement do not have them. See the trace and snapshot API references for the full event schema, and the Agent errors catalog for the failures these endpoints return.

Getting the agent's source data

A run writes its working output to artifacts as it goes, and you can retrieve them once you have the run's trace. Every artifact.updated event describes one change to one artifact: artifact.kind is json, markdown, html, screenshot, or text, artifact.path is where the run put it, and artifact.snapshotId is the handle you exchange for its content at GET /agent/{jobId}/snapshots/{snapshotId}. The snapshot endpoint returns that content in a snapshot field as a string: for json artifacts that string is JSON-encoded and needs decoding, while markdown, html, and text artifacts are the content itself.

To pull the page content a run produced, fetch the trace, keep the artifact.updated events whose kind you want, then fetch each snapshot:

import json

from firecrawl import Firecrawl

app = Firecrawl(api_key="fc-YOUR_API_KEY")

trace = app.get_agent_trace("JOB_ID")

for event in trace.events or []:
    if event.type != "artifact.updated":
        continue

    kind = event.artifact.kind
    if kind not in ("markdown", "html", "json"):
        continue

    snapshot = app.get_agent_snapshot("JOB_ID", event.artifact.snapshot_id)

    # markdown, html, and text snapshots are the content itself.
    # json snapshots are JSON-encoded, so decode those.
    content = json.loads(snapshot.snapshot) if kind == "json" else snapshot.snapshot

    print(kind, event.artifact.path, content)
import { Firecrawl } from 'firecrawl';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

const trace = await firecrawl.getAgentTrace("JOB_ID");

for (const event of trace.events ?? []) {
  if (event.type !== "artifact.updated") continue;

  const kind = event.artifact.kind;
  if (!["markdown", "html", "json"].includes(kind)) continue;

  const snapshot = await firecrawl.getAgentSnapshot("JOB_ID", event.artifact.snapshotId);

  // markdown, html, and text snapshots are the content itself.
  // json snapshots are JSON-encoded, so decode those.
  const content = kind === "json" ? JSON.parse(snapshot.snapshot) : snapshot.snapshot;

  console.log(kind, event.artifact.path, content);
}
# Fetch every markdown, html, or json artifact the run wrote.
curl -s "https://api.firecrawl.dev/v2/agent/JOB_ID/trace" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
| jq -r '.events[]
         | select(.type == "artifact.updated")
         | select(.artifact.kind == "markdown" or .artifact.kind == "html" or .artifact.kind == "json")
         | "\(.artifact.kind) \(.artifact.snapshotId)"' \
| while read -r kind snapshot_id; do
    body=$(curl -s "https://api.firecrawl.dev/v2/agent/JOB_ID/snapshots/$snapshot_id" \
      -H "Authorization: Bearer $FIRECRAWL_API_KEY")

    # markdown and html snapshots are the content itself; json is JSON-encoded.
    if [ "$kind" = "json" ]; then
      printf '%s' "$body" | jq -r '.snapshot | fromjson'
    else
      printf '%s' "$body" | jq -r '.snapshot'
    fi
  done

Two things worth knowing before you build on this:

  • Artifacts are the run's output, not a page-by-page archive. What a run writes to an artifact depends on how it works through your prompt, so treat the artifact set as what that particular run produced rather than a guaranteed record of every page it opened.
  • Tool results carry the rest. Each tool_call.finished event includes a result field holding what that tool returned, which is where content that never became an artifact shows up.

Share agent runs

You can share agent runs directly from the Agent playground. Shared links are public — anyone with the link can view the run output and activity — and you can revoke access at any time to disable the link. Shared pages are not indexed by search engines.

Model Selection

Firecrawl Agent runs on Spark 2 — cheaper and faster than the earlier Spark 1 models, at comparable accuracy. It is the default: every run executes on spark-2, whether or not you set the model parameter.

Spark 1 models are deprecated. The Spark 1 model names remain accepted for backwards compatibility, but requests that use them route to spark-2.

Spark 2

spark-2 handles the full range of tasks that previously called for a Mini-versus-Pro decision, so there is no accuracy-versus-cost trade-off to make.

Highlights:

  • Lowest cost per run
  • Fastest run time
  • Accuracy comparable to the former Spark 1 flagship
  • The only model with a reasoning budget: pass effort (low, medium, or high) to control how hard it thinks

Specifying a Model

The model parameter is optional — every request runs spark-2:

from firecrawl import Firecrawl

app = Firecrawl(api_key="fc-YOUR_API_KEY")

# Spark 2 is the default — every run executes on it
result = app.agent(
    prompt="Find the pricing of Firecrawl",
    model="spark-2"
)

# Deprecated: Spark 1 model names are still accepted, but route to "spark-2".

print(result.data)
import { Firecrawl } from 'firecrawl';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

// Spark 2 is the default — every run executes on it
const result = await firecrawl.agent({
  prompt: "Find the pricing of Firecrawl",
  model: "spark-2"
});

// Deprecated: Spark 1 model names are still accepted, but route to "spark-2".

console.log(result.data);
# Spark 2 is the default — every run executes on it
curl -X POST "https://api.firecrawl.dev/v2/agent" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Find the pricing of Firecrawl",
    "model": "spark-2"
  }'

# Deprecated: Spark 1 model names are still accepted, but route to "spark-2".

Use your connected Alexandria tools

Agent can call your team's Alexandria data providers during a run, alongside the web. The playground turns them on for you. From the API and the SDKs, a run uses the web only until you send an exchange object, so a request without one never uses your providers.

Send exchange with enabled: true to let the agent use every provider your team can use, or pin up to five with toolkits:

from firecrawl import Firecrawl

app = Firecrawl(api_key="fc-YOUR_API_KEY")

result = app.agent(
    prompt="Find recent podcast episodes about AI agents and who appeared on them",
    exchange={
        "enabled": True,
        # Up to 5 provider slugs. Leave out to let the agent use every provider.
        "toolkits": ["particle"],
    },
)

print(result.data)
if result.exchange:
    print(result.exchange.paid_calls, result.exchange.credits_used)
import { Firecrawl } from 'firecrawl';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

const result = await firecrawl.agent({
  prompt: "Find recent podcast episodes about AI agents and who appeared on them",
  exchange: {
    enabled: true,
    // Up to 5 provider slugs. Leave out to let the agent use every provider.
    toolkits: ["particle"]
  }
});

console.log(result.data);
console.log(result.exchange?.paidCalls, result.exchange?.creditsUsed);
curl -X POST "https://api.firecrawl.dev/v2/agent" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Find recent podcast episodes about AI agents and who appeared on them",
    "exchange": {
      "enabled": true,
      "toolkits": ["particle"]
    }
  }'
Field What it does
enabled Lets the agent call providers. Defaults to true once you send exchange, so an empty object also turns them on. Send false to turn them off for one turn of a thread.
toolkits Up to 5 provider slugs, such as ["apollo"]. The agent uses only those. Empty or left out means every provider your team can use.
maxCalls The most provider calls the agent may make in one turn, from 1 to 30. Defaults to 16.
requireApproval Stops the turn before any paid provider call and ends it with a pendingApproval for you to answer. Needs mode: "chat" on the same request. Defaults to false.
approve, decline Answer the previous turn's pendingApproval on the next turn of the thread. See Approve paid calls before they run.
onTermsRequired What to do when a provider needs data terms your team hasn't accepted. See Data providers that need terms.

The status response's exchange object reports what the run did: enabled, the toolkits and requireApproval it ran with, paidCalls (paid provider calls it made) and creditsUsed (what those calls cost, null when none were recorded).

Follow-up turns

A follow-up turn of a thread (a request with threadId) that leaves out exchange keeps the previous turn's settings. If it sends an exchange object, toolkits and onTermsRequired still carry over when left out, but enabled, maxCalls and requireApproval go back to their defaults unless you send them again.

Approve paid calls before they run

With requireApproval: true, the agent stops before its first paid provider call and the turn ends with a pendingApproval of kind: "calls". It carries an id, the agent's reason, and the calls it wants to make, each with an id, provider, capability, input and creditsEstimate. Show them to your user, then answer on the next turn of the same thread:

  • exchange.approve: { "approvalId": "<pendingApproval.id>" } runs the calls. Add callIds to run only some of them, or always: true to stop asking for the rest of the thread.
  • exchange.decline: { "approvalId": "<pendingApproval.id>" } skips them, and the agent answers without them.

Send requireApproval: true again on the answering turn to keep later paid calls waiting for approval. Both turns need mode: "chat".

from firecrawl import Firecrawl

app = Firecrawl(api_key="fc-YOUR_API_KEY")

# requireApproval needs chat mode on every request that sends it.
first = app.agent(
    prompt="Find the head of engineering at Firecrawl and a verified work email",
    mode="chat",
    exchange={"enabled": True, "toolkits": ["apollo"], "requireApproval": True},
)

approval = first.pending_approval
if approval is None or approval.is_terms:
    print(first.data or first.message)
else:
    for call in approval.calls or []:
        print(call.provider, call.capability, call.credits_estimate)

    # Answer on the next turn of the same thread. Sending requireApproval again
    # keeps later paid calls waiting for approval too.
    result = app.agent(
        thread_id=first.thread_id,
        prompt="Approved, go ahead.",
        mode="chat",
        exchange={"requireApproval": True, "approve": {"approvalId": approval.id}},
        # To refuse instead: exchange={"decline": {"approvalId": approval.id}}
    )
    print(result.data or result.message)
import { Firecrawl } from 'firecrawl';

const firecrawl = new Firecrawl({ apiKey: "fc-YOUR_API_KEY" });

// requireApproval needs chat mode on every request that sends it.
const first = await firecrawl.agent({
  prompt: "Find the head of engineering at Firecrawl and a verified work email",
  mode: "chat",
  exchange: { enabled: true, toolkits: ["apollo"], requireApproval: true }
});

const approval = first.pendingApproval;
if (!approval || approval.kind === "terms") {
  console.log(first.data ?? first.message);
} else {
  for (const call of approval.calls) {
    console.log(call.provider, call.capability, call.creditsEstimate);
  }

  // Answer on the next turn of the same thread. Sending requireApproval again
  // keeps later paid calls waiting for approval too.
  const result = await firecrawl.agent({
    threadId: first.threadId,
    prompt: "Approved, go ahead.",
    mode: "chat",
    exchange: { requireApproval: true, approve: { approvalId: approval.id } }
    // To refuse instead: exchange: { decline: { approvalId: approval.id } }
  });
  console.log(result.data ?? result.message);
}
# 1. Start a run that asks before any paid provider call.
curl -X POST "https://api.firecrawl.dev/v2/agent" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Find the head of engineering at Firecrawl and a verified work email",
    "mode": "chat",
    "exchange": { "enabled": true, "toolkits": ["apollo"], "requireApproval": true }
  }'

# 2. Poll the run. When it ends with a pendingApproval, read its id and calls.
curl -X GET "https://api.firecrawl.dev/v2/agent/<jobId>" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY"

# 3. Approve on the next turn of the same thread, or send
#    "decline": { "approvalId": "<pendingApproval.id>" } instead.
curl -X POST "https://api.firecrawl.dev/v2/agent" \
  -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "threadId": "<threadId from the first run>",
    "prompt": "Approved, go ahead.",
    "mode": "chat",
    "exchange": {
      "requireApproval": true,
      "approve": { "approvalId": "<pendingApproval.id>" }
    }
  }'

Data providers that need terms