用 Node.js 构建可流式返回答案的 AI 聊天后端
用 NestJS 在 Node.js 中构建 AI 聊天机器人后端:只读取用户本人数据的工具、流式发送到浏览器的答案,以及保存下来的会话。
这个助手工作在笔记 API 之上:已登录用户询问自己的笔记,模型用代表该用户运行的工具去查找,答案在模型撰写的同时流式发送到浏览器。调用模型只需要几行代码。功夫都在调用之外:模型绝不能读到别人的笔记,中途关闭的浏览器必须停止这次付费调用,发给模型的历史必须控制在预算之内,双击发送也不能启动两个答案。本教程的时间就花在这些部分。
到教程结束时,这个 API 将能够:
- 通过
@nestjs/ai调用一个从环境变量一次性配置好的模型:带超时、重试、单次模型调用输出 token 的上限,以及每个答案的 token 预算。 - 给模型三个针对笔记的工具,它们以已登录用户的身份运行,够不到别人的笔记。
- 把每个答案作为服务器发送事件流式发出,采用
useChat()读取的 AI SDK UI 消息流协议,并在浏览器离开时中止模型调用。 - 把会话保存在 PostgreSQL 中,每个会话一次只回答一条消息,并只把预算装得下的最新历史发给模型。
- 限制每个用户每小时发送的消息数。
- 用假模型而不是真实的提供方来运行端到端测试和开发服务器,两者都不需要 API 密钥。
它从 构建带 JWT 认证的 REST API 的 API 出发:那个 API 用访问令牌和刷新令牌让用户登录,用 Zod 校验请求,并通过 Drizzle 把笔记保存在 PostgreSQL 中。本教程不再重复解释这些部分。
下面是端点,以及添加每个端点的小节:
| 端点 | 小节 |
|---|---|
POST /auth/sign-up、POST /auth/token、POST /auth/token/refresh、POST /auth/token/revoke、GET /me、GET /notes、GET /notes/:id、POST /notes、PATCH /notes/:id、DELETE /notes/:id、GET /health/live、GET /health/ready |
从 JWT API 开始 |
POST /conversations、GET /conversations、GET /conversations/:id、DELETE /conversations/:id |
存储会话 |
POST /conversations/:id/messages |
流式返回答案 |
完成后的应用位于 GitHub:nestjs/example-ai-chat-backend,其中包含测试和 CI 工作流。
你需要 Node.js 22 或更高版本,以及一个 PostgreSQL 服务器。要得到真实答案,还需要某个模型提供方的 API 密钥;本教程用的是 Anthropic 的,与 AI 章节 一样。本页每个模型答案都来自 FakeModel,即 @nestjs/ai/testing 的脚本化模型:真实模型写出的文字不同,调哪些工具也由它自己决定,但工具、流、历史以及它们周围的限制运行的是同一套代码。
从 JWT API 开始
创建项目,并安装本教程用到的全部依赖。它们是 JWT 教程的那些包,再加上 @nestjs/ai、模型调用所依循其策略的 @nestjs/resilience、AI SDK(ai),以及它的 Anthropic 提供方:
$ npm i -g @nestjs/cli
$ nest new notes-assistant --minimal
$ cd notes-assistant
$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node zod @nestjs/config @nestjs/drizzle drizzle-orm@rc pg @nestjs/authentication @nestjs/throttler @nestjs/swagger @nestjs/terminus @nestjs/ai @nestjs/resilience ai @ai-sdk/anthropic
$ npm i --save-dev drizzle-kit@rc @types/pg @nestjs/testing vitest vite然后从 已完成的 JWT 教程 原样取来这些文件:
src/main.ts、src/database/schema.ts和drizzle.config.tssrc/auth/、src/users/、src/health/和src/notes/下的全部内容test/refresh-token.store.e2e-spec.ts
不要 JWT 教程的 drizzle/ 文件夹,因为本应用的第一个迁移来自它自己的 schema;也不要 test/notes.e2e-spec.ts,因为它跑在 PGlite 上:本教程的测试需要 PostgreSQL 服务器。src/config.ts、src/app.module.ts 和 vitest.config.e2e.ts 在下面完整给出。再把测试脚本加入 package.json:
"test:e2e": "vitest run --config ./vitest.config.e2e.ts"启动一个数据库,像 JWT 教程那样把它的 URL 和一个 JWT_SECRET 写进 .env。没有 API 密钥时,设置 AI_MODEL=fake,下一节会说明:
$ docker run -d --name assistant-db -e POSTGRES_PASSWORD=assistant -e POSTGRES_DB=assistant -p 5432:5432 postgres:17它的 URL 写进 .env,连同签名密钥和模型设置:
DATABASE_URL=postgres://postgres:assistant@localhost:5432/assistant
# 用以下命令生成:openssl rand -base64 32
JWT_SECRET=
# 要么是你的 Anthropic API 密钥……
# ANTHROPIC_API_KEY=
# ……要么是脚本化模型,它不需要任何密钥(仅限开发)。
AI_MODEL=fake配置模型
@nestjs/ai 按名称注册模型,经由 AiService 的每次调用都运行在其模型与模块的超时、重试和限制之下(参见 模型)。从环境变量一次性配置模型。配置 schema 增加了三个变量:
import { z } from 'zod';
export const envSchema = z
.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().default(3000),
DATABASE_URL: z.url(),
// 签发访问令牌:至少 32 字节。
JWT_SECRET: z.string().min(32),
// 允许调用该 API 的浏览器来源,用逗号分隔。默认没有。
CORS_ORIGINS: z
.string()
.default('')
.transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
.pipe(z.array(z.url())),
// 一个 Anthropic 模型 id,或用 `fake` 表示不需要 API 密钥的脚本化模型。
AI_MODEL: z.string().min(1).default('claude-opus-5-5'),
ANTHROPIC_API_KEY: z.string().min(1).optional(),
// 单次模型调用最多的输出 token 数:一个答案最多进行 `maxSteps` 次调用。
AI_MAX_OUTPUT_TOKENS: z.coerce.number().int().min(1).max(8_000).default(1_000),
})
.superRefine((env, ctx) => {
if (env.AI_MODEL === 'fake' && env.NODE_ENV === 'production') {
ctx.addIssue({ code: 'custom', path: ['AI_MODEL'], message: 'The fake model is for development and tests' });
}
if (env.AI_MODEL !== 'fake' && !env.ANTHROPIC_API_KEY) {
ctx.addIssue({ code: 'custom', path: ['ANTHROPIC_API_KEY'], message: `Required for the model ${env.AI_MODEL}` });
}
});
export type Env = z.infer<typeof envSchema>;AI_MODEL是模型在 Anthropic 的 id,除非另设,否则是claude-opus-5-5。fake选择一个脚本化模型,用于开发和测试,而 schema 在生产环境会拒绝它。ANTHROPIC_API_KEY是其他任何模型都要求的,所以缺少密钥会让应用在启动时停下,而不是等到第一个问题。AI_MAX_OUTPUT_TOKENS为每次模型调用的输出设上限。一个答案最多进行五次调用(见下面的maxSteps),因此它最多写出五倍于此的 token。
根模块在工厂函数中根据 ConfigService 构建模型,如 异步配置 所述。加上本教程引入的模块,它如下所示:
import { createAnthropic } from '@ai-sdk/anthropic';
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { AiModule } from '@nestjs/ai';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthenticationModule } from '@nestjs/authentication';
import { DrizzleModule } from '@nestjs/drizzle';
import { createObserveModule } from '@nestjs/observe';
import { ThrottlerGuard, ThrottlerModule, hours, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle } from 'drizzle-orm/node-postgres';
import { accountEmail } from './auth/account-email.js';
import { AuthModule } from './auth/auth.module.js';
import { ChatModule } from './chat/chat.module.js';
import { envSchema, type Env } from './config.js';
import { HealthModule } from './health/health.module.js';
import { NotesModule } from './notes/notes.module.js';
import { UsersModule } from './users/users.module.js';
export const { ObserveModule, ObserveInstrument } = createObserveModule();
@Module({
imports: [
// 放在最前,这样它最后关闭,仍能发送其他模块做过的事。
ObserveModule.forRoot({
// 在 `npx @nestjs/observe link` 把密钥对写进 .env 之前为空:此时 SDK 什么都不发送。
appKey: process.env.OBSERVE_APP_KEY ?? '',
appSecret: process.env.OBSERVE_APP_SECRET ?? '',
serviceId: 'notes-assistant',
}),
ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
DrizzleModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({
drizzle,
connection: config.get('DATABASE_URL', { infer: true }),
}),
}),
AuthenticationModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({
accessToken: {
key: config.get('JWT_SECRET', { infer: true }),
issuer: 'notes-api',
audience: 'notes-api',
ttl: '15m',
},
refreshToken: { ttl: '30d', absoluteTtl: '90d' },
}),
}),
AiModule.forRootAsync({
isGlobal: true,
inject: [ConfigService],
useFactory: async (config: ConfigService<Env, true>) => {
const modelId = config.get('AI_MODEL', { infer: true });
const model =
modelId === 'fake'
? // 仅在配置为此时加载:生产环境从不引入测试入口。
(await import('./chat/fake-model.js')).createFakeModel()
: createAnthropic({ apiKey: config.get('ANTHROPIC_API_KEY', { infer: true }) })(modelId);
return {
models: {
default: { model, maxOutputTokens: config.get('AI_MAX_OUTPUT_TOKENS', { infer: true }) },
},
defaults: {
timeout: '30s',
retry: { attempts: 3 },
// 每个答案的模型调用次数:每轮工具结果各多占一次。
maxSteps: 5,
// 一个答案所有模型调用合计的输入与输出 token。
budget: { maxTokens: 60_000 },
},
};
},
}),
ThrottlerModule.forRoot([
// 按 IP 地址,作用于每条路由。
{ name: 'default', ttl: minutes(1), limit: 100 },
// 按邮箱和 IP 地址,凡是请求体指明账户的地方。
{
name: 'account',
ttl: minutes(15),
limit: 5,
skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
},
// 按用户,作用于聊天路由:在用户已知之后由 ChatThrottlerGuard 计数。
{
name: 'chat',
ttl: hours(1),
limit: 30,
skipIf: (context) => !context.switchToHttp().getRequest().user,
getTracker: (req) => req.user.id,
},
]),
UsersModule,
AuthModule,
NotesModule,
ChatModule,
HealthModule,
],
providers: [
{ provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
{ provide: APP_GUARD, useClass: ThrottlerGuard },
],
})
export class AppModule {}isGlobal: true让聊天模块可以注入AiService。default模型定义里的maxOutputTokens会随每次对它的模型调用一起发送。达到该值的模型调用就此停止,结束原因为'length'。defaults应用于每次调用。一次尝试最多可用 30 秒,对流式答案而言,这是收到第一个块之前的时长。提供方标记为可重试的响应,即 408、409、429 和 5xx 以及失败的连接,会获得三次尝试,并带退避(参见 重试、超时与回退)。maxSteps为一个答案的模型调用次数设上限:模型每读一轮工具结果就多占一次。budget在一个答案的模型调用已用掉 60,000 个输入与输出 token 后,让它在下次模型调用之前停下。这项检查在每次模型调用之前进行,所以最后一次可能让一个答案略微超出(参见 用量、成本与预算)。- 只有
AI_MODEL为fake时才引入假模型,因此生产进程从不加载@nestjs/ai/testing。 - 限流器的
chat定义在 限制每个用户 中说明,ChatModule则在前面的小节中。
无法工作的配置会让应用在处理请求之前就停下:
$ NODE_ENV=production AI_MODEL=fake npm run start
ERROR [ExceptionHandler] Error: Config validation error: AI_MODEL: The fake model is for development and tests
$ AI_MODEL=claude-opus-5-5 npm run start
ERROR [ExceptionHandler] Error: Config validation error: ANTHROPIC_API_KEY: Required for the model claude-opus-5-5无 API 密钥开发
FakeModel 按你的脚本回答每次调用,并记录它收到的调用(参见 假模型)。对 AI SDK 而言它是真实语言模型,所以用它时,应用的运行方式与接真实提供方时相同:模型的工具调用以已登录用户的身份运行真实工具,它的答案按词大小的块流式到达。下面这个模型会用问题的最后一个词搜索笔记,然后说出找到的笔记:
import { FakeModel } from '@nestjs/ai/testing';
/**
* 一个脚本化模型,用于没有 API 密钥时的开发:它用真正的 search-notes 工具搜索笔记中
* 问题里的最后一个词,然后流式返回找到的标题。
*/
export function createFakeModel() {
return new FakeModel((call) => {
if (call.toolResults.length === 0) {
const words = call.lastUserMessage?.match(/[\p{L}\p{N}]+/gu) ?? ['note'];
return { toolCalls: [{ name: 'search-notes', input: { query: words[words.length - 1] } }] };
}
const found = call.toolResults[0].output;
if (!Array.isArray(found)) {
return `The search failed: ${String(found)}`;
}
const titles = found.map((note: { title: string }) => `"${note.title}"`).join(', ');
const text = found.length === 0 ? 'None of your notes mention that.' : `Your notes mention it in ${titles}.`;
return { text, chunkDelay: 40 };
});
}这样开发服务器、前端和测试都不需要 API 密钥,也不产生费用。
存储会话
浏览器本可以随每条消息发送整个会话,就像 AI 章节的 聊天路由 那样。那样一来,客户端就决定了模型读到什么,包括工具结果,还能把它们编造出来。这里服务器保存每个会话,客户端只发送它的新消息。
JWT 教程的 schema 增加了两张表,它的 import 中需要 bigint 和 integer:
import type { ModelMessage } from 'ai';
import { bigint, boolean, index, integer, jsonb, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';
// ...
export const conversations = pgTable(
'conversations',
{
id: uuid('id').primaryKey().defaultRandom(),
ownerId: uuid('owner_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
title: text('title').notNull(),
// 在撰写答案期间设置:每个会话一次只回答一条。
answeringUntil: at('answering_until'),
createdAt: at('created_at').notNull().defaultNow(),
updatedAt: at('updated_at').notNull().defaultNow(),
},
(table) => [index('conversations_owner_id_updated_at_idx').on(table.ownerId, table.updatedAt)],
);
export const messages = pgTable(
'messages',
{
// 递增,因此一轮的消息保持插入时的顺序。
id: bigint('id', { mode: 'number' }).primaryKey().generatedAlwaysAsIdentity(),
conversationId: uuid('conversation_id')
.notNull()
.references(() => conversations.id, { onDelete: 'cascade' }),
// 模型读取形式的一条消息:用户的文本、模型的答案与工具调用,或工具的结果。
content: jsonb('content').$type<ModelMessage>().notNull(),
// 其大小为 token 的估计值,历史按它裁剪。
tokens: integer('tokens').notNull(),
createdAt: at('created_at').notNull().defaultNow(),
},
(table) => [index('messages_conversation_id_id_idx').on(table.conversationId, table.id)],
);
// ...
export type Note = typeof notes.$inferSelect;
export type Conversation = typeof conversations.$inferSelect;- 消息按模型读取的形式存储:一个 AI SDK
ModelMessage,存放在jsonb中。它就是用户的问题、模型的答案与工具调用,以及工具的结果,所以发送历史就是把这些行读回来。 id是标识列。 一轮的消息由一条语句插入,因此它们共享created_at;它们的 id 让它们保持顺序。tokens是每条消息大小的估计值,约每个 token 四个字符,历史的预算会把它累加。准确的计数由提供方给出,并因模型而异;预算为这一差异留出了余量。answering_until在撰写答案期间设置,使一个会话一次只回答一条消息。
生成迁移并应用(参见 迁移):
$ npx drizzle-kit generate --name=chat
$ npx drizzle-kit migrate请求体:
import { z } from 'zod';
export const createConversationSchema = z.object({
title: z.string().trim().min(1).max(200).default('New conversation'),
});
export type CreateConversationDto = z.infer<typeof createConversationSchema>;
export const sendMessageSchema = z.object({
text: z.string().trim().min(1).max(4_000),
});
export type SendMessageDto = z.infer<typeof sendMessageSchema>;ConversationsService 读写会话,语句中始终带着其所有者,就像 NotesService 对待笔记那样:
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import type { ModelMessage } from 'ai';
import { and, asc, desc, eq, isNull, lt, or, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { conversations, messages, type Conversation } from '../database/schema.js';
/** 一个答案最多可用的时间,含工具:到时它的调用被中止,会话被释放。 */
export const ANSWER_TIMEOUT_MS = 120_000;
/** 认领会比它的答案活得更久,所以只有回答到一半死掉的进程才会留下认领。 */
const CLAIM_SECONDS = ANSWER_TIMEOUT_MS / 1000 + 30;
/** 发给模型的历史上限,按估计 token 计。 */
const HISTORY_BUDGET = 8_000;
/** 对英文文本和 JSON,约每个 token 四个字符:这是估计值,不是模型的计数。 */
const estimateTokens = (message: ModelMessage) => Math.ceil(JSON.stringify(message.content).length / 4);
@Injectable()
export class ConversationsService {
constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}
async create(ownerId: string, title: string): Promise<Conversation> {
const [conversation] = await this.db.insert(conversations).values({ ownerId, title }).returning();
return conversation;
}
findAll(ownerId: string): Promise<Conversation[]> {
return this.db
.select()
.from(conversations)
.where(eq(conversations.ownerId, ownerId))
.orderBy(desc(conversations.updatedAt))
.limit(100);
}
async findOne(ownerId: string, id: string) {
const [conversation] = await this.db.select().from(conversations).where(this.owned(ownerId, id));
if (!conversation) {
notFound();
}
const rows = await this.db
.select({ content: messages.content, createdAt: messages.createdAt })
.from(messages)
.where(eq(messages.conversationId, id))
.orderBy(asc(messages.id));
return { ...conversation, messages: rows.map(({ content, createdAt }) => ({ ...content, createdAt })) };
}
async remove(ownerId: string, id: string): Promise<void> {
const deleted = await this.db
.delete(conversations)
.where(this.owned(ownerId, id))
.returning({ id: conversations.id });
if (deleted.length === 0) {
notFound();
}
}
/** 把会话标记为正在回答,否则抛出:不是所有者的返回 404,另一个答案正在运行则返回 409。 */
async claim(ownerId: string, id: string): Promise<void> {
// 一条带条件的语句:同时发来的两条消息中,只有一条认领会话。
const claimed = await this.db
.update(conversations)
.set({ answeringUntil: sql`now() + make_interval(secs => ${CLAIM_SECONDS})` })
.where(
and(
this.owned(ownerId, id),
// 超过时间的认领是回答到一半死掉的进程留下的。
or(isNull(conversations.answeringUntil), lt(conversations.answeringUntil, sql`now()`)),
),
)
.returning({ id: conversations.id });
if (claimed.length === 0) {
const [exists] = await this.db.select({ id: conversations.id }).from(conversations).where(this.owned(ownerId, id));
if (!exists) {
notFound();
}
throw new ConflictException('The assistant is still answering in this conversation');
}
}
/** 装得下预算的最新消息,从用户的一个问题开始。 */
async history(id: string): Promise<ModelMessage[]> {
const rows = await this.db
.select({ content: messages.content, tokens: messages.tokens })
.from(messages)
.where(eq(messages.conversationId, id))
.orderBy(desc(messages.id))
.limit(200);
const kept: ModelMessage[] = [];
let total = 0;
for (const { content, tokens } of rows) {
if (total + tokens > HISTORY_BUDGET) {
break;
}
total += tokens;
kept.push(content);
}
// 在用户消息处截断:工具调用被裁掉的工具结果会被提供方拒绝。
while (kept.length > 0 && kept[kept.length - 1].role !== 'user') {
kept.pop();
}
return kept.reverse();
}
/** 保存完整的一轮,即问题与调用新增的一切,并释放会话。 */
async saveTurn(id: string, turn: ModelMessage[]): Promise<void> {
await this.db.transaction(async (tx) => {
// 这一轮用一条语句:它的消息一起按顺序存入,要么全都不存。
await tx
.insert(messages)
.values(turn.map((content) => ({ conversationId: id, content, tokens: estimateTokens(content) })));
await tx
.update(conversations)
.set({ answeringUntil: null, updatedAt: new Date() })
.where(eq(conversations.id, id));
});
}
/** 在答案失败或被取消后释放会话。这一轮什么都不保留。 */
async release(id: string): Promise<void> {
await this.db.update(conversations).set({ answeringUntil: null }).where(eq(conversations.id, id));
}
private owned(ownerId: string, id: string) {
return and(eq(conversations.id, id), eq(conversations.ownerId, ownerId));
}
}
function notFound(): never {
throw new NotFoundException('Conversation not found');
}claim()是一条带条件的UPDATE。 双击发送,或者第二个标签页,会在同一时刻向一个会话发来两条消息。两者都会读到同样的历史,都会启动付费的模型调用,而第二个答案不会知道第一个。PostgreSQL 在更新行时会锁住该行,所以同一时刻的两次认领中,第二次要等第一次完成,然后发现answering_until已被设置,什么都不改,返回 409。答案在ANSWER_TIMEOUT_MS之后会被中止,下一节会说明;而一次认领会多持续 30 秒,所以超过时间的认领是回答到一半死掉的进程留下的,会被接管。有一个 测试 一次发十条消息;而先读行、在 JavaScript 中检查再写入的认领,每次运行都会放过其中五六条。history()从最新的消息往回走,直到预算用尽,然后从最旧的一端丢弃消息,直到历史以一个问句开始。以工具结果开头、其工具调用被预算裁掉的历史,会被提供方拒绝。saveTurn()用一条语句插入整轮,并在同一个事务中释放会话。一轮要么完整保存,要么完全不存,所以历史中绝不会有问题缺少答案,或工具调用缺少结果。
给模型工具
代理函数(agent function)是你某个提供者的一个方法,模型可以调用它,并填入参数(参见 工具)。这个助手得到三个,都基于 NotesService,为此先给它加一个搜索方法:
import { and, desc, eq, ilike, or } from 'drizzle-orm';
// ...
@Injectable()
export class NotesService {
// ...
/** 所有者的笔记中,标题或正文包含 `query` 的那些,最新的在前。 */
search(ownerId: string, query: string, limit = 10): Promise<Note[]> {
const pattern = `%${escapeLike(query)}%`;
return this.db
.select()
.from(notes)
.where(and(eq(notes.ownerId, ownerId), or(ilike(notes.title, pattern), ilike(notes.body, pattern))))
.orderBy(desc(notes.updatedAt), desc(notes.id))
.limit(limit);
}
// ...
}
// ...
/** 搜索中的 `%` 和 `_` 是字面字符,不是通配符。 */
const escapeLike = (value: string) => value.replace(/[\\%_]/g, (char) => `\\${char}`);模型按名称和描述选择工具,并根据参数的 .describe() 文本填入参数:
import { Injectable } from '@nestjs/common';
import { AgentFunction, type AgentFunctionContext } from '@nestjs/ai';
import { CurrentUser } from '@nestjs/authentication';
import { SkipThrottle } from '@nestjs/throttler';
import { z } from 'zod';
import type { Note } from '../database/schema.js';
import { createNoteSchema, type CreateNoteDto } from './notes.schemas.js';
import { NotesService } from './notes.service.js';
/** 模型能读到的一条笔记:没有所有者,没有内部列。 */
const view = ({ id, title, body, updatedAt }: Note) => ({ id, title, body, updatedAt });
// 全局守卫也作用于代理函数调用,而限流器的守卫会把
// 每个用户的每次调用都算作一个客户端:改为在聊天路由上限制。
@SkipThrottle({ default: true, account: true, chat: true })
@Injectable()
export class NotesTools {
constructor(private readonly notesService: NotesService) {}
@AgentFunction({
name: 'search-notes',
description: "Search the user's notes for a word or phrase, in titles and bodies. Returns up to 10, newest first.",
inputSchema: z.object({
query: z.string().trim().min(1).max(100).describe('A word or phrase to look for, such as "dentist"'),
}),
})
async search({ query }: { query: string }, _ctx: AgentFunctionContext, @CurrentUser('id') userId: string) {
const found = await this.notesService.search(userId, query);
return found.map(view);
}
@AgentFunction({
name: 'read-note',
description: "Read one of the user's notes in full, by its id.",
inputSchema: z.object({ noteId: z.uuid().describe('The id of a note, from search-notes') }),
})
async read({ noteId }: { noteId: string }, _ctx: AgentFunctionContext, @CurrentUser('id') userId: string) {
// 别人的笔记显示为 "Note not found",与 GET /notes/:id 一致。
return view(await this.notesService.findOne(userId, noteId));
}
@AgentFunction({
name: 'create-note',
description: 'Save a new note for the user, when they ask you to remember or write something down.',
inputSchema: createNoteSchema,
})
async create(dto: CreateNoteDto, _ctx: AgentFunctionContext, @CurrentUser('id') userId: string) {
return view(await this.notesService.create(userId, dto));
}
}在 notes 模块中注册工具,紧挨它们调用的服务:
import { Module } from '@nestjs/common';
import { NotesController } from './notes.controller.js';
import { NotesService } from './notes.service.js';
import { NotesTools } from './notes.tools.js';
@Module({
controllers: [NotesController],
providers: [NotesService, NotesTools],
})
export class NotesModule {}- 所有者从不来自模型。 没有任何输入 schema 带用户 id。
@CurrentUser('id')读取的是认证守卫为这次调用所在请求加载的用户(参见 配合 @nestjs/authentication 与 @nestjs/authorization),而NotesService把它放进每条语句的WHERE子句,与处理路由时一样。无论模型传什么 id,它都只能触到用户自己的笔记:别人的笔记是Note not found,模型会把它读作工具的错误。如果某条笔记的文本让模型去做某事,它可以促使模型调用工具,但仍然只能以同一用户的身份。 - 全局守卫也作用于代理函数调用。 认证正是这样到达它们的,这也正是该类跳过全部三个限流器定义的原因:全局
ThrottlerGuard读取的是工具调用并没有的 HTTP 请求,并且把所有用户的每次工具调用都算作同一个客户端。若不跳过,一分钟内跨所有用户累计 100 次工具调用后,每个工具都会以ThrottlerException: Too Many Requests失败。聊天路由改为按用户限制。 - 模型读到的是方法的返回值,以 JSON 形式。
view()略去了所有者的 id,模型用不上它。 create-note复用路由的 schema。 它拒绝的参数不会到达方法:模型会被告知哪里不对,可以再试。
AiModule 会找到应用每个模块中的代理函数,所以只需把 NotesTools 注册为 NotesModule 的提供者。
流式返回答案
ChatService 认领会话,把历史和新问题发给模型,并把答案作为流返回:
import { Injectable, Logger } from '@nestjs/common';
import { AiModelError, AiService } from '@nestjs/ai';
import type { ModelMessage } from 'ai';
import { NotesTools } from '../notes/notes.tools.js';
import { ANSWER_TIMEOUT_MS, ConversationsService } from './conversations.service.js';
const instructions =
"You are the assistant of a notes app. Answer from the user's notes: search them before you answer " +
'a question about them, and say so when nothing matches. Save a note only when the user asks you to. ' +
'Keep answers short.';
@Injectable()
export class ChatService {
private readonly logger = new Logger(ChatService.name);
constructor(
private readonly ai: AiService,
private readonly conversationsService: ConversationsService,
) {}
/** 把对 `text` 的答案作为 AI SDK 的 UI 消息流发出,并在完成后保存这一轮。 */
async answer(userId: string, conversationId: string, text: string, request: unknown): Promise<Response> {
await this.conversationsService.claim(userId, conversationId);
try {
return await this.stream(conversationId, text, request);
} catch (error) {
await this.conversationsService.release(conversationId);
throw error;
}
}
private async stream(conversationId: string, text: string, request: unknown): Promise<Response> {
const question: ModelMessage = { role: 'user', content: text };
const history = await this.conversationsService.history(conversationId);
const answer = this.ai.streamText({
label: 'chat',
instructions,
messages: [...history, question],
tools: [NotesTools],
// 代理函数以发出该请求的用户身份运行。
caller: { request },
abortSignal: AbortSignal.timeout(ANSWER_TIMEOUT_MS),
});
// 调用结束时,整轮都会被保存;失败或被取消时,一点都不保存。
const settled = answer.responseMessages
.then(
(added) => this.conversationsService.saveTurn(conversationId, [question, ...added]),
() => this.conversationsService.release(conversationId),
)
.catch((error: unknown) => this.logger.error(`Could not save the turn of ${conversationId}`, error));
const response = answer.toUIMessageStreamResponse({
errorText: (error) =>
error instanceof AiModelError ? 'The assistant is unavailable. Try again in a minute.' : 'Something went wrong.',
});
// 流在这一轮保存之后才结束,这样客户端的下一条消息能在历史中找到它。
const body = response.body!.pipeThrough(new TransformStream({ flush: () => settled }));
return new Response(body, response);
}
}streamText()启动调用并立即返回。tools把NotesTools的每个代理函数提供给模型,caller传入请求,代理函数正是借此知道用户是谁。abortSignal会结束超过ANSWER_TIMEOUT_MS的答案,含工具在内。正因如此,接管比它更旧的认领才是安全的。toUIMessageStreamResponse()把答案作为 Web 标准的Response返回,内容是服务器发送事件,采用 AI SDK 的 UI 消息流协议,并带x-accel-buffering: no响应头,告诉 nginx 不要缓冲它。若 15 秒没有数据块,比如某个工具正在工作,它会发送一条: keep-alive注释,使代理不会把连接当作空闲而关闭。- 调用结束时,这一轮会被保存,来源是
responseMessages。失败或被取消时,会话被释放,这一轮什么都不保留:浏览器仍显示着问题,可以再发一次。 - 流在这之后才结束。
TransformStream的flush()把流的结束拖到这一轮保存完成。没有它,流会在模型一写完就结束,比保存早一瞬,而立刻发送下一条消息的客户端可能收到 409,或得到一份没有最后一轮的历史。
处理器返回这个 Response,Nest 在模型撰写的同时把它发送出去(参见 流式响应)。浏览器离开时,Nest 会取消响应的 body。取消顺着 pipeThrough() 传到 streamText() 的流,取消它就会中止模型调用,以及任何正在运行的代理函数的 signal,所以没有人会为一个没人读的答案付费(参见 客户端断开)。
响应的状态码 200 在流开始时就会发出,所以失败的模型调用是通过流到达浏览器的:一个 error 块,文本由 errorText 给出。AiModelError 意味着每次尝试都失败了,原因可能是提供方宕机、过载持续到重试之后,或拒绝该 API 密钥,因此请用户稍后再试。其他任何错误,比如答案用尽了预算,得到的消息不会透露服务器的任何情况。AI 章节的 pipeUIMessageStreamToResponse() 改为等待第一个数据块,好让异常过滤器能用错误状态码回应早期的失败,但它自己结束了响应,因而没有地方在结束之前保存这一轮。
控制器:
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Req, UseGuards } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import type { NodeRequest } from '@nestjs/platform-node';
import { z } from 'zod';
import { ChatThrottlerGuard } from './chat-throttler.guard.js';
import {
createConversationSchema,
sendMessageSchema,
type CreateConversationDto,
type SendMessageDto,
} from './chat.schemas.js';
import { ChatService } from './chat.service.js';
import { ConversationsService } from './conversations.service.js';
const conversationId = { schema: z.uuid() };
@Controller('conversations')
export class ChatController {
constructor(
private readonly conversationsService: ConversationsService,
private readonly chatService: ChatService,
) {}
@Post()
create(@CurrentUser('id') userId: string, @Body({ schema: createConversationSchema }) dto: CreateConversationDto) {
return this.conversationsService.create(userId, dto.title);
}
@Get()
findAll(@CurrentUser('id') userId: string) {
return this.conversationsService.findAll(userId);
}
@Get(':id')
findOne(@CurrentUser('id') userId: string, @Param('id', conversationId) id: string) {
return this.conversationsService.findOne(userId, id);
}
@Delete(':id')
@HttpCode(204)
remove(@CurrentUser('id') userId: string, @Param('id', conversationId) id: string) {
return this.conversationsService.remove(userId, id);
}
// 以服务器发送事件流作答,Nest 在模型撰写的同时把它们发出。
@Post(':id/messages')
@UseGuards(ChatThrottlerGuard)
send(
@CurrentUser('id') userId: string,
@Param('id', conversationId) id: string,
@Body({ schema: sendMessageSchema }) { text }: SendMessageDto,
@Req() request: NodeRequest,
) {
return this.chatService.answer(userId, id, text, request);
}
}聊天模块注册控制器,以及保存会话、运行代理的服务:
import { Module } from '@nestjs/common';
import { ChatController } from './chat.controller.js';
import { ChatService } from './chat.service.js';
import { ConversationsService } from './conversations.service.js';
@Module({
controllers: [ChatController],
providers: [ConversationsService, ChatService],
})
export class ChatModule {}从处理器返回 Response 需要 @nestjs/core 12.4.0 或更高版本。它的状态码始终是 Response 自身的,所以这个 POST 路由回答 200 而不是 201,@HttpCode() 对它无效。
在浏览器中
@ai-sdk/react 的 useChat() 读取这个流的方式与读取 AI 章节的流一样(参见 流式发送到浏览器)。默认情况下它会发送整个会话。本服务器保存会话,所以给 useChat() 一个只发送新消息文本的 transport:
import { DefaultChatTransport } from 'ai';
const transport = new DefaultChatTransport({
api: `/conversations/${conversationId}/messages`,
headers: { Authorization: `Bearer ${accessToken}` },
// 服务器保存历史:只发送新消息的文本。
prepareSendMessagesRequest: ({ messages }) => ({
body: {
text: messages
.at(-1)!
.parts.filter((part) => part.type === 'text')
.map((part) => part.text)
.join(''),
},
}),
});答案作为一条消息到达,其 parts 包含它的文本,工具调用则是 tool-search-notes 部分,带各自的 input 和 output。要展示过去的会话,从 GET /conversations/:id 读取它。
限制每个用户
每条消息都要花掉模型调用,所以要限制每个用户发送多少。按 IP 地址的限制,就像登录路由上的那种,会让同一间办公室地址背后的所有人共享一份配额,并允许单个用户把它花光。AppModule 中的 chat 限流器定义 按用户计数,每小时 30 条消息,以用户的 id 作为追踪键。
全局 ThrottlerGuard 在认证守卫之前运行,这使它也能统计带着猜测令牌的请求,但也意味着它运行时用户还未知。所以它跳过 chat(其 skipIf 找不到用户),改由绑定在聊天路由上的一个守卫在认证之后计数:
import { Injectable } from '@nestjs/common';
import { ThrottlerGuard, type ThrottlerRequest } from '@nestjs/throttler';
/**
* 按已登录用户统计 `chat` 限制。绑定在聊天路由上,它在全局
* 守卫(含认证守卫)之后运行,所以用户已知;全局限流器守卫跳过
* `chat`(它在认证之前运行),而这个守卫不统计其他任何东西。
*/
@Injectable()
export class ChatThrottlerGuard extends ThrottlerGuard {
protected async handleRequest(requestProps: ThrottlerRequest): Promise<boolean> {
return requestProps.throttler.name === 'chat' ? super.handleRequest(requestProps) : true;
}
}路由上的 @UseGuards(ChatThrottlerGuard) 在全局守卫之后运行。这个守卫只统计 chat,因为全局守卫已经统计过其他定义。一小时内第 31 条消息会得到 429,其 Retry-After-chat 响应头是用户还可以再等多少秒才能发送,其他用户不受影响。
有上限和预算,这就限定了一个用户一小时能花掉多少:30 个答案,每个最多五次模型调用、每次最多 1,000 个输出 token,并且任何答案在用掉 60,000 个 token 后都不再启动模型调用。
限流器默认在内存中计数,所以每个 API 实例各自允许每小时 30 条消息。有多个实例时,请使用共享 存储。
试一试
在 .env 中设置 AI_MODEL=fake,启动应用。下面的答案来自假模型,工具调用是它脚本里设定的;其余一切都是应用本身的行为:
$ npm run start注册,并写几条笔记(此处及以下的令牌与响应体都做了缩短):
$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"...","expiresIn":900}
$ ADA="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ curl localhost:3000/notes -H "$ADA" --json '{"title":"Buy milk","body":"Oat milk, 2 litres"}'
$ curl localhost:3000/notes -H "$ADA" --json '{"title":"Dentist on Tuesday","body":"9:00, and ask about the milk teeth"}'
$ curl localhost:3000/notes -H "$ADA" --json '{"title":"Book club","body":"Finish chapter 3"}'开始一个会话,然后提问。-N 关闭 curl 的缓冲,所以事件在服务器发送时逐个出现:工具调用、工具返回的内容,然后是答案,一次一个词:
$ curl localhost:3000/conversations -H "$ADA" --json '{"title":"Errands"}'
{"id":"a399d467-1c20-4927-9361-365e90dee98a","ownerId":"861e2960-fd51-4e00-aa97-6fa35d805417","title":"Errands","answeringUntil":null,"createdAt":"2026-11-19T22:14:15.991Z","updatedAt":"2026-11-19T22:14:15.991Z"}
$ curl -N -i localhost:3000/conversations/a399d467-1c20-4927-9361-365e90dee98a/messages -H "$ADA" --json '{"text":"What did I write about milk?"}'
HTTP/1.1 200 OK
X-RateLimit-Limit-chat: 30
X-RateLimit-Remaining-chat: 29
content-type: text/event-stream; charset=utf-8
x-accel-buffering: no
x-vercel-ai-ui-message-stream: v1
data: {"type":"start"}
data: {"type":"start-step"}
data: {"type":"tool-input-available","toolCallId":"call-1","toolName":"search-notes","input":{"query":"milk"}}
data: {"type":"tool-output-available","toolCallId":"call-1","output":[{"id":"def5fe96-8183-4db4-aa7e-e37a6a95dcc0","title":"Dentist on Tuesday","body":"9:00, and ask about the milk teeth","updatedAt":"2026-11-19T22:14:15.960Z"},{"id":"9e1ac526-c3b4-46b1-8941-fef441506ddc","title":"Buy milk","body":"Oat milk, 2 litres","updatedAt":"2026-11-19T22:14:15.942Z"}]}
data: {"type":"finish-step"}
data: {"type":"start-step"}
data: {"type":"text-start","id":"text-0"}
data: {"type":"text-delta","id":"text-0","delta":"Your "}
data: {"type":"text-delta","id":"text-0","delta":"notes "}
data: {"type":"text-delta","id":"text-0","delta":"mention "}
...
data: {"type":"text-delta","id":"text-0","delta":"milk\"."}
data: {"type":"text-end","id":"text-0"}
data: {"type":"finish-step"}
data: {"type":"finish","finishReason":"stop"}
data: [DONE]搜索找到了标题或正文提到 milk 的两条笔记,漏掉了第三条。同一时刻发往一个会话的两条消息,这里由两个同时启动的 curl 命令发出,会得到一个答案和一个 409:
$ curl localhost:3000/conversations/a399d467-1c20-4927-9361-365e90dee98a/messages -H "$ADA" --json '{"text":"And the book club?"}'
{"message":"The assistant is still answering in this conversation","error":"Conflict","statusCode":409}每条得到回答的消息都保存为一轮:问题、工具调用、工具的结果和答案,按顺序:
$ curl localhost:3000/conversations/a399d467-1c20-4927-9361-365e90dee98a -H "$ADA"
{"id":"a399d467-...","title":"Errands","answeringUntil":null,...,"messages":[{"role":"user","content":"What did I write about milk?","createdAt":"2026-11-19T22:14:16.753Z"},{"role":"assistant","content":[{"type":"tool-call","input":{"query":"milk"},"toolName":"search-notes","toolCallId":"call-1"}],...},{"role":"tool","content":[{"type":"tool-result","output":{"type":"json","value":[...]},"toolName":"search-notes","toolCallId":"call-1"}],...},{"role":"assistant","content":[{"text":"Your notes mention it in \"Dentist on Tuesday\", \"Buy milk\".","type":"text"}],...},{"role":"user","content":"And the book club?",...},...]}另一个用户读取或向 Ada 的会话发送,都会得到 404:
$ BOB="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ curl localhost:3000/conversations/a399d467-1c20-4927-9361-365e90dee98a/messages -H "$BOB" --json '{"text":"Hi"}'
{"message":"Conversation not found","error":"Not Found","statusCode":404}一小时内发满 30 条消息后,Ada 的下一条会得到 429。删除会话会删除它的消息:
$ curl -i localhost:3000/conversations/a399d467-1c20-4927-9361-365e90dee98a/messages -H "$ADA" --json '{"text":"One more about milk?"}'
HTTP/1.1 429 Too Many Requests
Retry-After-chat: 3600
{"statusCode":429,"message":"ThrottlerException: Too Many Requests"}
$ curl -X DELETE localhost:3000/conversations/a399d467-1c20-4927-9361-365e90dee98a -H "$ADA"
$ curl localhost:3000/conversations/a399d467-1c20-4927-9361-365e90dee98a -H "$ADA"
{"message":"Conversation not found","error":"Not Found","statusCode":404}测试
端到端测试启动真实的 AppModule,用一个 FakeModel 替代配置的模型。@nestjs/ai/testing 的 overrideModels() 按名称替换它,并保留其定义的其余部分:maxOutputTokens、超时和重试(参见 在端到端测试中覆盖模型)。代理函数带着它们的守卫真实运行,通过连接池连到真实的 PostgreSQL 服务器,对会话的两次认领在那里真的会竞争。而且应用监听在一个端口上,因为测试要在答案流式到达时读取它,并在回答中途挂断,而一次性交回整个响应的 app.inject() 做不到这一点。
测试配置把 AI_MODEL 设为 fake,所以测试同样不需要 API 密钥:
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
root: './',
include: ['test/**/*.e2e-spec.ts'],
env: {
DATABASE_URL: 'postgres://unused-in-tests',
JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
// 测试会用假模型替换它:不需要 API 密钥。
AI_MODEL: 'fake',
},
},
});测试会注册用户、编写假模型的答案,并检查工具、流、中止、历史预算和各项限制:
import { fileURLToPath } from 'node:url';
import { PasswordHasher } from '@nestjs/authentication';
import { FakeModel, overrideModels, providerError } from '@nestjs/ai/testing';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { eq, sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { AppModule } from '../src/app.module.js';
import { conversations } from '../src/database/schema.js';
// 带连接池的真实 PostgreSQL,这样同时发来的两条消息真的会竞争。
const url = process.env.TEST_DATABASE_URL;
type Chunk = { type: string; [key: string]: any };
describe.skipIf(!url)('Chat API (e2e)', () => {
const db = drizzle({ client: new Pool({ connectionString: url, max: 10 }) });
const model = new FakeModel();
let app: NestNodeApplication;
let baseUrl: string;
beforeAll(async () => {
await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
await db.execute(sql`TRUNCATE users, refresh_tokens CASCADE`);
const moduleRef = await overrideModels(Test.createTestingModule({ imports: [AppModule] }), { default: model })
.overrideProvider(getDrizzleToken())
.useValue(db)
// 默认成本的 scrypt 每次哈希要 128 MiB 和几百毫秒。
.overrideProvider(PasswordHasher)
.useValue(new PasswordHasher({ logN: 10 }))
.compile();
app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
// 真实的服务器:测试逐块读取答案,并在回答中途挂断。
await app.listen(0);
baseUrl = await app.getUrl();
});
afterAll(() => app.close()); // 也会关闭连接池
let clients = 0;
/** 注册一个用户,附一条笔记,并返回以该用户身份认证的请求头。 */
async function signUp(email: string, note = { title: 'Buy milk', body: 'Oat milk, 2 litres' }) {
const res = await app.inject({
method: 'POST',
url: '/auth/sign-up',
payload: { email, password: 'correct horse battery' },
// 注册按 IP 地址限流:每个用户从自己的地址注册。
remoteAddress: `10.0.0.${++clients}`,
});
const headers = { authorization: `Bearer ${res.json<{ accessToken: string }>().accessToken}` };
const created = await app.inject({ method: 'POST', url: '/notes', headers, payload: note });
return { headers, noteId: created.json<{ id: string }>().id };
}
async function startConversation(headers: Record<string, string>) {
const res = await app.inject({ method: 'POST', url: '/conversations', headers, payload: {} });
return res.json<{ id: string }>().id;
}
function send(headers: Record<string, string>, conversationId: string, text: string, signal?: AbortSignal) {
return fetch(`${baseUrl}/conversations/${conversationId}/messages`, {
method: 'POST',
headers: { ...headers, 'content-type': 'application/json' },
body: JSON.stringify({ text }),
signal,
});
}
/** 响应中的服务器发送事件,作为 UI 消息块,到达时即读取。 */
async function* events(response: Response): AsyncGenerator<Chunk> {
const decoder = new TextDecoder();
let buffer = '';
for await (const bytes of response.body!) {
buffer += decoder.decode(bytes, { stream: true });
let end: number;
while ((end = buffer.indexOf('\n\n')) !== -1) {
const event = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
if (event.startsWith('data: {')) {
yield JSON.parse(event.slice('data: '.length));
}
}
}
}
async function readAll(response: Response) {
const chunks: Chunk[] = [];
for await (const chunk of events(response)) {
chunks.push(chunk);
}
return chunks;
}
const textOf = (chunks: Chunk[]) =>
chunks
.filter((chunk) => chunk.type === 'text-delta')
.map((chunk) => chunk.delta)
.join('');
it("answers from the user's own notes, and saves the turn", async () => {
const ada = await signUp('ada@example.com');
await signUp('bob@example.com', { title: 'Milk for the cat', body: "Bob's note" });
const conversationId = await startConversation(ada.headers);
model.reply({ toolCalls: [{ name: 'search-notes', input: { query: 'milk' } }] }, (call) => {
const notes = call.toolResults[0].output as Array<{ title: string }>;
return `You have ${notes.length} note: ${notes[0].title}.`;
});
const response = await send(ada.headers, conversationId, 'What did I write about milk?');
expect(response.status).toBe(200);
expect(response.headers.get('content-type')).toContain('text/event-stream');
const chunks = await readAll(response);
// Bob 的笔记也匹配,但工具从未看到它。
const output = chunks.find((chunk) => chunk.type === 'tool-output-available')?.output;
expect(output).toEqual([expect.objectContaining({ title: 'Buy milk' })]);
expect(textOf(chunks)).toBe('You have 1 note: Buy milk.');
expect(model.lastCall?.options.maxOutputTokens).toBe(1000);
// 流在这一轮保存后才结束:立刻发出的消息能拿到历史。
model.reply('Anything else?');
const next = await send(ada.headers, conversationId, 'Thanks!');
expect(next.status).toBe(200);
await readAll(next);
expect(model.lastCall?.options.prompt.map((message) => message.role)).toEqual([
'system',
'user',
'assistant',
'tool',
'assistant',
'user',
]);
});
it('runs the tools as the signed-in user only', async () => {
const carol = await signUp('carol@example.com');
const dave = await signUp('dave@example.com', { title: "Dave's diary", body: 'Private' });
const conversationId = await startConversation(carol.headers);
model.reply(
{ toolCalls: [{ name: 'read-note', input: { noteId: dave.noteId } }] },
{ toolCalls: [{ name: 'create-note', input: { title: 'Call mum' } }] },
'Saved.',
);
await readAll(await send(carol.headers, conversationId, `Read note ${dave.noteId}, then remind me to call mum`));
// Dave 的笔记和不存在的一样找不到。
expect(model.calls.at(-2)?.toolResults).toEqual([
expect.objectContaining({ toolName: 'read-note', output: 'Note not found' }),
]);
const notes = await app.inject({ method: 'GET', url: '/notes', headers: carol.headers });
expect(notes.json().map((note: { title: string }) => note.title)).toEqual(['Call mum', 'Buy milk']);
});
it('streams the answer as the model writes it', async () => {
const { headers } = await signUp('erin@example.com');
const conversationId = await startConversation(headers);
model.reply({ text: 'One two three four five', chunkDelay: 100 });
const arrivals: number[] = [];
for await (const chunk of events(await send(headers, conversationId, 'Count to five'))) {
if (chunk.type === 'text-delta') {
arrivals.push(performance.now());
}
}
expect(arrivals).toHaveLength(5);
// 每个词各自到达,比前一个晚约 100 毫秒。
expect(arrivals[4] - arrivals[0]).toBeGreaterThan(300);
});
it('aborts the model call when the client goes away', async () => {
const { headers } = await signUp('frank@example.com');
const conversationId = await startConversation(headers);
model.reply({ text: 'A long answer that nobody reads to its end', chunkDelay: 200 });
const client = new AbortController();
const response = await send(headers, conversationId, 'Tell me a long story', client.signal);
for await (const chunk of events(response)) {
if (chunk.type === 'text-delta') {
break;
}
}
client.abort(); // 浏览器标签页关闭
await vi.waitFor(() => expect(model.lastCall?.options.abortSignal?.aborted).toBe(true));
// 这一轮什么都没保留,会话接受下一条消息。
await vi.waitFor(async () => {
const saved = await app.inject({ method: 'GET', url: `/conversations/${conversationId}`, headers });
expect(saved.json()).toMatchObject({ answeringUntil: null, messages: [] });
});
model.reply('Here is a shorter one.');
const next = await send(headers, conversationId, 'A shorter one, then');
expect(textOf(await readAll(next))).toBe('Here is a shorter one.');
});
it('answers one message at a time per conversation', async () => {
const { headers } = await signUp('grace@example.com');
const conversationId = await startConversation(headers);
// 一个答案:只有一条消息会到达模型。
model.reply({ text: 'First', delay: 200 });
// 先打开连接池的连接,这样没有请求需要等待:它们全部竞争。
await Promise.all(Array.from({ length: 10 }, () => db.execute(sql`select pg_sleep(0.05)`)));
const responses = await Promise.all(
Array.from({ length: 10 }, () =>
app.inject({ method: 'POST', url: `/conversations/${conversationId}/messages`, headers, payload: { text: 'Hi' } }),
),
);
expect(responses.map((res) => res.statusCode).sort()).toEqual([200, ...Array(9).fill(409)]);
// 死掉的进程留下且已过期的认领,会被接管。
await db
.update(conversations)
.set({ answeringUntil: new Date(Date.now() - 1_000) })
.where(eq(conversations.id, conversationId));
model.reply('Back.');
expect(textOf(await readAll(await send(headers, conversationId, 'Still there?')))).toBe('Back.');
});
it('sends the model the latest history that fits the budget, from a question', async () => {
// 每次搜索都返回这条笔记:每轮约 2,500 个 token。
const { headers } = await signUp('heidi@example.com', { title: 'Long', body: 'x'.repeat(10_000) });
const conversationId = await startConversation(headers);
for (let turn = 1; turn <= 4; turn++) {
model.reply({ toolCalls: [{ name: 'search-notes', input: { query: 'long' } }] }, 'Found it.');
await readAll(await send(headers, conversationId, `Question ${turn}`));
}
model.reply('Done.');
await readAll(await send(headers, conversationId, 'Question 5'));
const prompt = model.lastCall!.options.prompt;
// 第一轮装不下,历史从一个问题开始,绝不以工具结果开始。
expect(prompt[1].role).toBe('user');
const questions = prompt.filter((message) => message.role === 'user').map((message) => message.content);
expect(JSON.stringify(questions)).not.toContain('Question 1');
expect(JSON.stringify(questions)).toContain('Question 2');
});
it('retries an overloaded provider, and tells the user when it fails', async () => {
const { headers } = await signUp('ivan@example.com');
const conversationId = await startConversation(headers);
const unavailable = { type: 'error', errorText: 'The assistant is unavailable. Try again in a minute.' };
// 先过载,然后作答:会重试。
model.reply(providerError(529), 'Back again.');
expect(textOf(await readAll(await send(headers, conversationId, 'Hello?')))).toBe('Back again.');
// 被吊销的 API 密钥:不重试,流中会说明。
model.reply(providerError(401, { message: 'Invalid API key' }));
const refused = await send(headers, conversationId, 'Are you there?');
expect(refused.status).toBe(200);
expect(await readAll(refused)).toContainEqual(unavailable);
// 说完开头几个词后中断的流,以同样的错误结束。
model.reply({ text: 'Your notes say', streamError: providerError(500) });
const broken = await readAll(await send(headers, conversationId, 'What do my notes say?'));
expect(textOf(broken)).toBe('Your notes say');
expect(broken.at(-1)).toEqual(unavailable);
// 只保留得到回答的那一轮。
const saved = await app.inject({ method: 'GET', url: `/conversations/${conversationId}`, headers });
expect(saved.json()).toMatchObject({ answeringUntil: null });
expect(saved.json().messages).toHaveLength(2);
});
it('limits how many messages each user sends', async () => {
const { headers } = await signUp('ken@example.com');
const conversationId = await startConversation(headers);
model.reply(...Array.from({ length: 30 }, () => 'OK.'));
for (let i = 0; i < 30; i++) {
await readAll(await send(headers, conversationId, `Message ${i}`));
}
const limited = await send(headers, conversationId, 'One more');
expect(limited.status).toBe(429);
expect(limited.headers.get('retry-after-chat')).toBeTruthy();
// 另一个用户不受 Ken 消息的影响。
const other = await signUp('lena@example.com');
model.reply('Hi Lena.');
expect((await send(other.headers, await startConversation(other.headers), 'Hi')).status).toBe(200);
});
});- 一个
FakeModel服务于所有测试,各测试用reply()把它需要的答案排入队列。某个测试若留下未使用的答案,会交给下一个测试,所以竞争测试只排一个答案:它十条消息中只有一条到达模型。 - 竞争测试先打开连接池的连接。 否则第一个请求拿到连接池已打开的连接,其余的去等新连接,它在它们到达之前就认领了会话。随后它把认领的时间往回调,就像死掉的进程会留下的那样,下一条消息便会接管。
model.lastCall是发给模型的内容:options.prompt是历史和问题,即提供方会收到的样子;options.maxOutputTokens是上限。工具失败则出现在下一次调用的toolResults中,即模型读到的样子。providerError()是提供方包针对某个 HTTP 状态抛出的错误(参见 重试、超时与回退)。401 不会重试,529 会重试,退避最长一秒,所以测试会等那么久。
让它们跑在自己的数据库上,一个文件接一个文件地跑,因为两者都会清空表:
$ docker exec assistant-db psql -U postgres -c "CREATE DATABASE assistant_test"
$ TEST_DATABASE_URL=postgres://postgres:assistant@localhost:5432/assistant_test npm run test:e2e -- --no-file-parallelism
Test Files 2 passed (2)
Tests 13 passed (13)把 claim() 中带条件的 UPDATE 换成读、在 JavaScript 中检查、再写入,“每个会话一次只回答一条消息”就会失败:十条消息里有五六条绕过认领。给 pipeThrough() 传 preventCancel: true,让取消停在包装层,“客户端离开时中止模型调用”就会失败:模型调用永远不会被中止。
生产环境清单
JWT 教程 清单 中的一切都适用。针对这个助手,尤其要注意:
- 把
ANTHROPIC_API_KEY放在平台的密钥存储里,在运行时注入,并把NODE_ENV设为production,后者会拒绝假模型。 - 让流通过。 API 前面的代理或负载均衡器必须把
text/event-stream响应随到随传,并在一个答案所需的整个期间保持连接打开。x-accel-buffering头覆盖 nginx,keep-alive 注释覆盖 15 秒及以上的空闲超时。不要在聊天路由上挂 压缩 中间件:它会缓冲。 - 共享限流器的存储,一旦你运行不止一个实例,否则每个实例都允许每个用户每小时 30 条消息。
- 计量每个用户的花费。 给模型设置它的
pricing,并用调用的onUsage按用户记录每次调用的用量事件(参见 用量、成本与预算)。 - 决定会话保存多久。 一轮会保留其工具返回的内容,所以被删除的笔记会留在读过它的会话里,直到那些会话也被删除。删除超过保留期的会话,以及在用户要求时删除。
- 把工具限制在用户本来就能做的事情上。 笔记里的文本,无论是用户写的还是从别处粘贴的,都会到达模型并可能操纵它。工具以用户的身份运行,所以它最坏也只能做用户能做的事。不要提供会销毁数据的工具,或者让它们等待人的批准,如同 持久化的代理运行 所做的那样。
- 给生产环境单独一对 Observe 密钥,取自项目的 API Keys 页面,作为
OBSERVE_APP_KEY和OBSERVE_APP_SECRET放进平台的环境变量:start:prod不加载.env。NestJS Observe 随后会在请求跟踪中的出站 span 上记录对模型提供方的每次调用,包含模型、输入、输出和缓存的 token,对流式调用还记录到第一个事件的时间;提示词和答案从不发送给 Observe(参见 模型调用)。生产规则 可以限制一个请求发起多少次模型调用。
接下来
- 按含义而非仅按字面查找笔记:嵌入。
- 把同样的工具提供给 MCP 客户端,比如桌面助手:同时服务 MCP 客户端。
- 让代理跨重启地等待人的批准:持久化的代理运行。
- 单独测试代理函数,以及结构化输出:测试。
- 在生产中查看每个请求的模型调用:可观测性。