# 代理

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

代理是一个在循环中调用工具的模型：它读取每个工具返回的内容，然后调用更多工具或作答，直到给出答案或达到模型调用次数上限。

`AiService` 每一次带[工具](/ai/tools)（也就是你的代理函数）的调用，都在你的进程内运行这个循环：没有别的东西需要部署。本页介绍它所附带的能力：循环及其限制、对话、边写边流式发送到浏览器的答案，以及能跨越重启、并等待人批准的持久化运行。

#### 代理循环

带工具的调用会做一次模型调用，运行模型请求的工具，再用它们的结果做下一次模型调用，直到模型不再请求工具而直接作答。每次模型调用是一个**步骤**，结果会列出它们：

```typescript
@@filename(assistant/assistant.service)
import { Injectable, Logger } from '@nestjs/common';
import { AiService } from '@nestjs/ai';

@Injectable()
export class AssistantService {
  private readonly logger = new Logger(AssistantService.name);

  constructor(private readonly ai: AiService) {}

  async answer(question: string, request: unknown) {
    const result = await this.ai.generateText({
      label: 'assistant',
      prompt: question,
      tools: ['find-order', 'change-address'],
      caller: { request },
      maxSteps: 5,
    });
    for (const step of result.steps) {
      const tools = step.toolCalls.map((call) => call.toolName).join(', ');
      this.logger.log(
        `Step ${step.index}: ${tools || 'answered'}, ` +
          `${step.usage.totalTokens} tokens, ${step.attempts} attempt(s)`,
      );
    }
    return result.text;
  }
}
```

每个步骤有其 `text`、`toolCalls`、`toolResults`（每个工具以 `output` 返回的内容，或告知模型的 `error`）、`finishReason`、`usage`、`cost`，以及作答的 `model` 和它用了几次 `attempts`。

`maxSteps` 限定一次调用的模型调用次数，默认为 10（`defaults.maxSteps` 可为每次调用改动它）。当次数用尽而模型仍在请求工具时，`generateText()` 以已有的内容 resolve，其 `finishReason` 为 `'tool-calls'`；`generateObject()` 则以 `AiOutputError` 拒绝，因为它没有对象可以给出。工具在其步骤内运行：工具耗时不计入模型的 `timeout`，工具已开始的步骤永远不会被重试，因此没有工具会运行两次。

`toolChoice` 按 AI SDK 的方式传给模型：`'auto'`（默认）让模型自行选择，`'none'` 提供工具但不允许调用。`'required'` 和 `{{ '{' }} type: 'tool', toolName {{ '}' }}` 让它必须调用一个，并非所有模型都接受。

`abortSignal` 取消一次调用：进行中的模型调用、重试前的等待，以及正在运行的代理函数，后者通过其上下文的 `signal` 中止。一个不得超过两分钟的任务会传入 `abortSignal: AbortSignal.timeout(120_000)`，调用则以该信号的原因拒绝，不重试也不回退。

#### 对话

`messages` 接收整段对话，即 AI SDK 的 `ModelMessage` 对象，用以取代 `prompt`。一次调用的 `responseMessages` 是它新增的消息：模型的作答与工具调用，以及工具的结果。把它们追加到对话中，并与顾客的下一条消息一起发送：

```typescript
@@filename(assistant/conversations.service)
import { Injectable } from '@nestjs/common';
import { AiService } from '@nestjs/ai';
import type { ModelMessage } from 'ai';

@Injectable()
export class ConversationsService {
  // Keep conversations in your database: this one is lost on a restart.
  private readonly conversations = new Map<string, ModelMessage[]>();

  constructor(private readonly ai: AiService) {}

  async reply(conversationId: string, message: string, request: unknown) {
    const messages: ModelMessage[] = [
      ...(this.conversations.get(conversationId) ?? []),
      { role: 'user', content: message },
    ];
    const { text, responseMessages } = await this.ai.generateText({
      instructions: 'You help customers of the cat store with their orders.',
      messages,
      tools: ['find-order', 'change-address'],
      caller: { request },
    });
    this.conversations.set(conversationId, [...messages, ...responseMessages]);
    return text;
  }
}
```

