# @arizeai/phoenix-client 中文文档

规范地址：https://npmcn.com/package/%40arizeai/phoenix-client/

版本：7\.18\.1
npm 元数据更新时间：2026-11-04T21:35:00.946Z
中文译文更新时间：2026-11-06T19:20:59.155Z
软件包许可：Apache-2\.0

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

原始 npm 页面：https://www.npmjs.com/package/%40arizeai/phoenix-client
原文对照：https://npmcn.com/package/%40arizeai/phoenix-client/?lang=original
项目主页：https://github.com/Arize-ai/phoenix/tree/main/js/packages/phoenix-client
源码仓库：https://github.com/Arize-ai/phoenix

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

- 包体积（解压后）：6.6 MB，1617 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18
- 运行依赖：7 个
- peer 依赖：ai ^7\.0\.0，jest \>=27，openai ^6\.10\.0 \|\| ^7\.0\.0，vitest \>=1，@anthropic-ai/sdk ^0\.35\.0
- 首次发布：2025-01-10T23:25:43.705Z
- 最新版本发布：2026-11-04T21:35:00.468Z
- 近 30 天下载量：246551（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：107（近 12 个月 73 个）

## 中文简介

凤凰城API的客户端

## 安装

```sh
npm install @arizeai/phoenix-client
```

也可以使用：`pnpm add @arizeai/phoenix-client`、`yarn add @arizeai/phoenix-client`、`bun add @arizeai/phoenix-client`

## README

# 

