面向 AI 的数据蓝图——AI 应用生产化优化

0 阅读40分钟

一个可工作的 AI prototype 与一个 production-ready system 之间的差距,比大多数 practitioners 预想的更大。那些在 development environments 中表现出色的 solutions,一旦面对 real-world operations 的 scale、complexity 和 unpredictability,往往就会失效。能够交付 impressive demos 的 models,可能会在 noisy enterprise data 面前挣扎。能够对 curated test prompts 做出精彩回应的 agents,可能会在 million-token codebases 的压力下崩溃。那些单独看起来 robust 的 systems,一旦部署到 organization 范围内,可能会变得无法 monitor、secure 或 scale。

本章就是为了弥合这个 gap。

The Journey from Prototype to Production

构建 AI application 只是开始。从 prototype 走向 production,需要 carefully orchestrate 多种 optimization strategies——提升 response quality 和 accuracy,满足严格的 performance requirements,降低 operational costs,并简化 system complexity。这个过程的成功并不是靠某一种 technique 或 silver-bullet solution 实现的。相反,它需要一种 comprehensive approach,而这种 approach 建立在一个 fundamental truth 之上:你的 data 是 AI application 的 lifeblood。

虽然每个 practitioner 都同意 data quality 会驱动 AI performance,但很少有人能准确说明如何准备 data,才能达到 peak results。这个“知道”和“做到”之间的 gap,正是大多数 AI projects 失败的地方。秘密并不在 complex algorithms 或 cutting-edge models 中,而在于你如何战略性地 approach data preparation——先 architect foundation,再 build house。

贯穿本章,我们会提供 strategies、patterns 和 practical guidance,帮助你将 AI application 从一个 promising experiment 转变为 enterprise-grade system。我们的 journey 会经历五个 interconnected phases。

首先,我们建立 data quality assessment 和 preprocessing 的 foundations。你将学习为什么 business outcomes 必须驱动 data quality requirements,如何拥抱 flexibility 而不是 rigid schemas,以及 modular data design 如何同时优化 storage efficiency 和 query performance。通过具体 examples,我们会展示同一份 data 如何因 preparation 方式不同而服务于完全不同的 purposes。

第二,我们处理 scale 下的 context management challenge。随着 context windows 从几千 tokens 扩展到数百万 tokens,处理 large inputs 而不牺牲 output quality 的新 strategies 已经出现。我们引入一个系统化的 three-step process——segmentation、segment inference 和 organization,使 applications 能够对那些原本会压垮 model capabilities 的 datasets 进行 reasoning。

第三,我们探索 automated reasoning 的 frontier。从 token-based triggers,到 chain-of-thought、tree-of-thought 和 graph-of-thought 等 architectural patterns,我们会考察如何利用现代 foundation models 的 reasoning capabilities。你将学习什么时候 reasoning tokens 会增加 value,什么时候它们会引入不必要 overhead,以及如何针对 specific use cases 校准这些 capabilities。

第四,我们介绍一种面向 enterprise data management 的 transformative approach:intelligent semantic metadata layer。当 organizations 面对 petabytes 级 unstructured data——documents、images、legacy files 和 specialized formats——traditional retrieval approaches 会力不从心。我们提出一种建立在 knowledge graph technology 之上的 pattern,使 AI agents 能够在 scale 上 discover、interpret 并 reason over enterprise content,而不需要 wholesale data migration 或抛弃 existing infrastructure。

最后,我们处理在 production environments 中部署 AI agents 的 operational realities。Accuracy alone 并不能保证成功。我们提供一个 comprehensive framework,用于评估 application 所需 capabilities,从 core runtime 和 deployment options,到 security、observability 和 multi-agent orchestration。最后,我们会对 leading AI agent platforms 做 comparative analysis,并提供 guidance,帮助你选择最符合 organizational requirements 的 infrastructure。

这里提出的 techniques 不是 theoretical concepts,而是在 production environments 中被验证过的 practical approaches。它们反映了来自 real-world implementations 的经验教训——从管理几十年累积下 quadrillions of files 的 semiconductor manufacturers,到面对复杂 regulatory requirements 的 medical device companies。

无论你是在为第一个 AI application 做 production 准备,还是在优化 existing system 以获得更高 scale 和 reliability,本章都会提供你需要的 blueprint。从 prototype 到 production 的道路要求很高,但只要采用正确 strategies,它完全可以实现。

让我们开始。

Preparing Your AI Application for Production Success

大多数 AI initiatives 失败,并不是因为缺少 sophisticated models,而是在 intention 和 execution 之间那个不安的空间里跌倒:data 没有以足够 strategic care 的方式被准备好。请把 data preparation 看作 building 的 structural foundation:如果你匆忙处理 footings,那么上面建的任何东西都撑不了多久。把这个做对,后面一切都会顺畅。那么,如何打造 winning data strategy?答案建立在接下来要探讨的两个 fundamental pillars 之上。

The Twin Pillars of AI Optimization

你的 data preparation strategy 必须由两个不可分割的因素指导:

Your desired business outcomes
你的 AI application 必须实现哪些 specific goals,才能交付 value?

Your data readiness
你当前的 data infrastructure、quality 和 accessibility 处于什么状态?

这两个 elements 是 intrinsically linked 的,不能孤立处理。不同于 traditional data management approaches,在那里你可能会实施一个 universal solution——例如在 data warehouse 中为 relational data 建立 canonical star schema,服务各种 use cases——AI applications 需要一种更 nuanced、context-specific 的 approach。One-size-fits-all paradigm 在这里根本不适用,至少以我们当前的 technology capabilities 来看是这样。

接下来的 sections 中,我们将探索具体、可执行的 techniques,用于准备 data infrastructure,以优化 AI application performance,同时保持与 specific business objectives 的 alignment。这些不是 theoretical concepts,而是已经被证明可以弥合 AI potential 和 production reality 之间差距的 practical approaches。


Engineering Efficient Data Workflows for Production AI Systems

本节中,你将学习如何为 production AI systems 设计 efficient data workflows:通过将 data quality 与 business objectives 对齐、设计 modular vector store indexes、管理 large context windows,以及同时针对 performance 和 cost 调优 automated reasoning。先从把这些 high-level principles 转化为 practical data quality assessment 和 preprocessing fundamentals 开始,说明如何 inspect、clean 并 structure input data,使其忠实服务于 AI objectives。

Data Quality Assessment and Preprocessing Fundamentals

在优化 AI applications 时,会出现一个关键问题:如何判断 specific use case 所需的 input data quality 应该达到什么水平?虽然第 4 章讨论了 general data quality considerations,例如 sensitive data management 和 data formats,但本章聚焦一个更 nuanced challenge:在 AI systems 中将 data quality 与 business objectives 对齐。

Business outcomes drive data quality requirements

基本原则很简单:你的 desired business outcome 应该决定什么样的 input data 才算 “quality”。在一个 context 中看似 noise 的内容,在另一个 context 中可能是 essential information。

考虑下面这封来自虚构公司 TechCorp 的 customer service email。Emails 通常包含两个主要 components——headers,这里用 bold 标出,包括 sender 和 recipient(s) 的 names 和 email addresses、timestamps 和 subject lines;以及 body content,也就是 actual message:

From: "Michael Chen" <michael.chen@techcorp.com>
Date: Monday, August 25, 2025 at 9:36 PM
To: sarah <sarah@mycompany.com>
Cc:
Subject: Resolution for Your Recent Order Issue - Order #12345
 
Dear Sarah,
 
Thank you for contacting us about the delayed delivery of your order #12345. 
I sincerely apologize for the inconvenience this has caused.
 
I've investigated your order and found that it was delayed due to a warehouse 
processing error. To resolve this immediately, I've:
 
• Expedited your order for next-day delivery at no additional cost
• Applied a $25 credit to your account for the inconvenience
• Added tracking information that you'll receive via text and email
 
