返回首页
🤖 AI / LLM

LLM 应用工程化实战:从 Prompt 到 Agent 部署的完整指南

LLM 应用从原型到生产有 10 倍差距。本文从 0 到生产级 LLMOps,含 Prompt 管理 / 评估 / 监控 / 成本优化 / Guardrails 完整链路。

LLM · LLMOps · Prompt Engineering · AI Agent · 工程化 · 监控 · 成本优化
📰

今日技术简讯

📰 技术简讯 · 2026-08-01

今日聚合 6 条热门技术内容(中文素材优先)。

🤖 AI / LLM

1. LangSmith 推出 Prompt Hub

2. Helicone 推出 LLM Observability

🎨 前端 / Web

3. Vercel AI SDK 4.0 GA

  • 链接https://sdk.vercel.ai/docs
  • 来源:Vercel
  • 摘要:Vercel AI SDK 4.0 推出完整 RSC + Tools + 多模型统一接口(OpenAI / Anthropic / Google)。

⚙️ 后端 / 架构

4. LiteLLM 推出生产级路由

5. Portkey 推出 AI Gateway 2.0

🚀 独立开发 / OPC

6. 即刻"LLM 工程化"专题

  • 链接https://m.okjike.com/llm-ops-2026
  • 来源:即刻
  • 摘要:即刻 200+ 独立开发者分享 LLM 应用生产化经验,Prompt 管理 / 评估 / 监控 / 成本优化。

数据来源:掘金 / InfoQ 中文 / 即刻 / 少数派 / HN 采集时间:2026-08-01 09:00 (UTC+8)

📝

今日深度文

LLM 应用工程化实战:从 Prompt 到 Agent 部署的完整指南

一句话结论:LLM 应用 = 1% Prompt + 99% 工程化。本文从 0 到生产级 LLMOps,含 Prompt 管理 / 评估 / 监控 / 成本优化 / Guardrails。

背景

2026 年 LLM 应用爆发,但 90% 死在生产化阶段:

❌ 原型到生产:90% 失败
✅ 核心原因:
- Prompt 散落在代码中
- 无评估体系
- 无监控
- 成本失控
- 无 Guardrails

LLMOps 是什么:

LLM Ops = Prompt 管理
       + 评估体系
       + 监控告警
       + 成本优化
       + 安全护栏
       + A/B 测试
       + 持续改进

7 大工程化挑战

1. Prompt 管理

❌ 散落在代码中的字符串
✅ 版本化的 Prompt 库(Prompt Hub)

2. 评估体系

❌ 凭感觉判断效果
✅ 自动化评估(指标 + 人工 + LLM-as-Judge)

3. 监控

❌ 上线后不知道效果
✅ 实时监控(延迟 / 成本 / 质量)

4. 成本控制

❌ 月账单 $5K+ 失控
✅ 智能路由 + 缓存 + 限流

5. 安全护栏

❌ 用户输入绕过限制
✅ Guardrails + 内容审查

6. 可靠性

❌ 单一模型宕机全停
✅ 多模型 fallback

7. 持续改进

❌ 上线后不再迭代
✅ 数据反馈循环

6 大核心实践

实践 1:Prompt 版本化管理

// ❌ 错误:散落
const prompt = "你是一个助手,请回答...";

// ✅ 正确:LangSmith Prompt Hub
// lib/prompts.ts
import { PromptTemplate } from "@langchain/core/prompts";

export const customerSupportPrompt = new PromptTemplate({
  template: `你是一个专业的客服助手。

任务:{task}
客户问题:{question}
相关知识:{context}

要求:
1. 友好专业
2. 基于提供的知识回答
3. 不确定时建议联系人工

回答:`,
  inputVariables: ["task", "question", "context"],
});

// 团队共享 + 版本管理
// LangSmith Hub: prod/customer-support/v3
# Python 版本
from langchain import hub

# 拉取团队共享 Prompt
prompt = hub.pull("prod/customer-support", version="v3")

# 本地缓存
prompt.save("prompts/customer-support.yaml")

实践 2:自动化评估

// evals/customer-support.eval.ts
import { evaluate } from "@langchain/evals";

const dataset = [
  {
    input: "如何退款?",
    expected: "请提供订单号...",
    metadata: { category: "refund" },
  },
  {
    input: "什么时候发货?",
    expected: "订单确认后 24 小时内...",
    metadata: { category: "shipping" },
  },
  // ... 100+ 测试用例
];

const result = await evaluate({
  dataset,
  task: async (input) => {
    return await customerSupport.run(input);
  },
  evaluators: [
    // 1. 字符串相似度
    { type: "string_distance", config: { metric: "cosine" } },
    
    // 2. LLM-as-Judge
    {
      type: "llm",
      config: {
        prompt: `评估回答质量:
1. 准确性(1-5)
2. 友好度(1-5)
3. 是否基于知识回答(是/否)

问题:{input}
回答:{output}
期望:{expected}`,
      },
      model: "claude-sonnet-4-5",
    },
    
    // 3. 业务指标
    {
      type: "custom",
      fn: async (input, output) => {
        return {
          containsRefundProcess: output.includes("退款流程"),
          mentionsHumanSupport: output.includes("人工"),
        };
      },
    },
  ],
});