[![Arize Phoenix logo](https://raw.githubusercontent.com/Arize-ai/phoenix-assets/refs/heads/main/logos/Phoenix/phoenix.svg)](https://phoenix.arize.com/?utm_medium=github&utm_content=header_img&utm_campaign=phoenix-client-ts)  
@arizeai/凤凰客户端

 [![NPM Version](https://img.shields.io/npm/v/%40arizeai%2Fphoenix-client)](https://www.npmjs.com/package/@arizeai/phoenix-client)[![Documentation](https://img.shields.io/badge/docs-blue?logo=typescript&logoColor=white) ](https://arize-ai.github.io/phoenix/)![](https://static.scarf.sh/a.png?x-pxid=8e8e8b34-7900-43fa-a38f-1f070bd48c64&page=js/packages/phoenix-client/README.md)

此软件包提供了一个 TypeScript 客户端 [阿里兹·凤凰](https://github.com/Arize-ai/phoenix) API (英语). 它仍在积极发展之中,并可能发生变化.

## 安装

```bash
# or yarn, pnpm, bun, etc...
npm install @arizeai/phoenix-client
```

## 配置

如果有的话,客户端会自动读取环境变量.

使用了下列环境变量:

-   `PHOENIX_ENDPOINT` -你的凤凰城的地基URL 这是给客户设定的.
-   `PHOENIX_API_KEY` - 用于认证的 API 密钥 .
-   `PHOENIX_CLIENT_HEADERS` - 在所有请求中添加自定义信头。 JSON 字符串对象 .
-   `PHOENIX_COLLECTOR_ENDPOINT` - 由OTel SDK读取以进行微量导出,通常与 URL 相同 `PHOENIX_ENDPOINT`。当 `PHOENIX_ENDPOINT` 未设定.

```bash
PHOENIX_ENDPOINT='http://localhost:12345' PHOENIX_API_KEY='xxxxxx' pnpx tsx examples/list_datasets.ts
# emits the following request:
# GET http://localhost:12345/v1/datasets
# headers: {
#   "Authorization": "Bearer xxxxxx",
# }
```

或者,您可以直接将配置选项传递给客户端,这些选项将优先于环境变量和默认值.

```ts
const phoenix = createClient({
  options: {
    baseUrl: "http://localhost:6006",
    headers: {
      Authorization: "Bearer xxxxxx",
    },
  },
});
```

对于过期的证书,创建认证的获取执行 并传递给客户。 令牌提供者控制存储和刷新 旋转 收到的请求 `401` 共享一个刷新操作 复试一回.

```ts
import { createAuthFetch, createClient } from "@arizeai/phoenix-client";

const authFetch = createAuthFetch({
  getAccessToken: async ({ forceRefresh }) => {
    if (forceRefresh) {
      await refreshAndPersistTokens();
    }
    return loadTokens().accessToken;
  },
});

const phoenix = createClient({
  options: {
    baseUrl: "http://localhost:6006",
    fetch: authFetch,
  },
});
```

## 提示

`@arizeai/phoenix-client` 页:1 `prompts` 输出会暴露公用事业公司与LLMs合作的提示.

### 创建提示并推向凤凰城

这个 `createPrompt` 函数可用于在凤凰城创建用于版本控制和再利用的提示.

```ts
import { createPrompt, promptVersion } from "@arizeai/phoenix-client/prompts";

const version = createPrompt({
  name: "my-prompt",
  description: "test-description",
  version: promptVersion({
    description: "version description here",
    modelProvider: "OPENAI",
    modelName: "gpt-3.5-turbo",
    template: [
      {
        role: "user",
        content: "{{ question }}",
      },
    ],
    invocationParameters: {
      temperature: 0.8,
    },
  }),
});
```

被推到凤凰城的提示被版本并可以被标记.

### 从凤凰城拉出快讯

这个 `getPrompt` 函数可用于根据 Phoenix 的一些“快速识别符”从 Phoenix 中拉出一个提示并返回到 Phoenix SDK Expoon 类型.

```ts
import { getPrompt } from "@arizeai/phoenix-client/prompts";

const prompt = await getPrompt({ name: "my-prompt" });
// ^ you now have a strongly-typed prompt object, in the Phoenix SDK Prompt type

const promptByTag = await getPrompt({ tag: "production", name: "my-prompt" });
// ^ you can optionally specify a tag to filter by

const promptByVersionId = await getPrompt({
  versionId: "1234567890",
});
// ^ you can optionally specify a prompt version Id to filter by
```

### 使用带有 LLM 提供者 SDK 的 Phoenix 提示

这个 `toSDK` 帮助器功能可用于将 Phoenix Express转换为 LLM 提供者 SDK 所期望的格式. 然后,您可以使用 LLM 提供者 SDK 作为正常的, 用您的快取 .

如果你的提示在凤凰城保存为 `openai`,可以使用 `toSDK` 函数可以将提示转换为OpenAI,甚至Anthropic和Vercel AI SDK所期望的格式。 我们会尽力的 工作转换为您所选择的 LLM 提供者 SDK .

支持下列LLM供应商SDK:

-   Vercel AI SDK: (中文(简体) ) `ai` [页:1](https://www.npmjs.com/package/ai)
-   打开AI : `openai` [打开](https://www.npmjs.com/package/openai) (v6和v7) (中文(简体) )
-   安东尼: `anthropic` [@ 慈善- ai/ sdk](https://www.npmjs.com/package/@anthropic-ai/sdk)

> **说明:** 这些提供者 SDK 是可选的对等依赖性 — 安装 `@arizeai/phoenix-client` 不拉他们进来。 安装您转换到自己的一个, 例如 . `npm install ai`, (中文(简体) ), `npm install openai`,或 `npm install @anthropic-ai/sdk`调用 `toSDK({ sdk: "ai" | "openai" | "anthropic" })` 未安装匹配的 SDK 在运行时失败 .

```ts
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
import { getPrompt, toSDK } from "@arizeai/phoenix-client/prompts";

const prompt = await getPrompt({ name: "my-prompt" });
const promptAsAI = toSDK({
  sdk: "ai",
  // ^ the SDK you want to convert the prompt to, supported SDKs are listed above
  variables: {
    "my-variable": "my-value",
  },
  // ^ you can format the prompt with variables, if the prompt has any variables in its template
  //   the format (Mustache, F-string, etc.) is specified in the Prompt itself
  prompt,
});
// ^ promptAsAI is now in the format expected by the Vercel AI SDK generateText function

const response = await generateText({
  model: openai(prompt.model_name),
  // ^ the model adapter provided by the Vercel AI SDK can be swapped out for any other model
  //   adapter supported by the Vercel AI SDK. Take care to use the correct model name for the
  //   LLM provider you are using.
  ...promptAsAI,
});
```

## REST 终点

客户端为定义于 [凤凰城 OpenAPI 光谱](https://github.com/Arize-ai/phoenix/blob/main/schemas/openapi.json)。 。 。 .

端点通过强类型的字符串字元和TypeScript自动完成客户对象内部可以访问.

```ts
import { createClient } from "@arizeai/phoenix-client";

const phoenix = createClient();

// Get all datasets
const datasets = await phoenix.GET("/v1/datasets");

// Get specific prompt
const prompt = await phoenix.GET("/v1/prompts/{prompt_identifier}/latest", {
  params: {
    path: {
      prompt_identifier: "my-prompt",
    },
  },
});
```

凤凰城内的OpenAPI取景器或 [凤凰城 OpenAPI 光谱](https://github.com/Arize-ai/phoenix/blob/main/schemas/openapi.json)。 。 。 .

## 数据集

这个 `@arizeai/phoenix-client` 软件包允许您创建和管理数据集,这些数据集是用于实验和评价的实例集.

### 创建数据集

您可以通过提供名称、描述和一系列实例来创建数据集(每个实例都有) `input`, (中文(简体) ), `output`选择 `metadata`) (中文(简体) ).

```ts
import { createDataset } from "@arizeai/phoenix-client/datasets";

const { datasetId } = await createDataset({
  name: "questions",
  description: "a simple dataset of questions",
  examples: [
    {
      input: { question: "What is the capital of France" },
      output: { answer: "Paris" },
      metadata: {},
    },
    {
      input: { question: "What is the capital of the USA" },
      output: { answer: "Washington D.C." },
      metadata: {},
    },
  ],
});
// You can now use datasetId to run experiments or add more examples
```

### 管理分割

使用 `createDatasetSplit`, (中文(简体) ), `updateDatasetSplit`,以及 `deleteDatasetSplit` 以创建、编辑和删除在现有数据集上的拆分(例如训练和测试子集)并添加或删除示例。 这些帮助者需要凤凰城服务器QQ 19.20.

```ts
import {
  createDatasetSplit,
  deleteDatasetSplit,
  updateDatasetSplit,
} from "@arizeai/phoenix-client/datasets";

const dataset = { datasetName: "questions" };

const testSplit = await createDatasetSplit({
  dataset,
  name: "test",
  exampleIds: ["example-1"], // example ids or nodeIds from getDatasetExamples
});

await updateDatasetSplit({
  dataset,
  splitId: testSplit.id,
  addExampleIds: ["example-2"],
  removeExampleIds: ["example-1"],
});

// Removes the split and its memberships, not the examples
await deleteDatasetSplit({ dataset, splitId: testSplit.id });
```

见 [数据集参考](https://arize.com/docs/phoenix/sdk-api-reference/typescript/packages/phoenix-client/datasets#manage-splits-on-an-existing-dataset) 用于所有参数和服务器版本注释.

## 实验

这个 `@arizeai/phoenix-client` 软件包提供了用于运行和评价数据集任务的实验 API。 这对于制定基准模型、评价产出和跟踪凤凰城的实验结果很有用.

### 运行一个实验

要进行实验,你通常:

1.  创建数据集( 或使用已有的数据集)
2.  定义要运行在每个实例上的任务函数
3.  定义一名或多名评价员对产出进行评分或标签
4.  运行实验并检查结果

下面是一个完整的例子:

```ts
import { createDataset } from "@arizeai/phoenix-client/datasets";
import {
  asExperimentEvaluator,
  runExperiment,
} from "@arizeai/phoenix-client/experiments";

// 1. Create a dataset
const { datasetId } = await createDataset({
  name: "names-dataset",
  description: "a simple dataset of names",
  examples: [
    {
      input: { name: "John" },
      output: { text: "Hello, John!" },
      metadata: {},
    },
    {
      input: { name: "Jane" },
      output: { text: "Hello, Jane!" },
      metadata: {},
    },
  ],
});

// 2. Define a task to run on each example
const task = async (example) => `hello ${example.input.name}`;

// 3. Define evaluators
const evaluators = [
  asExperimentEvaluator({
    name: "matches",
    kind: "CODE",
    evaluate: async ({ output, expected }) => {
      const matches = output === expected?.text;
      return {
        label: matches ? "matches" : "does not match",
        score: matches ? 1 : 0,
        explanation: matches
          ? "output matches expected"
          : "output does not match expected",
        metadata: {},
      };
    },
  }),
  asExperimentEvaluator({
    name: "contains-hello",
    kind: "CODE",
    evaluate: async ({ output }) => {
      const matches = typeof output === "string" && output.includes("hello");
      return {
        label: matches ? "contains hello" : "does not contain hello",
        score: matches ? 1 : 0,
        explanation: matches
          ? "output contains hello"
          : "output does not contain hello",
        metadata: {},
      };
    },
  }),
];

// 4. Run the experiment
const experiment = await runExperiment({
  dataset: { datasetId },
  task,
  evaluators,
});
```

> **提示 :** 任务和评估员使用仪器 [打开几何](https://opentelemetry.io/)。您可以在凤凰卫视UI中直接查看实验运行和评估的详细痕迹,用于调试和性能分析.

## Eval 测试

该套件还曝光了用于写作的Vitest和Jest子模块 作为普通测试套件的数据集支持评价.

```bash
npm install -D @arizeai/phoenix-client vitest dotenv
```

```ts
import * as px from "@arizeai/phoenix-client/vitest";
import { expect } from "vitest";

px.describe(
  "text-to-sql",
  () => {
    px.test(
      "select all",
      {
        input: { userQuery: "Get all users" },
        expected: { sql: "SELECT * FROM users;" },
      },
      async ({ input, expected }) => {
        const sql = await generateSql(input.userQuery);
        px.logOutput({ sql });
        expect(sql).toEqual(expected?.sql);
      }
    );
  },
  {
    acceptanceCriteria: [
      // every test must pass (100% of the auto-logged `pass` boolean is true)
      {
        annotationName: "pass",
        metric: "passRate",
        passFn: (a) => a.score === true,
        minPassRate: 1,
      },
    ],
  }
);
```

可在可互换的三种模式中的任何一种下提供参考输出 键 - `expected`, (中文(简体) ), `reference`,或 `output` - 这样你就可以匹配任何名称 您的评审人员预计。 他们都决心到同一个位置: 数据集 实例 `output`,与评估者和测试机构接触,作为 `expected`。 。 。 . 一次提供多个是类型错误.

使用 `@arizeai/phoenix-client/vitest/reporter` 或者说 `@arizeai/phoenix-client/jest/reporter` 打印凤凰城数据集 试验链接、注释总量和最后的接受标准 运行。 接受标准 门的套房完成后 - `average` 检查一个聚合栏( 这样 CI 就可以允许平均 80% 同时运行) (每个案件) `passRate` 需要运行的最小分数满足 每次运行 `passFn` 上观相.

见 [CI Eval 测试](https://arize.com/docs/phoenix/sdk-api-reference/typescript/packages/phoenix-client/ci-evals), (中文(简体) ), [维特](https://arize.com/docs/phoenix/sdk-api-reference/typescript/packages/phoenix-client/ci-evals-vitest), (中文(简体) ), [欢乐](https://arize.com/docs/phoenix/sdk-api-reference/typescript/packages/phoenix-client/ci-evals-jest), (中文(简体) ), 财务报告和审定财务报表 [说明](https://arize.com/docs/phoenix/sdk-api-reference/typescript/packages/phoenix-client/ci-evals-annotations) 设置的指南,全 `describe` 编号 : `test` 编号 : `test.each` API,接受标准,重复, 干运行模式和注释细节.

## 追踪

这个 `@arizeai/phoenix-client` 软件包提供 `traces` 从凤凰城项目获取微量数据的导出.

### 获取追踪

使用 `getTraces` 以可选过滤、排序和页码来取回痕迹.

```ts
import { getTraces } from "@arizeai/phoenix-client/traces";

// Get the latest 10 traces
const result = await getTraces({
  project: { projectName: "my-project" },
  limit: 10,
});
console.log(result.data); // array of trace objects

// Filter by time range and include full span details
const detailed = await getTraces({
  project: { projectName: "my-project" },
  startTime: "2026-03-01T00:00:00Z",
  endTime: new Date(),
  includeSpans: true,
  sort: "latency_ms",
  order: "desc",
});

// Filter by session
const sessionTraces = await getTraces({
  project: { projectName: "my-project" },
  sessionId: "my-session-id",
});

// Filter by error status and latency (requires Phoenix server >= 20.12.0)
const slowFailures = await getTraces({
  project: { projectName: "my-project" },
  filter: "error_count > 0 and latency_ms >= 1000",
});
```

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `project` | `ProjectIdentifier` | 项目(名称或ID) - **所需经费** |
| `startTime` | `Date | string | null` | 跟踪起始时间包含下限 |
| `endTime` | `Date | string | null` | 跟踪起始时间独有上限 |
| `sort` | `"start_time" | "latency_ms"` | 排序字段 |
| `order` | `"asc" | "desc"` | 排序方向 |
| `limit` | `number` | 返回的最大痕迹数 |
| `cursor` | `string | null` | 相位光标 |
| `includeSpans` | `boolean` | 包含每个跟踪的全部跨度细节 |
| `sessionId` | `string | string[] | null` | 按会话标识符过滤痕迹 |
| `filter` | `string | null` | 跟踪过滤表达式 |
| `error` | `boolean | null` | 仅标注有( E)`true`)或无(`false`) 错误的跨度 |
| `minLatencyMs` | `number | null` | 微量耐久性下限包含在内 |
| `maxLatencyMs` | `number | null` | 微量纬度时的包容性上限(毫秒) |

`error`, (中文(简体) ), `minLatencyMs`,以及 `maxLatencyMs` 已贬值,但仍支持在 服务器 QQ 20.8.0. 使用 `error_count > 0` 编号 : `error_count == 0`, (中文(简体) ), `latency_ms >= N`,以及 `latency_ms <= N` 内 `filter` 换句话说 空表达式不过滤; 无效 表达式返回 HTTP 400。 请求下一页时保留相同的表达式 .

### 倾斜

使用 `cursor` 从上一个结果获取下一页:

```ts
import { getTraces } from "@arizeai/phoenix-client/traces";

let cursor: string | null = null;
const allTraces = [];

do {
  const result = await getTraces({
    project: { projectName: "my-project" },
    limit: 50,
    cursor,
  });
  allTraces.push(...result.data);
  cursor = result.nextCursor ?? null;
} while (cursor);
```

> **说明:** 需要凤凰城服务器 QQ 13.15.0.

### 追踪说明

添加结构反馈( 标签/ 按名称计分) 到整个跟踪 。 使用 `addTraceAnnotation` 用于一个跟踪或 `logTraceAnnotations` 为分批.

```ts
import {
  addTraceAnnotation,
  logTraceAnnotations,
} from "@arizeai/phoenix-client/traces";

// Single annotation
const result = await addTraceAnnotation({
  traceAnnotation: {
    traceId: "abc123",
    name: "correctness",
    label: "correct",
    score: 1.0,
    annotatorKind: "HUMAN",
  },
  sync: true, // returns { id: "..." } when sync, null when async
});

// Batch
await logTraceAnnotations({
  traceAnnotations: [
    {
      traceId: "abc123",
      name: "correctness",
      label: "correct",
      score: 1.0,
      annotatorKind: "HUMAN",
    },
    {
      traceId: "def456",
      name: "faithfulness",
      label: "faithful",
      score: 0.9,
      annotatorKind: "LLM",
    },
  ],
  sync: true,
});
```

保留名称 `note` 被拒绝 – 使用 `addTraceNote` 改为自由式说明(见下文).

### 追踪注释

注是自由格式文本的一种特殊注释类型——用于开口编码,审查者在任何标题存在之前都会在追踪上留下定性的观察. 多个音符可以在同一行迹上并存.

```ts
import { addTraceNote } from "@arizeai/phoenix-client/traces";

await addTraceNote({
  traceNote: {
    traceId: "abc123",
    note: "Needs follow-up — unexpected tool call sequence",
  },
});
```

> **说明:** `addTraceNote` 需要凤凰城服务器 QQ 14.13.0.

## 西班牙语

这个 `@arizeai/phoenix-client` 软件包提供 `spans` 导出用于有强大过滤功能的查询跨度.

### 正在获取 Spans

使用 `getSpans` 按类型、状态、名称、追踪等进行过滤.

```ts
import { getSpans } from "@arizeai/phoenix-client/spans";

// Get recent spans
const result = await getSpans({
  project: { projectName: "my-project" },
  limit: 100,
});

// Filter by span kind and status
const errorLLMSpans = await getSpans({
  project: { projectName: "my-project" },
  spanKind: "LLM",
  statusCode: "ERROR",
});

// Filter by name and trace
const spans = await getSpans({
  project: { projectName: "my-project" },
  name: "chat_completion",
  traceIds: ["trace-abc", "trace-def"],
});

// Root spans only
const rootSpans = await getSpans({
  project: { projectName: "my-project" },
  parentId: null,
});
```

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `project` | `ProjectIdentifier` | 项目(名称或ID) - **所需经费** |
| `startTime` | `Date | string | null` | 包含较低的约束时间 |
| `endTime` | `Date | string | null` | 绝对上限 |
| `limit` | `number` | 返回的最大间隔数 |
| `cursor` | `string | null` | Pangination 光标( Span GlobalID) |
| `traceIds` | `string[] | null` | 通过微量ID过滤 |
| `parentId` | `string | null` | 按父跨 ID 过滤( S)`null` 仅用于根跨) |
| `name` | `string | string[] | null` | 按跨度名称过滤 |
| `spanKind` | `SpanKindFilter | SpanKindFilter[]` | 按跨度类型过滤( E)`LLM`, (中文(简体) ), `CHAIN`, (中文(简体) ), `TOOL`, (中文(简体) ), `RETRIEVER`页:1 |
| `statusCode` | `SpanStatusCode | SpanStatusCode[]` | 按状态代码过滤( E)`OK`, (中文(简体) ), `ERROR`, (中文(简体) ), `UNSET`(中文(简体) ) |

### 记录垃圾邮件

使用 `logSpans` 直接向项目提交跨度, 使用凤凰城的简化跨度结构—— 相同的形状 `getSpans`。这对不经过OpenTeleometry的回填或迁移跨度有用。 如果您的应用程序已经装入了 OpenTeleometry 的仪器,导出周期为 `@arizeai/phoenix-otel` 换句话说.

```ts
import { logSpans } from "@arizeai/phoenix-client/spans";

const result = await logSpans({
  project: { projectName: "my-project" },
  spans: [
    {
      name: "chat_completion",
      context: { trace_id: "abc123", span_id: "def456" },
      span_kind: "LLM",
      start_time: "2024-01-01T00:00:00Z",
      end_time: "2024-01-01T00:00:01Z",
      status_code: "OK",
      attributes: { "llm.model_name": "gpt-4" },
    },
  ],
});
console.log(`Queued ${result.totalQueued} of ${result.totalReceived} spans`);
```

如果请求中的任何跨度无效或重复已经存在的跨度,则所有跨度均不排队 `logSpans` 丢出一个 `SpanCreationError` 与 `invalidSpans` 财务报告和审定财务报表 `duplicateSpans` 细节.

## 扩展说明

这个 `spans` 导出还提供了管理跨度说明的功能——将评价、反馈和标签加入跨度.

### 添加单一注释

```ts
import { addSpanAnnotation } from "@arizeai/phoenix-client/spans";

const result = await addSpanAnnotation({
  spanAnnotation: {
    spanId: "f8b1c3a2d4e5f678",
    name: "correctness",
    label: "correct",
    score: 1.0,
    explanation: "The response accurately answered the question",
    annotatorKind: "HUMAN",
  },
  sync: true, // wait for the annotation ID to be returned
});
// result: { id: "annotation-id" } when sync: true, null when sync: false
```

### 日志多重说明

```ts
import { logSpanAnnotations } from "@arizeai/phoenix-client/spans";

const results = await logSpanAnnotations({
  spanAnnotations: [
    {
      spanId: "f8b1c3a2d4e5f678",
      name: "relevance",
      label: "relevant",
      score: 0.95,
      annotatorKind: "LLM",
    },
    {
      spanId: "a1b2c3d4e5f67890",
      name: "relevance",
      label: "irrelevant",
      score: 0.2,
      annotatorKind: "LLM",
    },
  ],
  sync: true,
});
// results: [{ id: "..." }, { id: "..." }]
```

### 获取 Span 说明

```ts
import { getSpanAnnotations } from "@arizeai/phoenix-client/spans";

const result = await getSpanAnnotations({
  project: { projectName: "my-project" },
  spanIds: ["f8b1c3a2d4e5f678", "a1b2c3d4e5f67890"],
  includeAnnotationNames: ["relevance", "correctness"],
  limit: 100,
});
console.log(result.data); // array of span annotation objects
```

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `project` | `ProjectIdentifier` | 项目(名称或ID) - **所需经费** |
| `spanIds` | `string[]` | 获取注释的 span ID **所需经费** |
| `includeAnnotationNames` | `string[]` | 只有带有这些名称的返回注释 |
| `excludeAnnotationNames` | `string[]` | 排除带有这些名称的说明 |
| `cursor` | `string | null` | 相位光标 |
| `limit` | `number` | 返回的最大说明 |

## 会议

这个 `@arizeai/phoenix-client` 软件包提供 `sessions` 导出用于管理对话会话及其说明.

### 获取会话

使用 `listSessions` 以列出项目的所有会话,或 `getSession` 以 ID 获取单个会话.

```ts
import {
  listSessions,
  getSession,
  addSessionAnnotation,
  addSessionNote,
} from "@arizeai/phoenix-client/sessions";

// List all sessions for a project
const sessions = await listSessions({
  project: "my-project",
});

for (const session of sessions) {
  console.log(
    `Session: ${session.sessionId}, Traces: ${session.traces.length}`
  );
}

// Get a single session by its ID
const session = await getSession({ sessionId: "my-session-id" });
console.log(session.traces); // array of trace summaries in the session
```

### 添加会话说明

```ts
await addSessionAnnotation({
  sessionAnnotation: {
    sessionId: "my-session-id",
    name: "user-satisfaction",
    label: "satisfied",
    score: 0.9,
    annotatorKind: "HUMAN",
  },
});
```

### 添加会话说明

需要 Phoenix 服务器的会话笔记 `14.17.0` 或更新.

```ts
await addSessionNote({
  sessionNote: {
    sessionId: "my-session-id",
    note: "Needs review",
  },
});
```

## 项目

这个 `@arizeai/phoenix-client` 软件包提供 `projects` 用于列出项目和管理其保留政策和注释配置任务.

### 获取项目

使用 `getProjects` 以列表项目。 刺伤是为你处理的.

```ts
import { getProjects } from "@arizeai/phoenix-client/projects";

// List every project
const projects = await getProjects();

for (const project of projects) {
  console.log(`Project: ${project.name} (${project.id})`);
}
```

过 `nameContains` 以对项目名称不敏感子字符串过滤。 过滤器是应用服务器侧并需要 Phoenix 服务器 `17.16.0` 或更新.

```ts
const agentProjects = await getProjects({ nameContains: "agent" });
```

### 指定保留政策

使用 `setProjectRetentionPolicy` 通过GlobalID指定现有的痕量保留政策。 按名称或 GlobalID 选择工程 .

```ts
import { setProjectRetentionPolicy } from "@arizeai/phoenix-client/projects";

await setProjectRetentionPolicy({
  projectName: "support-bot",
  policyId: "UHJvamVjdFRyYWNlUmV0ZW50aW9uUG9saWN5OjI=",
});
```

过 `policyId: null` 将项目重置为凤凰的默认保留政策:

```ts
await setProjectRetentionPolicy({
  projectId: "UHJvamVjdDox",
  policyId: null,
});
```

此助手只将项目的任务更改为现行政策. 创建、读取、更新和删除保留政策不属于TypeScript项目帮助器的范围.

### 指定注释配置

使用 `assignProjectAnnotationConfig` 财务报告和审定财务报表 `unassignProjectAnnotationConfig` 要添加或删除单个注释配置。 按名称或GlobalID选择工程和配置。 两通电话都是一流的。 这些助手需要凤凰城服务器 `17.16.0` 或更新.

```ts
import {
  assignProjectAnnotationConfig,
  listProjectAnnotationConfigs,
  setProjectAnnotationConfigs,
  unassignProjectAnnotationConfig,
} from "@arizeai/phoenix-client/projects";

await assignProjectAnnotationConfig({
  projectName: "support-bot",
  configName: "correctness",
});

await unassignProjectAnnotationConfig({
  projectName: "support-bot",
  configName: "correctness",
});
```

使用 `setProjectAnnotationConfigs` 用配置 GlobalID 替换整个设置。 通过一个空列表来清除每个任务 :

```ts
const configs = await listProjectAnnotationConfigs({
  projectName: "support-bot",
});

// Keep only the categorical configs
await setProjectAnnotationConfigs({
  projectName: "support-bot",
  configIds: configs
    .filter((config) => config.type === "CATEGORICAL")
    .map((config) => config.id),
});

await setProjectAnnotationConfigs({
  projectName: "support-bot",
  configIds: [],
});
```

如果配置名称包含 `/`中选择 `configId` 换句话说 服务器无法路由 a `/` 在 URL 路径中.

## 秘诀

使用 `secrets` 原子创建、更新或删除加密的条目点 供应商证书。 字符串值创建或更新密钥,同时 `null` 删除它。 复制密钥使用批次中的最后一个出错 。 结果 只包含已更改的密钥名称,绝不返回密钥值.

```ts
import { upsertOrDeleteSecrets } from "@arizeai/phoenix-client/secrets";

const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) throw new Error("OPENAI_API_KEY is required");

const result = await upsertOrDeleteSecrets({
  secrets: [
    { key: "OPENAI_API_KEY", value: apiKey },
    { key: "OLD_PROVIDER_API_KEY", value: null },
  ],
});

console.log(result.upsertedKeys);
console.log(result.deletedKeys);
```

管理机密需要一位管理员 当凤凰城认证 启用 。 避免记录请求批次或以其他方式保留其值.

## 实例

要运行示例,请使用 `pnpm` 运行 :

```bash
pnpm install
pnpx tsx examples/list_datasets.ts
# change the file name to run other examples
```

## 兼容性

此套件使用 [打开( o)](https://openapi-ts.pages.dev/) 以生成来自 Phoenix OpenAPI spec 的类型.

因此,这个软件包只与 `arize-phonix` 服务器 8.0.0及以上.

兼容性表 :

| 凤凰客户端版本 | 凤凰城服务器版本 |
| --- | --- |
| ^ 2. 0 | ^ 9.0.0 (中文(简体) ) |
| ^ 1. 0 | ^ 8.0.0 (韩语) |

* * *

## 社区

加入我们的社区,与成千上万的人工智能建设者建立联系:

-   加入我们的行列 [黑社会](https://join.slack.com/t/arize-ai/shared_invite/zt-3r07iavnk-ammtATWSlF0pSrd1DsMW7g)。 。 。 .
-   读取 [凤凰网文献](https://arize.com/docs/phoenix)。 。 。 .
-   \* 提问并提供反馈 _#凤凰支持 #_ 频道.
-   留下一颗星星在我们身上 [GitHub 图像](https://github.com/Arize-ai/phoenix)。 。 。 .
-   报告错误 [GitHub 问题](https://github.com/Arize-ai/phoenix/issues)。 。 。 .
-   X 跟着我们 [页:1](https://twitter.com/ArizePhoenix)。 。 。 .
-   跟着我们 [链接](https://www.linkedin.com/showcase/113218220)。 。 。 .
-   看看我们 [路线图](https://github.com/orgs/Arize-ai/projects/45) 看看我们下一步要去哪儿.

## 常见问题

### @arizeai/phoenix-client 是什么？

凤凰城API的客户端

### 如何安装 @arizeai/phoenix-client？

在项目目录运行 npm install @arizeai/phoenix-client，或使用 pnpm add / yarn add / bun add。

### @arizeai/phoenix-client 支持 TypeScript 吗？

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

### @arizeai/phoenix-client 支持 ESM 还是 CommonJS？

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

### @arizeai/phoenix-client 需要什么版本的 Node\.js？

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

### @arizeai/phoenix-client 可以商用吗？

@arizeai/phoenix-client 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @arizeai/phoenix-client 的下载量有多少？

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

### @arizeai/phoenix-client 还在维护吗？

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

