# 模型

来源：https://docs.nestjs.com/ai/models

每次模型调用都在超时、重试与回退模型的约束下运行，这些策略由调用本身、其模型以及模块的设置构建而成；调用还会报告它用了多少 token、花了多少。

#### 模型设置

`forRoot({{ '{' }} models {{ '}' }})` 中的模型，是提供者包给出的 `LanguageModel`，或者一个以该 `LanguageModel` 为 `model` 并带自己设置的定义。这家商店的 Claude 模型带上了价格，默认的那个还带了来自另一家提供者的回退：

```typescript
@@filename(app.module)
import { anthropic } from '@ai-sdk/anthropic';
import { openai } from '@ai-sdk/openai';
import { Module } from '@nestjs/common';
import { AiModule } from '@nestjs/ai';

@Module({
  imports: [
    AiModule.forRoot({
      isGlobal: true,
      models: {
        default: {
          model: anthropic('claude-opus-5-5'),
          pricing: { input: 4, output: 20, cachedInput: 0.2 },
          maxOutputTokens: 4_000,
          fallback: 'backup',
        },
        fast: {
          model: anthropic('claude-haiku-5-5'),
          pricing: { input: 0.1, output: 0.5 },
          timeout: '15s',
        },
        backup: openai('gpt-5'),
      },
      defaults: { timeout: '45s', maxOutputTokens: 1_000 },
    }),
  ],
})
export class AppModule {}
```

每项设置先取自调用，其次取自模型的定义，最后取自模块的 `defaults`。上面调用 `default` 时会发送 `maxOutputTokens: 4000`，调用 `fast` 或 `backup` 时则为 `maxOutputTokens: 1000`；若某次调用设置了 `maxOutputTokens: 200`，无论由哪个模型作答都发送该值。`fast` 给一次尝试 15 秒，其余模型为 45 秒。

| 设置 | 可设在 |
| --- | --- |
| `timeout`、`retry`、`resilience` | 调用、模型、`defaults` |
| `maxOutputTokens`、`temperature`、`providerOptions`、`headers` | 调用、模型、`defaults` |
| `maxSteps`、`budget` | 调用、`defaults` |
| `fallback` | 调用、模型 |
| `pricing` | 模型 |
| `onUsage` | 调用与模块：两者都会被调用 |
| `topP`、`topK`、`seed`、`stopSequences`、`presencePenalty`、`frequencyPenalty`、`toolChoice`、`fallbackIf`、`abortSignal` | 调用 |

`providerOptions` 是提供者包自己的选项，以提供者的名称为键；`headers` 是每次向提供者发起请求时附带的 HTTP 头。

