匠人学院 JR Academy
  • Position

    Where am I now, and where should I go?

    How your job is changing, where your experience can take you and what you still need for a target role, worked out from what you have actually done. Free, and the full result needs no sign-up.

    Analyse my career and skills

    Look up a career

    Will AI replace my job?AI impact and transition paths for common careersNew jobs in the AI eraWhat they do, what they need, how to move in

    Focused tools

    AI Engineer interview readiness30 timed questions on what you still need before interviewsCareer personality testDirections that suit how you workReturning to China checkJob prospects in China by school, major and graduation date

    AI coach

    Talk to your AI coachStill unsure after your result? Talk through what is holding you back
  • Core courses

    AI Engineer BootcampEngineering bootcamp from LLM apps to agentsAI Engineer Full-Stack Project Class16 weeks · RAG and full-stack AI projectsVibe Coding Masterclass8 weeks · direct agents to build and ship a productAI Essentials10 hours · use AI for email, reports, data and copyAI Office Automation Course8 weeks · help a whole company adopt AIOne-Person Company (OPC) Bootcamp15 weeks in person · build a one-person company with AIAll courses →

    AI engineering

    Machine Learning & Data Engineering Full-Stack ClassAI Agent & MCP Project BootcampAI Engineer Core TechniquesAI Engineer FoundationsAI Engineer Advanced: RAG to Agents and TuningClaude Code TasterAll AI engineering courses →

    AI at work

    AI Coding for everyoneClaude Code One-Day Masterclass (Non-Technical)Enterprise AI Automation BootcampAI Marketing BootcampAI Risk, Governance and Audit CourseOpenClaw 4-Week Personal AI Assistant BootcampAll AI-at-work courses →

    Career development

    AI Product Manager (BA) Bootcamp + InternshipAustralia IT Interview BootcampAustralia IT Technical Interview BootcampAustralia IT Resume BootcampAustralia Big Tech Job Search BootcampAustralia IT Career Planning BootcampAll career courses →

    Learn free first

    Vibe CodingAI for office workPrompt MasterAI EngineerAI data analysisResource centerInstructorsAll learning paths →
  • Evidence

    What will convince an employer?

    Certifications, projects, team work and competition entries, collected into one portfolio.

    See the portfolio

    Certifications

    Cert Master · all certificationsPrep and mock exams for AWS, Azure, GCP, Claude and moreAWS CLF-C02Entry-level AWS cloud certificationAWS SAA-C03Entry certification for cloud architectsClaude certificationsAnthropic Claude certification seriesAll certifications →

    Projects and team work

    P3 team projectsBuild a project with real teammates in a simulated team workflowP3 project experienceThe parts of a P3 project that go on your resumeDemo DayProject showcaseP3 certificatesProof once a project is completeAll of P3 →

    Competitions and work

    HackathonsBuild something against the clockSubmit your workAdd your project to the showcaseCareerOS portfolioDo tasks in the desktop app; your results become portfolio pieces
    Cert MasterBrowser extension, app and mini programScreenshot a question for analysis and practise anywhereAbout Cert Master
  • Connect

    How do I get myself in front of employers?

    Resume, interviews, referrals and mentors. See how far you are from the target role first, then decide what to fix.

    Start with Jobpin

    Resume and openings

    Graduate careersGraduate preparation across Australia, China, Malaysia, Singapore, the US and UKJobpinAI job search workspace: resume, roles, applicationsAI resumeRewrite your resume against a job descriptionReferralsRoles shared by students and mentorsOpportunitiesInternships, projects and collaborationsOffer boardOffers students have received

    Interviews

    AI Engineer interview guideSeven areas, with worked examplesFDE interview guideFive rounds, from scoping to the customer roundAI mock interviewPractise by text or voice and see the gapsInterview storiesReal interview experiencesSystem Design handbookPrepare for system design interviewsAll interview prep →

    Mentors

    1:1 mentorsBook AI, career and technical mentors by the hourGroup tutoringShare a tutor with a few others and pay less eachCareer coachingResume, interview and direction packages
    Jobpin desktopOne workspace for the whole job searchOrganise real experience and refine resume versions for target roles on macOS or Windows.About Jobpin