Your order will arrive tomorrow by 6 P.M., and you'll receive tracking updates 
throughout the day.
 
If you have any other concerns or questions, please don't hesitate to reach out 
to me directly at this email or call our priority line at (555) 123-4567.
 
Thank you for your patience and for being a valued customer.
 
Best regards,
 
Michael Chen
Customer Success Specialist
TechCorp Solutions
michael.chen@techcorp.com
Direct: (555) 123-4567

为了展示同一份 data 如何根据你提出的问题,在 signal 和 noise 之间切换,我们通过两个不同 business lenses 来评估这封 email。

Scenario 1: Intent classification

如果你的 business objective 是理解 customer intent,以便将 emails 路由到 appropriate departments,那么 email headers 就会成为降低 model performance 的 noise。在 data processing phase 中,这些 headers 应该被移除,使 foundation model 专注于表达 intent 的 message body。

Scenario 2: Interaction analysis

相反,如果你需要分析 specific customers(例如 Sarah)与 service representatives(例如 Michael Chen)之间的 interactions frequency,那么 headers——尤其是 email addresses 和 timestamps——就会成为 primary data of interest。在这种情况下,message body 反而代表 noise,应在 processing 中被过滤掉。

Data quality 的 context-dependent nature 挑战了 traditional approaches。试图将 unstructured data 强行塞进一个带固定 quality constraints 的 rigid canonical model,可能会主动阻碍你的 business goals。相反,保留对 raw、unprocessed data 的访问,可以提供 flexibility,使你在新的 use cases 出现时提取不同层面的 quality。

对于熟悉 traditional data analytics 的 practitioners 来说,这种 approach 可能看起来 counterintuitive,甚至像 antipattern。然而,unstructured data 具有 latent value;今天被认为 irrelevant 的信息,可能在解决明天的 business challenges 时变得 critical。

Efficient data management through modular design

这种 flexibility 自然引出一个 practical concern:你应该维护多少 copies 和 versions of data?答案在于 thoughtful architectural design,尤其是在使用 vector stores 实施 retrieval-augmented generation(RAG)systems 时。

一个设计良好的 vector store 应该避免 significant data duplication,同时保持 flexibility。图 6-1 使用 customer service email 示例展示了这个 concept。

image.png

图 6-1:将 email components 分离的 modular vector store design

该 architecture 在 vector store 中使用多个 indexes:

  • Index 1 只包含 email headers,也就是 sender、recipient、timestamp、subject。
  • Index 2 存储 email body content。

每封 email 都会经过 processing step,在其中被 parsed,并获得 unique identifier(email_id_numeric)。当 chunks 插入 vector database index 时,这个 identifier 会被添加到 metadata 中。这种 approach 类似 traditional data warehouses 中用于 join tables 的 surrogate keys 概念。

如果未来某个 use case 同时需要这两个 components,你的 AI agents 可以同时 query 两个 indexes。随后,postprocessing operations 可以使用 shared identifier 将 results join 起来,创建完整 email 的 unified view,而无需存储 redundant copies。

Best practices for modular data design

关键原则是:将 data conceptualize 为 modular subsets,每个 subset 只包含解决 specific business problems 所需的 minimal information。这种 approach 带来多个优势:

Storage efficiency

消除 redundant data storage。

Query performance

更小、更 focused indexes 会提升 retrieval speed。

Flexibility

随着 requirements 演进,可以创建新的 combinations。

Maintenance

Updates 只会影响 relevant indexes。

Cost optimization

降低 storage 和 processing requirements。

通过采用这种 modular approach,你可以创建一个 adaptable foundation,使其能够随 business needs 演进,同时在 AI applications 中维持 optimal performance 和 cost-effectiveness。接下来,我们来看如何为 AI application 准备正确的 context,使其能够表现良好。

Understanding Context Windows and Their Implications

自 2022 年 ChatGPT 出现以来,context window sizes 已经显著增加。支撑其发布的 GPT-3.5 model 最大 context length 为 4,096 tokens,约等于 3,000 words(一个 token 大约等于三到四个 characters,或英语中约四分之三个 word);而现在一些 frontier models 支持最高 1M tokens 的 context windows。随着这些 models 改进,在 large context sizes 下也能提供强 performance,同时 inference costs per token 逐步下降,modern AI applications 越来越多地使用 larger context sizes。然而,一些 domains 仍然超出这些 limits。例如,考虑一家 chip manufacturing company 的 embedded systems code:codebase 可能大到需要超过 1M-token context window,而大多数 frontier models 目前还无法支持。

使用 foundation models 时,一个 fundamental challenge 在于 context size 与 output quality 之间的关系。AI practitioners 已经观察到,随着 context windows 扩大,它们往往会引入 noise,从而掩盖生成 accurate responses 所需的 critical information。这一现象催生了一个关键 best practice:在 model inference 前进行 aggressive preprocessing,以消除 unnecessary content。

当处理 large datasets,这些 datasets 要么超过 model token limit,要么包含大量会降低 output quality 的 noise 时,strategic approach 就变得 essential。解决方案是实施一个系统化 process 来处理 large input contexts,确保 models 接收到 clean、relevant information,同时保留 complex reasoning tasks 所需的数据深度。

Handling Large Input Contexts

如图 6-2 所示,处理 large input contexts 是一个 three-step process:

1. Segmentation

首先,将 large inputs segment(chunk)成更小的 text pieces。

2. Segment inference

接下来,对每个 segment 执行 inference。为了提升 performance,这一步可以 parallel 执行。例如,假设你正在对 Slack chat message history 做 categorization,总 data size 为 1M tokens。假设每个 segment 拥有 100k-token context,那么可以并行处理 10 个 segments,每次 inference 对其对应部分的 text 进行 categorization。

3. Organization

最后,将上一步 outputs 合并。在 Slack 示例中,每个 segment 生成的 categories 会通过 combiner process 或 agent 聚合,合并所有 segment outputs,并生成 final response。

image.png

图 6-2:Handling large input contexts 的完整过程

某些 applications 要求能够从 large contexts 中 search 和 extract relevant information,同时不依赖 external storage systems。这种 approach 类似 RAG architectures,但完全在 processing pipeline 内运行,适用于那些因 security constraints 不能冒险将 intellectual property 或 sensitive data 暴露给 persistent data stores 的组织。

考虑前面提到的 embedded systems 中 codebases 的挑战。这些 massive monolithic files 在许多 industries 中都很常见,尤其是 legacy systems 已经演进为 complex、interconnected architectures 的场景。当 developers 需要修改 specific functions 或 debug particular code sections 时,将 entire codebase 通过 model context window 传输,既 inefficient 也 impractical。

解决方案是部署 specialized search agent,并让它分阶段运行。首先,它将 large codebase 分割成 manageable chunks,并根据 specific query 或 modification request 识别 relevant sections。然后,agent 识别 target function 及其 dependencies,并只提取 pertinent code blocks,从而为 primary AI system 创建 focused context。修改完成后,secondary agent 处理 integration phase,将 updated code merge 回 original structure,同时执行 comprehensive comparisons,以确保 consistency,并识别任何 unintended changes。

这种 in-context search methodology 在保留 data security 的同时,维持 complex code modifications 所需的 analytical depth。当 traditional RAG implementations 不可行时,它提供了一种 practical alternative。

现在,我们已经建立了 context handling 在 AI applications 中的关键重要性。接下来,我们将关注一个正在重塑我们对 inference quality 理解的突破性发展:reasoning tokens 的使用。

Optimizing Inference Quality Using Automated Reasoning

Reasoning mechanisms 代表 context-aware AI systems 的下一步 evolution。在这里,models 不只是处理 information,而是会利用你提供的 contextual framework 主动 reason through problems。