在 `models` 中，模型也可以是形如 `'openai/gpt-5'` 的模型 ID 字符串，AI SDK 会经 [AI Gateway](https://vercel.com/docs/ai-gateway) 发送它。而在调用里，字符串始终是模块中某个模型的名字。调用也可以把 `LanguageModel` 作为其 `model`，或作为其 `fallback`：它没有自己的设置，结果的 `model.name` 为 `undefined`。

#### 自行调用 AI SDK

要自行调用 AI SDK，请注入模型。`@InjectModel('fast')` 注入 `fast` 所指的 `LanguageModel`，`@InjectModel()` 注入 `default` 那个：

```typescript
@@filename(support/summaries.service)
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/ai';
import { generateText, type LanguageModel } from 'ai';

@Injectable()
export class SummariesService {
  constructor(@InjectModel('fast') private readonly model: LanguageModel) {}

  async summarize(thread: string): Promise<string> {
    const { text } = await generateText({
      model: this.model,
      instructions: 'Summarize the support thread in three sentences.',
      prompt: thread,
    });
    return text;
  }
}
```

模块未配置的名称会在启动时失败，并指出请求它的类：`SummariesService: @InjectModel('fats') asks for a model AiModule does not configure.` 模型就是提供者原样的 `LanguageModel`，因此用它发起的调用得不到 `AiService` 附加的任何东西：没有超时、回退模型、预算或用量事件，取而代之的是 AI SDK 自己的重试（`maxRetries`，默认 2 次），而非下面这些策略。`AiModels` 列出已配置的模型，提供 `names()`、`has(name)` 和 `get(name)`。

#### 重试、超时与回退

模型提供者会失败：发送太多时回 429，过载时回 529，偶尔也会花一分钟才作答。每次模型调用都在 [`@nestjs/resilience`](/reliability/resilience) 的策略下运行，这些策略由三项设置构建：

- **`timeout`**：一个 `TimeoutPolicy`，默认 `'60s'`，按每次尝试计：对 `generateText()` 和 `generateObject()` 是直到完整答案，对 `streamText()` 是直到第一个分块。工具耗时不计入，因为那时模型已经作答。`false` 关闭它。
- **`retry`**：一个 `RetryPolicy`，含其选项：`attempts`（默认 3 次，含首次）、`backoff`（从 `'1s'` 起，翻倍直到 `'30s'`，带完全抖动）和 `retryIf`。提供者标记为可重试的错误会被重试：408、409、429 与 5xx 响应以及连接失败，超时亦然。`retry-after` 头会被遵守，若它要求的时间超过 `backoff.maxDelay`，则转而使用回退。`retry: false` 关闭重试。
- **`fallback`**：该模型的多次重试耗尽后，按顺序尝试的模型，每个都在自己的策略下运行。调用可用 `fallback: ['default']` 设置自己的回退，或用 `fallback: false` 关闭，`fallbackIf` 则可收窄哪些失败会继续。

调用可以改动其中任何一项：

```typescript
const { text } = await this.ai.generateText({
  model: 'fast',
  prompt: email,
  timeout: '10s',
  retry: { attempts: 2, backoff: { delay: '500ms' } },
  fallback: ['default', 'backup'],
  // A request the provider refused (400) would be refused by the next one too
  fallbackIf: (error) =>
    !APICallError.isInstance(error) || error.statusCode !== 400,
});
```

只有调用自身模型的 `fallback` 会被遵循：回退模型的 `fallback` 不会被遵循，因此若一次调用应当接着走到第三个模型，就要像上面那样把两者都列出。`APICallError` 是 AI SDK 中表示提供者响应的错误，来自 `ai`。有些失败无论 `fallbackIf` 如何说都不会继续：调用的中止、与 `generateObject()` 的模式（schema）不匹配的答案，以及 AI SDK 对无法发出的调用所报的错误，例如无效的提示词（prompt）。

每次回退都会通过 Nest 的 `Logger` 记为警告，带有失败的模型、调用接着转向的模型以及原因：错误的类、其 HTTP 状态和消息。被吊销的 API key 或被拒的请求无法藏在能正常工作的回退之后：`The model "default" failed (APICallError, 401: Invalid API key); falling back to "backup".`

一旦某个分块已到达浏览器，或某次模型调用的工具已开始执行，其结果就已确定：超时、重试或回退都不会替换它，因此答案不会被发送两次，工具也不会运行两次。

传给调用的 `abortSignal` 会立刻取消该调用，不重试也不回退，调用以该信号的原因拒绝。在可容错路由内部，例如使用 `@nestjs/resilience` 的 `@Timeout()` 的路由，路由的那次尝试会以同样的方式中止它发起的模型调用。

#### 调用失败时

当每一次尝试、每一个尝试过的模型都失败时，调用以 `AiModelError` 拒绝。它的 `attempts` 列出每个模型、每次尝试和错误（尝试超时的为 `ResilienceTimeoutError`），其 `cause` 是最后一个错误。该包的错误都继承 `AiError`：

| 错误 | 何时 |
| --- | --- |
| `AiModelError` | 每一次尝试、每一个尝试过的模型都失败：`attempts`、`cause` |
| `AiOutputError` | `generateObject()` 的答案不是 JSON 或不符合模式，或模型在 `maxSteps` 之后仍在调用工具：`text` |
| `AiBudgetExceededError` | 该调用已用完预算，发生在下一次模型调用之前：`usage`、`cost`、`limit` |
| `AiConfigurationError` | 某个模型、代理函数或选项该包无法使用：在启动时，或在发起调用时，在发送任何内容之前 |
| `AiToolError` | 工具调用失败时告知模型的内容：`toolName`，即代理函数的名字 |

调用模型的路由对 `AiModelError` 的响应是 500，与其他错误相同。异常过滤器可以改为声明助手不可用：

```typescript
@@filename(assistant/model-unavailable.filter)
import {
  Catch,
  HttpStatus,
  type ArgumentsHost,
  type ExceptionFilter,
} from '@nestjs/common';
import { AiModelError } from '@nestjs/ai';
import type { Response } from 'express';

@Catch(AiModelError)
export class ModelUnavailableFilter implements ExceptionFilter {
  catch(_error: AiModelError, host: ArgumentsHost) {
    host
      .switchToHttp()
      .getResponse<Response>()
      .status(HttpStatus.SERVICE_UNAVAILABLE)
      .json({
        statusCode: HttpStatus.SERVICE_UNAVAILABLE,
        message: 'The assistant is unavailable. Try again in a minute.',
      });
  }
}
```

#### 自己的策略

`resilience` 接受一个策略，或 `ResilienceService` 某个预设的名称，用以取代 `retry` 和 `timeout`：比如与应用的其余部分共用的断路器或隔离舱（bulkhead）。回退模型仍在它之外被尝试，因此调用一个断路器已打开的模型会继续走到下一个：

```typescript
@@filename(app.module)
import { anthropic } from '@ai-sdk/anthropic';
import { openai } from '@ai-sdk/openai';
import { Module } from '@nestjs/common';
import { AiModule } from '@nestjs/ai';
import { ResilienceModule } from '@nestjs/resilience';

@Module({
  imports: [
    ResilienceModule.forRoot({
      presets: {
        anthropic: {
          retry: { attempts: 3 },
          timeout: '30s',
          circuitBreaker: { name: 'anthropic', failureRateThreshold: 50 },
        },
      },
    }),
    AiModule.forRoot({
      isGlobal: true,
      models: {
        default: {
          model: anthropic('claude-opus-5-5'),
          resilience: 'anthropic',
          fallback: 'backup',
        },
        backup: openai('gpt-5'),
      },
    }),
  ],
})
export class AppModule {}
```

预设用自己的 `retry` 和 `timeout` 取代模型的：没有 `timeout` 的预设会让该模型的所有调用都没有超时；预设的重试只有在其 `backoff` 支持时才会遵守 `retry-after`。此类策略的拒绝（`CircuitOpenError`、`BulkheadFullError`）若没有回退接手，会原样到达调用方：这是 `@nestjs/resilience` 的错误，在 HTTP 路由上由 `ResilienceModule` 以 503 响应。指定了预设却未导入 `ResilienceModule`，会以 `AiConfigurationError` 失败。

这些策略把 `@nestjs/resilience` 的事件发布到 `nestjs:resilience:<type>` 诊断通道上：`retry`、`timeout` 和 `fallback`，以模型命名（`ai:fast retry`、`ai:fast fallback`），并以调用的 `label` 作为其 `source`（未指定时是 `AiService`）。要记录每次模型调用的重试：

```typescript
@@filename(main)
import { subscribe } from 'node:diagnostics_channel';
import { Logger } from '@nestjs/common';
import type { ResilienceRetryEvent } from '@nestjs/resilience';

const logger = new Logger('Models');

subscribe('nestjs:resilience:retry', (message) => {
  const event = message as ResilienceRetryEvent;
  logger.warn(
    `${event.source}: attempt ${event.attempt} of ${event.policy} failed, ` +
      `retrying in ${Math.round(event.delayMs)} ms`,
  );
});
```

#### 用量、花销与预算

每次作答的模型调用都会发出一个用量事件。若模型配置了 `pricing`（以你选定的单位、每百万 token 计），事件还带有同一单位下的 `cost`。`onUsage` 接收它们：

```typescript
@@filename(app.module)
import { anthropic } from '@ai-sdk/anthropic';
import { Logger, Module } from '@nestjs/common';
import { AiModule } from '@nestjs/ai';

const usage = new Logger('Usage');

@Module({
  imports: [
    AiModule.forRoot({
      isGlobal: true,
      models: {
        // US dollars per million tokens
        default: {
          model: anthropic('claude-opus-5-5'),
          pricing: { input: 4, output: 20, cachedInput: 0.2 },
        },
      },
      onUsage: (event) =>
        usage.log(
          `${event.label ?? 'call'} on ${event.model.name}: ` +
            `${event.usage.totalTokens} tokens, $${event.cost?.toFixed(4)}`,
        ),
    }),
  ],
})
export class AppModule {}
```

| 属性 | 含义 |
| --- | --- |
| `label` | 该调用的 `label`，用于区分不同调用 |
| `model` | 作答的模型：`name`、`provider`、`modelId` |
| `step`、`attempt` | 该模型调用在整次调用中的步骤（从 0 起），以及此模型针对它的第几次尝试（从 1 起） |
| `fallback`、`stream` | 是否为回退模型作答，以及该调用是否为流式 |
| `usage` | `inputTokens`（含缓存部分）、`outputTokens`、`totalTokens`、`cachedInputTokens`、`reasoningTokens` |
| `cost` | 未从缓存读取的输入 token 按 `input` 计价、缓存部分按 `cachedInput`（默认 `input`）计价，输出 token 按 `output` 计价；无 `pricing` 时为 `undefined` |
| `durationMs`、`finishReason` | 该模型调用花了多久，以及模型为何停止 |

调用也可以有自己的 `onUsage`，它在模块的之后被调用。监听器抛出的内容会被记录，绝不会让调用失败。这家商店按顾客计量助手的 token：

```typescript
const { text } = await this.ai.generateText({
  label: 'assistant',
  prompt: question,
  onUsage: (event) =>
    this.metering.record(customerId, event.usage.totalTokens, event.cost),
});
```

`budget` 限制单次调用：`maxTokens` 与 `maxCost`，覆盖它的全部模型调用。使用工具的调用会做多次模型调用，预算在每次之前检查：已用完预算的调用会在下一次模型调用之前以 `AiBudgetExceededError` 拒绝，其中带有已花费的（`usage`、`cost`）和 `limit`。这项检查无法让模型调用中途停下，因此最后一次可能使调用超出预算。没有 `pricing` 的模型按免费计。`defaults.budget` 为每次调用施加预算：

```typescript
const { object } = await this.ai.generateObject({
  model: 'fast',
  schema: Triage,
  prompt: email,
  tools: ['find-order'],
  budget: { maxTokens: 20_000, maxCost: 0.01 },
});
```

> info **提示** 自 `@nestjs/observe` 0.3.20 起，[NestJS Observe](/observability/overview) 会在每次模型调用的出站 span 上记录模型与 token，与它对任何 AI SDK 调用的做法一致：见[模型调用](/observability/sdk#model-calls)。以网关 ID 命名的模型，例如 `'openai/gpt-5'`，是经 AI Gateway 的主机 `ai-gateway.vercel.sh` 调用的：把它加入 `outgoing.llm.hosts`，Observe 也能读到这些调用。
