> ## Documentation Index
> Fetch the complete documentation index at: https://firecrawl-claude-eager-dijkstra-4orfll.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 代理

> 从网络上的任意位置获取数据。

**选择合适的工具。** 当你**不知道 URL**，或需要在网页上进行自主导航时，代理就是正确的选择。

* 对于**单个已知 URL**，[`/scrape` 的 JSON 模式](/zh/features/llm-extract)成本更低，而且是同步的。
* 完整对比见：[选择数据提取器](/zh/developer-guides/usage-guides/choosing-the-data-extractor)。

Firecrawl `/agent` 是一个魔法般的 API，它可以在最广泛的网站范围内进行搜索、导航并收集数据，在难以触及的角落中找到数据，并以其他任何 API 都无法做到的方式发掘信息。它可以在几分钟内完成原本需要人类耗费数小时的工作——从端到端的数据采集，全程无需脚本或人工操作。
无论你只需要一个数据点，还是需要大规模的完整数据集，Firecrawl `/agent` 都能为你获取这些数据。

**把 `/agent` 想象成：无论数据藏在哪里，它都能替你做深度调研！**

<Info>
  **Research Preview**：代理目前处于早期访问阶段。可能会有不完善之处，但它会随着时间显著变好。
</Info>

<div className="firecrawl-cta-box">
  <div style={{ display: "flex", alignItems: "flex-start", gap: "8px", marginBottom: "8px" }}>
    <Icon icon="sack-dollar" color="#ff4d00" size={22} />

    <div className="firecrawl-cta-title" style={{ margin: 0 }}>
      <span style={{ color: "#ff4d00" }}>悬赏：5,000 额度奖励</span>
      <span style={{ fontWeight: 400 }}>，征集关于 /agent 的优质反馈</span>
    </div>
  </div>

  <p className="firecrawl-cta-description">
    只需与我们的 Firecrawl Feedback Assistant 完成一次高质量访谈 (分享经过思考的具体用例等) ，即可获得奖励资格。整个过程只需几分钟，随时可以停止，对人类和代理都很友好 (只需将链接粘贴到你的代理测试框架中！) 。从未使用过 /agent？你的看法同样重要。
  </p>

  <a href={"https://www.firecrawl.dev/survey/7pjb4?src=" + (props.src || "docs-agent")} className="firecrawl-cta-btn-primary firecrawl-cta-btn-inline">
    开始访谈
  </a>

  <p className="firecrawl-cta-description" style={{ fontSize: "12px", fontStyle: "italic", margin: "12px 0 0 0" }}>
    请填写邮箱，以获得奖励资格。我们会在每周末审核访谈质量。
  </p>
</div>

代理构建于 `/extract` 的全部优势之上，并在此基础上更进一步：

* **无需提供 URL**：只需通过 `prompt` 参数描述你的需求，URL 是可选的。
* **深度网页搜索**：自主搜索并深入浏览站点以找到所需数据
* **可靠且准确**：适用于多种类型的查询和使用场景
* **更快**：并行处理多个数据源以更快返回结果

<Card title="在 Playground 中体验" icon="play" href="https://www.firecrawl.dev/agent">
  在交互式 Playground 中测试该 Agent，无需编写代码。
</Card>

<div id="using-agent">
  ## 使用 `/agent`
</div>

唯一必需的参数是 `prompt`。只需描述你想要提取的数据。要获得结构化输出，请提供一个 JSON schema。SDK 支持使用 Pydantic (Python) 和 Zod (Node) 来定义类型安全的 schema：

<CodeGroup>
  ```python Python theme={null}
  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="专业背景")

  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)
  ```

  ```js Node theme={null}
  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);
  ```

  ```bash cURL theme={null}
  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": "专业背景" }
              },
              "required": ["name"]
            }
          }
        },
        "required": ["founders"]
      }
    }'
  ```
</CodeGroup>

<div id="response">
  ### 响应
</div>

```json JSON theme={null}
{
  "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
}
```

<div id="providing-urls-optional">
  ## 提供 URL (可选)
</div>