Automated reasoning 指 AI systems 通过 systematic computational processes 执行 logical inference、problem solving 和 decision making 的能力。它可以分为三类:

  • Token-based reasoning
  • Architectural reasoning
  • Processing patterns

Token-based reasoning

Token-based reasoning 可以由不同类型 tokens 触发或引导,包括:

Automated reasoning tokens

这些是 explicit tokens 或 phrases,用于激活 AI models 中的 reasoning processes。可以把它们看作 cognitive switches,用来告诉 model 进入 deliberate thinking 状态。

Example:当你在 prompt 中加入 “Think step by step” 这样的短语时——通常是在 system prompt 中——model 会识别出这是一个 signal,表示需要系统化拆解问题,而不是直接跳到结论。

prompt = "Think step by step: How do we optimize database performance?"

Learned reasoning tokens

这些是 models 通过 training 学会与 deeper reasoning 关联起来的 tokens,即使没有 explicit instruction 也会触发。

Example:Models 可能会学到某些 complex problem types 会自动触发 reasoning processes,例如 multivariable optimization problems 或 logical puzzles。

Context-sensitive tokens

这些 tokens 会根据 problem 的 specific context 和 domain 调整 model 的 reasoning approach。Prompt 和 surrounding context 会决定哪种 reasoning strategy 被激活。

Example:Prompt 可以明确告诉 model 应用 structured reasoning mode:

prompt = """
Use systematic reasoning to solve this:
<reasoning_mode>step_by_step</reasoning_mode>
Problem: {complex_problem}
"""

Architectural reasoning

有三种主要 reasoning frameworks,用于结构化 language models 如何解决 complex problems:chain-of-thought(CoT)、tree-of-thought(ToT)和 graph-of-thought(GoT)。

Chain-of-thought

CoT reasoning 会将 complex problems 拆解为 logical sequence of intermediate steps,其中每一步都建立在前一步之上。这种 approach 对 multistep analysis、mathematical problem solving 以及其他 complex reasoning tasks 尤其有用。然而,它并非所有 tasks 都需要,并且确实会引入额外 overhead,包括 increased latency 和更多 output tokens。不需要 explanation 的 simple tasks 通常并不是 CoT reasoning 的好候选。

在解决 math word problem 时,CoT reasoning 会先识别 given information,然后确定需要计算什么,建立 relevant formula,逐步执行 calculations,并最终验证 answer。

为 reasoning 分配 tokens 的能力,使 developers 可以根据 task complexity 控制 reasoning process 的深度。更大的 reasoning tokens 数量可以支持更详细的 step-by-step planning。当启用这些 tokens 时,reasoning trace 可能在 model output 中可见。重要的是,reasoning tokens 会计入 total output token limit,因此分配的数量必须始终低于该 limit。

下面是一个没有给 reasoning model 分配 reasoning tokens 的例子:

Prompt: I have 5 apples in a basket. I added 6 bananas to it. Then I gave away 
2 apples and 3 bananas but added 7 plums. I ate 2 plums and a banana. How many 
total fruits are left in the basket? 
 
Output: 10 Fruits
Input- 75 tokens, Output -203 tokens, Latency-4380 ms

注意,由于 model 具有 inherent learned reasoning capabilities,其 output 中包含 reasoning content,这会增加 output token count。为了简洁,本书展示的 output 中移除了这些 reasoning content。

下面是给同一个 reasoning model 分配 1,024 reasoning tokens 的例子:

Prompt: I have 5 apples in a basket. I added 6 bananas to it. Then I gave away 
2 apples and 3 bananas but added 7 plums. I ate 2 plums and a banana. How many 
total fruits are left in the basket? 
 
Output: 10 Fruits
Input- 75 tokens, Output - 470 tokens, Latency-7132 ms

比较两次运行会发现显著影响:output tokens 数量增加了一倍以上,total latency 几乎翻倍,导致第二次运行 inference costs 明显更高。这强调了 careful calibrating reasoning token allocation 的重要性。为了避免 overprovisioning,你应该使用能代表 real-world usage patterns 的 prompts sample,迭代测试 configuration。

Tree-of-thought

ToT reasoning 使用 branching exploration,同时评估 multiple possible reasoning paths,就像树上的 branches,然后选择最 promising direction。例如,当规划一个 project 时,ToT 可能会探索不同 approaches(Branch A: agile methodology;Branch B: waterfall approach;Branch C: hybrid model),评估每个 branch 的 pros and cons,然后选择 optimal path。

Graph-of-thought

GoT reasoning 使用 network-based relationships,形成 interconnected networks,其中不同 concepts 和 reasoning steps 可以以 complex ways 相互影响。例如,在 medical diagnosis 中,symptoms、test results、patient history 和 potential treatments 构成一个 network,每个 element 都可能影响其他 elements 的 interpretation。

Reasoning framework selection

你的 prompt 对决定使用哪种 reasoning technique 至关重要。如果你需要 specific technique,请在 prompt 中明确指定,例如:

prompt = """
Can you solve this by using the tree-of-thought technique?
Context:
    Bob is in the living room.
    He walks to the kitchen, carrying a cup.
    He puts a ball in the cup and carries the cup to the bedroom.
    He turns the cup upside down, then walks to the garden.
    He puts the cup down in the garden, then walks to the garage.
Question: Where is the ball?
"""

Output:

# Tree-of-Thought Solution
 
I'll solve this by exploring multiple reasoning paths and evaluating them.
 
## Initial State Analysis
 
**Thought 1:** Track the ball's location through each action
**Thought 2:** Track the cup's state (upright/upside down) and contents
**Thought 3:** Identify the critical action that affects the ball
 
Let me explore each thought:
 
---
 
## Path 1: Direct Ball Tracking
 
1. **Initial**: Bob is in living room (ball location unknown initially)
2. **Kitchen**: Bob walks to kitchen with cup (no ball mentioned yet)
3. **Ball enters**: Bob puts ball IN the cup (ball is now in cup)
4. **To bedroom**: Bob carries cup to bedroom (ball still in cup)
5. **Critical action**: Bob turns cup upside down in bedroom
   - **This releases the ball!** The ball falls out in the BEDROOM
6. **To garden**: Bob walks to garden (ball was left behind in bedroom)
7. **Cup down**: Bob puts cup down in garden (cup is empty)
8. **To garage**: Bob walks to garage (ball still in bedroom)
 
**Conclusion from Path 1: Ball is in the BEDROOM**
 
---
 
## Path 2: Cup State Tracking
 
- Cup starts upright  ball can stay inside
- Cup turned upside down in bedroom  ball falls out
- Cup moved to garden while upside down  already empty
- **Ball location: BEDROOM** (where it fell out)
 
---
 
## Path 3: Location Verification
 
Could the ball be anywhere else?
-  Living room? No, ball was put in cup after leaving
-  Kitchen? No, ball added here but then moved
-  **Bedroom?** Yes - cup was inverted here
-  Garden? No, ball already fell out before cup arrived
-  Garage? No, Bob went there alone
---
 
## Final Answer
 
**The ball is in the BEDROOM.**
 
The critical moment was when Bob turned the cup upside down in the bedroom, 
causing the ball to fall out. The cup then traveled empty to the garden and Bob 
continued to the garage, but the ball remained where it fell.

如果没有明确指定其他 structured reasoning approach,通常默认会使用 CoT。根据 task 不同,也可以动态 classify problem,并调整 prompt,以利用最适合的 reasoning strategy。

Processing patterns

除了 token-level 和 architectural techniques,许多 modern reasoning models 也依赖 distinct processing patterns——也就是随时间组织其 thinking 的 structured ways,会影响它们如何 explore options、refine partial answers,并得出 final decisions。下面看几个 leading patterns:

Interleaved thinking

使用 alternating reasoning and response。Model 在 internal reasoning 和 generating output 之间交替进行,并随着 progress refine its approach。