BusinessMembershipDownload CareerOS
0
匠人学院 JR Academy

Follow Us

linkedinfacebooktwitterinstagramyoutube

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png
Airbotix · AI learning & creation for kids Another Life · AI story game
Products46

CareerOS and tools

  • CareerOS
  • Cert Master
  • Jobpin
  • Jobpin web
  • Jobpin report
  • Jobpin desktop download
  • My job search reports
  • Buy report credits
  • Jobpin billing
  • AI Toolbox
  • AI Skill Marketplace

Membership

  • Membership
  • AI membership

Courses

  • Bootcamps
  • Training Camp
  • Kanban learning
  • AI Builder course
  • MCP course
  • NotebookLM workshop
  • Business Analyst course
  • Web Full-Stack Bootcamp
  • DevOps Bootcamp
  • Data Engineering Bootcamp
  • Data Analysis Bootcamp
  • Coding for Beginners
  • Algorithm Bootcamp

Career services

  • Graduate careers
  • Graduate careers in Australia
  • Graduate careers in China
  • Graduate careers in Malaysia
  • Graduate careers in Singapore
  • Graduate careers in the US
  • Graduate careers in the UK
  • 1:1 coaching
  • Career coaching
  • AI Engineer VIP
  • BA & PM Internship
  • Data Science Internship
  • Data Analysis Internship
  • Marketing Internship
  • Resume Review
  • Interview Coaching
  • Job Application Service
  • Job Monitoring
  • LinkedIn Management
  • LinkedIn Networking
Library57

Learning paths

  • All Learning Paths
  • AI Engineer
  • Context Engineering
  • Vibe Coding
  • Prompt Master
  • AI Builder
  • AI Product Manager
  • Python Basics
  • AI Productivity
  • AI Data Analysis
  • AI Finance
  • AI Content Creation
  • AI Image Creation
  • Frontend Development
  • Hermes Agent
  • OpenClaw Local Agent

Interactive labs

  • Prompt Lab
  • Frontend Lab
  • JavaScript Lab
  • Python Lab
  • AWS Lab
  • Azure Lab
  • LLM Lab
  • Git Lab

Reference and guides

  • Resources
  • Wiki
  • Cheat sheets
  • Roadmaps
  • AI roadmaps
  • Videos
  • Ebooks
  • Blog
  • Interview handbook
  • Mock exams
  • Free resources

Cities

  • Sydney
  • Melbourne
  • Brisbane
  • Adelaide
  • Singapore
  • Kuala Lumpur
  • London
  • New York
  • San Francisco
  • Los Angeles
  • Seattle
  • Toronto
  • Vancouver

Immigration

  • Australia Immigration
  • Skilled Visa 189/190/491
  • Employer Sponsored 482/186/494
  • Business Visa 188/888
  • UK Immigration
  • US Immigration
  • Canada Immigration
  • Singapore immigration
  • Malaysia immigration
Business20

For business

  • AI for Business
  • Business portal sign-in
  • Corporate Training
  • Internship Partnership
  • Recruitment Partnership
  • Enterprise (EN)

Metatree AI Lab

  • Metatree AI Lab (Chinese)
  • AI solutions (Chinese)
  • Digital employees (Chinese)
  • Case studies (Chinese)
  • Metatree AI Lab
  • AI services
  • Digital employees
  • Case studies

AI education for kids

  • Airbotix — AI Learning & Creation for Kids
  • AU Family Resource Hub
  • NAPLAN Report Guide
  • My School Data Guide
  • Sydney Private School Fees 2026
  • Kids Coding Programs
About15

Company

  • About Us
  • Our Mentors
  • Become a Mentor
  • Metaverse Classroom
  • JR Careers
  • Another Life — AI Story Game
  • Contact Us

Help and policies

  • FAQs
  • Terms & Conditions
  • Privacy Policy
  • Cancellation & Refund Policy
  • Site map

Friend links

  • CS Browser

Contact

  • hello@jiangren.com.au
  • 0421-672-555

Offices

