如何将模型推理结果(如情感分数)作为 API 响应的一部分返回?

解读

在国内一线/二线互联网公司的后端面试中,这道题表面问“怎么把模型结果塞到接口里”,实则考察三层能力:

  1. 对 NestJS 请求-响应生命周期的完整掌握(Guard、Interceptor、Pipe、ExceptionFilter、Controller、Service、Repository)。
  2. 对“模型推理”这一耗时、易错、资源敏感任务的工程化封装(同步/异步、缓存、降级、超时、线程池、GPU 资源隔离)。
  3. 对高并发场景下“稳定性”与“可观测性”的落地经验(熔断、限流、Prometheus 指标、链路追踪、灰度发布)。
    如果仅回答“在 Service 里调一下模型然后 return”,只能拿到 30 分;只有把“模型”当成外部不稳定依赖,给出可灰度、可回滚、可观测的完整方案,才能拿到 90+。

知识点

  1. NestJS 依赖注入与分层:Controller → Service → InferenceAdapter(自定义 Provider,可切换本地 onnx / TensorFlow Serving / 阿里云 PAI-EAS)。
  2. 异步任务选型:
    • 同步:CPU 密集场景用 Node 18 的 worker_threads,避免阻塞事件循环。
    • 异步:推理耗时 >200 ms 走 Bull 队列 + Redis,消费进程可部署在 GPU 节点,通过 GRPC 回写结果。
  3. 缓存策略:
    • 请求级缓存:同一文本 5 min 内不复用,用 LRU 内存缓存(nestjs-cache-manager)。
    • 热点缓存:夜间离线批量推理结果写 MySQL + 索引,白天直接查表。
  4. 超时与熔断:
    • 方法级:axios-retry + 500 ms 超时,3 次失败后熔断 30 s(hystrix 模式)。
    • 服务级:阿里云 MSE 或腾讯云 TSF 配置基于 QPS 的熔断。
  5. 可观测:
    • 自定义 Counter:inference_total、inference_error、inference_duration。
    • 链路:@opentelemetry/instrumentation-nestjs 自动注入 TraceId,方便定位慢推理。
  6. 数据契约:
    • 响应 DTO 继承 BaseResponse,情感分数字段用 @ApiProperty({ example: 0.87, description: '情感极性,区间 [-1,1]' }) 生成 Swagger。
    • 出错时返回 206 Partial Content,主流程数据仍返回,情感字段为 null,前端可降级展示。
  7. 安全合规:
    • 文本先脱敏(正则剔除手机号、身份证),再送模型,满足《个人信息保护法》。
    • 模型文件存储在私有 OSS,通过 VPC 内网拉取,避免公网泄露。

答案

下面给出可直接落地的“生产级”代码骨架,演示如何把“情感分数”优雅地嵌入接口返回,同时兼顾高可用与可观测。

  1. 定义模型推理端口(防腐层)
// src/inference/sentiment.interface.ts
export interface SentimentResult {
  score: number;      // [-1, 1]
  label: 'positive' | 'negative' | 'neutral';
}

export abstract class SentimentInference {
  abstract predict(text: string): Promise<SentimentResult>;
}
  1. 实现本地 Worker 线程推理(CPU 密集隔离)
// src/inference/worker-inference.service.ts
import { Worker } from 'worker_threads';
import { join } from 'path';
import { promisify } from 'util';

export class WorkerInferenceService extends SentimentInference {
  async predict(text: string): Promise<SentimentResult> {
    return new Promise((resolve, reject) => {
      const worker = new Worker(join(__dirname, 'sentiment.worker.js'), {
        workerData: { text },
      });
      worker.once('message', resolve);
      worker.once('error', reject);
      // 500 ms 超时
      setTimeout(() => {
        worker.terminate();
        reject(new Error('Inference timeout'));
      }, 500);
    });
  }
}
  1. Service 层聚合缓存与熔断