Example:当被要求写一份 complex product launch report 时,model 会先 plan structure,并为 global markets 起草 outline;随后根据 specific regions 的 demographic information 调整 outline;最后继续 content generation,同时不断 evaluate 和 adjust its approach。

Recursive reasoning

使用 self-referential problem decomposition。Model 将同样的 reasoning process 应用到逐渐更小的 subproblems 上,直到达到 manageable components。

Example:当被要求提升一家拥有多层 hierarchy 的 large company 的 operational efficiency 时,model 会先考虑 department-level improvements,然后是 team-level optimizations,再然后是 individual process enhancements,并在每一层都应用相同 analytical framework。

Multistage reasoning

使用 layered cognitive processing。这包含多个 distinct phases of reasoning,每个 phase 有自己的 focus 和 methodology。

Example:假设 AI assistant 被要求为一家公司的 production database 设计 cost-effective backup strategy。Model 会将问题拆成四个 distinct stages:

1. Problem identification and scope definition
通过识别 critical systems、acceptable recovery times 和 budget constraints 来澄清问题。

2. Data gathering and analysis
收集并分析 current storage usage、historical failure rates 和 available backup technologies。

3. Solution generation and evaluation
提出 candidate strategies,例如 daily full backups、continuous replication,比较它们的 reliability 和 cost,并推荐 best option。

4. Implementation planning and risk assessment
安排 backup jobs,定义 monitoring alerts,并评估 network failures 或 missed backup windows 等 risks。

Model 使用的 reasoning pattern 通常由 prompt structure、optional model settings,以及有时 explicit user instructions 决定。下面示例展示了针对给定问题,如何触发这里描述的每种 pattern:

Question: Given the list of numbers [2, 3, 4, 5, 6], find all unique pairs whose 
sum is a prime number. Show your reasoning process.  
# Interleaved Thinking System Prompt
interleaved_system_prompt = (
    "You are an AI agent that alternates between thinking and acting."
    "For each step: reason about which numbers might form pairs, simulate 
    checking their sums, observe whether the sum is prime, and repeat until all 
    pairs are considered."
    "Present the answer at the end."
)
 
# Recursive Reasoning System Prompt
recursive_system_prompt = (
    "You are an AI agent that recursively breaks problems into smaller 
    subproblems."
    "For each pair, calculate the sum, check if it is prime, and if not, move to 
    the next pair."
    "Continue recursively until all pairs are tested, then list those whose sums 
    are prime."
)
 
# Multistage Reasoning System Prompt
multistage_system_prompt = (
    "You are an AI agent that solves problems in clearly defined stages."
    "Stage 1: List all possible pairs from the given numbers."
    "Stage 2: For each pair, calculate their sum."
    "Stage 3: Check which sums are prime numbers."
    "Stage 4: Present the pairs whose sums are prime."
)

NOTE

该示例的完整代码可在本书 GitHub repository 中下载。它已经测试可与 Amazon Bedrock models 一起工作,但你可以根据所使用的 model 进行修改。注意,并不是所有 models 都支持 reasoning。请参考 model card 或 documentation,以确定你选择的 model 是否提供这些 capabilities。

无论是 token-based、architectural,还是 pattern-driven,automated reasoning capabilities 都构成 sophisticated AI decision making 的 intellectual backbone。然而,如果没有在正确 context、正确时间交付正确 data,这些能力的真正潜力无法实现。Reasoning alone 并不能让 AI system production-ready;真正区分 experimental prototypes 和 enterprise-grade solutions 的,是能否通过 trusted metadata layers 和 connected knowledge graphs 智能导航 complex data landscapes。这些 foundational elements 转变了 AI agents 如何 discover、interpret 和 act upon available data,使它们能够在 real-world environments 中 reliable scale。下一节中,我们将探索 intelligent semantic metadata 如何成为连接 raw reasoning power 和 production readiness 的关键桥梁。

Metadata Readiness for Agentic AI Systems

构建一个 AI agent 并不难。然而,那只是开始。Enterprise organizations 坐拥一座尚未开发的 knowledge goldmine。正如第 5 章所讨论的,行业估计显示 80–90% 的 enterprise data 以 unstructured formats 存在——documents、images、presentations 和 files,这些是 traditional AI systems 很难有效利用的内容。

The Challenges of Scale and Complexity

这个 challenge 的 scale 令人震惊。典型 enterprise 管理着从 tens of terabytes 到 multiple petabytes 的 unstructured data,反映出几十年累积的 institutional knowledge,并对应数以亿计——在某些情况下甚至超过 quadrillion——的 individual files。这些不是 abstract projections,而是我们在多个 industries 中 firsthand 见过的现实。

在许多情况下,这个 organizational intelligence 的巨大 reservoir 仍然 untapped,并未为 AI consumption 做好准备。

The complexity within

挑战远不止 volume 本身。这些 files 覆盖 typical enterprise formats 的完整 spectrum:

  • Office documents,例如 Word(.docx)、Excel(.xls)、PowerPoint(.ppt)files。
  • Portable formats,例如 PDFs、plain-text files 和 compressed archives(.zip)。
  • Legacy 和 specialized formats,例如 proprietary engineering files 和 scanned documents。

更关键的是,这些 files 中的 content 往往无法简单分类。一个 enterprise repository 可能同时包含:

  • Hand-drawn engineering sketches
  • Medical imaging(chest X-rays、MRIs)
  • Factory process documentation
  • Support manuals
  • Complex data tables
  • Handwritten notes and annotations
  • Standard textual narratives

这种 heterogeneity 是 enterprise unstructured data 的 authentic composition,也给试图 extract actionable insights 的 AI systems 带来了 formidable obstacle。

Why traditional approaches fall short

为了让 AI agents 交付 meaningful business value,它们必须理解的不只是 data exists,还要理解这些 data 在 context 中意味着什么。Traditional RAG pipelines 和 vector stores 对 well-structured content 非常强大,但很难为 agents 提供回答 complex enterprise questions 所需的 nuanced context。它们 retrieve fragments,但并不 comprehend relationships。

A new paradigm: Intelligent semantic metadata

这就是 intelligent semantic metadata 登场的地方。它是一种面向 enterprise data management 的 transformative approach,弥合 raw technical artifacts 与 meaningful business understanding 之间的 gap。

它不是把 metadata 当作 passive catalog of file attributes,而是构建 rich、interconnected layers of semantic meaning,使 AI agents 能够:

  • 跨 fragmented repositories discover relevant data。
  • 在 proper business context 中 interpret content。
  • Reason over 跨 documents、systems 和 domains 的 relationships。

这个领域仍在 emerging,而我们在下一节提出的 pattern,来自我们在 production environments 中观察到的早期但 compelling successes。接下来的内容不是 theoretical,而是由 real-world implementation 和 measurable outcomes 支撑。

Pattern: Leveraging Raw Files Directly

许多 enterprises 的 use cases 更希望或要求 AI workloads 直接在 native formats 的 files 上运行,而不迁移到 specialized data stores。

一线现实是:

  • Enterprise data 以 native formats 存在,例如 PDFs、CSVs、Word documents、compressed archives、MIME files 等,并分布在 distributed sources 中。
  • 由于各种原因,将所有 files embedding 到 vector store 并不是 option。
  • 单独来看,file characteristics 通常是 manageable 的——我们在一些 organizations 的分析显示,平均每个 file 少于 20,000 tokens,约 40 页。

Why organizations choose this path

Customers 越来越多地寻找能够 in place query raw files 的 solutions,而不希望将 data copy 到 secondary systems,或迁移 content 到 vector databases。驱动因素各不相同,但我们最常见的一些包括:

Security and compliance

Sensitive data 不能离开 controlled environments。

Cost

Embedding 并存储 billions 到 trillions of vectors 的成本过高。

Unproven at scale

Vector stores 作为 data stores 尚未在如此多样和如此大规模下被充分证明。

Operational simplicity