`instructions` 不属于对话：每次调用都发送自己的。浏览器中的聊天自己维护对话，并随每条消息发送：见[流式发送到浏览器](/ai/agents#streaming-to-the-browser)。

#### 流式发送到浏览器

助手边想边答，因此浏览器在答案写成之时就能显示它。`streamText()` 发起调用并立即返回其流，`pipeUIMessageStreamToResponse()` 把它以服务器发送事件（server-sent events）的形式、按 AI SDK 的 UI 消息流协议，写到 `@Res()` 注入的响应上：

```typescript
@@filename(assistant/assistant.controller)
import { Body, Controller, Post, Req, Res } from '@nestjs/common';
import { AiService } from '@nestjs/ai';
import { convertToModelMessages, type UIMessage } from 'ai';
import type { Request, Response } from 'express';

@Controller('assistant')
export class AssistantController {
  constructor(private readonly ai: AiService) {}

  @Post('chat')
  async chat(
    @Body() { messages }: { messages: UIMessage[] },
    @Req() request: Request,
    @Res() response: Response,
  ) {
    const answer = this.ai.streamText({
      label: 'assistant',
      instructions:
        'You help customers of the cat store with their orders. ' +
        'Look an order up before you answer about it.',
      messages: await convertToModelMessages(messages),
      tools: ['find-order', 'change-address'],
      caller: { request },
    });
    await answer.pipeUIMessageStreamToResponse(response);
  }
}
```

该路由在 Fastify 和 Node 适配器上表现相同：`pipeUIMessageStreamToResponse()` 接受平台自己的响应对象，在 Fastify 上是 `FastifyReply`，流开始之前设置的响应头（例如 CORS 头）会保留。来自 `ai` 的 `convertToModelMessages()` 把浏览器提交的 `UIMessage` 对象变成该调用所接收的模型消息。

在浏览器中，来自 `@ai-sdk/react`（或 AI SDK 面向 Vue、Svelte 和 Angular 的包）的 `useChat()` 把对话提交到该路由，并在答案到达时逐步构建：

```typescript
import { useChat } from '@ai-sdk/react';
import { DefaultChatTransport } from 'ai';

const { messages, sendMessage, status } = useChat({
  transport: new DefaultChatTransport({ api: '/assistant/chat' }),
});
```

每条消息的 `parts` 容纳其文本（`type: 'text'`）和模型所做的工具调用，后者为带 `state`、`input` 与 `output` 的 `tool-find-order` 部分。该调用中每次模型调用的答案都作为一条消息流出，包含其工具调用及其结果。

- **错误。** 在第一个分块之前失败的调用会拒绝，什么都没发出，因此由路由的异常过滤器作答。在那之前，流会重试，并回退到另一个模型，与其他调用一样。之后的失败会用一个内容为 `An error occurred.` 的错误分块结束流，以免泄露服务器的任何细节：`errorText` 选项可以给出更多信息。
- **保活。** 若 15 秒没有分块，例如某个工具正在执行，就会发出一条注释行（`: keep-alive`），使代理和负载均衡器不会因空闲而关闭连接。`useChat()` 会跳过它。`keepAlive` 选项设置间隔，`false` 关闭它。
- **浏览器离开。** 当浏览器关闭连接时，模型调用被中止，正在运行的代理函数的 `signal` 也被中止。
- **响应头。** 响应为 `text/event-stream`，带 `x-accel-buffering: no`，告诉 nginx 不要缓冲它。`status` 和 `headers` 可添加你自己的。

```typescript
await answer.pipeUIMessageStreamToResponse(response, {
  keepAlive: '10s',
  errorText: (error) =>
    error instanceof AiModelError
      ? 'The assistant is unavailable. Try again in a minute.'
      : 'Something went wrong.',
});
```

代理函数的 `ctx.reportProgress()` 以瞬态的 `data-tool-progress` 分块到达浏览器，`useChat()` 把它交给其 `onData` 回调，而不加入消息：

```typescript
@@filename(catalog/catalog.tools)
@AgentFunction({
  name: 'check-stock',
  description: 'Check the stock of a product in every warehouse',
  inputSchema: z.object({
    sku: z.string().describe('The product SKU, such as SKU-1042'),
  }),
})
async checkStock({ sku }: { sku: string }, ctx: AgentFunctionContext) {
  const warehouses = await this.stock.warehouses();
  const counts: Record<string, number> = {};
  for (const [index, warehouse] of warehouses.entries()) {
    counts[warehouse.name] = await this.stock.count(warehouse.id, sku, {
      signal: ctx.signal,
    });
    await ctx.reportProgress(index + 1, warehouses.length, warehouse.name);
  }
  return counts;
}
```

```typescript
const { messages, sendMessage } = useChat({
  transport: new DefaultChatTransport({ api: '/assistant/chat' }),
  onData: (part) => {
    if (part.type === 'data-tool-progress') {
      // { toolCallId, toolName, progress, total, message }
      console.log(part.data);
    }
  },
});
```

这个流还有其他读取方式。`pipeTextStreamToResponse(response)` 只发送文本，类型为 `text/plain`；`textStream` 可迭代它；`toUIMessageStream()` 给出作为 `ReadableStream` 的 UI 消息流，`toUIMessageStreamResponse()` 给出作为 Web 标准 `Response` 的版本。`text`、`usage`、`steps`、`finishReason` 和 `responseMessages` 是在调用结束时敲定的 promise，`result` 包含它们全部；它们以该调用的错误拒绝。无论谁来读取，调用只运行一次，每个读取者都从头拿到整个流。`abort()` 取消它。选项中的错误，例如引用不存在的代理函数，会由 `streamText()` 立刻抛出。

```typescript
@Post('summary')
async summary(
  @Body() { thread }: { thread: string },
  @Res() response: Response,
) {
  const answer = this.ai.streamText({
    model: 'fast',
    instructions: 'Summarize the support thread in three sentences.',
    prompt: thread,
  });
  await answer.pipeTextStreamToResponse(response);
}
```

#### 持久化代理运行

退款请求需要人来处理：代理查询订单并请求退款，客服团队里有人批准——可能是第二天早上，也可能在一次部署之后。`@nestjs/ai/workflows` 在 [`@nestjs/workflows`](/reliability/workflows) 之上运行代理循环，每次模型调用是一个步骤，每次工具调用是另一个步骤。被重启打断的运行为从中断处继续，其日志中已有的内容是被回读的，而不是重新执行。安装该包：

```bash
$ npm i --save @nestjs/workflows
```

在你的工作流模块中导入 `AiWorkflowsModule`。应用导入 `WorkflowsModule`，并按[持久化工作流](/reliability/workflows#keep-workflows-in-your-database)所述在数据库中配置存储，同时照常导入 `AiModule`：

```typescript
@@filename(refunds/refunds.module)
import { Module } from '@nestjs/common';
import { AiWorkflowsModule } from '@nestjs/ai/workflows';
import { OrdersModule } from '../orders/orders.module.js';
import { PaymentsModule } from '../payments/payments.module.js';
import { ApprovalsController } from './approvals.controller.js';
import { RefundRequest } from './refund-request.workflow.js';
import { RefundTools } from './refund.tools.js';
import { RefundsService } from './refunds.service.js';

@Module({
  imports: [AiWorkflowsModule, OrdersModule, PaymentsModule],
  controllers: [ApprovalsController],
  providers: [RefundRequest, RefundTools, RefundsService],
})
export class RefundsModule {}
```

用 `AiAgents` 在你自己的工作流中运行该代理：

```typescript
@@filename(refunds/refund-request.workflow)
import { AiAgents } from '@nestjs/ai/workflows';
import { Workflow, type WorkflowContext } from '@nestjs/workflows';

export interface RefundRequestInput {
  email: string;
  customerId: string;
}

@Workflow('refund-request')
export class RefundRequest {
  constructor(private readonly agents: AiAgents) {}

  run(ctx: WorkflowContext, input: RefundRequestInput) {
    return this.agents.run(ctx, {
      label: 'refund-request',
      instructions:
        'You handle the refund requests of the cat store. Look the order ' +
        'up, and refund it when the customer is right.',
      prompt: input.email,
      tools: ['find-order', 'refund'],
      approve: ['refund'],
      caller: { user: { id: input.customerId } },
    });
  }
}
```

像任何工作流一样启动它，用票据中的 ID 作为标识，这样为同一票据再次启动会返回已存在的运行：

```typescript
@@filename(refunds/refunds.service)
import { Injectable } from '@nestjs/common';
import { WorkflowClient } from '@nestjs/workflows';
import { RefundRequest } from './refund-request.workflow.js';

@Injectable()
export class RefundsService {
  constructor(private readonly workflows: WorkflowClient) {}

  async request(ticket: { id: string; body: string; customerId: string }) {
    await this.workflows.start(
      RefundRequest,
      { email: ticket.body, customerId: ticket.customerId },
      { id: `refund-${ticket.id}` },
    );
  }
}
```

在 `approve` 中列出的代理函数，其调用在执行前要等人批准，等多久都行；`approvalTimeout` 限定等待时长。`pendingApprovals(runId)` 列出在等待的调用，每个带其 `key`、`toolName` 和 `input`，`approve(key)` 或 `reject(key, {{ '{' }} reason {{ '}' }})` 为其中一个作答，无论客服团队在何处工作：

```typescript
@@filename(refunds/approvals.controller)
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { AiAgents } from '@nestjs/ai/workflows';

@Controller('refunds')
export class ApprovalsController {
  constructor(private readonly agents: AiAgents) {}

  @Get(':runId/approvals')
  pending(@Param('runId') runId: string) {
    return this.agents.pendingApprovals(runId);
  }

  @Post('approvals/:key')
  answer(
    @Param('key') key: string,
    @Body() body: { approved: boolean; reason?: string },
  ) {
    return body.approved
      ? this.agents.approve(key)
      : this.agents.reject(key, { reason: body.reason });
  }
}
```

被拒绝的调用不会执行：模型会被告知它被拒绝及其原因，然后回答顾客。在 `approvalTimeout` 内无人作答的调用同样不会执行。以对一个调用给出的第一个答复为准，`approve()` 和 `reject()` 接受 `by`，即作答者，会与答复一起保存。运行等待期间，其工作流实例处于挂起状态，不占用进程。

运行恢复所需的信息与它一起存储，因此其选项都是数据：按名称给出的模型、按名称或提供者类给出的代理函数（运行会把它们存为名称），以及代理函数所需的 `user` 和 `scopes` 形式的 `caller`，因为重启之后没有请求可读。代理函数以 `ctx.user` 和 `ctx.scopes` 取得它们；配合 `@nestjs/authentication` 时，它们的提供者要标注为 [`@Public()`](/ai/tools#with-nestjsauthentication-and-nestjsauthorization)，与任何没有请求的调用一样。运行的模型调用使用其模型和模块的 `timeout`、`retry` 和生成设置，其 `maxSteps` 与 `budget` 回落到模块的 `defaults`，与调用一致。

代理函数调用至少执行一次：运行期间死掉的进程会在重启后再执行一次，`ctx.idempotencyKey` 相同。会改动数据的函数把该键传下去，使改动只发生一次：

```typescript
@@filename(refunds/refund.tools)
import { Injectable, NotFoundException } from '@nestjs/common';
import { AgentFunction, type AgentFunctionContext } from '@nestjs/ai';
import * as z from 'zod';
import { OrdersService } from '../orders/orders.service.js';
import { PaymentsService } from '../payments/payments.service.js';

@Injectable()
export class RefundTools {
  constructor(
    private readonly orders: OrdersService,
    private readonly payments: PaymentsService,
  ) {}

  @AgentFunction({
    name: 'refund',
    description: 'Refund an order to the card it was paid with',
    inputSchema: z.object({ orderId: z.string() }),
  })
  async refund({ orderId }: { orderId: string }, ctx: AgentFunctionContext) {
    const order = await this.orders.findById(orderId);
    if (!order) {
      throw new NotFoundException(`There is no order ${orderId}`);
    }
    await this.payments.refund(order.paymentId, order.total, {
      idempotencyKey: ctx.idempotencyKey,
    });
    return { refunded: order.id, amount: order.total };
  }
}
```

代理函数的失败是模型读到的一个结果，与任何调用中一样，而不是其步骤失败。模型调用保留其重试、超时和回退模型；仍失败的那次会作为工作流的一个步骤被重试，在两次尝试之间持久化等待（默认三次尝试）。经过 `stepsPerInstance` 次模型调用（10）后，运行在子工作流中继续，使任何实例的日志都不会过长：每次恢复都要完整重放它，而它是有上限的。`maxSteps`（25）限定一次运行的模型调用次数。

运行以 `generateText()` resolve 的内容 resolve：`text`、`steps`、`toolResults` 等等，作为 JSON：它就是该工作流的输出，`WorkflowClient` 的 `getStatus(runId)` 也能读到。

`run()` 的选项：

| 选项 | 默认值 | 说明 |
| --- | --- | --- |
| `model`、`fallback` | `'default'`，即模型的 | 按名称给出的模型 |
| `instructions`、`prompt`、`messages` | | 与调用相同 |
| `tools` | | 代理函数名称与提供者类，存为名称 |
| `approve` | `[]` | `tools` 中其调用需等待人批准的代理函数 |
| `approvalTimeout` | 直到获得答复 | 一个调用等待批准的时长 |
| `caller` | | 代理函数运行时所用的 `user` 和 `scopes` |
| `maxSteps` | `defaults.maxSteps`，否则 `25` | 该运行的模型调用次数 |
| `stepsPerInstance` | `10` | 单个工作流实例的模型调用次数，超过后运行转到子工作流 |
| `budget` | `defaults.budget` | 整个运行的 `maxTokens` 与 `maxCost` |
| `label`、`toolChoice`、`maxOutputTokens`、`temperature`、`providerOptions` | | 与调用相同 |