// src/article/article.service.ts
import { Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';
import { InjectCache } from '@nestjs/cache-manager';
import { CircuitBreaker } from 'opossum';
import { SentimentInference } from '../inference/sentiment.interface';

@Injectable()
export class ArticleService {
  private breaker: CircuitBreaker;

  constructor(
    @InjectCache() private cache: Cache,
    // 通过 Provider 切换实现
    private readonly inference: SentimentInference,
  ) {
    this.breaker = new CircuitBreaker(
      (text: string) => this.inference.predict(text),
      {
        timeout: 500,
        errorThresholdPercentage: 50,
        resetTimeout: 30000,
      },
    );
  }

  async findOne(id: number) {
    const article = await this.getArticleFromDb(id);
    // 缓存 key 示例:sentiment:md5(text)
    const key = `sentiment:${this.hash(article.content)}`;
    let sentiment = await this.cache.get<SentimentResult>(key);
    if (!sentiment) {
      try {
        sentiment = await this.breaker.fire(article.content);
        await this.cache.set(key, sentiment, 300); // 5 min
      } catch (e) {
        // 熔断或超时,返回中性兜底
        sentiment = { score: 0, label: 'neutral' };
      }
    }
    return { ...article, sentiment };
  }
}
  1. Controller 与 DTO
// src/article/article.dto.ts
import { ApiProperty } from '@nestjs/swagger';
export class ArticleResponseDto {
  id: number;
  title: string;
  content: string;
  @ApiProperty({ example: 0.87 })
  sentimentScore: number;
}

// src/article/article.controller.ts
@Get(':id')
async findOne(@Param('id', ParseIntPipe) id: number) {
  const data = await this.articleService.findOne(id);
  // 自动序列化,无需手动拷贝
  return plainToInstance(ArticleResponseDto, data);
}
  1. Provider 注册(可运行时切换)
// src/inference/inference.module.ts
@Module({
  providers: [
    {
      provide: SentimentInference,
      useClass:
        process.env.INFERENCE_MODE === 'remote'
          ? RemoteInferenceService // 走 TensorFlow Serving
          : WorkerInferenceService,
    },
  ],
  exports: [SentimentInference],
})
export class InferenceModule {}
  1. 指标暴露
// src/metrics/metrics.service.ts
import { PrometheusHistogram } from '@willsoto/nestjs-prometheus';

@Injectable()
export class InferenceMetrics {
  constructor(
    @InjectMetric('inference_duration_seconds')
    private readonly h: PrometheusHistogram,
  ) {}

  record(duration: number, status: 'success' | 'error') {
    this.h.labels(status).observe(duration);
  }
}

在 Service 里调用 this.metrics.record(time, 'success'),即可在 Grafana 实时看板看到 P99 曲线。

通过上述 6 步,模型推理结果作为字段无缝嵌入 API 响应,同时具备缓存、熔断、超时、灰度、监控、脱敏等生产特性,可直接应对国内互联网高并发场景。

拓展思考

  1. 如果模型升级为多模态(文本+图片),如何复用现有链路?
    思路:把 Inference 端口泛化为 MultiModalInference<Input, Output>,Input 增加媒体类型字段;Worker 线程内调用 Python 子进程(torch 环境),通过 IPC 返回结果,其余缓存、熔断逻辑零改动。

  2. 离线批量推理与实时请求合并,如何防止“缓存穿透”?
    夜间 Spark 任务把结果写 MySQL 并同步到 Redis 布隆过滤器;白天请求先查布隆,不存在则直接返回“预测中”占位,并发送 MQ 延迟消息触发异步推理,避免瞬间打爆 GPU 节点。

  3. 国内监管要求“算法备案”,如何快速回滚模型?
    在 Provider 层增加“版本路由”:请求头带 X-Model-Version=v1.2,Provider 根据版本号映射到不同模型文件;若线上 v1.2 出现舆情,5 秒内切换回 v1.1,无需重新发版。