避免再引入一个 data store,可以降低 architectural complexity。

Data freshness

In-place access 消除了 synchronization lag。

The emergence of intelligent semantic metadata

随着 agentic AI systems 增多,organizations 面临一个共同 imperative:引导 AI agents 导航 vast unstructured data landscapes,traverse 到所需 precise documents,并 extract accurate answers。

这一 imperative 催生了 intelligent semantic metadata layer 的概念——一个 rich、interconnected map of enterprise content,它告诉 AI systems 的不只是 data 在哪里,还包括它意味着什么,以及它如何与其他 knowledge assets 相关。

一个类比很有启发:正如 Hive Metastore 会引导 processing engines 在 traditional data lake 中定位正确 data files,intelligent semantic metadata layer 会引导 AI agents 在 scale 上 discover、interpret 并 reason over unstructured content。

接下来我们探索 intelligent semantic metadata 如何将 enterprise data 从 dormant archive 转变为 active knowledge asset。

Building Data-Aware Agents Through Intelligent Semantic Metadata

无论 organization 是直接在 raw files 上运行,还是增强 existing vector database,intelligent semantic metadata layer 都作为 connective tissue,将 isolated documents 转换为 navigable knowledge graph。它提供一种 unified architectural approach,可同时处理这两类 enterprise patterns。

该层建立在 knowledge graph technology 之上,创建 enriched metadata foundation,引导 AI agents 和 workloads 找到 precise information。关键是,它不需要 wholesale data migration、rearchitecture 或放弃 existing infrastructure investments。

结果是一个 enterprise content 的 navigable semantic map——它不只是知道 data reside 在哪里,还理解 data 意味着什么、如何连接,以及为什么对 specific business questions 重要。请看图 6-3,它描绘了 semantic metadata layer 的 high-level functionality。正如 “Before” 部分所示,在 content 通过这一层之前,你拥有的是一组 isolated documents,AI agents 需要逐个处理,才能判断每个 document 包含什么,以及是否与当前 task 相关。

image.png

图 6-3:Intelligent semantic metadata layer 如何工作

当 content 通过 semantic metadata layer 时,AI application 可以读取每个 document、extract key information,并将其映射到 graph 的 properties 中,我们会在 “From Raw Content to Semantic Intelligence: Constructing the Metadata Layer” 中更详细讨论。Existing 和 future AI agents 随后可以 traverse graph,快速识别哪些 documents 与它们正在执行的 task 相关。这在图 6-3 的 “After” 部分中展示。

Core capabilities

Intelligent semantic metadata layer 提供五项 foundational capabilities,改变 AI systems 与 enterprise data 交互的方式:

Contextual relationship mapping

捕获 documents、data assets 和 business entities 之间 explicit 和 inferred relationships,使 AI agents 可以 traverse connections,而不是孤立搜索。

Intelligent classification and semantic tagging

使用 domain-aware classification models 自动分类 content,应用反映 business meaning 而非 technical attributes 的 semantic tags。

Hierarchical business taxonomy

维护 structured taxonomies,映射 organizational knowledge domains、product hierarchies、regulatory frameworks 和 operational categories。

Embedded semantic links

直接在 node properties 中存储 semantic connections,支持 rich graph traversal,而不需要昂贵的 runtime inference。

Ontology mapping and source lineage

将 content 与 enterprise ontologies 对齐,同时保留 full lineage,记录 data 从哪里来、如何 transformation,以及哪些 systems 仍然 authoritative。结合起来,这些 capabilities 创建了一种 living knowledge architecture,它会与 enterprise 一起演进,而不是成为随时间衰减的 static index。

Operational efficiency gains

除了 semantic richness,intelligent semantic metadata layer 还带来可衡量的 operational benefits,直接影响 cost、performance 和 user experience。这些包括:

Direct graph answers

对于相当一部分 queries,knowledge graph 本身包含足够 context,可以直接返回 answers,完全不需要 downstream document retrieval、chunking 或 LLM processing。这会大幅降低 common question patterns 的 latency 和 computational costs。我们会在 “Example Implementation: Leveraging Raw Files Directly” 中看到它如何实际工作。

Intelligent graph traversal

对于需要 source documentation 的 complex queries,metadata layer 支持 precise traversal 到 relevant documents,或在 large files 情况下 traversal 到 specific document chunks。AI agents 通过 navigation semantic relationships 来定位 authoritative sources,提高 accuracy 和 explainability。

Reduced computational overhead

通过在 metadata layer 进行 filtering 和 targeting retrieval,organizations 显著降低:

  • Token consumption,因为 LLMs 处理更少 irrelevant chunks。
  • Embedding operations,因为使用 selective vectorization,而不是 exhaustive indexing。
  • Response latency,因为 intelligent routing 支持更快 time-to-answer。

The value proposition

总结来说,表 6-1 从几个关键维度比较了 traditional RAG-based search approaches 与 intelligent semantic metadata layer。

表 6-1:RAG-based search 与 semantic metadata layer 对比

DimensionTraditional approachWith intelligent semantic metadata layer
Data migrationRequiredOptional——works in place
Retrieval precisionSimilarity-basedContext-aware traversal
Query resolutionAlways requires LLMMany queries answered directly
ScalabilityDegrades with volumeMaintains accuracy at scale
ExplainabilityOpaque embeddingsTraceable lineage and relationships

为了更具体一些,下一节会看一个 practical example,说明 intelligent semantic metadata layer 如何工作。

Example Implementation: Leveraging Raw Files Directly

考虑一个场景:AI agent 需要回答 healthcare / medical field 相关的问题,数据 corpus 跨越数百万 files。我们用于 illustration 的 example user query 是:

QUESTION: "What medications were prescribed by doctors, and what are the specific 
instructions for each?"

AI agent steps

AI agent 使用 semantic metadata 作为起点,通过 graph database MCP server 访问它,以 discover available schema。为了演示,我们使用 Amazon Neptune 作为 semantic graph database,并逐步解释 agent behavior:

  1. Agent 首先对 semantic metadata 运行 schema discovery:
get_graph_schema {}

这会揭示一个 rich healthcare data model,其中包含不同 node types,包括 Doctor、Prescription、Medication、Dosage、Patient 和 Healthcare_Provider,并通过多种 relationship types 相互连接。

Schema 暴露了将指导 search 的关键 relationship patterns。例如:

Doctor → PRESCRIBED_BY → Prescription
Prescription → CONTAINS → Medication
Medication → HAS_DOSAGE → Dosage

这种 initial reconnaissance 非常关键——如果不理解 graph structure,agent 就会在可能数百万 nodes 中盲目搜索。Schema 提供了第一层 trust:理解存在什么 data,以及它是如何 organized 的。

  1. 接下来,agent 检查 medications 如何连接到其他 entities。注意,modern frontier models 能够以高 accuracy 生成这样的 code:
g.V().hasLabel('Medication').limit(1)
  .bothE()
  .project('label','direction','otherVertex')
  .by(label())
  .by(__.choose(__.inV().hasLabel('Medication'), 
                constant('out'), 
                constant('in')))
  .by(__.otherV().label())

Result:

[  {"label": "PRESCRIBED", "direction": "out", "otherVertex": "Patient"},  {"label": "PRESCRIBED", "direction": "out", "otherVertex": "Patient"},  {"label": "CONTAINS", "direction": "out", "otherVertex": "Prescription"}]

这揭示了正确 traversal pattern:Medications 拥有来自 Prescriptions 的 incoming CONTAINS edges,而不是 outgoing edges。

  1. 在识别出正确 relationship direction 后,agent 构造 refined query,从 Medications 反向 traversal 到 Doctors:
g.V().hasLabel('Medication').as('medication')
  .in('CONTAINS').hasLabel('Prescription').as('prescription')
  .in('PRESCRIBED_BY').hasLabel('Doctor').as('doctor')
  .select('doctor','medication','prescription')
  .by(valueMap('name:String','prescribing_doctor:String').fold())
  .by(valueMap('medication_name:String','dosage:String',
               'frequency:String','s3FilePath').fold())
  .by(valueMap('prescriptionDate:String','s3FilePath').fold())

Result: Success! The query returned:

{
  "doctor": {
    "name:String": ["Dr. Soey"],
    "prescribing_doctor:String": ["50 813-263-3776"]
  },
  "medication": {
    "medication_name:String": ["200mg"],
    "dosage:String": ["3 times a day"],
    "frequency:String": ["Avoid on an empty stomach"],
    "s3FilePath": ["s3://.../Doc2-Masked.docx"]
  },
  "prescription": {
    "s3FilePath": ["s3://.../Doc2-Masked.docx"]
  }
}

这建立了完整的 trust chain:Doctor → Prescription → Medication,并且每个 node 都可以通过 s3FilePath trace 到 source document,确保 data provenance。

  1. 为了获取回答问题所需的所有 files,agent 查询所有 unique file paths,利用上一步确定的 filter:
g.V().or(hasLabel('Medication'),
         hasLabel('Prescription'),
         hasLabel('Doctor'))
  .values('s3FilePath')
  .dedup().fold()

Result: Three unique source files identified:

[  "s3://.../Doc2-Masked.docx",  "s3://.../Mock data.xlsx",  "s3://.../test_docs/Doc3.docx"]

这个 query 建立 data lineage——agent 现在知道哪些 source documents 贡献了 knowledge graph,从而为 compliance 和 trust 创建 audit trail。

  1. 建立 provenance 后,agent 下载 source files,以 verify 和 enrich graph data:
aws s3 cp "s3://.../Doc2-Masked.docx" ./Doc2-Masked.docx
aws s3 cp "s3://.../Mock data.xlsx" ./Mock-data.xlsx

6. 然后,agent 动态 interpret files,并为每个 file extract 相关 context,以得到 desired output:

ANSWER:
Contains 100 patient records with prescribed medications including:
• **Ibuprofen** - prescribed to multiple patients for Hypertension and Asthma
• **Aperin** - for Asthma, Obsessive Compulsive Disorder, Anxiety
• **Amoxicillin** - for Hypertension, Asthma, Anxiety
• **Atorvastin** - for PTSD, Seizure Disorder, Hypertension, Obsessive 
  Compulsive Disorder
• **Insulin** - for Asthma, Anxiety, PTSD, Seizure Disorder
• **Diazepam** - for PTSD, Obsessive Compulsive Disorder, Seizure Disorder, 
  Anxiety
• **Pandac** - for Hypertension, PTSD, Obsessive Compulsive Disorder, Asthma, 
  Anxiety
• **Warfarin** - for Asthma, Obsessive Compulsive Disorder, Anxiety, PTSD, 
  Seizure Disorder
 
# Summary of Medications Prescribed by Doctors:
 
From the knowledge graph and source files, I found:
 
Dr. Moey prescribed:
• **Medication**: Ibuprofen (200mg)
• **Dosage**: 3 times a day
• **Instructions**: Avoid on an empty stomach
• **Contact**: 77 123-456-789
 
The Excel file shows 100 patients with various medications prescribed, but 
the specific doctor names and detailed instructions for each medication were 
only found in the graph for Dr. Moey's Ibuprofen prescription.

注意,100 patients 的 count 是直接使用 graph 中的 metadata 得出的,其中每个 patient 都是一个 node,并不需要实际 file processing。

然而,agent 关于 Dr. Moey prescribed Ibuprofen 及其 specific instructions 的报告,并不只是从 graph 中 extract 出来的。这个 information 是:

  • 通过 systematic relationship traversal 被 discovered。
  • 被 linked 到 source file Doc2-Masked.docx
  • Mock data.xlsx 中的 patient records 做了 cross-reference。
  • 通过 multiple query approaches 被 verified。

The intelligence in the approach

这种 retrieval 之所以智能,在于 agent 的 systematic methodology:

Plan strategically:先执行 schema discovery,以最小化 unnecessary queries。

Adapt dynamically:当 queries 失败时,用 targeted exploration 诊断原因。

Think bidirectionally:测试 relationship directions,而不是做 assumptions。

Establish provenance:将每一条 data trace 回 source。

Verify comprehensively:将 graph data 与 source documents 做 cross-reference。

Optimize efficiency:在 downloading 前使用 deduplication 识别 unique files。

添加到 graph nodes 和 edges 的 properties 越丰富,semantic metadata 就越 intelligent,使 agents 能够跳过 backend LLM calls 和 file downloads,直接从 graph 中回答 queries。

Example 6-1 展示了一个 sample patient node,也就是文件 Mock data.xlsx 中的 entities 之一,以及它在 JSON format 中的 properties,代表该 entity 的 metadata。

Example 6-1:Graph database 中 patient node 的 JSON representation

{
  "n": {
    "~id": "patient_P0003",
    "~entityType": "node",
    "~labels": [
      "Patient"
    ],
    "~properties": {
      "medical_record_number:String": "MRN-████",
      "treatment_start_date:String": "2025-03-07",
      "s3FilePath": "s3://████kspace009/████test-data/████chill/█████_01_PRODUCTION/
      Mock data.xlsx",
      "national_id:String": "████████600",
      "phone_number:String": "001-373-489-████",
      "home_address:String": "████████ Forest Suite 240, ████ Laura, KY 92825",
      "name:String": "Raj ███████ali",
      "date_of_birth:String": "2006-██-█1",
      "email_address:String": "raj.████████ali@example.com"
    }
  }
},

图 6-4 是 nodes 和 edges 如何连接到 adverse condition 的 graphical representation。每个 relationship 的 direction 都被标示出来,这有助于 agents 更清楚理解 relationships,从而 formulate 更 precise queries。

image.png

图 6-4:展示 inbound 和 outbound traversals 的 node–edge relationships

From Raw Content to Semantic Intelligence: Constructing the Metadata Layer

我们已经说明了 intelligent semantic metadata layer 能实现什么,以及为什么它对 production-grade AI systems 重要。但还有一个关键问题尚未回答:如何构建这个 layer?

前面描述的 seamless navigation、contextual retrieval 和 direct-answer capabilities 之所以可能,是因为有人——或者某种系统——从 raw enterprise content 中构建了一个 richly connected knowledge structure。这正是 engineering 与 vision 交汇的地方。

本节中,我们将探索一种 architecture approach,它将 unstructured data 转换为 AI systems 可以 reason over 的 coherent knowledge fabric。你将学习如何从 outside in 设计 graph-based semantic metadata layer:从 agents 需要回答的问题开始,塑造 flexible schema,其中包含 nodes、relationships 和 properties;然后通过 automated metadata extraction、robust loading 和 validation pipelines,以及 continuous feedback loops,incrementally enrich graph,使 model 始终与 evolving business needs 对齐。

Start with the end in mind

构建 semantic metadata layer 最有效的 approach,是从 consumption patterns 反向推导。在设计 schemas 或处理 files 之前,organizations 必须对两个 foundational elements 有清晰理解:

What data exists

也就是 enterprise systems 中 source data 的 formats、volumes、content types 和 distribution。

What questions will be asked

也就是 AI agents 必须支持的 queries、use cases 和 decision patterns。

这种 consumption-first mindset 确保 metadata schema 中的每个 element 都有 purpose——捕获能直接支撑 users 所需 answers 的 entities、relationships 和 attributes。

Designing the graph schema

在 clarifying use cases 后,下一步是设计 graph database schema。这个 schema 定义:

Node types

被表示的 entities,例如 documents、people、products、processes、concepts。

Relationship types

Entities 如何连接,例如 authored by、references、belongs to、derived from。

Properties

