如何在 NestJS 中使用 axios 或 fetch 调用 OpenAI 的 ChatCompletion API?
解读
面试官问这道题,并不是单纯想听你“调个接口”,而是考察你对 NestJS 三层架构(Controller → Service → Provider)的理解深度、对依赖注入的熟练度、对配置安全与可测试性的重视程度,以及对国内网络环境(需科学上网或代理)的应对经验。回答时要把“企业级”三个字体现出来:配置分层、异常统一、日志追踪、重试熔断、单元测试、可灰度、可回滚。
知识点
- 配置中心:@nestjs/config + 自定义 Configuration,区分 local、prod、灰度环境,敏感信息(OPENAI_API_KEY)走环境变量,禁止硬编码。
- 依赖注入:将 Http 请求封装成可替换的 Provider(OpenAIChatApiService),方便单测 mock。
- 网络层选型:
- axios:国内使用最广泛,支持拦截器、取消、重试,配合 axios-retry 做指数退避。
- fetch:Node 18 内置,轻量但缺重试、超时、代理能力,需自封装或加 undici。
- 国内代理:若公司出口走统一代理网关,需在 axios 实例里加 httpsAgent;若用云函数(阿里云 FC、腾讯云 SCF),需配置 VPC NAT 或函数内代理。
- 异常映射:OpenAI 返回 429/500/503 要转成业务异常(TooManyRequestsException、OpenAIUnavailableException),由 @nestjs/common 的 ExceptionFilter 统一转 JSON,前端可识别。
- 日志与链路:使用 NestJS 内置 Logger + cls-hooked/traceId,在拦截器里把 chatCompletion 的耗时、token 用量、choices 长度打到日志,方便告警。
- 单元测试:@nestjs/testing 的 Test.createTestingModule,把 HttpModule 换成 axios-mock-adapter,断言 header 里是否带 Authorization: Bearer ${key}。
- 流式输出:若业务需要 SSE,OpenAI 支持 stream: true,用 axios 的 onDownloadProgress 或 fetch 的 ReadableStream,再转发到前端 EventSource,注意背压与连接泄露。
- 费用控制:后端先估算 prompt token(tiktoken 库),超过预算直接拒绝,避免“天价账单”。
- 灰度与回滚:配置中心动态开关 model 版本(gpt-3.5-turbo 与 gpt-4),出问题秒级回滚。
答案
下面给出可直接落地的最小可运行(但生产级)代码,全部用 TypeScript,兼容 Node 18,默认走 axios,已考虑国内代理、重试、异常映射、单测 mock。
- 安装依赖
pnpm add @nestjs/config axios axios-retry tiktoken
pnpm add -D @types/axios axios-mock-adapter
- 配置层 src/config/configuration.ts
export default () => ({
openai: {
apiKey: process.env.OPENAI_API_KEY, // 必填
baseURL: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1',
maxRetries: Number(process.env.OPENAI_MAX_RETRIES || 3),
timeout: Number(process.env.OPENAI_TIMEOUT || 15000),
// 若公司出口代理
proxy: process.env.HTTPS_PROXY || undefined,
},
});
- OpenAI 模块 src/openai/openai.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { HttpModule } from '@nestjs/axios';
import { OpenAIChatApiService } from './openai-chat-api.service';
@Module({
imports: [
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (cs: ConfigService) => {
const httpsProxy = cs.get<string>('openai.proxy');
return {
timeout: cs.get<number>('openai.timeout'),
maxRedirects: 5,
// 代理配置
...(httpsProxy && {
httpsAgent: require('https-proxy-agent')(httpsProxy),
}),
};
},
}),
],
providers: [OpenAIChatApiService],
exports: [OpenAIChatApiService],
})
export class OpenAIModule {}
- 核心服务 src/openai/openai-chat-api.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
import axiosRetry from 'axios-retry';
import { TooManyRequestsException, OpenAIUnavailableException } from '../common/exceptions';
@Injectable()
export class OpenAIChatApiService {
private readonly logger = new Logger(OpenAIChatApiService.name);
private readonly apiKey: string;
private readonly baseURL: string;
private readonly maxRetries: number;
constructor(
private readonly http: HttpService,
private readonly config: ConfigService,
) {
this.apiKey = this.config.get<string>('openai.apiKey');
this.baseURL = this.config.get<string>('openai.baseURL');
this.maxRetries = this.config.get<number>('openai.maxRetries');
axiosRetry(this.http.axiosRef, {
retries: this.maxRetries,
retryDelay: axiosRetry.exponentialDelay,
retryCondition: (err) => {
const status = err.response?.status;
return status === 429 || status >= 500;
},
});
}
async createChatCompletion(messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>) {
const url = `${this.baseURL}/chat/completions`;
const payload = {
model: 'gpt-3.5-turbo',
messages,
temperature: 0.7,
};
try {
const { data } = await firstValueFrom(
this.http.post(url, payload, {
headers: {
Authorization: `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
}),
);
return data.choices[0].message.content;
} catch (err: any) {
const status = err.response?.status;
if (status === 429) throw new TooManyRequestsException();
if (status >= 500) throw new OpenAIUnavailableException();
throw err;
}
}
}
- 业务 Service 注入
@Injectable()
export class ChatService {
constructor(private readonly openai: OpenAIChatApiService) {}
async ask(prompt: string) {
return this.openai.createChatCompletion([{ role: 'user', content: prompt }]);
}
}
- 单元测试
describe('OpenAIChatApiService', () => {
let service: OpenAIChatApiService;
let httpMock: MockAdapter;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [OpenAIModule],
}).compile();
service = module.get<OpenAIChatApiService>(OpenAIChatApiService);
httpMock = new MockAdapter(service['http'].axiosRef);
});
it('should return content on 200', async () => {
httpMock.onPost('/chat/completions').reply(200, {
choices: [{ message: { content: 'hello' } }],
});
const res = await service.createChatCompletion([{ role: 'user', content: 'hi' }]);
expect(res).toBe('hello');
});
});
- 启动入口 main.ts 正常 bootstrap 即可,无需额外改动。
拓展思考
- 流式输出:若业务需要“打字机”效果,把 createChatCompletion 入参加 stream: true,返回 Observable<string>,用 map + switchMap 逐块推给前端 EventSource;同时要在拦截器里统计首 token 时间(TTFT),作为核心 SLA 指标。
- 多模型路由:根据 prompt 长度、用户会员等级、灰度标签,动态选择 gpt-3.5-turbo 或 gpt-4,配置中心实时下发权重,实现“零重启”切换。
- 费用治理:接入公司统一计费平台,每次请求后把 prompt_tokens、completion_tokens、total_cost 写入 MQ,财务系统次日对账;超过预算自动降配额并给飞书告警。
- 缓存与相似度:对高频重复问题,先用向量数据库(Milvus/PGVector)做语义检索,命中缓存直接返回,可节省 60%+ token。
- 合规审计:国内上线需通过网信办算法备案,对话内容落盘到加密 OSS,保留 90 天,支持关键字审核与人工复核。