Level 10b, 144 Edward Street, Brisbane CBD (Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
45A13, Block B, Oriental Hope Tianxiang Plaza, 500 Tianfu Avenue Middle Section, Wuhou District, Chengdu, Sichuan, China
Business Hub, 155 Waymouth St, Adelaide SA 5000
Disclaimer
footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

All content on the JR Academy website, including course materials, logos, and information provided, is protected under Australian intellectual property laws. Unauthorized use, sale, distribution, reproduction, or modification is strictly prohibited. Violations may result in legal action. By accessing our website, you agree to respect our intellectual property. JR Academy Pty Ltd reserves all rights, including patents, trademarks, and copyrights. Any infringement will be subject to legal prosecution. View Terms of Service

© 2017-2026 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572

HomeLearnCoursesCerts
  1. Home
  2. Learn
  3. Blog
  4. AI Engineer 完全指南 — 生产部署:Latency / Cost / Observability / Safety 四件套
JR Academy · BlogCareer insights

AI Engineer 完全指南 — 生产部署:Latency / Cost / Observability / Safety 四件套

AI 产品上线后真正的工程难题:怎么压 latency、怎么省 cost、怎么 trace、怎么挡 abuse 和 PII

Published2026-11-30
Reading time5 min
Author

Contents

  • AI 产品上线之后的真正难题
  • ① Latency:用户感知速度
  • 数字基准
  • 优化手段(按性价比排序)
  • ② Cost:账单怎么压
  • 优化策略矩阵
  • Batch API:非实时任务降 50%
  • 混合模型路由(Router)
  • 监控成本
  • ③ Observability:出问题怎么 debug
  • 三层 trace 是标配
  • 工具
  • 必须打的字段
  • ④ Safety:挡住坏请求 + 别泄露敏感
  • Rate Limiting(必须)
  • Content Moderation
  • PII 处理
  • Prompt Injection 防御
  • 监控异常 query
  • 一个完整的 production AI endpoint 长这样
  • 本章小结

AI 产品上线之后的真正难题

前 6 章把"做出来"教完了。这一章讲"上线后不挂"。这部分面试经常问到、JD 里写"production experience" 真正考察的就是这些。

四个核心维度:

        Latency
           ▲
           │
Cost ◀────┼────▶ Observability
           │
           ▼
         Safety

四个互相 tradeoff——压 latency 通常涨 cost、增 observability 涨 latency、加 safety 加 latency 又加 cost。生产 AI Engineer 的工作就是在这四个之间找最优解。

① Latency:用户感知速度

数字基准

体验 TTFT (首 token) 总时延 用户反应
极佳 < 500ms 流式持续 "感觉很快"
可接受 < 1.5s 流式 "还行"
差 > 3s 阻塞 "卡死了"
灾难 > 10s 超时 "再也不用"

TTFT (Time To First Token) 是关键指标。只要流式开 + TTFT < 1s,用户主观体验就 OK,哪怕总时长 30 秒。

优化手段(按性价比排序)

a. 开 Streaming(必做)

第 2 章提过。不开 streaming 的 AI 产品是过去式。

b. Prompt Caching(Anthropic 必开)

system prompt + RAG chunks 缓存 5 分钟,命中部分 input 价格 1/10、latency 降 50%+:

await client.messages.create({
  model: 'claude-sonnet-4-6',
  system: [{
    type: 'text',
    text: longSystemPrompt,
    cache_control: { type: 'ephemeral' } // ← 关键
  }],
  messages: [...]
});

OpenAI 也有自动 prompt caching(24h TTL)但需要 prompt 完全相同。Anthropic 是 5min ephemeral 但能精确控制缓存哪段。

c. 减小输入 token 量

  • RAG top-k 从 10 改 5
  • system prompt 精简(去掉冗余话)
  • 长 history 做摘要

每砍 1K token,latency 降 ~100-200ms,cost 降同比例。

d. 用 Haiku / Flash 处理简单任务

简单分类用 Sonnet 是杀鸡用牛刀。大部分客服分类、内容审核、关键词提取用 Haiku 都够,latency 减半 + 价格 1/4。

e. 并发调用而不是串行

// ❌ 串行 (慢)
const summary = await llmCall(p1);
const tags = await llmCall(p2);
const sentiment = await llmCall(p3);

// ✅ 并发 (快 3 倍)
const [summary, tags, sentiment] = await Promise.all([
  llmCall(p1), llmCall(p2), llmCall(p3)
]);

注意 rate limit—— Anthropic 默认 RPM 是 50(Tier 1),并发太多会 429。生产要算好 RPS。

② Cost:账单怎么压

匠人内部经验:从"完全不优化"到"全套优化",AI 月度账单可降 60-80%。

优化策略矩阵

策略 节省比例 实施难度
模型选型 (Sonnet → Haiku) 70% ⭐ 简单
Prompt Caching 40-50% ⭐ 简单(一行代码)
限制 max_tokens 20-30% ⭐ 简单
Batch API(非实时任务) 50% ⭐⭐ 改架构
Prompt 精简 10-20% ⭐⭐ 调 prompt
混合模型路由 20-40% ⭐⭐⭐ 加 router 层
本地部署小模型 80%+ ⭐⭐⭐⭐ 自维护 GPU

Batch API:非实时任务降 50%

OpenAI / Anthropic / Google 都开了 batch API,定价是实时 API 的 50%,但 24 小时内才返回。

适用场景:

  • 每晚跑的内容审核
  • 离线 evaluation
  • 历史数据回填
  • 任何"可以隔夜处理"的
# OpenAI Batch API 例子
client.batches.create(
    input_file_id=file.id,
    endpoint='/v1/chat/completions',
    completion_window='24h'
)

匠人 daily-eval cron 就用 batch API,月省 ~$200。

混合模型路由(Router)

写一个小 LLM 先判断"这个 query 难度多少",简单的路由到 Haiku,复杂的到 Sonnet:

async function smartRoute(query: string) {
  // Step 1: cheap classifier (Haiku, 一次 ~$0.0001)
  const difficulty = await haiku.classify({
    system: '判断 query 难度:simple / complex',
    messages: [{ role: 'user', content: query }]
  });
  
  // Step 2: route to right model
  if (difficulty === 'simple') {
    return await haiku.chat(query);
  } else {
    return await sonnet.chat(query);
  }
}

前提:分类成本 << 模型差价。计算盈亏点:每 1000 query 用 Sonnet $X,加 router 后 800 走 Haiku + 200 走 Sonnet 的总成本应明显低于 $X,否则别加 router。

监控成本

Helicone / Portkey 这种代理把 LLM 调用 proxy 一遍,给你一个 dashboard 看每个用户、每个 endpoint、每天 / 周的 token 和 $ 消耗。匠人内部用 Langfuse 自带的 cost tracking,每个 trace 都有 cost 字段。

永远监控总 cost、单用户 cost、每个 endpoint cost。看到突涨立刻查(一般是被 abuse 或某个 user query 异常)。

③ Observability:出问题怎么 debug

LLM 应用 debug 比传统应用难 10 倍。原因:

  • 输出非确定性(同样 query 可能不同结果)
  • 调用链长(query rewrite → embed → vector search → rerank → LLM)
  • 错误形态多(拒答、幻觉、格式错、慢、贵)

必须有专门的 observability。

三层 trace 是标配

Layer 1: Request trace
  └── /api/ai/resume-analyze (req_id=abc, user=xyz, latency=2.3s, cost=$0.012)
       │
Layer 2: LLM call trace
  ├── embed (model=text-embedding-3-small, tokens=120, latency=80ms)
  ├── vector_search (top_k=20, latency=15ms)
  ├── rerank (model=rerank-3, latency=180ms)
  └── llm_call
       │
Layer 3: LLM call detail
  ├── system prompt: "..." (cached: yes, 1200 tokens)
  ├── user msg: "..." (300 tokens)
  ├── output: "..." (450 tokens)
  ├── tokens: input=1500, output=450, cached=1200
  ├── cost: $0.012
  └── latency: 1.8s (TTFT=400ms)

工具

  • Langfuse(开源 / SaaS,自托管首选)
  • LangSmith(LangChain 出,Python 生态深度集成)
  • Datadog APM(传统 APM 加 LLM 插件)
  • Helicone(轻量 proxy,1 行代码集成)

匠人用 Langfuse self-hosted:免费、所有数据自己控、Postgres 后端不另起新 infra。

必须打的字段

{
  trace_id: 'abc-123',
  user_id: 'user-456',
  endpoint: 'POST /api/ai/resume-analyze',
  model: 'claude-sonnet-4-6',
  prompt_version: 'resume-analysis@1.2.0',  // ← 关键,prompt 出问题能定位
  input: { ... },
  output: { ... },
  tokens: { input: 1500, output: 450, cached: 1200 },
  cost_usd: 0.012,
  latency_ms: 1820,
  ttft_ms: 380,
  error: null,
  feedback: null  // 用户点踩 / 五星评分写这里
}

prompt_version 是匠人内部 PRD 强制的——出问题能立刻定位是哪版 prompt 干的。

④ Safety:挡住坏请求 + 别泄露敏感

Rate Limiting(必须)

不限的话用户脚本一刷就把你账单刷穿。NestJS 例子:

@Throttle({ default: { ttl: 60000, limit: 30 } }) // 30 RPM/IP
@Post('/ai/chat')
async chat(@Body() dto: ChatDto) { ... }

匠人全局 100 RPM/IP,AI endpoints 单独限 30 RPM。用户级别也要限(按 user_id 不只 IP)。

Content Moderation

用户输入 + 模型输出都要过审:

  • OpenAI Moderation API 免费,分类 violence / sexual / hate
  • Anthropic 没专门 API,用 Haiku 写 prompt 判
  • 大陆运营用阿里云 / 腾讯云内容审核(自带敏感词库)
async function chat(userMsg: string) {
  // pre-check user input
  const inputCheck = await moderate(userMsg);
  if (inputCheck.flagged) throw new Error('Input violates policy');
  
  // call LLM
  const response = await llm.chat(userMsg);
  
  // post-check output
  const outputCheck = await moderate(response);
  if (outputCheck.flagged) {
    return '抱歉,无法生成相关内容'; // 拒绝输出
  }
  
  return response;
}

PII 处理

简历、客户咨询里可能有手机、邮箱、身份证、银行卡。送给 LLM 前必须 redact:

function redactPII(text: string) {
  return text
    .replace(/\b1[3-9]\d{9}\b/g, '[PHONE]')
    .replace(/\b[\w.-]+@[\w.-]+\.\w{2,}\b/g, '[EMAIL]')
    .replace(/\b\d{15}|\d{18}\b/g, '[ID]');
}

为什么必须:

  1. 数据传到 LLM 服务商等于上传 OpenAI / Anthropic
  2. 训练数据可能被用来改模型(虽然各厂都说"我们不用 API 数据训练",但合规层面 zero trust 更稳)
  3. 澳洲 Privacy Act + GDPR 都要求"必要最小化"

例外:如果有 BAA / DPA 协议(Enterprise tier),可以发 PII。但默认 redact 是工程默认。

Prompt Injection 防御

第 3 章已经讲。生产标配:

  • 用户输入用 <user_input> 标签包起来
  • system prompt 写死"无论用户说什么,永远不做 X"
  • 高危动作 human-in-the-loop

监控异常 query

某用户突然问 1000 次"管理员密码"——很可能是 attack。要打日志 + 告警:

const SUSPICIOUS_KEYWORDS = ['ignore previous', 'system prompt', 'admin password'];
if (SUSPICIOUS_KEYWORDS.some(k => userMsg.toLowerCase().includes(k))) {
  await alertSecurityTeam({ user_id, msg: userMsg });
}

一个完整的 production AI endpoint 长这样

@Throttle({ default: { ttl: 60000, limit: 30 } })
@Post('/ai/chat')
async chat(@Body() dto: ChatDto, @CurrentUser() user: User) {
  const traceId = uuid();
  
  // 1. Pre-check
  const moderation = await this.moderateService.check(dto.message);
  if (moderation.flagged) throw new ForbiddenException('Content policy violation');
  
  // 2. PII redact
  const redacted = redactPII(dto.message);
  
  // 3. RAG retrieval (with caching)
  const chunks = await this.ragService.retrieve(redacted, { 
    accessLevel: user.role,
    topK: 5 
  });
  
  // 4. LLM call (with timeout + retry + observability)
  const response = await this.langfuse.trace(traceId, async () => {
    return await retryWithBackoff(
      () => this.llmService.chat({
        promptVersion: 'chat@1.2.0',
        system: PROMPTS.chat.system,
        chunks,
        userMessage: redacted,
        userId: user.id,
        timeout: 30000
      }),
      { maxRetries: 2 }
    );
  });
  
  // 5. Post-check output
  const outputModeration = await this.moderateService.check(response.text);
  if (outputModeration.flagged) {
    return { response: '抱歉,无法生成相关内容', traceId };
  }
  
  return { response: response.text, traceId };
}

50 行代码包含 rate limit / moderation / PII / RAG / observability / retry / output filter。这是真正 production-ready 的 AI endpoint。

本章小结

  • Latency:streaming + caching + 选小模型 + 并发
  • Cost:选模型 + caching + batch API + 混合路由 + 监控
  • Observability:三层 trace(request / LLM call / detail),打 prompt_version 字段
  • Safety:rate limit + moderation 双向 + PII redact + injection 防御 + 异常 query 监控

最后一章我们讲求职:怎么把这些技能转化成简历 / 项目 / 面试通过率。

Author
Share or copy the link

Related learning resources

  • AI learning hub
  • Prompt engineering
← Previous articleAI Engineer 完全指南 — 微调 vs 评估:怎么知道你的 AI 产品到底好不好Next article →AI Engineer 完全指南 — 求职:从转行到拿 offer 的实操路径

Related articles

🇦🇺测一下:袋鼠国码农能当FDE吗?

2026-12-01

Monash 研究:肠道酸度是膳食纤维降血压的关键;AI 搬运新闻冲击维州选举信息;MPAC 公布 2027 演出季

2026-12-01

Adelaide 物理学家获 $250,000 总理科学奖;全球葡萄酒消费六十年降四分之一;残障师范生实习障碍研究

2026-12-01

DVA-C03今日上线首发 · Google Cloud AI Agent认证完整解析 · AZ-401本月GA替代AZ-400

2026-12-01

Anthropic推迟下一代模型并调百人做安全,AWS推出AI办公三件套,Google让用户单独关掉AI训练

2026-12-01

GitHub Copilot 实战指南 — Copilot AI Code Review:30 秒让 AI 帮你审 PR,三档深度随需切换

2026-11-30
View all articles →

Done reading? Next steps

Not sure what to learn next? Tell us where you are

Tell us what you do now and where you want to go. See your gaps in skills, evidence, experience, expression and positioning, and what to work on first. No sign-in needed.

Compare with my situation
  • SkillAI Engineer Bootcamp13 weeks, 12 Theory + 13 Practice live classes. You build one Agent system across Context, RAG, Tools, Memory and production Evals. Built for Applied AI and Agent Engineer roles.See the program →
  • PositioningLearning roadmaps by roleFrontend, backend, data, AI and more, laid out stage by stage in the order to learn them.All roadmaps →
  • ExpressionTry an AI mock interviewPick a role and run a mock interview to practise explaining your experience and projects.Practise now →

Not sure what to do next?

Take this page's topic with you and see where your gaps are.

Compare with my situation
JR Academy
AI learning for the global Chinese community
BootcampsFree resourcesLearn AICareer coaching
精选推荐
AI Career Impact Map
Assess career exposure and explore transition paths and learning options
Popular tool
AI & Data Bootcamps
Build your skills through structured courses and hands-on projects
Popular courses
1:1 Career Coaching
Work with an experienced mentor on your resume and interview preparation
Career coaching
Custom Corporate Training
AI training tailored to your team
Business services
Popular tags
Vibe CodingAI codingCursorClaudeJob searchPromptFrontend developmentBackend development
Subscribe to updates

Receive AI learning resources, technical tutorials and career advice by email.

We respect your privacy and do not send spam.