存储在 nodes 和 edges 上的 attributes,例如 dates、classifications、confidence scores、source lineage。

Embracing iteration over perfection

不存在适合所有 use cases 的 universal schema——这是一种 feature,而不是 limitation。Graph databases 具有 relational structures 无法比拟的 inherent flexibility。Key characteristics 包括:

Schema flexibility

Nodes 和 relationships 可以演进,而不会破坏 existing structures。

Additive enrichment

随着 understanding 加深,可以向 existing nodes 添加 new properties。

Use case expansion

随着 new use cases 出现,可以引入 additional node types 和 relationships。

这意味着 schema design 永远不是 one-and-done task。最成功的 implementations 会将 metadata layer 视为 living asset,随着 organization 对 data、users 和 AI applications 了解加深,持续 iterative refinement。每次 iteration 都会提升 accuracy、扩大 coverage,并增强 usability。

NOTE

抵制一开始就试图设计 “perfect” schema 的诱惑。先从一个 focused schema 开始,覆盖最高优先级 use cases,然后随着 requirements 成熟,有意识地演进。

Extracting and generating metadata

一旦 schema 定义完成,下一个 challenge 是用从 source files 提取的 data 填充它。这正是 intelligent automation 变得 essential 的地方。Practical approach 是单独处理每个 file,以 extract schema 所需的 entities、relationships 和 attributes。Workflow 通常遵循图 6-5 所示 pattern。

image.png

图 6-5:Metadata extraction pipeline

Leveraging prompt engineering

如图 6-5 所示,现代 extraction pipelines 利用 large language models,并通过 carefully crafted prompts 引导它们生成 desired metadata。Model 会:

  • 识别与你的 domain 相关的 named entities。
  • 按 business taxonomies 对 documents 分类。
  • Extract concepts、people 和 processes 之间的 relationships。
  • Generate semantic tags 和 summaries。
  • Output conforming to graph schema 的 structured data。

Prompt engineering process 本身也会成为 reusable asset,并随着时间推移被 refine,以改善 extraction quality,同时适配 corpus 中不同 content types。

Handling large files

Enterprise documents 的 size 差异巨大。表 6-2 列出了超过 practical processing limits 的 larger files 常见 challenges,以及处理它们的 straightforward strategies。

表 6-2:Handling large files 时的问题与解决方案

ChallengeSolution
File exceeds token limitsSplit into logical sections(chapters、pages、segments)
Context loss from splittingTreat each segment as an independent unit with parent-file linkage
Relationship continuityMaintain explicit connections between segments and source documents

每个 segment 在 extraction 期间会独立处理,然后在 graph 中通过 relationships 重新连接,从而保留 document integrity 和 navigational context。

Loading and activating the metadata layer

最后一步是将 extracted metadata 转换为 operational knowledge graph。这包括:

Validation:确保 extracted data 符合 schema constraints 和 quality thresholds。

Ingestion:将 nodes、relationships 和 properties 加载到 graph database。

Indexing:配置 indexes,以支持 efficient traversal 和 query performance。

Activation:将 metadata layer 连接到 AI agents 和 application workloads。

加载完成后,由 knowledge graph 驱动的 intelligent semantic metadata layer 会引导 AI systems 找到它们需要的 precise information。

The iterative lifecycle

值得强调的是,这个 process 是 cyclical 的,而不是 linear 的,如图 6-6 所示。

image.png

图 6-6:Enriching semantic metadata 的循环性质

随着 AI applications 利用 metadata layer,feedback loops 会揭示:

  • Missing entities 或 relationships。
  • Classification inconsistencies。
  • 需要 schema evolution 的 new question patterns。
  • Deeper enrichment 的 opportunities。

每个 cycle 都会强化 foundation,逐步提升 AI application accuracy、coverage 和 user trust。然而,accuracy alone 并不能保证成功。Production readiness journey 的最后一个里程碑,是确保 agentic applications 已经在 operational 层面准备好以 scale 运行。

这绝非简单任务。Scaling AI systems 引入的 complexity 远超 model performance,覆盖 infrastructure resilience、monitoring、security、cost management 和 graceful failure handling。下一节提供 comprehensive guide,涵盖 confidently deploy 和 operate agents at scale,实现真正 production readiness 所需考虑的一切。

Key Capabilities for Production Readiness for Agentic AI Platforms

实现 agentic AI applications 的 production readiness,需要有意识地评估几个关键 capabilities。每个 capability 都在确保 system 在 scale 下 reliable、secure、efficient 运行方面扮演不同角色。下面的 framework 概述了准备 production deployment 时需要评估的七个关键 areas。

必须认识到,并不是每个 application 都需要每一项 capability。你的 specific use case、organizational requirements 和 risk tolerance 会决定哪些 areas 值得最深入投资。目标不是实现所有东西,而是做出 informed decisions,判断你的 application 在 production 中真正需要什么才能成功。

Core runtime and deployment

任何 production-grade agent system 的 foundation 都始于 robust compute infrastructure。这包括用于 elastic scalability 的 serverless runtime options、支持超过 typical request timeouts 的 long-running workloads、确保 secure multitenant operations 的 session isolation,以及横跨 cloud native 和 self-hosted environments 的 deployment flexibility。

Framework and protocol interoperability

随着 agent ecosystem 成熟,interoperability 已经成为 essential capability。这个能力区域覆盖对 multiple agent frameworks 的支持,例如 Strands、LangGraph、LlamaIndex、Google ADK、OpenAI Agent SDK 等;遵循 MCP 等 emerging protocol standards 以支持 tool integration;并支持 agent-to-agent(A2A)communication patterns。结合起来,这些能力支持 framework-agnostic deployments,并让 architecture 能抵御 ecosystem 快速变化带来的风险。

Tool integration and execution

Agents 的很大价值来自它们与 external systems 交互的能力。这个 capability 涵盖 API gateway transformations、popular services 的 prebuilt connectors、web-based tasks 的 browser automation、sandboxed code execution environments,以及 file 或 document processing pipelines。

Memory and knowledge management

Effective context management 是 capable agent 和真正 intelligent agent 的区别所在。这个 area 关注 application 如何处理 session 内的 short-term memory、跨 sessions 的 long-term memory、用于 contextual retrieval 的 semantic search、通过 RAG 进行 knowledge retrieval,以及支持从 user prompts 中 dynamic、in-context learning 的 custom stores。

Security and compliance

Enterprise deployments 需要严格 security controls。这个 capability area 包括 identity 和 token management、用于 secure authorization 的 OAuth 2.0 flow support、与 enterprise identity providers 的 integration、VPC 和 private network deployment options,以及用于执行 safety boundaries 和 policy compliance 的 configurable guardrails。

Observability and quality assurance

你无法运营你看不见的东西。这个 capability area 通过 OpenTelemetry-based observability、real-time dashboards、visual workflow debugging tools、用于 continuous quality assurance 的 evaluation 和 testing frameworks,以及带 versioning 的 agent registries 来管理 deployments over time,从而确保对 agent behavior 的 comprehensive visibility。

Multi-agent and interaction capabilities

随着 agent architectures 变得更 sophisticated,多个 specialized agents 之间的 orchestration 变得关键。这个 capability area 覆盖 multi-agent coordination patterns、支持 oversight 和 intervention 的 human-in-the-loop workflows,以及用于 real-time user interactions 的 streaming response capabilities。

Leading AI Agent Platform Choices

AI agent platforms 的 landscape 近年来已经迅速成熟,几个 providers 成为 frontrunners,提供我们刚刚描述的部分或全部 core capabilities。本节基于我们在 2024–2025 年与数十家不同规模 enterprises 合作的经验,包括许多 Fortune 500 companies,对今天可用的 leading options 在所有这些 capability areas 上做 comparative overview。我们比较五个平台:

  • Amazon Bedrock AgentCore
  • Google Vertex AI
  • Azure AI Foundry
  • LangSmith Deployment(formerly LangGraph Platform)
  • CrewAI Enterprise

