96SEO 2026-12-02 18:45 0
痛点背景: 在实际开发中,AI 调用若直接在前端进行会导致 API Key 泄露、业务逻辑混乱还有无法进行历史存储、审计与计费等主要功能。不能不将 AI 能力搬至服务端并进行封装与抽象。
上一篇文章我们聊了通过 mock 文件在 Vite 开发服务器里转发 DeepSeek 请求。但那只是开发阶段的权宜之计。真正上线时AI 调用必须放在后端,原因很直接:

→ 痛点我们在 NestJS 后端引入 LangFrame 架构封装了 AI 对话能力;框架在这里扮演“万能插座”角色——今天接 DeepSeek 若明天换 OpenAI 或 Claude 業務代碼零改动。
下面展示本章相关代码目录结构:→
-backend/posts/src/ai/
├── ai.module.ts # NestJS 模块注册&
├── ai.controller.ts # 路由 + SSE 响应头 + 帧格式转换&
├── ai.service.ts # LangChain 调用主要原因&
└── dto/
└── chat.dto.ts # 参数校验 DTO
→
→ 数据流向概览这方面,
\| SSE 流返回\|浏览器 ← Controller ← Service←┘\|\|-----------||--------------------------------------||---------------------------||------------------------------\|\| \|\|\|\|\|----------------------||-------------------------------||-------------------------------||---------------------------\|\|前\/post 数据 \| \| 参数检验 \| \| \u001b;其实,}\uFEFF/class \uFEFF/class \uFEFF/class \uFEFF/class \uFEFF/class \uFEFF/class \uFEFF/class
→
Pain-point note:
The combination of class-valiator &。translates request objects into strict validated structures before any business logic executes.
Pain-point highlights:
Pain-point notes:
Core rationale explained above repeated here briefly front SDK messages differ internal representation behind scenes forcing conversion step essential orwise model receives malformed prompts silently dropping context em }
{| ts} async chat=>void){ const lcMessages=convertToLcMessages;const stream=await this.chatModel.stream;for await{ const content=chunk.content as string;if{onToken,}} }
Pain-point clarifications below flowing explanation elaboartes stepwise reasons behind choice design decisions core reasons chosen patterns adopted strongly strongly strongly strongly strongly strongly strongly strongly strongly strongly strongly strongly strongly -- reasons bullet list condensed reason bullets:- *** not simply return array would block until all tokens gared defeating streaming purpose immediate push required reason callbacks decouple consumption who decides what happens token downstream controller wants pipe to browser store redis ws whatever service stays blissfully ignorant emphasis separation concerns good design.- *** await stream even returns async iterable rar than promise because internally sdk sets up http request lazily only upon first iteration awaiting ensures iterator ready before loop entry important nuance.- *** for await loop works this js async iteration yields chunks incrementally deepseek emits token-by-token response each iteration suspends yields control back event loop allowing or requests processed meanwhile pure non-blocking advantage node async model offers.- *** callback instead return control flow immediate push token out without buffering entire response eliminates memory pressure latency reduction service never cares downstream consumer usage enabling flexible reuse cases res.write webSocket broadcast redis pubsub etc emphasis loose coupling high value architectural benefit./ul}oltems}/td{/tr}/ad}.
{
``ts@Controller}
export AiController{
constructor{}
@Post
async chatchatDto ChatDto,@Resres){
res.setHeader;res.setHeader;res.setHeader;try{
await this.aiService.chat=>{res.write}`);}),话说回来,res.end;}catch{res.status.end;}}
},
Pain-point rationales listed next triple bullet points beneath header bullet summarizing three critical response-header settings communicated below:- Content-Type tells browser flow is event-stream rar plain http response although using ai-sdk-data-stream format same effect semantics wise clearer.- Cache-Control no-cache prevents browser edge caches storing partial stale responses every reply differs caching meaningless leads users see outdated messges.- Connection keep-alive maintain tcp connection alive streaming dialogue may last seconds even dozens seconds if mid-way disconnect all prior effort lost waste.em /bullet-list}
{| summary '' scope "" cols "" rows "" scope "" name ""!怎么说呢,scope "" mock/chat.js!其实,scope "" ai.service.ts "" scope!environment,!Vite 开发服务器,!NestJS 生产服务器 "" scope!invocation方式!,原生 fetch!,LangChat ChatDeepSeek "" scope!message-format-conversion!,不需要!,convertToLcMessages 函数转换 "" scope!stream-consumption-mode!,response.body.getReader! ,for await "" scope! conversion-location!,mock内部?,Controller 层可测试性!,Service可单独单元测试模型切换成本改 fetch URL + body 改一行 import ""
{enumerate}项强langchain 做抽象层chatDeepSeek 屏蔽 api细节stream返回异步迭代让消费 token 僟遍历数组自然理由二回调做解耦service只管取到token就传出去controller只管收写响应各职责清晰理由三forawaitof 做流消费不需手动管理buffer半行解码脏活langchain内部已做好仅需循环处理每个干净token enumerate}.
{painpoint recap summary}The entire approach exists specifically because direct frontend calls expose secrets force model-coupling prevent essential backend services like persistence billing audit..
原著版权归所有者所有未经允许勿转载全篇完结
作为专业的SEO优化服务提供商,我们致力于通过科学、系统的搜索引擎优化策略,帮助企业在百度、Google等搜索引擎中获得更高的排名和流量。我们的服务涵盖网站结构优化、内容优化、技术SEO和链接建设等多个维度。
| 服务项目 | 基础套餐 | 标准套餐 | 高级定制 |
|---|---|---|---|
| 关键词优化数量 | 10-20个核心词 | 30-50个核心词+长尾词 | 80-150个全方位覆盖 |
| 内容优化 | 基础页面优化 | 全站内容优化+每月5篇原创 | 个性化内容策略+每月15篇原创 |
| 技术SEO | 基本技术检查 | 全面技术优化+移动适配 | 深度技术重构+性能优化 |
| 外链建设 | 每月5-10条 | 每月20-30条高质量外链 | 每月50+条多渠道外链 |
| 数据报告 | 月度基础报告 | 双周详细报告+分析 | 每周深度报告+策略调整 |
| 效果保障 | 3-6个月见效 | 2-4个月见效 | 1-3个月快速见效 |
我们的SEO优化服务遵循科学严谨的流程,确保每一步都基于数据分析和行业最佳实践:
全面检测网站技术问题、内容质量、竞争对手情况,制定个性化优化方案。
基于用户搜索意图和商业目标,制定全面的关键词矩阵和布局策略。
解决网站技术问题,优化网站结构,提升页面速度和移动端体验。
创作高质量原创内容,优化现有页面,建立内容更新机制。
获取高质量外部链接,建立品牌在线影响力,提升网站权威度。
持续监控排名、流量和转化数据,根据效果调整优化策略。
基于我们服务的客户数据统计,平均优化效果如下:
我们坚信,真正的SEO优化不仅仅是追求排名,而是通过提供优质内容、优化用户体验、建立网站权威,最终实现可持续的业务增长。我们的目标是与客户建立长期合作关系,共同成长。
Demand feedback