# @fiberai/sdk 中文文档

规范地址：https://npmcn.com/package/%40fiberai/sdk/

版本：0\.0\.66
npm 元数据更新时间：2026-10-30T22:53:22.874Z
中文译文更新时间：2026-11-14T16:49:32.800Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40fiberai/sdk
原文对照：https://npmcn.com/package/%40fiberai/sdk/?lang=original
项目主页：https://fiber.ai/
源码仓库：https://github.com/fiber-ai/typescript-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：76.3 MB，11 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18\.0\.0
- 运行依赖：1 个
- peer 依赖：typescript \>=5\.0\.0
- 首次发布：2026-01-23T18:00:28.786Z
- 最新版本发布：2026-10-30T22:53:22.362Z
- 近 30 天下载量：2159（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：66（近 12 个月 66 个）

## 中文简介

Fiber AI API 的正式类型SDK

## 安装

```sh
npm install @fiberai/sdk
```

也可以使用：`pnpm add @fiberai/sdk`、`yarn add @fiberai/sdk`、`bun add @fiberai/sdk`

## README

# @fiberai/sdk (英语)

正式类型SDK [纤维AI](https://fiber.ai/) API - 联系到地球上任何经核实的联系人

[![npm version](https://img.shields.io/npm/v/@fiberai/sdk.svg)](https://www.npmjs.com/package/@fiberai/sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## 用于AI代理(Cursor / Claude / Codex / ChatGPT / 副驾驶)

请不要猜测操作名称 —— 请首先读取 Cononical 代理处理文件 :

-   **运行索引 + 关键规则:** [https://api.fiber.ai/llms.txt (中文(简体) )](https://api.fiber.ai/llms.txt)
-   **行动减少:** `https://api.fiber.ai/ai-docs/<operationId>.md` (例如:. [`companySearch`](https://api.fiber.ai/ai-docs/companySearch.md), (中文(简体) ), [`syncQuickContactReveal`](https://api.fiber.ai/ai-docs/syncQuickContactReveal.md), (中文(简体) ), [`triggerExhaustiveContactEnrichment`](https://api.fiber.ai/ai-docs/triggerExhaustiveContactEnrichment.md)(中文(简体) )
-   **操作索引 :** [https://api.fiber.ai/ai-docs/index.md](https://api.fiber.ai/ai-docs/index.md)
-   **完整文件( 单个文件) :** [https://api.fiber.ai/llms-full.txt (中文(简体) )](https://api.fiber.ai/llms-full.txt)
-   **OpenAPI 规格 :** `https://api.fiber.ai/openapi.json` (发送) `Accept: text/markdown` 用于方便剂的变体)
-   **MCP 服务器 :** `https://mcp.fiber.ai/mcp/v2` (另见 [纤维-ai/mcp](https://github.com/fiber-ai/mcp)(中文(简体) )

## 目录

-   [安装](https://npmcn.com/package/%40fiberai/sdk/#readme-installation)
-   [快速启动](https://npmcn.com/package/%40fiberai/sdk/#readme-quick-start)
-   [认证](https://npmcn.com/package/%40fiberai/sdk/#readme-authentication)
-   [核心特征](https://npmcn.com/package/%40fiberai/sdk/#readme-core-features)
    -   [公司和人员搜索](https://npmcn.com/package/%40fiberai/sdk/#readme-company--people-search)
    -   [联系人浓缩](https://npmcn.com/package/%40fiberai/sdk/#readme-contact-enrichment)
    -   [链接到现场浓缩](https://npmcn.com/package/%40fiberai/sdk/#readme-linkedin-live-enrichment)
    -   [不适用名单](https://npmcn.com/package/%40fiberai/sdk/#readme-exclusion-lists)
    -   [谷歌地图搜索](https://npmcn.com/package/%40fiberai/sdk/#readme-google-maps-search)
    -   [AI 授权研究](https://npmcn.com/package/%40fiberai/sdk/#readme-ai-powered-research)
-   [高级使用](https://npmcn.com/package/%40fiberai/sdk/#readme-advanced-usage)
-   [处理错误](https://npmcn.com/package/%40fiberai/sdk/#readme-error-handling)
-   [类型脚本支持](https://npmcn.com/package/%40fiberai/sdk/#readme-typescript-support)
    -   [运行时间与 Zod 验证](https://npmcn.com/package/%40fiberai/sdk/#readme-runtime-validation-with-zod)
-   [利率限制和信用](https://npmcn.com/package/%40fiberai/sdk/#readme-rate-limits--credits)
-   [支助](https://npmcn.com/package/%40fiberai/sdk/#readme-support)

## 安装

```bash
npm install @fiberai/sdk
# or
yarn add @fiberai/sdk
# or
pnpm add @fiberai/sdk
```

**所需经费:** 节点.js 18.0.0或以上

## 快速启动

```typescript
import { peopleSearch, companySearch, getOrgCredits } from "@fiberai/sdk";

// Check your organization's credit balance
const credits = await getOrgCredits({
  query: { apiKey: "your-api-key" },
});

console.log(`Available credits: ${credits.data?.output.available}`);

// Search for companies
const companies = await companySearch({
  body: {
    apiKey: "your-api-key",
    searchParams: {
      industriesV2: {
        anyOf: ["Software", "Information Technology"],
      },
      // Bucket-valued range. Allowed bounds: 0 | 1 | 10 | 50 | 200 | 500 | 1000 | 5000 | 10000 | null.
      employeeCountV2: {
        lowerBoundExclusive: 50,
        upperBoundInclusive: 1000,
      },
      headquartersCountryCode: {
        anyOf: ["USA"],
      },
    },
    pageSize: 25,
  },
});

// Search for people
const people = await peopleSearch({
  body: {
    apiKey: "your-api-key",
    searchParams: {
      jobTitleV2: {
        anyOf: [
          { type: "term", term: "CEO" },
          { type: "term", term: "CTO" },
          { type: "static-groups", groups: ["c-suite"] },
        ],
      },
      country3LetterCode: { anyOf: ["USA"] },
    },
    pageSize: 25,
  },
});

// Every successful response also carries a `chargeInfo` envelope alongside
// `output`. Source of truth for cost — prefer this over the static table below.
console.log(people.data?.chargeInfo);
// e.g. { method: 'charged-now', creditsCharged: 25, lowCreditAlert: null }
```

## 认证

所有API请求都需要API密钥. 让你的 [纤维.ai/app/api](https://fiber.ai/app/api)。 。 。 .

**在每个请求中包含您的 API 密钥 :**

-   **请求**: 传出 `apiKey` 请求中
-   **获取请求**: 传出 `apiKey` 作为查询参数

```typescript
// POST request example
await companySearch({
  body: {
    apiKey: process.env.FIBERAI_API_KEY,
    searchParams: {
      /* ... */
    },
  },
});

// GET request example
await getOrgCredits({
  query: { apiKey: process.env.FIBERAI_API_KEY },
});
```

**最佳做法:** 在环境变量中存储您的 API 密钥 :

```bash
# .env
FIBERAI_API_KEY=your_api_key_here
```

## 核心特征

### 公司和人员搜索

#### 公司搜索

寻找使用40+过滤器的公司,包括工业,地点,收入,资金等.

```typescript
import { companySearch, companyCount } from "@fiberai/sdk";

// Advanced company search
const result = await companySearch({
  body: {
    apiKey: process.env.FIBERAI_API_KEY,
    searchParams: {
      // Industry filters
      industriesV2: {
        anyOf: ["Software", "Cloud"],
      },

      // Size filters
      employeeCountV2: {
        lowerBoundExclusive: 50,
        upperBoundInclusive: 500,
      },

      // Location filters
      headquartersCountryCode: {
        anyOf: ["USA"],
      },

      // Funding filters
      totalFundingUSD: {
        lowerBound: 1000000,
      },

      // Keywords filter
      keywords: {
        containsAny: ["venture-backed-startup"],
      },
    },
    pageSize: 50,
    cursor: null, // For pagination
  },
});

console.log(`Found ${result.data?.output.data.length} companies`);
console.log(
  `Cursor for next page: ${result.data?.output.nextCursor ?? "none"}`,
);

// Get total count before searching
const count = await companyCount({
  body: {
    apiKey: process.env.FIBERAI_API_KEY,
    searchParams: {
      /* same filters */
    },
  },
});

console.log(`Total companies matching: ${count.data?.output.count}`);
```

#### 搜寻

找到决策者和关键联系人,确定目标.

```typescript
import { peopleSearch, peopleSearchCount } from "@fiberai/sdk";

const people = await peopleSearch({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    searchParams: {
      // Job title filter. Mix free-form `term` matches with curated
      // `static-groups` ('founder' | 'c-suite' | 'board-member') and
      // `dynamic-groups` ('vp' | 'director' | 'management' | 'entry-level' | ...).
      jobTitleV2: {
        anyOf: [
          { type: "term", term: "CEO" },
          { type: "term", term: "Chief Executive Officer" },
          { type: "static-groups", groups: ["founder", "c-suite"] },
        ],
      },

      // Country filter — ISO 3166-1 alpha-3 codes, not city names.
      country3LetterCode: { anyOf: ["USA"] },

      // Geographic radius filter (use this, not "cities"/"countries").
      location: {
        unionAll: [
          {
            strategy: "radial-distance",
            center: { latitude: 37.7749, longitude: -122.4194 }, // San Francisco
            radius: { unit: "miles", quantity: 50 },
          },
        ],
      },

      // Curated tags. Allowed values include 'decision-maker', 'c-suite',
      // 'experienced-executive', 'second-time-founder', 'phd', etc.
      tags: { anyOf: ["decision-maker", "c-suite"] },

      // Education filter — match by school identifier (LinkedIn id, slug,
      // or domain), not by free-form school name.
      education: {
        anyOf: [
          {
            school: {
              anyOf: [{ domain: "stanford.edu" }, { domain: "harvard.edu" }],
            },
          },
        ],
      },

      getDetailedWorkExperience: true,
      getDetailedEducation: true,
    },

    // `currentCompanies` is a TOP-LEVEL body field, NOT inside searchParams.
    // It expects concrete identifiers, not industry filters. To filter by
    // industry/size/etc, use `syncCombinedSearch` and put company filters
    // under `companyParams`.
    currentCompanies: [
      { domain: "example.com" },
      { linkedinSlugOrURL: "https://linkedin.com/company/example" },
    ],

    pageSize: 100,
  },
});

// Access profile data — `output.data` is a direct array, no `.items` wrapper.
people.data?.output.data.forEach((profile) => {
  console.log(`${profile.name} — ${profile.headline}`);
  console.log(`LinkedIn: ${profile.url}`);

  // There is no `profile.currentJob` field. Current role lives in
  // `experiences[]` filtered by `is_current`.
  const currentRole = profile.experiences?.find((e) => e.is_current);
  if (currentRole) {
    console.log(`Current: ${currentRole.title} at ${currentRole.company_name}`);
  }
});

console.log(`Charged: ${people.data?.chargeInfo.method}`);
```

#### 合并搜索(公司+人)

返回匹配公司及其员工 在一个单一同步呼叫。 公司一侧的过滤器( E)`companyParams`)和人侧(`profileParams`)同时. 对于更大的结果集,您也可以运行 `companySearch` 财务报告和审定财务报表 `peopleSearch` 各自独立而活泼.

```typescript
import { syncCombinedSearch } from "@fiberai/sdk";

const result = await syncCombinedSearch({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    companyParams: {
      industriesV2: {
        anyOf: ["Software"],
      },
      employeeCountV2: {
        lowerBoundExclusive: 200,
      },
    },
    profileParams: {
      jobTitleV2: {
        anyOf: [
          { type: "term", term: "VP of Sales" },
          { type: "term", term: "Sales Director" },
          { type: "static-groups", groups: ["c-suite"] },
          { type: "dynamic-groups", groups: ["vp", "director"] },
        ],
      },
    },
    companyItemLimit: 25,
    profileItemLimit: 100,
  },
});

result.data?.output.companies?.forEach((company) => {
  console.log(company.preferred_name);
});

result.data?.output.profiles?.forEach((profile) => {
  console.log(`${profile.name} - ${profile.headline}`);
});
```

> 见 [`syncCombinedSearch`](https://api.fiber.ai/ai-docs/syncCombinedSearch.md) ,或者通过 `companySearch` + 键 `peopleSearch` 当您需要基于光标的页码时.

### 联系人浓缩

一个已知的 LinkedIn 配置文件的公开邮件和电话号码 。 纤维会暴露 **三级公共合同** 选择与你的时间、覆盖面和成本权衡相匹配的层次:

| 级别 | 运行 | 形状 | 何时使用 |
| --- | --- | --- | --- |
| 默认 | `syncQuickContactReveal` | 同步, 一个 HTTP 呼叫 | 默认的单发显示 。 快速,良好的覆盖. |
| Ium | `syncTurboContactEnrichment` | 同步, 一个 HTTP 呼叫 | 你需要绝对最快的响应 并且需要最宽的第一通瀑布 Pre价. |
| 穷尽 | `triggerExhaustiveContactEnrichment` + 键 `pollExhaustiveContactEnrichmentResult` | Async,触发+民意调查 | 最高覆盖率。 开出一个背景瀑布 尝试每一个可用的提供者, 然后投票结果. |

关于10至2000个标识符的清单,取而代之的是批量终点(见 [批量联系人启示](https://npmcn.com/package/%40fiberai/sdk/#readme-batch-contact-reveal)) (中文(简体) ).

#### 默认 —— `syncQuickContactReveal`

```typescript
import { syncQuickContactReveal } from "@fiberai/sdk";

const result = await syncQuickContactReveal({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    linkedinUrl: "https://www.linkedin.com/in/example",
    enrichmentType: {
      getWorkEmails: true,
      getPersonalEmails: true,
      getPhoneNumbers: true,
    },
    // Emails are bounce-validated by default. Set validateEmails: false to skip.
  },
});

console.log("Emails:", result.data?.output.profile?.emails);
console.log("Phones:", result.data?.output.profile?.phoneNumbers);
```

#### Ium -- `syncTurboContactEnrichment`

```typescript
import { syncTurboContactEnrichment } from "@fiberai/sdk";

const result = await syncTurboContactEnrichment({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    linkedinUrl: "https://www.linkedin.com/in/example",
    enrichmentType: {
      getWorkEmails: true,
      getPersonalEmails: true,
      getPhoneNumbers: true,
    },
  },
});

console.log("Emails:", result.data?.output.profile?.emails);
```

#### 精通(同步瀑布)- `triggerExhaustiveContactEnrichment` + 键 `pollExhaustiveContactEnrichmentResult`

`triggerExhaustiveContactEnrichment` 启动一个背景瀑布,以牺牲时间为代价返回最高的覆盖。 它返回一个 `taskId` 立即; 民意调查 `pollExhaustiveContactEnrichmentResult` 每5至15个 `output.done === true`。 。 。 .

```typescript
import {
  triggerExhaustiveContactEnrichment,
  pollExhaustiveContactEnrichmentResult,
} from "@fiberai/sdk";

const trigger: Awaited<ReturnType<typeof triggerExhaustiveContactEnrichment>> =
  await triggerExhaustiveContactEnrichment({
    body: {
      apiKey: process.env.FIBERAI_API_KEY!,
      linkedinUrl: "https://www.linkedin.com/in/example",
      enrichmentType: {
        getWorkEmails: true,
        getPersonalEmails: true,
        getPhoneNumbers: true,
      },
    },
  });

const taskId: string = trigger.data!.output.taskId;

let done: boolean = false;
while (!done) {
  await new Promise<void>((resolve) => setTimeout(resolve, 5000));

  const poll: Awaited<ReturnType<typeof pollExhaustiveContactEnrichmentResult>> =
    await pollExhaustiveContactEnrichmentResult({
      body: { apiKey: process.env.FIBERAI_API_KEY!, taskId },
    });

  done = poll.data?.output.done ?? false;
  if (done) {
    console.log("Emails:", poll.data?.output.profile.emails);
    console.log("Phones:", poll.data?.output.profile.phoneNumbers);
    console.log("Status:", poll.data?.output.profile.status);
  }
}
```

#### 批量联系人启示录 - `startBatchContactEnrichment` + 键 `pollBatchContactEnrichment`

10 - 2000年 链接 在一个任务中的标识符中. `startBatchContactEnrichment` 退款后退款a `taskId`· ; `pollBatchContactEnrichment` 返回每个任务进度的分解结果(`output.overallStats`和 `output.done` 打开环路 对于更大的列表或可重复的工作流程,上传一个CSV支持的受众,取而代之通过受众工作流程来丰富.

```typescript
import {
  startBatchContactEnrichment,
  pollBatchContactEnrichment,
} from "@fiberai/sdk";

const start: Awaited<ReturnType<typeof startBatchContactEnrichment>> =
  await startBatchContactEnrichment({
    body: {
      apiKey: process.env.FIBERAI_API_KEY!,
      personDetails: [
        { linkedinUrl: { value: "https://www.linkedin.com/in/example1" } },
        { linkedinUrl: { value: "https://www.linkedin.com/in/example2" } },
      ],
      enrichmentTypes: {
        getWorkEmails: true,
        getPersonalEmails: true,
        getPhoneNumbers: true,
      },
    },
  });

const taskId: string = start.data!.output.taskId;
console.log(`Queued ${start.data!.output.numPeopleEnqueued} profiles`);

let cursor: string | null | undefined = undefined;
let done: boolean = false;

while (!done) {
  await new Promise<void>((resolve) => setTimeout(resolve, 10000));

  const poll: Awaited<ReturnType<typeof pollBatchContactEnrichment>> =
    await pollBatchContactEnrichment({
      body: {
        apiKey: process.env.FIBERAI_API_KEY!,
        taskId,
        cursor,
        take: 100,
      },
    });

  if (!poll.data) break;

  for (const row of poll.data.output.pageResults) {
    console.log(row.inputs.linkedinUrl.value, row.outputs?.emails);
  }

  done = poll.data.output.done;
  cursor = poll.data.output.nextCursor ?? null;

  // `nextCursor` may go null before `done` flips — pause and re-poll if so.
  if (!done && !cursor) await new Promise<void>((r) => setTimeout(r, 5000));
}
```

### 链接到现场浓缩

从 LinkedIn 获得实时数据 与现场刮取.

#### Live 配置文件浓缩

```typescript
import { profileLiveEnrich } from "@fiberai/sdk";

const profile = await profileLiveEnrich({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    // `identifier` accepts a slug ('williamhgates'), a full LinkedIn URL,
    // a Sales Navigator URN ('ACwAAA...'), or a numeric LinkedIn user ID.
    identifier: "https://www.linkedin.com/in/example",
  },
});

// `output` is a discriminated union: { found: true; profile: ... } |
// { found: false; message: string }. Narrow on `output.found` before
// touching `output.profile`.
const out = profile.data?.output;
if (out?.found) {
  console.log(out.profile.name);
  console.log(out.profile.summary);
  console.log(out.profile.experiences);
  console.log(out.profile.detailed_education);
} else if (out) {
  console.warn("not found:", out.message);
}
```

#### 现场公司浓缩

```typescript
import { companyLiveEnrich } from "@fiberai/sdk";

const company = await companyLiveEnrich({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    // The `type` discriminator picks how `value` is interpreted:
    //   'slug'   — LinkedIn slug, e.g. 'microsoft'
    //   'orgId'  — LinkedIn organization id, e.g. '1441'
    //   'liUrl'  — full LinkedIn URL, e.g. 'https://www.linkedin.com/company/microsoft'
    type: "liUrl",
    value: "https://www.linkedin.com/company/example",
  },
});

// Company fields live under `output.company`, not directly on `output`.
console.log(company.data?.output.company.headline);
console.log(company.data?.output.company.description);
console.log(company.data?.output.company.follower_count);
```

#### 获取链接到的职位

```typescript
import { profilePostsLiveFetch, companyPostsLiveFetch } from "@fiberai/sdk";

// Get profile posts. `identifier` accepts a slug, full LinkedIn URL,
// or Sales Navigator URN — same shape as `profileLiveEnrich`.
const profilePosts = await profilePostsLiveFetch({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    identifier: "https://www.linkedin.com/in/example",
    cursor: null, // For pagination
  },
});

// Get company posts. `identifier` accepts a LinkedIn slug, URL, or org ID.
const companyPosts = await companyPostsLiveFetch({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    identifier: "https://www.linkedin.com/company/example",
    cursor: null,
  },
});
```

### 不适用名单

管理排除名单,从搜索中过滤公司或前景.

```typescript
import {
  createCompanyExclusionList,
  addCompaniesToExclusionList,
  getExcludedCompaniesForExclusionList,
  createCompanyExclusionListFromAudience,
} from "@fiberai/sdk";

// Create an exclusion list
const list = await createCompanyExclusionList({
  body: {
    apiKey: process.env.FIBERAI_API_KEY,
    name: "Competitors",
    isOrganizationWide: true,
  },
});

// Add companies to the list
await addCompaniesToExclusionList({
  body: {
    apiKey: process.env.FIBERAI_API_KEY,
    listId: list.data.output.listId,
    companies: [
      { domain: "competitor1.com", linkedinUrl: null },
      { domain: "competitor2.com", linkedinUrl: null },
    ],
  },
});

// Create exclusion list from an existing audience
const audienceList = await createCompanyExclusionListFromAudience({
  body: {
    apiKey: process.env.FIBERAI_API_KEY,
    audienceId: "audience-123",
    name: "Existing Customers",
    isOrganizationWide: true,
  },
});

// View excluded companies
const excluded = await getExcludedCompaniesForExclusionList({
  body: {
    apiKey: process.env.FIBERAI_API_KEY,
    exclusionListId: list.data.output.listId,
    pageSize: 100,
  },
});
```

### 谷歌地图搜索

在Google地图上搜索本地企业.

```typescript
import {
  googleMapsSearch,
  checkGoogleMapsResults,
  pollGoogleMapsResults,
} from "@fiberai/sdk";

// Start Google Maps search. `query` is the keywords only (no location info)
// and `strategy` is required — see below for the available strategies.
const search = await googleMapsSearch({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    query: "coffee shops",
    maxResults: 100,
    strategy: {
      // Options:
      //   { strategy: 'whole-usa' }
      //   { strategy: 'specific-areas', unionAll: [{ regionType: 'circle', center: {latitude, longitude}, radiusMiles }] }
      //   { strategy: 'world-cities', countriesAndRegions: { unionAll: ['USA', 'GBR', ...] } }
      strategy: "specific-areas",
      unionAll: [
        {
          regionType: "circle",
          center: { latitude: 37.7749, longitude: -122.4194 },
          radiusMiles: 10,
        },
      ],
    },
  },
});

const searchID = search.data!.output.searchID;

// Check search progress.
const progress = await checkGoogleMapsResults({
  body: { apiKey: process.env.FIBERAI_API_KEY!, searchID },
});

console.log(`Progress: ${progress.data?.output.percentageCompleted}%`);

// Poll for results once complete.
if (progress.data?.output.status === "COMPLETED") {
  const results = await pollGoogleMapsResults({
    body: {
      apiKey: process.env.FIBERAI_API_KEY!,
      searchID,
      pageSize: 50,
    },
  });

  results.data?.output.results.forEach((place) => {
    console.log(`${place.name} — ${place.address}`);
    console.log(`Rating: ${place.rating}, Reviews: ${place.numReviews}`);
    console.log(`Website: ${place.website}`);
  });
}
```

### AI 授权研究

使用AI代理进行智能公司研究和域名查询.

```typescript
import { domainLookupTrigger, domainLookupPolling } from "@fiberai/sdk";

// Trigger domain lookup. `overAllContext` is required and helps the agent
// disambiguate similar names; `companyInfo` is an array of objects (not
// a list of bare strings).
const lookup = await domainLookupTrigger({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    overAllContext: "YC startups in the US",
    companyInfo: [
      { name: "Acme Corp" },
      { name: "Globex", country: "USA" },
      { name: "Initech" },
    ],
  },
});

const domainAgentRunId = lookup.data!.output.domainAgentRunId;

// Poll for results.
let lookupDone = false;
while (!lookupDone) {
  await new Promise((resolve) => setTimeout(resolve, 3000));

  const results = await domainLookupPolling({
    body: {
      apiKey: process.env.FIBERAI_API_KEY!,
      domainAgentRunId,
      pageSize: 10,
    },
  });

  lookupDone = results.data?.output.status === "DONE";

  if (lookupDone) {
    results.data?.output.data.forEach((company) => {
      console.log(`${company.companyName}: ${company.bestDomain}`);
      console.log(`Confidence: ${company.confidence}/10`);
      console.log(`Rationale: ${company.rationale}`);
    });
  }
}
```

## 高级使用

### 配置内置客户端

SDK 输出一个预配置 `client` 已经指向 `https://api.fiber.ai`。每个操作默认使用它 **没有** 需要打电话 `createClient` 请求.

如果您需要自定义信头, 请在自定义中互换 `fetch`,或添加请求/响应截取器,改变共享实例:

```typescript
import { client } from "@fiberai/sdk";

// One-time configuration: extra headers, a custom fetch, etc.
client.setConfig({
  headers: { "X-Trace-Id": "my-app/1.0.0" },
});

// Log every outgoing request — handy as a poor man's debug mode.
client.interceptors.request.use((request) => {
  console.log(`[fiberai] ${request.method} ${request.url}`);
  return request;
});
```

`createClient` 从软件包中可以找到一个需要第二个独立客户端(如多租户应用程序)的稀有情况。 通过 `client:` 选项.

### 植入辅助器

```typescript
import type { CompanySearchData, CompanySearchResponse } from "@fiberai/sdk";

async function* paginateCompanies(
  initial: CompanySearchData,
): AsyncGenerator<
  NonNullable<CompanySearchResponse["data"]>["output"]["data"]
> {
  let cursor: string | null | undefined = initial.body.cursor ?? null;

  do {
    const result = await companySearch({
      ...initial,
      body: { ...initial.body, cursor },
    });

    if (!result.data) break;
    yield result.data.output.data;
    cursor = result.data.output.nextCursor;
  } while (cursor);
}

// Usage
for await (const companies of paginateCompanies({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    searchParams: {
      /* ... */
    },
    pageSize: 100,
  },
})) {
  console.log(`Processing batch of ${companies.length} companies`);
  // Process batch
}
```

### 工具端点

```typescript
import {
  getRegions,
  getLanguages,
  getTimeZones,
  getIndustries,
  getTags,
  getNaicsCodes,
  getAccelerators,
} from "@fiberai/sdk";

// Get available regions for filtering
const regions = await getRegions({
  query: { apiKey: process.env.FIBERAI_API_KEY },
});

// Get available industries
const industries = await getIndustries({
  query: { apiKey: process.env.FIBERAI_API_KEY },
});

// Get profile and company tags
const tags = await getTags({
  query: { apiKey: process.env.FIBERAI_API_KEY },
});
```

## 处理错误

### 标准错误处理

默认情况下, 每个操作返回 `{ data, error, response }`. 关于来自 `response.status` 而不是字符串匹配出错的机体——不保证出错的有效载荷包含可解析的 `message` 每个失败模式.

```typescript
import { companySearch } from "@fiberai/sdk";

const result = await companySearch({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    searchParams: {
      /* ... */
    },
  },
});

if (result.error) {
  switch (result.response.status) {
    case 400:
      console.error("Bad request:", result.error);
      break;
    case 401:
      console.error("Invalid API key");
      break;
    case 402:
      // 402 errors carry an `outOfCreditsAlert` with a top-up link.
      console.error("Insufficient credits:", result.error);
      break;
    case 429:
      console.error("Rate limit exceeded — back off and retry");
      break;
    default:
      console.error(
        `Request failed (${result.response.status}):`,
        result.error,
      );
  }
} else {
  console.log("Success:", result.data?.output);
  console.log("Charged:", result.data?.chargeInfo);
}
```

### 丢入错误

```typescript
try {
  const result = await companySearch({
    body: {
      apiKey: process.env.FIBERAI_API_KEY!,
      searchParams: {
        /* ... */
      },
    },
    throwOnError: true,
  });

  // result.data is guaranteed to exist when throwOnError is true.
  console.log(result.data.output);
} catch (error) {
  console.error("Request failed:", error);
}
```

### 常见的 HTTP 错误代码

| 代码 | 含义 | 解决方案 |
| --- | --- | --- |
| 400个 | 错误请求 | 检查您的请求参数 |
| 401 (中文(简体) ) | 未经授权 | 校验您的 API 密钥是有效的 |
| 402 (韩语) | 所需付款 | 入帐不足 - 填充您的账户 |
| 403 (韩语) | 禁止 | 您无法访问此资源 |
| 404 (韩语) | 未找到 | 资源不存在 |
| 429个 | 请求过多 | 超过费率限制 - 减慢请求 |
| 500个 | 内部服务器出错 | 联系支助 |

## 类型脚本支持

所有SDK方法都用TypeScript完全打入.

```typescript
import { companySearch } from "@fiberai/sdk";

// SDK functions return `{ data, error, response }`. Annotate the awaited call
// with `Awaited<ReturnType<typeof fn>>` — the exported `<Op>Response` /
// `<Op>Errors` types describe the inner body union, NOT the wrapper.
const result: Awaited<ReturnType<typeof companySearch>> = await companySearch({
  body: {
    apiKey: process.env.FIBERAI_API_KEY!,
    searchParams: {
      industriesV2: { anyOf: ["Software"] },
      employeeCountV2: {
        lowerBoundExclusive: 50,
        upperBoundInclusive: 1000,
      },
    },
    pageSize: 25,
  },
});

if (result.data) {
  console.log(`${result.data.output.data.length} companies`);
  console.log(result.data.chargeInfo);
}

// Need a name for the request shape (e.g. building a request in one place,
// passing it elsewhere)? Derive it from the function — the bare `<Op>Data`
// export carries an internal `url` literal and is not meant to be
// hand-constructed.
type CompanySearchArgs = Parameters<typeof companySearch>[0];
```

> **命名公约:** 每个操作 `foo` 船伴类型: `FooResponse` (200个机构工会)和 `FooErrors` (4xx/5xx体会). 使用 `Parameters<typeof foo>[0]` 输入参数和 `Awaited<ReturnType<typeof foo>>` 对结果信封。 这同样适用于 `peopleSearch`, (中文(简体) ), `syncQuickContactReveal`等 (中文(简体) ).

### 运行时间与 Zod 验证

每个请求和响应形状也作为 [佐德语Name](https://zod.dev/) schema),由与TypeScript类型相同的OpenAPI spec生成. 他们活在奉献的背后 `@fiberai/sdk/zod` subpath so 不需要运行时验证的应用程序支付零捆绑成本——主条目保持在50 KB以下,而Zod捆绑(~3–6 MB取决于API表面)只有在您导入时才会被加载.

```typescript
import { zPeopleSearchData, zCompanySearchData } from "@fiberai/sdk/zod";
import { peopleSearch } from "@fiberai/sdk";

const rawInput: unknown = JSON.parse(req.body);

const parsed: ReturnType<typeof zPeopleSearchData.parse> =
  zPeopleSearchData.parse(rawInput);

const result: Awaited<ReturnType<typeof peopleSearch>> =
  await peopleSearch(parsed);
```

使用 `safeParse` 如果您想要处理验证失败而不丢弃。 Zod 4 艘船只 顶级错误帮助器——使用 `z.flattenError` 用于方便格式的输出或 `z.treeifyError` 对于嵌入式形状:

```typescript
import { z } from "zod";
import { zCompanySearchData } from "@fiberai/sdk/zod";

const parsed: ReturnType<typeof zCompanySearchData.safeParse> =
  zCompanySearchData.safeParse(req.body);

if (!parsed.success) {
  return res.status(400).json({ errors: z.flattenError(parsed.error) });
}
```

> **命名公约:** 每个类型脚本 `Foo` 具有匹配 `zFoo` 计划 这么说吧 `PeopleSearchData` ↔ `zPeopleSearchData`, (中文(简体) ), `CompanySearchResponse` ↔ `zCompanySearchResponse`等 (中文(简体) ).

`zod` 船舶作为运行时间依赖 `@fiberai/sdk` 并且从捆绑中被外部化( 所以软件包管理器会用 Zod 复制您的应用程序已有的软件去除) 。 如果你不导入 `@fiberai/sdk/zod`你的捆绑的树摇出 计划,你从来没有支付.

## 利率限制和信用

### 费率限制

每个终点都有自己的收分限度. 共同限制 :

-   **公司/人员搜索**:180项请求/分钟
-   **联系人浓缩**: 120个请求/分钟(单一)、10个请求/分钟(批次)
-   **活浓缩**: 60项请求/分钟
-   **工具端点**:10-50次请求/分钟

### 信贷费用

定价因计划而异,按组织配置. **应用软件里不要硬码** 每一个成功的对策都包含: `chargeInfo` 信封旁边 `output` 告诉你那通电话的罪名

```typescript
const result = await peopleSearch({
  /* ... */
});

console.log(result.data?.chargeInfo);
// {
//   method: 'charged-now',          // 'charged-now' | 'charging-later' | 'charged-for-async-process' | 'free'
//   creditsCharged: 25,             // present when method !== 'free'
//   lowCreditAlert: null            // populated with a top-up URL when running low
// }
```

非充电干线式接触浓缩成本估算,使用 [`estimateEnrichmentCost`](https://api.fiber.ai/ai-docs/estimateEnrichmentCost.md). 检查各业务单位的人均定价细目 `getOrgCredits().data.output.creditsPerOperation`。 。 。 .

### 自由终点

下列终点从不收取信用:

-   `getOrgCredits` ——检查贷方余额
-   `getRegions`, (中文(简体) ), `getLanguages`, (中文(简体) ), `getTimeZones`, (中文(简体) ), `getIndustries`, (中文(简体) ), `getTags`, (中文(简体) ), `getNaicsCodes`, (中文(简体) ), `getAccelerators` ——公用事业终点
-   所有排除列表管理端点

### 检查您的信用

```typescript
import { getOrgCredits } from "@fiberai/sdk";

const credits = await getOrgCredits({
  query: { apiKey: process.env.FIBERAI_API_KEY! },
});

console.log(`Available: ${credits.data?.output.available}`);
console.log(`Used: ${credits.data?.output.used}`);
console.log(`Max: ${credits.data?.output.max}`);
console.log(`Resets on: ${credits.data?.output.usagePeriodResetsOn}`);
```

## 支助

-   **文档**数字 : [api.fiber.ai/ 文档](https://api.fiber.ai/docs)
-   **电子邮件**数字 : [团队@fiber.ai](mailto:team@fiber.ai)
-   **网站**数字 : [纤维.ai](https://fiber.ai/)
-   **获取 API 密钥**数字 : [纤维.ai/app/api](https://fiber.ai/app/api)

## 许可证

麻省理工学院

* * *

由 Q 制作 [纤维AI](https://fiber.ai/)

## 常见问题

### @fiberai/sdk 是什么？

Fiber AI API 的正式类型SDK

### 如何安装 @fiberai/sdk？

在项目目录运行 npm install @fiberai/sdk，或使用 pnpm add / yarn add / bun add。

### @fiberai/sdk 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @fiberai/sdk 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @fiberai/sdk 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @fiberai/sdk 可以商用吗？

@fiberai/sdk 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @fiberai/sdk 的下载量有多少？

根据 npm 官方下载统计，@fiberai/sdk 在 2026/10/15 – 2026/11/13 这 30 天内被下载 2,159 次，日均约 72 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @fiberai/sdk 还在维护吗？

最新版本 0\.0\.66 发布于 2026/10/31（14 天前）；至今共发布 66 个版本，其中过去 12 个月发布了 66 个；首次发布于 2026/01/24。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