不过需要提醒一句:这里的 assessment 是本书写作期间捕获的 point-in-time snapshot。AI agent ecosystem 正以 extraordinary pace 演进——new features、pricing models 和 capabilities 会定期推出。今天成立的判断,明天可能会变化。我们鼓励你在为 production environment 做 architectural 或 vendor decisions 前,对照最新 offerings 验证这些 comparisons。

Core Runtime and Deployment Strategy

为了为 agentic applications 选择正确的 core runtime 和 deployment strategy,比较 leading platforms 如何处理 execution、isolation 和 framework integration 会很有帮助。表 6-3 总结了关键 characteristics。

表 6-3:Leading agentic AI platforms 的 runtime 和 deployment characteristics

PlatformDeployment modelMax runtimeSession isolationFramework support
Amazon Bedrock AgentCoreServerlessUp to 8 hours(longest)Complete microVM isolationAny framework
Google Vertex AIServerlessNot explicitly bounded(resource-based)Managed runtime + sandboxed execution(VPC-SC optional)ADK、LangGraph、LangChain(full);CrewAI、others via custom templates
Azure AI FoundryManaged serviceDepends on underlying servicesDepends on hostingFramework-agnostic(Azure-native tooling)
LangSmith DeploymentCloud / hybrid / self-hostedDepends on deploymentDepends on hostingLangGraph-native;extensible to others
CrewAI EnterpriseCloud / self-hosted / on-premisesNot explicitly bounded;long-running supportedLogical / agent-levelCrewAI only

AgentCore 的 eight-hour extended runtime capability 尤其值得注意,它适合需要持续处理数小时的 complex、multistep agent tasks。Example use cases 包括 procurements、order management and logistics、quote generation 和 inventory management,其中两个或更多 interdependent tasks 可能相隔数小时处理。

Framework, Tool Integration, and Protocol Support

要理解每个平台如何插入 emerging open tooling ecosystem,仅比较 core runtime 还不够,还需要考察 protocol、gateway 和 execution capabilities。表 6-4 总结了 framework-level integration。

表 6-4:Open framework integration comparison

PlatformMCP supportA2A protocolAPI gatewayCode execution
Amazon Bedrock AgentCoreYes, nativelyYesLambda / API conversionSandbox environment
Google Vertex AIYes, via ADKYes100+ connectors、ApigeeSandbox environment
Azure AI FoundryVia toolsVia toolsLogic Apps、Azure FunctionsCode interpreter
LangSmith DeploymentVia toolsNoCustom integrationVia callbacks
CrewAI EnterpriseYesNoIntegration hubVia agents

Memory and Knowledge Management Capabilities

不同平台的 memory management capabilities 差异显著:

Amazon Bedrock AgentCore 提供 dual-layer memory——short-term memory(STM)用于 immediate conversation context,long-term memory(LTM)用于 cross-session persistence——在 zero infrastructure management 的前提下提供 industry-leading accuracy。

Google Vertex AI Agent Engine 包含 Sessions,用于存储 individual user–agent interactions,以及 Memory Bank,用于 personalized agent interactions。Example Store 在写作时处于 preview 阶段,支持 dynamic retrieval of few-shot examples 以提升 performance。

Azure AI Foundry 提供 built-in conversation state management,自动处理 thread management 和 retrieval of conversation history,避免构建 custom thread management systems。

LangSmith Deployment 提供 checkpointing 和 memory store,并支持 TTL,用于 conversation threads 和 long-term memory,以及基于 expiration 的 cleanup。

CrewAI Enterprise 包含 persistent memory 和 conversation buffer capabilities,并为 complex workflows 中的 memory management 提供 self-healing features。

Security and Compliance Features

虽然所有主要 providers 都提供 enterprise-grade security,但 AgentCore 与 existing identity providers 的 integration(避免 user migration)以及用于减少 consent fatigue 的 secure token vault,具有明显优势。Google Vertex AI 通过 Security Command Center 提供 Agent Engine Threat Detection,增加 proactive threat investigation capabilities。表 6-5 比较了 authentication、identity 和 compliance features。

表 6-5:Leading agentic AI platforms 的 security 和 compliance features

PlatformAuthenticationIdentity featuresCompliance
Amazon Bedrock AgentCoreIAM、OAuth 2.0、CognitoToken vault、permission delegationVPC、PrivateLink
Google Vertex AIIAM、VPC-SC、CMEKAgent identity(preview)HIPAA、data residency
Azure AI FoundryEntra ID、RBAC、OBOKeyless setupEnterprise conditional access
LangSmith DeploymentCustom OAuthAPI authenticationVaries by deployment
CrewAI EnterpriseEnterprise SSOIP protectionHIPAA、SOC 2

Observability and Quality Assurance Support

所有平台都支持 OpenTelemetry,用于 standardized observability:

Amazon Bedrock AgentCore 提供由 Amazon CloudWatch 支撑的 comprehensive dashboards,支持 agent workflows 的 real-time visibility、automatic X-Ray tracing 和 Transaction Search configuration。

Google Vertex AI 与 Cloud Trace、Cloud Monitoring 和 Cloud Logging 集成,完整 tracing 支持 OpenTelemetry standards。

Azure AI Foundry 提供 OpenTelemetry-based tracing,并与 Application Insights 集成,为每个 agent decision 提供 conversation-level visibility 和 telemetry。

LangSmith Deployment 原生集成 LangSmith,支持 visual debugging,并对 agent trajectories、branching logic 和 retry flows 提供 detailed visibility。

CrewAI 在其 core framework 中不包含 native OpenTelemetry export,需要 third-party instrumentors。然而,CrewAI Enterprise platform 提供 comprehensive built-in dashboards、tracing 和 monitoring。它与 10+ observability tools 的 integration ecosystem,使其在 enterprise deployments 中非常 flexible。

Summary

从 AI prototype 到 production-ready system 的 journey,要求的不只是 technical proficiency——它需要我们在 data、context、reasoning 和 operational excellence 方面做出 fundamental shift。

本章已经确立:data 是 AI application 的 lifeblood——但 data quality 并不是 absolute。它是 context-dependent 的,由 business objectives 塑造,并且最好通过 modular design 来服务,以在 preserving flexibility 的同时优化 performance。我们通过 systematic segmentation、parallel inference 和 intelligent organization strategies 处理了 scale 下的 context management,防止 large inputs 降低 output quality。

我们探索了 automated reasoning,它是一项强大但需要校准的 capability。Chain-of-thought、tree-of-thought 和 graph-of-thought patterns 为 complex problems 提供 structured approaches,但 examples 也展示了 reasoning tokens 会带来真实的 latency 和 cost trade-offs,需要 careful tuning。

Intelligent semantic metadata layer 成为一种 transformative pattern,适用于那些面对 petabytes of unstructured data 的 enterprises。该 approach 建立在 knowledge graph technology 之上,使 AI agents 能够在 scale 上 discover、interpret 并 reason over content——它交付的不只是 accuracy,还有基于 verifiable source documents 的 explainability 和 trust。

最后,我们提供了一个 comprehensive framework,用于评估七个 critical capability areas 上的 operational readiness——从 core runtime 和 security,到 observability 和 multi-agent orchestration——并对当前 leading platforms 进行了 comparative analysis,以支持你的 architectural decisions。

Production readiness 不是一个 destination,而是一种 continuous practice。每一次 iteration 都会强化 foundation、提升 accuracy,并加深 user trust。这里提出的 techniques 来自 real-world implementations,提供了已经被证明可以弥合 AI potential 和 production reality 之间 gap 的 practical approaches。

你的 data 是一种 strategic asset,值得 deliberate architecture。把这件事做对,后面的一切都会随之而来。

Blueprint 已经在你手中。现在,是时候 build 了。