console.log(result.metrics);
// { accuracy: 0.94, friendliness: 4.7, cost: 0.023 }

实践 3:实时监控

// lib/llm.ts
import { LangChainTracer } from "langchain/callbacks";
import { Client } from "langsmith";

const langsmithClient = new Client({
  apiKey: process.env.LANGSMITH_API_KEY,
});

const tracer = new LangChainTracer({
  projectName: "production",
  client: langsmithClient,
});

export async function callLLM(prompt: string) {
  const start = Date.now();
  try {
    const response = await anthropic.messages.create({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      messages: [{ role: "user", content: prompt }],
    }, {
      callbacks: [tracer],
    });
    
    // 记录指标
    metrics.llmLatency.observe(Date.now() - start);
    metrics.llmCost.inc({
      model: "claude-sonnet-4-5",
      tokens: response.usage.input_tokens + response.usage.output_tokens,
    });
    
    return response;
  } catch (error) {
    metrics.llmErrors.inc({ model: "claude-sonnet-4-5" });
    throw error;
  }
}
# prometheus/alerts.yml
- alert: LLMHighLatency
  expr: llm_latency_p99 > 5000
  for: 5m
  annotations:
    summary: "LLM P99 latency > 5s"

- alert: LLMHighCost
  expr: llm_cost_daily > 100
  for: 1h
  annotations:
    summary: "Daily LLM cost > $100"

- alert: LLMHighErrors
  expr: rate(llm_errors_total[5m]) > 0.1
  for: 5m
  annotations:
    summary: "LLM error rate > 10%"

实践 4:成本优化(智能路由 + 缓存)

// lib/llm-router.ts
import { Redis } from "@upstash/redis";

const cache = new Redis({ url: process.env.UPSTASH_REDIS_URL });

interface RouteConfig {
  cheap: "claude-haiku-4";
  balanced: "claude-sonnet-4-5";
  premium: "claude-opus-4";
}

export async function smartCall(prompt: string, options: {
  complexity: "low" | "medium" | "high";
  maxCost?: number;
}) {
  // 1. 检查缓存
  const cacheKey = `llm:${hashPrompt(prompt)}`;
  const cached = await cache.get(cacheKey);
  if (cached) {
    metrics.cacheHit.inc();
    return cached;
  }
  
  // 2. 选择模型
  const model = {
    low: "claude-haiku-4",        // $0.25/M input
    medium: "claude-sonnet-4-5",  // $3/M input
    high: "claude-opus-4",         // $15/M input
  }[options.complexity];
  
  // 3. 调用(带 fallback)
  try {
    const response = await callModel(model, prompt);
    
    // 缓存(按成本)
    const ttl = options.complexity === "high" ? 3600 : 86400;
    await cache.set(cacheKey, response, { ex: ttl });
    
    return response;
  } catch (error) {
    // Fallback 到便宜模型
    if (model !== "claude-haiku-4") {
      console.warn(`Fallback to haiku: ${error.message}`);
      return await callModel("claude-haiku-4", prompt);
    }
    throw error;
  }
}

// 使用
const response = await smartCall(question, {
  complexity: isComplex ? "high" : "low",
});

成本对比

策略 月成本(10K 请求)
❌ 全部 Opus $1,500
✅ 智能路由(70% Haiku + 25% Sonnet + 5% Opus) $340
✅ + 缓存(40% 命中率) $200

实践 5:Guardrails(安全护栏)

// lib/guardrails.ts
import { Portkey } from "portkey-ai";

const portkey = new Portkey({
  apiKey: process.env.PORTKEY_API_KEY,
  virtualKey: process.env.ANTHROPIC_VIRTUAL_KEY,
});

// 配置 Guardrails
const guardrails = {
  // 1. PII 过滤
  pii: {
    type: "pii",
    config: {
      redact: ["email", "phone", "ssn"],
    },
  },
  
  // 2. 有害内容
  harmful: {
    type: "content",
    config: {
      categories: ["violence", "hate", "sexual"],
      threshold: 0.8,
      action: "block",
    },
  },
  
  // 3. Prompt 注入检测
  injection: {
    type: "prompt_injection",
    config: {
      threshold: 0.7,
      action: "block",
    },
  },
  
  // 4. 主题限制
  topic: {
    type: "topic",
    config: {
      allowedTopics: ["customer-support", "product-info"],
      action: "block",
    },
  },
};

export async function safeCall(prompt: string) {
  return portkey.withOptions({ guardrails }).chat.completions.create({
    model: "claude-sonnet-4-5",
    messages: [{ role: "user", content: prompt }],
  });
}