你可以选择提供 URL，让 agent 专注于特定页面：

<CodeGroup>
  ```python Python theme={null}
  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="比较这些页面的功能和定价信息"
  )

  print(result.data)
  ```

  ```js Node theme={null}
  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);
  ```

  ```bash cURL theme={null}
  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"
    }'
  ```
</CodeGroup>

<div id="job-status-and-completion">
  ## 任务状态与完成
</div>

Agent 任务以异步方式运行。提交任务后，你会收到一个 Job ID，用于检查任务状态：

* **默认方式**：`agent()` 会阻塞等待，并返回最终结果
* **先启动再轮询**：使用 `start_agent` (Python) 或 `startAgent` (Node) 立即获取 Job ID，然后通过 `get_agent_status` / `getAgentStatus` 进行轮询

<Note>任务结果在完成后可通过 API 获取，保留 24 小时。在此之后，你仍然可以在 [activity logs](https://www.firecrawl.dev/app/logs) 中查看你的 Agent 历史记录和结果。</Note>

<CodeGroup>
  ```python Python theme={null}
  from firecrawl import Firecrawl

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

  # 启动一个 Agent 任务
  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
  ```

  ```js Node theme={null}
  import { Firecrawl } from 'firecrawl';

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

  // 启动一个 Agent 任务
  const started = await firecrawl.startAgent({
    prompt: "Find the founders of Firecrawl"
  });

  // 检查任务状态
  if (started.id) {
    const status = await firecrawl.getAgentStatus(started.id);
    console.log(status.status, status.data);
  }
  ```

  ```bash cURL theme={null}
  curl -X GET "https://api.firecrawl.dev/v2/agent/<jobId>" \
    -H "Authorization: Bearer $FIRECRAWL_API_KEY"
  ```
</CodeGroup>

<div id="possible-states">
  ### 可能的状态
</div>

| 状态           | 描述                                              |
| ------------ | ----------------------------------------------- |
| `processing` | 代理仍在处理你的请求                                      |
| `completed`  | 提取已成功完成                                         |
| `failed`     | 提取过程中发生错误，或任务被取消 (被取消的任务会报告 `failed`，并附带取消错误消息) |

<Note>
  **取消是协作式的。** 当你调用取消端点时，请求会立即登记，但任何已经在进行中的步骤 (如 LLM 推理步骤、工具调用或浏览器操作) 都会先运行到可安全停止的节点，然后任务才会停止。在这段短暂时间内，额度仍可能继续累积，因此最终的 `creditsUsed` 可能高于你点击取消时显示的数值。被取消的任务在轮询时会报告状态 `failed`，并触发 `agent.cancelled` Webhook 事件。
</Note>

<div id="pending-example">
  #### 等待中示例
</div>

```json JSON theme={null}
{
  "success": true,
  "status": "processing",
  "expiresAt": "2024-12-15T00:00:00.000Z"
}
```

<div id="completed-example">
  #### 已完成示例
</div>

```json JSON theme={null}
{
  "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
}
```

<div id="execution-traces-and-snapshots">
  ## 执行追踪和快照
</div>

每次运行都会记录一份规范的执行追踪，其中按顺序包含工具调用、推理摘要、进度更新、浏览器会话和输出工件变更等事件。可获取该追踪以调试运行，或为实时进度 UI 提供数据：

<CodeGroup>
  ```python Python theme={null}
  from firecrawl import Firecrawl

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

  # 单次运行的执行轨迹：有序事件（tool calls、推理、产物）
  trace = app.get_agent_trace("JOB_ID")

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

  # 运行进行中时，一并返回当前活跃的浏览器会话
  live = app.get_agent_trace("JOB_ID", live_view=True)
  for session in live.active_browser_sessions or []:
      print(session.live_view_url)
  ```

  ```js Node theme={null}
  import { Firecrawl } from 'firecrawl';

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

  // 某次运行的执行轨迹：按顺序排列的事件（tool calls、推理、产物）
  const trace = await firecrawl.getAgentTrace("JOB_ID");

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

  // 运行进行中时，一并返回当前活跃的浏览器会话
  const live = await firecrawl.getAgentTrace("JOB_ID", { liveView: true });
  console.log(live.activeBrowserSessions);
  ```

  ```bash cURL theme={null}
  curl "https://api.firecrawl.dev/v2/agent/JOB_ID/trace" \
    -H "Authorization: Bearer $FIRECRAWL_API_KEY"

  # 在运行进行中时，包含当前活跃的浏览器会话
  curl "https://api.firecrawl.dev/v2/agent/JOB_ID/trace?liveView=true" \
    -H "Authorization: Bearer $FIRECRAWL_API_KEY"
  ```
</CodeGroup>

`artifact.updated` 追踪事件通过 `snapshotId` 引用代理的工作输出。使用快照端点可获取快照的完整内容：

<CodeGroup>
  ```python Python theme={null}
  from firecrawl import Firecrawl

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

  # artifact.updated 追踪事件通过 snapshotId 引用快照内容
  snapshot = app.get_agent_snapshot("JOB_ID", "SNAPSHOT_ID")

  print(snapshot.snapshot)
  ```

  ```js Node theme={null}
  import { Firecrawl } from 'firecrawl';

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

  // artifact.updated 跟踪事件通过 snapshotId 引用快照内容
  const snapshot = await firecrawl.getAgentSnapshot("JOB_ID", "SNAPSHOT_ID");

  console.log(snapshot.snapshot);
  ```

  ```bash cURL theme={null}
  curl "https://api.firecrawl.dev/v2/agent/JOB_ID/snapshots/SNAPSHOT_ID" \
    -H "Authorization: Bearer $FIRECRAWL_API_KEY"
  ```
</CodeGroup>

<Note>Spark 2 运行会记录追踪和快照，也就是说所有新运行都会记录；在 Spark 1 模型退役前启动的任务则不包含这些记录。有关完整的事件 schema，请参见[追踪](/zh/api-reference/endpoint/agent-trace)和[快照](/zh/api-reference/endpoint/agent-snapshot) API 参考。</Note>

<div id="share-agent-runs">
  ## 分享代理运行记录
</div>

你可以直接在 Agent playground 中分享代理运行记录。共享链接是公开的，任何拥有链接的人都可以查看运行输出和活动；你也可以随时撤销访问权限以停用该链接。共享页面不会被搜索引擎收录。

<div id="model-selection">
  ## 模型选择
</div>

Firecrawl 代理使用 **Spark 2**，相比早期的 Spark 1 模型成本更低、速度更快，准确率相当。它是默认值：无论是否设置 `model` 参数，每次运行都会使用 `spark-2`。

<Note>
  **Spark 1 模型已弃用。** 为保持向后兼容，仍接受 Spark 1 模型名称，但使用这些名称的请求会被路由到 `spark-2`。
</Note>

<div id="spark-2">
  ### Spark 2
</div>

`spark-2` 覆盖了此前需要在 Mini 和 Pro 之间取舍的全部任务，因此无需再权衡准确率与成本。

**亮点：**

* 单次运行成本最低
* 运行时间最快
* 准确率可媲美之前的 Spark 1 旗舰模型
* 唯一支持推理预算的模型：传入 `effort` (`low`、`medium` 或 `high`) 以控制其思考深度

<div id="specifying-a-model">
  ### 指定模型
</div>

`model` 参数可选——每个请求都会运行 `spark-2`：

<CodeGroup>
  ```python Python theme={null}
  from firecrawl import Firecrawl

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

  # Spark 2 是默认值 —— 每次运行都使用它
  result = app.agent(
      prompt="Find the pricing of Firecrawl",
      model="spark-2"
  )

  # 已弃用:仍可使用 Spark 1 的模型名称,但会被路由到 "spark-2"。

  print(result.data)
  ```

  ```js Node theme={null}
  import { Firecrawl } from 'firecrawl';

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

  // Spark 2 为默认值 — 每次运行都会使用它
  const result = await firecrawl.agent({
    prompt: "Find the pricing of Firecrawl",
    model: "spark-2"
  });

  // 已弃用：仍接受 Spark 1 的模型名称，但会路由到 "spark-2"。

  console.log(result.data);
  ```

  ```bash cURL theme={null}
  # Spark 2 为默认模型——所有运行均使用它执行
  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"
    }'

  # 已弃用：仍可传入 Spark 1 的模型名称，但会路由到 "spark-2"。
  ```
</CodeGroup>

<div id="parameters">
  ## 参数
</div>

| 参数                      | 类型      | 必填    | 描述                                                                                                                                                                                                                                                         |
| ----------------------- | ------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `prompt`                | string  | **是** | 用自然语言描述你想要提取的数据 (最多 10,000 个字符)                                                                                                                                                                                                                            |
| `model`                 | string  | 否     | 默认使用 `spark-2`，所有运行均使用该模型。Spark 1 模型已弃用，并会路由至 `spark-2`                                                                                                                                                                                                    |
| `effort`                | string  | 否     | 推理预算：`low`、`medium` 或 `high`。所有运行均使用 `spark-2`，因此无论是否指定 `model`，都可以传入 `effort`                                                                                                                                                                             |
| `urls`                  | array   | 否     | 可选的 URL 列表，用于聚焦提取                                                                                                                                                                                                                                          |
| `schema`                | object  | 否     | 用于结构化输出的可选 JSON schema                                                                                                                                                                                                                                     |
| `strictConstrainToURLs` | boolean | 否     | 如果为 `true`，代理仅访问 `urls` array 中提供的 URL                                                                                                                                                                                                                     |
| `webhook`               | object  | 否     | 用于接收代理生命周期事件 (`agent.started`、`agent.action`、`agent.completed`、`agent.failed`、`agent.cancelled`) 的 Webhook。请参见 [webhook payloads](/zh/api-reference/endpoint/webhook-agent-started)                                                                        |
| `maxCredits`            | number  | 否     | 此代理任务中可花费的最大额度数。如果未设置，默认值为 **2,500**。Dashboard 最高支持 **2,500**；如需更高上限，请通过 API 设置 `maxCredits` (高于 2,500 的值始终按付费请求处理) 。如果达到上限，任务会失败，并且**不会返回任何数据**。失败的运行不会计费：用于 AI 推理的额度在失败时绝不会收费，运行期间任何用于工具调用的额度 (scraping、search、mapping 等) 都会退还，并且响应会返回 `creditsUsed: 0`。 |

<div id="agent-vs-extract-whats-improved">
  ## Agent 与 Extract：有哪些改进
</div>

| 特性         | Agent (新) | Extract |
| ---------- | --------- | ------- |
| 是否需要提供 URL | 否         | 是       |
| 速度         | 更快        | 标准      |
| 成本         | 更低        | 标准      |
| 可靠性        | 更高        | 标准      |
| 查询灵活性      | 高         | 中等      |

<div id="example-use-cases">
  ## 示例用例
</div>

* **调研**: "找出前 5 家 AI 初创公司及其融资金额"
* **竞品分析**: "比较 Slack 和 Microsoft Teams 的定价方案"
* **数据收集**: "从公司网站中提取联系方式"
* **内容摘要**: "总结关于网页抓取的最新博客文章"

<div id="csv-upload-in-agent-playground">
  ## 在 Agent Playground 中上传 CSV
</div>

[Agent Playground](https://www.firecrawl.dev/app/agent) 支持通过上传 CSV 进行批量处理。你的 CSV 可以包含一列或多列输入数据。例如：一列公司名称，或者多列数据，如公司名称、产品和网站 URL。每一行都代表一个需要由 Agent 处理的条目。

上传你的 CSV，然后使用表头中的 "+" 按钮添加输出列。每一列都有自己的 prompt——点击列表头，描述 Agent 应为该字段查找什么内容 (例如，“CEO 或创始人姓名”、“融资总额”) 。点击 Run，Agent 会并行处理每一行并填充结果。

<div id="troubleshooting-with-ask">
  ## 使用 Ask 排查问题
</div>

如果你的代理任务失败或返回了异常结果，请使用 [Ask API](/zh/features/ask) 进行代理式调试。描述问题，即可获取经过验证的答案以及可直接应用的修复参数：

```bash theme={null}
curl -X POST https://api.firecrawl.dev/v2/support/ask \
  -H "Authorization: Bearer fc-YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "question": "my agent returned incomplete results"
  }'
```

请参见 [Ask 文档](/zh/features/ask)，了解完整详情和集成示例。

<div id="api-reference">
  ## API 参考
</div>

请参阅 [Agent API Reference](/zh/api-reference/endpoint/agent) 以了解更多详情。

有反馈或需要帮助？请发送邮件至 [help@firecrawl.com](mailto:help@firecrawl.com)。

<div id="pricing">
  ## 价格
</div>

Firecrawl Agent 使用 **动态计费** 模式，费用会随你的数据提取请求复杂度而变化。你根据 Agent 实际完成的工作量付费，无论是提取简单的数据点，还是从多个来源获取复杂的结构化信息，都能享受公平的定价。

<div id="how-agent-pricing-works">
  ### Agent 计费方式
</div>

在 Research Preview 阶段，Agent 的计费是**动态的、基于 credit 的**：

* **简单抽取任务** (例如从单个页面提取联系方式) 通常消耗更少的 credits，成本更低
* **复杂研究任务** (例如对多个域名进行竞品分析) 会消耗更多 credits，但更能体现整体投入的工作量
* **用量透明**会清楚展示每个请求具体消耗了多少 credits
* **Credit 换算**会自动将 Agent 的 credit 使用量换算为 credits，便于计费

<Info>
  Credit 使用量会因 prompt 的复杂度、处理的数据量以及期望输出的结构而有所不同。大致来说，大多数 Agent 运行会消耗**数百个 credits**，更简单的单页任务可能会用得更少，而复杂的多域名研究可能会用得更多。
</Info>

<div id="parallel-agents-pricing">
  ### 并行 Agent 计费
</div>

如果你使用 Spark-1 Fast 并行运行多个 agent，费用会更加可预测：每个 cell 消耗 10 个积分。

<div id="getting-started">
  ### 入门
</div>

**所有用户**每天都会获得**5 次免费运行**，可以通过 playground 或 API 使用，用于在无需付费的情况下体验 Agent 的功能。

额外用量会根据 credit 消耗计费，并换算为 credits。

<div id="managing-costs">
  ### 成本管理
</div>

代理可能会比较昂贵，但有一些方法可以降低成本：

* **从免费运行开始**：利用你每天 5 次免费请求来了解定价
* **设置 `maxCredits` 参数**：通过设置你愿意花费的最大额度数来限制支出。Dashboard 将此上限设为 2,500 额度；若要设置更高的上限，请直接通过 API 使用 `maxCredits` 参数 (注意：高于 2,500 的值始终按付费请求计费)
* **优化 prompt**：更具体的 prompt 通常会消耗更少的额度
* **将大型任务拆分为更小的运行**：单次代理运行的输出上限取决于底层模型的生成能力 (约 150-200 行结构化数据) 。对于大型提取任务，可按类别、地区或 URL 批次 (每次运行 3-5 个 URL) 进行拆分，再合并结果。这也能让每次运行都保持在 `maxCredits` 限制之下。
* **监控用量**：通过 Dashboard 追踪你的使用情况
* **设定预期**：跨多个站点/领域的复杂研究会比简单的单页提取消耗更多额度

现在访问 [firecrawl.dev/app/agent](https://www.firecrawl.dev/app/agent) 试用代理，看看在你的具体用例下额度的使用如何随规模变化。

<Note>
  随着我们从 Research Preview 过渡到正式开放，定价可能会发生变化。现有用户将在任何价格更新前提前收到通知。
</Note>

> 你是需要 Firecrawl API 密钥的 AI 代理吗？请参阅 [firecrawl.dev/agent-onboarding/SKILL.md](https://www.firecrawl.dev/agent-onboarding/SKILL.md) 了解自动化引导说明。