实践 6:多模型 Fallback

// lib/resilient.ts
const models = [
  { name: "claude-sonnet-4-5", priority: 1, timeout: 10000 },
  { name: "gpt-4o", priority: 2, timeout: 10000 },
  { name: "gemini-2-pro", priority: 3, timeout: 10000 },
];

export async function resilientCall(prompt: string) {
  let lastError;
  
  for (const model of models) {
    try {
      return await Promise.race([
        callModel(model.name, prompt),
        timeout(model.timeout),
      ]);
    } catch (error) {
      console.warn(`${model.name} failed:`, error.message);
      lastError = error;
      continue;  // 试下一个
    }
  }
  
  throw lastError;
}

function timeout(ms: number) {
  return new Promise((_, reject) => 
    setTimeout(() => reject(new Error("timeout")), ms)
  );
}

4 个实战项目

项目 1:AI 客服 SaaS(与 7/14 关联)

LLMOps 实践:
1. Prompt Hub:prod/customer-support/v3
2. 评估:500+ 测试用例 + LLM-as-Judge
3. 监控:延迟 / 成本 / 准确率仪表板
4. 路由:80% Haiku + 20% Sonnet
5. Guardrails:PII + 主题限制

成本:$200/月(10K 用户)
准确率:94%
P99 延迟:1.5s

项目 2:AI 代码助手(与 7/24 关联)

LLMOps 实践:
1. Prompt 分层:系统 / 任务 / 用户
2. 评估:单元测试 + 集成测试 + 用户反馈
3. 监控:Token / 成本 / 完成率
4. 路由:Haiku(简单)→ Sonnet(中等)→ Opus(复杂)
5. Guardrails:代码安全检查

成本:$500/月(1K 付费用户)
满意度:4.6/5

项目 3:RAG 应用(与 7/15 关联)

LLMOps 实践:
1. Prompt Hub:prod/rag-answer/v2(含 system + context)
2. 评估:检索准确率 + 回答准确率
3. 监控:检索延迟 / 生成延迟
4. 路由:根据问题复杂度
5. Guardrails:内容安全 + 幻觉检测

成本:$300/月(50K 查询)
准确率:92%

项目 4:AI 数据分析(与 7/28 关联)

LLMOps 实践:
1. Prompt Hub:prod/sql-generator + prod/insight
2. 评估:SQL 正确率 + 业务准确性
3. 监控:查询延迟 / 结果采用率
4. 路由:Haiku(简单查询)→ Sonnet(复杂)
5. Guardrails:SQL 注入检测 + 权限检查

成本:$400/月(500 客户)
SQL 准确率:96%

5 个常见坑

坑 1:Prompt 硬编码

❌ 代码里散落字符串
✅ Prompt Hub 统一管理

坑 2:无评估

❌ "我觉得效果不错"
✅ 100+ 测试用例 + 自动化评估

坑 3:成本失控

❌ 全部用 GPT-4 / Opus
✅ 智能路由 + 缓存 + 限流

坑 4:单一模型

❌ Claude 宕机就停摆
✅ 多模型 + 自动 fallback

坑 5:无监控

❌ 上线后成"黑盒"
✅ 实时监控 + 告警 + 数据反馈

与之前内容的关系

7/8-10   AI 编程工具
7/11-13  AI Agent 编排
7/14     一人公司 AI Agent
7/15     RAG + pgvector
7/23     10 大 AI 工具
7/24     Cursor + Claude Code 工作流
7/28     AI SaaS 月入 $10K
7/29     WebGPU 浏览器端 AI
8/1      LLM 应用工程化  ← 今天(8 月开篇)
→ "工具 → 框架 → 商业 → 工程化"完整闭环

7 天落地路径

Day 1:Prompt Hub

# 注册 LangSmith
$ npm install langsmith
# 创建第一个 Prompt

Day 2:评估体系

// 100+ 测试用例 + LLM-as-Judge

Day 3:监控

// Helicone / LangSmith 接入

Day 4:成本优化

// 智能路由 + Redis 缓存

Day 5:Guardrails

// Portkey / 内置护栏

Day 6:多模型

// Claude + GPT + Gemini fallback

Day 7:持续改进

// 数据反馈循环 + 每周迭代

我的看法

LLMOps 是 2026 年 AI 应用的"分水岭"

  1. 从原型到生产:90% 失败的根源
  2. 成本可控:智能路由省 80%
  3. 可靠性:多模型 fallback
  4. 可观测:实时监控 + 评估
  5. 安全:Guardrails 必备

对独立开发者的建议:

  • 必装 Prompt Hub:统一管理
  • 必装评估:100+ 测试用例
  • 必装监控:Helicone / LangSmith
  • 必装 Guardrails:PII + 注入
  • 必装路由:智能选模型

参考


本文基于 2026 年 8 月最新 LLMOps 工具链。

📚 同主题文章

🤖 AI / LLM 分类更多