随着 organizations 快速采用 generative AI applications 来转型其 operations,一个关键挑战随之出现:如何确保这些强大的 systems 在安全、可靠、负责的前提下运行,同时保持支撑其有效性的 data integrity?AI systems 正在处理大量 structured 和 unstructured data,这使 data governance 从传统 IT concern 上升为 mission-critical capability,甚至可能决定 AI initiatives 的成败。不同于为 structured databases 设计的 conventional data management approaches,AI applications 需要一种 fundamentally different governance framework——它必须能够处理 unstructured data 的复杂性,管理 large language models 带来的独特风险,并确保符合不断演进的 regulatory requirements。
本章提供一份 comprehensive roadmap,用于实施专门面向 generative AI applications 设计的 robust data governance、security 和 orchestration frameworks。你将了解 AI data governance 与 traditional approaches 的区别,并探索构成 effective AI governance operating model 的九个 fundamental components,从 data stewardship 和 metadata management,到 data quality assurance 和 security protocols。本章会深入 responsible AI principles,提供 practical guidance,说明如何在 AI systems 中实施 fairness、transparency、accountability、privacy protection、reliability 和 human oversight。你将学习保护 sensitive information、实施 content filtering 和 topic restrictions,以及在整个 AI pipeline 中确保 end-to-end data protection 的 hands-on techniques。
除了 governance 和 security,本章还将帮助你掌握通过 large language model operations(LLMOps)中的 operational practices,有效 orchestrate complex AI workflows 所需的知识。我们会探索面向 retrieval-augmented generation(RAG)systems 和 agentic AI frameworks 的各种 orchestration patterns,并提供 practical code examples 和 implementation strategies,使用 Strands Agents 等现代 orchestration tools。无论你是在构建 simple linear RAG applications,还是 sophisticated multi-agent systems,本章都会提供必要的 technical foundation 和 best practices,帮助你部署不仅 powerful 和 efficient,而且 secure、compliant 和 trustworthy 的 AI applications。
Data Governance and Data Security for AI Applications
Data governance 和 security 已经成为 organizations 部署 AI systems 的关键支柱。本节中,我们将考察它们具体包含什么。
Data governance 是一种 structured approach,organizations 通过结合 technology、people 和 processes 来管理和使用 data。
Data security 包含用于确定哪些 data 可以被谁、在什么条件下查看的 strategies 和 controls implementation。这包括管理 access permissions,识别并保护 sensitive data,例如 personally identifiable information,实施 encryption 和 monitoring,并维护与 GDPR、HIPAA 和 SOC 2 等 frameworks 对齐的 regulatory 和 compliance postures。
Data governance 虽然 essential,但经常被视为 complex 和 challenging undertaking。也正因为其复杂性,它往往只被部分实施。Organizations 通常会启动独立 initiatives,评估完整 capabilities range,并只优先 rollout 其中少数能力。不过,过去五年左右,随着 organizations 越来越多地采用 data-first strategies,对 robust data governance 的需求变得更加明显。
这个领域仍在持续成熟,我们预计未来五年会出现显著进展。Data governance 的未来成功,很可能在于它能 seamless integration 到 data applications 中,成为内在 component,而不是一个 separate initiative。这种 evolution 已经可以在一些 basic data governance principles 中看到,例如 data quality checks、null value handling 和 data type validations,如今这些原则已经自然嵌入 data pipelines 的初始 development 中。
这种 organic integration 代表了一种转变:不再把 data governance 看作独立、沉重的 process,而是把它视为 data management lifecycle 的 integral part。随着这种趋势延续,data governance 很可能变得更加 streamlined、efficient 和 user-friendly,同时继续发挥确保 data integrity 和 compliance 的关键作用。
Data sovereignty 是 AI data governance 中另一个关键 consideration。随着 organizations 部署跨多个 regions 处理 data 的 AI systems,它们必须确保符合 local data residency 和 sovereignty requirements。不同 data protection regulations,例如 EU 的 GDPR、Brazil 的 Lei Geral de Proteção de Dados(LGPD),以及各种 Asia–Pacific frameworks,都对 data 可以存储、处理和传输的位置提出了具体规则。AWS 等 cloud providers 提供 data residency controls 和 regional service availability,帮助 organizations 满足这些 requirements,但 compliance 的最终责任仍然在 organization 自身。
虽然 data security 传统上被整合进更广义的 data governance framework,但在 AI 时代,它值得特别关注。以前所未有速度流入 vector stores、embedding models 和 knowledge bases 的 unstructured data,往往会绕过为 structured、well-cataloged data 设计的 conventional access controls 和 audit trails。如果在每个阶段没有 robust classification、lineage tracking 和 encryption,organizations 将面临重大的 compliance 和 breach risks,尤其是在 AI agents autonomous retrieve 并 act on 这些 data 的情况下。
这种强调反映了不断演进的 landscape:organizations 必须应对由 diverse data types、formats 和 sources 带来的复杂 security challenges,而这些数据正是 AI systems 的燃料。Data security 已经远远超越 compliance checkbox;在 AI-driven world 中,理解并实施 robust security measures,是维持 competitive edge、保护 intellectual property,并建立支撑 long-term AI adoption 的 trust 的关键。
我们先从 AI data governance 与 traditional data governance 的区别开始。
The AI Data Governance Operating Model
Traditional data governance 历史上主要聚焦 relational online analytical processing(OLAP)systems 中的 structured data,例如 data lakes 和 data warehouses。这种 approach 依赖一个围绕三个关键元素构建的 operating model:people、process 和 technology。
虽然 AI data governance 需要更 comprehensive 的 approach,覆盖 structured 和 unstructured data,但 traditional data governance 的 core building blocks,也就是图 4-1 中列出的 fundamental components,仍然适用。
图 4-1:AI data governance operating model
这个 holistic framework 的关键 components 包括:
Data stewardship
将 responsibility 分配给 individuals,也就是 data stewards,由他们在整个 lifecycle 中监督 structured 和 unstructured data 的 definition、quality、accessibility 和 integrity,确保 data 能在 organization 内被正确使用,同时保持与 organizational policies 和 regulations 的 compliance。
在实践中,data stewardship 是一个 dynamic function。Data stewards 最接近每个 data-producing domain 中 data 的 business context。他们决定某个 specific data domain 中哪些 components 应该被哪些 roles 访问,以及哪些 data assets 适合不同 consumers。Data stewards 会与 data engineering teams 合作,相应地准备 data,并代表 producing domain orchestrate data approval process。
Data quality management
通过 validation、cleansing 和 standardization,保持 data accurate、complete、consistent 和 timely 的 processes 和 controls,以确保 AI systems 可以基于 reliable data 进行 training 和 operation。
Metadata management
捕获、组织和维护关于 data 的信息,也就是 metadata,例如其 source、structure、lineage 和 usage,以支持所有 data types 的 transparency、traceability 和 effective governance。
Master data management(MDM)
一组 processes 和 tools,用于在 organization 范围内创建并维护 critical business data entities,例如 customers 或 products 的 single、consistent、accurate view,确保 structured 和 unstructured data 的 quality、accessibility 和 security。
Data lifecycle management
从 data 最初 creation 和 collection,到 storage、usage、archival,再到最终 deletion 的 end-to-end management,确保 data 保持 high-quality、secure,并符合 GDPR 和 CCPA 等 privacy regulations。
Data security
实施 policies、technologies 和 controls,以保护 data 免受 unauthorized access、breaches 和 misuse,包括 encryption、access controls 和 monitoring,并特别关注 AI systems 带来的 unique risks。它还包括对 data management practices、data usage 以及 governance policies compliance 的定期、系统检查,包括创建 audit trails,以追踪 structured 和 unstructured data 的 data access、changes 和 lineage。
Issue escalation and accountability
用于识别、报告和解决 data-related issues 的 formal processes,并配有明确定义的 roles 和 responsibilities,以确保及时解决,并对 data governance failures 或 breaches 建立 accountability。
Training and communication
持续的 education 和 awareness programs,确保所有 stakeholders 理解 data governance policies 和 best practices、AI 带来的新 risks 和 requirements,以及他们在维护 data quality、security 和 compliance 中的 roles。
这些 components 共同构成 robust AI data governance framework 的 foundation,确保 structured 和 unstructured data 都能以 responsible、secure,并与 organizational 和 regulatory standards 对齐的方式被管理。
Differences in Governance of Structured and Unstructured Data
虽然 data governance 的 fundamental components 对 structured 和 unstructured data 都保持一致,但值得注意的是,用于实施它们的 approaches 和 techniques 可能存在显著差异。AI governance 最容易偏离 traditional data governance 的 areas 是 data stewardship、metadata management、data quality 和 data security。这些领域共同构成 effective governance 的 strategic foundation:data stewardship 和 metadata management 使 AI systems 能正确 interpret 和 use data;data quality 确保 feeding AI systems 的 data 是 reliable 的;data security 则保护从 ingestion 到 inference 的整个 pipeline。接下来的 sections 中,我们会依次探索这些领域。
Data Stewardship and Metadata Management
Data stewardship 和 metadata management 紧密耦合。如前所述,data stewardship 通常由 data steward 承担,他们对 data 的 business use 有扎实理解。他们位于 data security 和 metadata management 的交叉点上——他们的责任是确保 technical metadata 被翻译为 business terms。这通常涉及构建一个可在 organization 范围内广泛使用的 business glossary。过去,这通常只是简单添加 short descriptions,并假设 human 会 review 这些 descriptions 并能理解它们。然而,为了让 AI agents 有效使用 business glossary,descriptions 必须既 verbose 又 concise,并且要精心构造,确保没有 overlapping definitions,并且 agents 能准确判断何时使用每个 data object。
Making Data Accessible for Humans and Agentic AI
请看表 4-1,其中展示了一个以 structured format 组织的 human gene dataset 的简化版本,通常 gene dataset 中还会有一些 additional columns,这里已经移除。可以想象它是 data lake 的一部分。假设你希望让 AI application 分析这张表,并回答与 drug discovery 相关的问题。然而,部分 column names,也就是这张表中的 technical metadata,可能会让 users 和 applications 都难以 interpret,从而很难理解每个 column 的含义,以及如何有效使用这些 data。
表 4-1:Human gene catalog
| geneid | genename | chr | strand | start | end | genesum | entrezid | genesyn | uniprot_accs |
|---|---|---|---|---|---|---|---|---|---|
| ENSG00000139618 | BRCA2 | 13 | + | 32315474 | 32400266 | Breast cancer type 2 susceptibility protein | 675 | ['FAD1', ‘FANCD1'] | ['P51587'] |
| ENSG00000141510 | TP53 | 17 | – | 7668402 | 7687550 | Tumor protein p53 | 7157 | ['P53', ‘BCC7'] | ['P04637'] |
| ENSG00000157764 | BRAF | 7 | + | 140719327 | 140924929 | B-Raf proto-oncogene | 673 | ['RAFB1'] | ['P15056'] |
| ENSG00000198786 | CFTR | 7 | – | 117120016 | 117308718 | Cystic fibrosis transmembrane conductance regulator | 1080 | ['ABCC7'] | ['P13569'] |
| ENSG00000121879 | EGFR | 7 | + | 55086714 | 55279321 | Epidermal growth factor receptor | 1956 | ['ERBB', ‘ERBB1'] | ['P00533'] |
为了让 structured data 对 users 和 AI applications 更 accessible 和 useful,必须由 data steward 开发 business glossary。这个 glossary 应使用从 business perspective 容易理解的 clear、descriptive terms,并说明每个 data element 何时、何地可以使用。Modern AI systems 依赖这类 glossaries 来 interpret 并 productive work with your data。
下面看看这样的 glossary 可能是什么样子。
Table description
这张表提供 human protein-coding genes 的 comprehensive catalog,集成来自主要 genomic databases 的 standardized identifiers 和 key biological attributes。每一行表示一个 unique gene,并包含其 genomic coordinates、official nomenclature、functional summaries、对 external resources 的 cross-references,例如 Ensembl、NCBI、OMIM、HGNC 和 UniProt,以及 known synonyms 和 canonical transcript information。这个 structure 支持 robust gene annotation、disease association studies,以及 research 和 clinical genomics 中的 cross-database integration。Genomic data table 中的每个 column 都有其 biological significance,并说明它如何以及何时可以使用。
Column definitions
geneid
Format:String,例如 ENSG00000139618
Description:来自 Ensembl database 的 unique gene identifier,格式为 ENSG + 11 digits。用于在 genomic databases 之间通用引用 genes。该 column 可用于与 Shet、missense tolerance data 和 transcript tables join。
genename
Format:String,例如 BRCA2、TP53
Description:由 HUGO Gene Nomenclature Committee(HGNC)批准的 official gene symbol。在 research 和 clinical contexts 中标准化 gene names,以保持 consistency。
chr
Format:Integer,例如 7、17
Description:gene 所在的 chromosome number。Humans 有 22 条 autosomes(1–22)和 2 条 sex chromosomes(X / Y)。
strand
Format:String,+ 或 –
Description:表示编码该 gene 的 DNA strand:
- = Forward / positive strand(5’ → 3')
– = Reverse / negative strand(complementary strand)
start
Format:Integer,例如 32315474、32400266
Description:基于 reference genome assembly,例如 GRCh38,标记该 gene 在 chromosome 上 start position 的 genomic coordinates。
end
Format:Integer,例如 32315474、32400266
Description:基于 reference genome assembly,例如 GRCh38,标记该 gene 在 chromosome 上 end positions 的 genomic coordinates。
genesum
Format:String,例如 “Breast cancer type 2 susceptibility protein”
Description:gene 的 concise functional summary,通常来源于 NCBI’s Gene database 或 UniProt database。使用该 column 可以理解 disease condition,从而更好地 filter 出 right gene of interest。
entrezid
Format:Integer,例如 BRCA2 的 675
Description:来自 NCBI’s Gene database 的 unique identifier。对 biomedical research 中 cross-referencing gene data 非常关键。
genesyn
Format:Array of strings,例如 BRCA2 的 ['FAD1', ‘FANCD1']
Description:gene 的 alternative names 或 historical symbols,例如 outdated symbols 或 aliases。
uniprot_accs
Format:Array of strings,例如 BRCA2 的 ['P51587']
Description:来自 UniProt database 的 primary protein accession numbers,引用该 gene 的 canonical protein product。
当为 organization 建立 glossary definitions 时,你可以灵活使用最适合需求的任何 tool。有些 organizations 选择开发 custom in-house solutions,另一些则利用 commercial platforms,例如 Collibra、Amazon SageMaker Catalog 或 Informatica Business Catalog。跨不同规模 organizations 的经验反复表明,没有任何 single tool 能提供 complete solution——每个工具都有自己的 strengths 和 limitations。真正的 effectiveness 来自合适 tools、skilled people 和 well-defined processes 的组合;technology alone 并不能保证 AI governance 成功。
Testing Our Tools
如前所述,AI systems 需要 clear instructions 来说明如何使用 available data。这些 instructions 通常作为 prompt 的一部分发送,也就是 context,使 large language models 能执行 desired tasks。现代 LLMs,例如 Anthropic 的 Claude、OpenAI 的 ChatGPT、Meta 的 Llama,以及 Amazon 的 Nova models,支持从大约 128k 到 1M tokens 的 context lengths,因此这些 prompts 可以非常大。作为参照,200k token limit 大约可以容纳 500 页文本,这对大多数 enterprise use cases 来说已经绰绰有余。
继续考虑前面的例子:让 AI applications 利用 gene catalog table 来回答 drug discovery 相关问题。我们想回答的问题是:每条 chromosome 上有多少 protein-coding genes?
假设我们已经在 Amazon SageMaker Catalog 中创建了 business glossary。下面的 code excerpt 会 fetch 回答这个问题所需的 table definitions。如果你使用不同 catalog tool,API 会不同,但市场上大多数 commercial tools 都支持这个 function:
# Instantiate Unified Studio Catalog
client = UnifiedStudioClient()
# API call to central business glossary, SageMaker Catalog
response = client.get_table(
GetTableRequestTypeDef(
ProjectIdentifier=project_id,
TableName=gene
)
)
# Define the output template in JSON format with the fields of interest
# from the business catalog
return tdefinition
{
"TableName": response["TableName"],
"Description": response.get("Description", "No description available"),
"Columns": [
{
"Name": col["Name"],
"DataType": col["DataType"],
"BusinessDescription": col.get("BusinessGlossaryTerm", "")
}
]
}
现在,使用 table definitions 构建 prompt template,如下面 code excerpt 所示:
# Prompt template to pass gene table schema and descriptions and help
# the model answer questions related to gene catalog data.
prompt_template = (
"""
You are a friendly bot, an expert in the field of genomics.
## Task
Generate an ANSI SQL query related to drug discovery using the context
provided to you.
## Context
The context provided to you contains the schema of a table from a database
with detailed descriptions about the table and its columns, when to use
each column, and for what purpose.
"TABLE-DEFINITION: {tdefinition}\n\n"
"EXAMPLES: {examples}\n\n"
## Model Instructions
- The TABLE-DEFINITION is in JSON format
- You MUST interpret the question and understand what table(s) and column(s)
you will need to generate the right SQL
- You MUST think before generating the SQL
- SQL MUST be syntactically correct and in ANSI format
## Response Style and Output Format Requirements
- You MUST respond with a SQL query
- You MUST generate the SQL response using the CONTEXT provided to you
## Success Criteria
- Generate syntactically correct ANSI SQL
"""
)
Answer:
SELECT chromosome, COUNT(*) AS gene_count
FROM human_gene_catalog
WHERE array_length(uniprotprimaryaccessions) > 0
GROUP BY chromosome
ORDER BY gene_count DESC;
得益于 business glossary 中的 definitions,并且这些 definitions 以 JSON object 形式传入,我们假设中的 AI application 将能够准确回答这个问题,而不需要 application developer 或 prompt engineer 显式把每个 definition 加到 prompt 中。
只要你拥有 clear 和 comprehensive 的 business glossary definitions,就可以创建这种格式的 prompts,并在 organization 中几乎任何 table、各种 AI applications 中复用。这种 approach 消除了 data steward 为某个 AI application 指定需要哪些 data 来回答问题的需求,并支持 seamless scalability。
接下来,我们将关注 AI data governance operating model 中另外两个关键元素:data quality 和 data security。
Data Quality
Insights 的质量直接取决于你所使用 data 的质量。Organizations 通常熟悉 structured data 的 standard data quality checks,例如识别 columns 中的 null values 和验证 data types。随着时间推移,许多组织也开发了 comprehensive frameworks,用于 use case–specific validations,包括 timestamp conversions to epoch time、range validations 等检查。今天,这些已经成为 structured data 的 data transformation pipelines 中的 table stakes。
然而,modern AI use cases 往往会更多利用 unstructured data,而这类 data 在大多数 organizations 中更丰富。因此,本章剩余部分会从 AI 使用 unstructured data 的视角来看 data governance。
尽管 structured data quality 已经取得进展,许多 organizations 仍然面临挑战:甚至连 unstructured data 的 data quality 意味着什么都难以定义,更不用说开发 effective data validation rules 和 strategies 来应对这些挑战,以支持 successful AI initiatives。
有多种 data validation rules 可以应用于 unstructured data,尤其是 text。常见示例包括:
File format validation
确保 files 采用 accepted formats,例如 HTML、PDF、TXT、DOC 或 PPT。
Metadata format validation
检查 metadata files 是否采用 JSON 等格式。
Metadata field checks
验证某个 document 的 title、description 和 category 等 fields 是否存在且正确。
Table extraction
从 PDFs、DOCs 或 image files 中 extract tables,并提取 associated titles。
Image extraction
识别并提取 images 中的 specific points of interest,例如检测图表中的最高峰。Images 可以是 PNGs 等 image files 的一部分,也可以存在于 PDFs 等其他 document types 中。
Header, footer, and text normalization
移除 headers 和 footers,或对 emails 和 HTML documents 中的 text 进行 normalization。
Range validation
确保 extracted text values 落在 acceptable ranges 内,例如验证 ratings 是 1 到 5 之间的 numeric values。
这个列表并不 exhaustive。所需的 specific data validation rules 取决于具体 use case。例如,当处理 customer service emails 时,移除 extraneous text 非常重要,例如 Example 4-1 中以 bold 标出的 headers、footer 和 signature,从而为 language model 提供 cleaner input。这不仅提升 model 的 data quality,也减少 input tokens 总数,而这会直接影响 inference cost。
Example 4-1:Sample customer service email
From: *** <***>
Sent: Monday, April 6, 2026 8:00 PM
To: *** <***>
Subject: Re: Help & Support: Requesting a Quote
Dear Customer,
Good day.
Thank you for choosing XYZ LLC!
I am happy to provide you a quote for the below-mentioned item.
If you have an account with us please provide your account number, and I
will provide you with your account pricing.
If you do not have a business account with us and would like to set one up,
please visit our website at www.xyz.com and click on 'My Account' in
the top-right corner. A drop-down menu will appear, and you may choose
'Register for an Account' then follow the instructions to apply for an
account.
Thank you for your patience in this matter.
I appreciate your business. Please contact us again if we can help you with
anything in the future.
Thank you,
***
Customer Service Representative
XYZ LLC
A part of ABC Products division
For quick and easy access to
xyz.com<https://urldefense.com/v3/__https://linkprotect.cuasvc.com/url?a=ht>
please click below:
[cid:image003.jpg@01D0A73.1264B0Z0]<https://urldefense.com/v3/__https>
通常,你会使用自己偏好的 programming language 中的 regular expressions,来移除这类 emails 中被标出的 sections,因为这些部分对 AI applications 没有必要,并且会引入 unwanted noise。
通过为 structured 和 unstructured data 建立 robust data quality 和 validation practices,organizations 能够创建一个 reliable foundation。在这个 foundation 之上,更广泛的 governance concerns,例如 security、privacy 和 responsible AI,才能被有效处理。Data security 拥有最高优先级。它非常重要,因此接下来的两个 sections,也就是 responsible AI 和 generative AI 的 data privacy and security,都专门讨论这个主题。
Responsible AI
Responsible AI 没有一个 single、universally accepted definition。尽管如此,参考 Institute of Electrical and Electronics Engineers(IEEE)、Organisation for Economic Co-operation and Development(OECD)、Harvard University’s Berkman Klein Center for Internet & Society 等 prominent organizations,以及 EU 的 Ethics Guidelines for Trustworthy AI 和 UNESCO’s Recommendation on the Ethics of AI,我们将其定义如下:以 ethical、transparent、fair 和 accountable 的方式设计、开发、部署和使用 AI systems,确保与 human values 和 societal well-being 对齐。
表 4-2 概述了 responsible AI 的 core principles。
表 4-2:Responsible AI principles
| Principle | Description(AI that…) |
|---|---|
| Fairness | 避免 bias 和 discrimination |
| Transparency | 做出 explainable 和 understandable 的 decisions |
| Accountability | 确保 decisions 的 responsibility 清晰,并提供 redress mechanisms |
| Privacy and security | 保护 individual data,并确保 security |
| Reliability | 安全并按 intended way 运作 |
| Human oversight | 保持 human control 和 judgment |
下面进一步查看每一项原则,并看看如何在 AI applications 中 enforce 它们。
Fairness
Fairness principle 简单来说,要求 AI application 不得在 responses 中显示任何 bias 或 discriminate。举例来说,假设一家公司使用 AI-driven hiring tool 来筛选 job applicants 的 resumes,目标是基于 qualifications 和 work history 快速识别最有希望的 candidates。
下面是这种场景中 unintentional bias 可能如何产生的例子:
- AI model 使用公司过去的 hiring data 进行 training 或 fine-tuning,而过去几年中,公司的招聘偏好来自某些 universities 的 applicants,并无意中忽视了其他 schools 的 candidates,包括 minority-serving institutions。
- 如果没有适当 fairness evaluation,AI model 会学习这些 historical preferences,并给 favored schools 的 applicants 更高排名,即使他们的 qualifications 与其他人相似,甚至更弱。
- 结果是,来自 less-represented backgrounds 的 qualified candidates 获得 interviews 的机会更低,从而 reinforce existing inequalities。
Tools to detect bias
为了 mitigate bias,首先必须有办法 detect 它。为此有多种 tools 可用。表 4-3 列出了一些 popular open source options,以及主要 cloud providers 的工具。
表 4-3:Fairness evaluation tools
| Provider | Tools | Notable features |
|---|---|---|
| AWS | SageMaker Clarify、Bedrock with an LLM as a judge | Dataset / model bias analysis、legal metrics、explainability dashboards |
| Azure | Fairlearn(integrated)、Responsible AI Dashboard | Interactive dashboard、mitigation algorithms、full workflow integration |
| Google Cloud | Vertex AI Fairness Evaluation、What-If Tool | Built-in fairness metrics、interactive analysis、subgroup diagnostics |
| Open source | IBM AIF360、Fairlearn、Aequitas | Extensive fairness metrics、dashboards、bias mitigation algorithms |
虽然这些 tools 在评估 fairness 的具体方法上不同,但它们共享相同的 underlying goal。
How to handle bias
一旦检测到 bias,就需要确定如何 mitigate 它。尤其是在使用 RAG pattern 时,两种常见 approaches 是 prompt engineering 和 implementing guardrails。
Prompt engineering 是指 carefully design 和 adjust prompts,引导 LLM 生成 neutral、inclusive 和 contextually appropriate responses。例如,如果观察到 biased outputs,可以重写 prompts,加入关于 neutrality 的明确指令,或显式排除 sensitive attributes。这有助于降低 AI 生成 biased 或 stereotypical answers 的可能性。
另一种常见 technique 是使用 security guardrails 或类似 safety tools,定义 denied topics、配置 content filters,并建立过滤 harmful 或 biased content 的 thresholds。随后可以使用 Amazon CloudWatch 等工具监控和分析 bias interventions 何时以及如何被触发。Guardrails 也可用于自动移除或 redact personally identifiable information,帮助防止与 sensitive data 相关的不公平或歧视性 outputs。
Transparency
Transparency principle 要求 AI systems 所采用的 processes 和做出的 decisions 必须对 humans explainable 和 understandable。Foundation models 的解释能力是 comprehension 的 cornerstone,它照亮了这些 systems 得出 conclusions 的路径。这种 explanatory function 不仅让 decision-making process 不再神秘,也为系统化增强 response quality 打开了道路。通过考察 underlying reasoning mechanisms,researchers 和 practitioners 可以识别 potential weaknesses、refine model behavior,并构建更 reliable 和 transparent 的 AI systems。
Explainability 和 monitoring 是达到适当 transparency level 的 focal points。根据 AI application 运行在哪里,有多种 mechanisms 和 tools 可以提供帮助。这里使用 AWS offerings 作为例子,介绍一些选项。放心,其他 cloud providers 的 native services 也可以实现一套 comparable capabilities。
Amazon Bedrock 提供多种 built-in model transparency features,用于支持 explainability,包括:
- Response provenance tracking:显示 context 中哪些 data 影响了 output。使用 Bedrock Converse API 中的 citations,你可以 retrieve response 使用的 chunks references。
- Confidence scoring mechanisms:表示 model certainty。
- Input and output token counts:提供 prompts 和 generated responses size 的 visibility。
- Reasoning steps in the output:当使用 reasoning model 做 inference 时,输出 reasoning steps。
- Watermarking for generated content:Bedrock 的 Titan models 对 generated images 包含 invisible watermarking,提高 AI output 的 traceability。
此外,Amazon SageMaker 提供 comprehensive explainability tools:
- SageMaker Clarify:提供 feature importance analysis、bias detection 和 model interpretability metrics。
- SageMaker Model Monitor:支持持续 tracking model behavior 和 performance drift。
- SageMaker Experiments:允许系统化比较 model variants 及其 reasoning patterns。
通过使用 traces,还可以进一步洞察 model responses,稍后我们会讨论。
Transparency 的第二个 foundation 是 monitoring。对 generative AI applications 的 effective monitoring 能够为其当前和长期 performance 提供关键 visibility,并通过 comprehensive logging 确保 transparency。这支持对 functional 和 security aspects 的 validation,增强对 application 和 reliability 的 trust。
Audit logs 和 monitoring 支持 tracking 和 auditing model usage 与 system actions,确保关于 models 如何以及何时被 accessed 或 modified 的 transparent documentation。这也包括 tracking model responses。所有 major public cloud providers 都通过其 native service logging capabilities 支持这一功能:
- 在 AWS 上,这些 details 位于 CloudTrail 和 CloudWatch logs 下。
- 在 Azure 上,它们位于 Azure Log Analytics、diagnostic logging 和 Azure monitor logs 下。
- 在 Google Cloud Platform(GCP)上,它们位于 cloud logging 和 cloud audit logs 下。
为了提高 costs、latency 和 response traces 等 metrics 维度上的 transparency,还可以使用 observability tools,例如 open source Langfuse 和 MLFlow Tracing、Datadog LLM Observability、Helicone 等。支撑这种 observability 的两个重要 mechanisms 是 GenAI systems 的 tracing,以及 agents 的 telemetry capture and export。
Tracing with LLMs
Generative AI systems 中一种特别强大的 monitoring technique 是 tracing,它捕获 prompts、model interactions 和 responses 的完整 lifecycle。为了说明这个概念,请看图 4-2,它展示了 Langfuse observability interface 中的一个 example trace,用于 Amazon Bedrock 中由 Amazon Nova model 服务的 request。Langfuse 中的 trace 通常表示一个 single request 或 operation。它包含 function 的 overall input 和 output,以及 request 的 metadata,例如 user、session 和 associated tags。
图 4-2:Bedrock RAG API request 的 Langfuse trace
下面拆解图中高亮部分:
- 该 request 的 LLM configuration 和 output metrics,包括 latency、cost、model name 和 max tokens。
- 发送给 LLM 的 augmented context。
- User’s question。
- Model’s output。
- 可能需要用于进一步深入分析该 API request 的 additional metadata。
这些元素共同提供了 RAG pipeline 如何处理 single request 的 end-to-end view,使 debugging issues、optimizing performance 和随时间提升 answer quality 变得更容易。
Capturing and exporting telemetry
在 agentic architecture 中,你可能会使用完全不同的一组 tools 和 capabilities 来监控 application behavior。OpenTelemetry(OTEL)提供一个 flexible 且广泛采用的 framework,用于为 single-agent 和 multi-agent orchestration systems 发出 telemetry data。随后,这些 data 可以被任何 OTEL-compatible backend tool 消费用于 visualization、troubleshooting 和 evaluation。常用工具包括 Prometheus、Grafana、Jaeger、Zipkin、Dynatrace 和 Datadog。
从 agents 捕获并导出 telemetry 时,最佳 tools 和 approaches 通常取决于所需 telemetry signal 类型(metrics、traces、logs)、integration requirements 和 observability stack。以下是一些 common patterns:
Native agent instrumentation
Agents 可以直接以 structured format,例如 JSON 或 CSV,将 telemetry events、metrics 或 traces 写入 log files 或 stdout。然后,external log scrapers,例如 Fluent Bit 或 Filebeat,可以 collect 并 forward 这些 data 用于 analysis 和 visualization。
你也可以使用 popular language-specific libraries,例如 Java 的 Micrometer、StatsD clients 或 Prometheus client libraries,将 custom metrics 直接 emit 到 compatible backends。
Export to dedicated monitoring systems
假设你使用 Prometheus 作为 monitoring system。Agents 可以通过 HTTP endpoint 以 Prometheus exposition format 暴露 metrics,使 Prometheus 可以 poll 和 scrape 这些 data,用于 monitoring 和 alerting。这种 approach 非常适合 time-series metrics,但不适合 traces 或 logs。市场上许多其他 systems,包括针对 traces 和 logs 的系统,也可以实现类似功能。
Direct export to backends and middleware
Agents 可以将 telemetry 作为 structured log entries 发送到 Elasticsearch 或 Logstash endpoints,通常通过 HTTP 发送。
对于 cloud native agents,telemetry 可以通过 APIs 直接 push 到 AWS CloudWatch、Azure Monitor 或 Google Cloud Operations 等 services。
Accountability
Responsible AI systems 的关键 accountability requirements 包括:
- 为 outcomes 建立清晰 responsibility chains,包括追踪不同 stages 和 components 由谁负责。
- 当出现问题时,提供 effective mechanisms for redress and correction,确保 harms 或 errors 被识别并处理。
下面快速看看如何在 AWS、Microsoft Azure 和 GCP 上实施这些 accountability requirements。
Responsibility
为了 enforce clear responsibility chains:
- 通过 GenAIOps pipelines 使用 cloud audit trails 和 versioning,将 actions 和 changes 归因到 specific users。
- 使用 providers 的 built-in tools 和 logging,维护 model lineage、deployment 和 data usage 的 documentation。
- 参考 Cloud Security Alliance 的 AI Controls Matrix 等 frameworks,在 teams 和 stakeholders 之间 map 并 document responsibilities。
Correction
你也必须提供 effective mechanisms for correction,以便在出现问题时处理 issues:
- 使用 contextual grounding checks 检测 hallucinations,并通过验证 model outputs 是否 factually accurate 且 grounded in source material 来 filter responses。主要 public cloud providers 和 open source initiatives 都提供支持此功能的 guardrails。
- 启用 human-in-the-loop oversight 和 appeals,允许 reviewers 在被 flagged 时 override、reprocess 或 roll back AI decisions。
Privacy and Security
Data privacy and security 包含 encryption、access controls、data masking 和 regular monitoring 等 measures,用于保护 information assets。
当处理 text 和 images 等 unstructured data 时,organizations 必须采用 robust security measures,保护 sensitive information,并确保符合 privacy regulations。以下 strategies 被广泛推荐。
Encryption at rest and in transit
Data files 应始终进行 encryption,无论是在存储时(“at rest”)还是传输时(“in transit”)。所有主要 cloud providers 都为其 storage services 提供 built-in encryption capabilities,例如 Amazon S3、Azure Blob Storage,可用于自动化 data security 中这个关键方面。
Sensitive data identification and redaction
必须识别并妥善处理嵌入在 unstructured data 中的 sensitive information。这类信息可能是什么样子?
Example 4-2 高亮了前面 example email 中的关键 PII elements,包括 sender 和 receiver 的 email addresses、customer name,以及 customer service representative 的 name。
Example 4-2:Customer service email 中的 PII
From: markl@xyz.com
Sent: Monday, April 6, 2026 8:00 PM
To: dbarns@mycompany.com
Subject: Re: Help & Support: Requesting a Quote
Dear Dan Barns,
Good day.
Thank you for choosing XYZ LLC!
I am happy to provide you a quote for the below-mentioned item.
If you have an account with us please provide your account number, and I
will provide you with your account pricing.
If you do not have a business account with us and would like to set one up,
please visit our website at www.xyz.com and click on 'My Account' in
the top-right corner. A drop-down menu will appear, and you may choose
'Register for an Account' then follow the instructions to apply for an
account.
Thank you for your patience in this matter.
I appreciate your business. Please contact us again if we can help you with
anything in the future.
Thank you,
Mark Lamberg
Customer Service Representative
XYZ LLC
在 “Sensitive Information Protection” 中,我们会探索如何使用 prompt engineering 和 LLMs 处理这类内容中的 PII。不过需要注意,虽然经过精心设计 prompts 的 LLMs 可以检测常见 PII elements,例如 names 和 email addresses,但它们并不能可靠识别所有形式的 sensitive data,例如 Social Security numbers(SSNs)、national ID numbers 或可能以 unexpected formats 出现的 financial account numbers。为了 robust PII protection,organizations 应使用 dedicated tools,例如 Amazon Bedrock Guardrails,后者可以在 runtime 对 user inputs 和 model outputs 检测并 redact PII;也可以使用 Amazon Comprehend、Amazon Macie、Azure AI Language PII Detection 或 Google Cloud Data Loss Prevention(DLP)API。
Access control in vector stores
在 vector database 中存储 unstructured data 时,必须实施 access controls,用来 mirror traditional relational databases 中的 row-level security(RLS)。这可以通过设计 vector store schema,使其包含 relevant metadata fields 来实现。例如,如果 vector store(如 OpenSearch)包含 customer order data,那么每个 orders 的 embedded vector chunk 都应标记对应 username。随后,如果 user 请求其 past orders 的信息,queries 可以在 data retrieval 期间基于该 metadata 进行过滤,确保 users 只能访问自己的信息,而不能访问其他人的 data。
通过系统性应用这些 measures,organizations 可以显著降低 data breaches 风险,并维护 unstructured data assets 的 confidentiality 和 integrity。
Reliability
Responsible AI 中的 reliability 意味着确保 systems robust、performance consistent 且 safe,在变化或 unexpected conditions 下也能按 intended way 交付 results。Deployment 前需要 thorough testing。
所有主要 cloud providers 都提供 native tools,用于在 AI applications 中 enforce reliability。例如:
- 在 AWS 上,使用 SageMaker Clarify 进行 predeployment bias detection 和 explainability assessment;使用 SageMaker Model Monitor tracking model performance、identify drift,并对 production 中的 anomalous behavior alert;使用 Amazon Bedrock Guardrails 实施 safety guardrails,用于 block harmful content、filter hallucinations,并应用 customized safety checks。使用 automated reasoning 支持 factual accuracy 和 enhanced robustness。在典型 product setup 中,orchestration layer 会确保这些 components 到位,使所有内容 end to end automated。
- 在 Microsoft Azure 上,使用 Responsible AI dashboard 执行 error analysis、识别 failure rates 较高的 cohorts,并理解 deployment 前后的 error distribution。使用 Azure Monitor 持续监控 model 和 infrastructure health,例如 CPU、memory、inference success rates。当 performance degrade 时,自动化 alerting 和 remediation。
- 在 GCP 上,使用 Vertex AI Model Evaluation 进行 predeployment validation,包括 accuracy、bias 和 robustness tests。启用 Vertex AI Model Monitoring,以检测 deployed models 中的 data drift 和 unexpected behavior。使用 Google Cloud 的 Recommended AI Controls Framework within Audit Manager,自动化 continuous compliance 和 reliability audits。定义 scope、运行 assessments,并生成 automated reports,记录 reliability controls。
Human Oversight
AI 中的 human oversight 确保:
- 对 AI systems 保持 meaningful human control。
- 尤其对于 critical decisions,确保 human in the loop(HITL)参与。
这种 approach 是 EU AI Act 等 regulations 所要求的,也是 responsible AI practices 的基础。
在整个 GenAI application lifecycle 中,有多个 stages 必须考虑 HITL involvement。表 4-4 列出这些 stages,并概述可能需要 human oversight 的 tasks。
表 4-4:Agentic 和 RAG application lifecycle stages 中 HITL involvement 的建议
| Agentic / RAG lifecycle stage | HITL required? | Example HITL tasks |
|---|---|---|
| Data collection and preparation | Sometimes | Spot-checking data quality,validating exclusion / inclusion choices |
| Data labeling and annotation | Always | Ensuring labels are accurate,resolving ambiguity,correcting errors |
| Model training and fine-tuning | Sometimes | Prompt design,reviewing fine-tuning data,setting thresholds |
| Evaluation and validation | Always | Manual reviews for factuality、safety、bias 和 ethical issues |
| Deployment / integration | Sometimes | Approving go-live decisions,尤其当 risk 较高时 |
| Inference / serving | For critical tasks | Critical、high-impact 或 safety-sensitive decisions 中的 real-time intervention |
| Monitoring and feedback | Often | Reviewing flagged outputs,investigating edge cases 或 escalations |
| Retraining and improvement | Sometimes | 基于 human-verified failures 优先确定 retraining areas |
对于影响 safety、compliance 或 ethical considerations 的关键 stages,human-in-the-loop involvement 是 mandatory;在其他地方也建议持续 oversight,以维护 responsible AI operation。
接下来,我们会关注 data privacy 和 security——AI data governance 的两个 foundational elements,其重要性再怎么强调都不过分。
Data Privacy and Security for GenAI Applications
由于 AI applications 快速采用,并处理、生成和推理 vast volumes 的 text、images 和其他 unstructured formats,data privacy and security 的处理正在发生 paradigm shift。这些 data types 是 traditional security frameworks 从未被设计来治理的。
表 4-5 展示了你的 AI application 需要考虑的 data privacy 和 data security 的关键 capabilities。
表 4-5:Data privacy and security capability matrix
| Capability | Data privacy | Security |
|---|---|---|
| Content safety and filtering | ✓ | |
| Sensitive information protection(PII) | ✓ | |
| Topic restriction and word filtering | ✓ | ✓ |
| Hallucination prevention(factuality) | ✓ | |
| Data encryption(at rest / in transit) | ✓(platform-level) | |
| Access control and authentication(IAM) | ✓(platform-level) | |
| Network security(VPC、PrivateLink) | ✓(platform-level) | |
| Audit logging and monitoring | ✓(platform-level) | |
| End-to-end data protection | ✓ | ✓ |
可以看到,某些 capabilities,特别是 topic restriction and word filtering,以及 end-to-end data protection,会同时跨 data privacy 和更广义的 application security domains。
本节将重点探索 data privacy capabilities,因为这些往往是 enterprises 面临最大挑战的领域。不过,在深入具体 capabilities 之前,有必要先澄清这个术语的含义。Data privacy 指保护 personal 或 sensitive information 免受 unauthorized access、use、disclosure 或 destruction 的 practice。它包括 policies、processes 和 technologies,用于确保 individuals’ data 的 collection、processing、storage 和 sharing 尊重其 rights,并符合 legal 和 regulatory requirements。
Sensitive Information Protection
处理 sensitive data 有多种 techniques,包括:
- Prompt engineering with LLM
- External tools,例如 Amazon Bedrock Guardrails、Amazon Comprehend、Amazon Macie、Azure AI Language PII Detection 和 Google Cloud Data Loss Prevention(DLP)API
本节中,我们将演示如何使用第一种 technique 来处理 text data 中的 sensitive information,仍然使用前面的 sample customer service email 作为 example document。在 Example 4-2 中,我们识别了该 document 中的 PII elements:sender(customer service representative)和 receiver(customer)的 names 和 email addresses。下面的 snippet 展示了识别并 redact 这些 elements 所需的 prompt template code:
# Template for the user message with placeholders
prompt_template = (
"""
## Task
You MUST identify SENSITIVE data elements from the E-MAIL provided to you.
## Context
The email consists of interactions from external customers with customer
service representatives of XYZ, a medical device manufacturer and seller.
"EXAMPLES: {email_examples} \n\n"
"ENTITIES: {entities} \n\n"
"E-MAIL: {email} \n\n\n"
## Model Instructions
-You MUST use the EXAMPLES provided to arrive at the right intent for a
given email.
-You MUST use the ENTITIES to find all the sensitive elements of interest
in the email.
-COUNT the number of exchanges between XYZ customer reps and external
customers in the E-MAIL thread.
-Replace ALL the sensitive entities from the E-MAIL using *****.
## Response Style and Output Format Requirement
-You MUST respond in text format.
-In your response, DO NOT start with "Let me analyze the email and determine
the intent".
-You MUST generate the response with a confidence score (0-100%) based on
the CONTEXT and EXAMPLES provided to you.
## Success Criteria
-Entity detection MUST focus on extracting ALL ENTITIES found in the E-MAIL
-Output text generated MUST replace sensitive ENTITIES with *****
"""
)
NOTE
使用 Amazon Bedrock model 的完整代码可在本书 GitHub repository 中找到。
这个 prompt template 包含 clear instructions,并采用 modular approach,指定了需要在 context 中 extract 和 replace 的 entities list。它还提供 examples,教 model 如何识别并 mask sensitive data。Example 4-3 展示了 model 生成的 output,其中 email 中的 sensitive entities 已被 masked。
Example 4-3:Model 生成的 response,其中 PII 已被识别并 redact
From: *****
Sent: Monday, April 6, 2026 8:00 PM
To: *****
Subject: Re: Help & Support: Requesting a Quote
Dear *****,
Good day.
Thank you for choosing XYZ LLC!
I am happy to provide you a quote for the below-mentioned item.
If you have an account with us please provide your account number, and I
will provide you with your account pricing.
If you do not have a business account with us and would like to set one up,
please visit our website at www.xyz.com and click on 'My Account' in
the top-right corner. A drop-down menu will appear, and you may choose
'Register for an Account' then follow the instructions to apply for an
account.
Thank you for your patience in this matter.
I appreciate your business. Please contact us again if we can help you with
anything in the future.
Thank you,
*****
Customer Service Representative
XYZ LLC
Sensitive Entities Detected:
1. Full Name: Mark Lamberg (replaced with *****)
2. Email Addresses:
- markl@xyz.com (replaced with *****)
- dbarns@mycompany.com (replaced with *****)
Number of Exchanges: 1 (initial customer service response)
Confidence Score: 95% (based on clear identification of sensitive entities and
following the example provided)
WARNING
再次注意,虽然这里展示的 prompt-based approach 对 names 和 email addresses 等常见 PII elements 有效,但不应将其作为唯一 PII detection mechanism。为了 comprehensive protection,需要使用更 sophisticated tools,例如 Amazon Bedrock Guardrails 的 sensitive information filters,它们可以在 single API call 中检测 dozens of PII types,包括 SSNs、credit card numbers 和 international ID formats,并同时应用于 inputs 和 outputs。
理解 data sensitivity 对保护 confidential information 和确保 compliance with regulatory standards 至关重要。在这个 foundation 之上,同样重要的是考虑如何引导 generative AI systems 避免生成或参与 sensitive content——这就是 topic restriction 和 word filtering 发挥作用的地方。
Topic Restriction and Word Filtering
LLMs 被训练为可以回答 diverse range of topics 的问题。然而,当 enterprises 部署这些 models 时,需要确保 applications 的 responses 被限制在 topics of interest 内。除了确保 relevance,这也有助于降低 costs,并防止 security exploits,即 attackers 试图 misuse application 来回答 unrelated questions。
这要求 organizations 在 application design 中,将 topic restriction 和 word filtering 集成到 LLM 前后,如图 4-3 所示。
图 4-3:将 topic restriction 和 word filtering 集成到 application design 中
有多种方式可以实施这些 filters。当在 public cloud environment 中运行时,organizations 可以利用 provider 的 native tools。一些 providers,例如 AWS,提供与任意 model 集成的 topic 和 word filtering capabilities,使这些 filters 即使在使用 custom models 时也可应用。
Popular content filtering tools 包括:
- Azure AI Content Safety
- Google Vertex AI Safety Filters
- Amazon Bedrock Guardrails
- Llama Guard(open source)
- NVIDIA NeMo Guardrails(open source)
为了说明如何在 AI applications 中利用这些 tools,我们快速走一个使用 Amazon Bedrock Guardrails 的例子。
假设你正在为 fintech company ABC Inc. 构建一个 AI chatbot。Claude 和 ChatGPT 等 frontier models 被构建为能可靠遵循 prompt instructions。你可以使用一个简单 prompt,如下所示,它也可在本书 GitHub repository 中下载,用于建立初始保护层,指示 model 只回答与你的 application 相关 topics 的问题。在这里,我们告诉 model 只回答关于公司 products 和 services 的问题,而这些内容会被动态传入 prompt:
system_prompt = f"""You are a virtual customer service agent for ABC Inc., a
fintech company in the USA.
<rules>
- Only respond to questions related to ABC Inc.'s {products} and {services}.
- If asked about anything else, politely inform the user that you can only
assist with ABC Inc.-related inquiries.
- Do not discuss any sensitive financial information or provide financial
advice.
- Keep responses concise and professional.
- The company phone number is +100022200
- The company email is abc@example.com
</rules>
"""
下面的 example interactions 展示了使用该 prompt 时,LLM 可能如何 respond。如预期,chatbot 正确回答了关于公司 products 的问题,同时拒绝回答 unrelated topic 的问题:
Question1: What is the best stock to invest in?
Answer: I apologize, but as a customer service agent for ABC Inc., I am not able
to provide any investment advice or recommendations. ABC Inc. is a fintech
company that offers financial services, but we do not give specific stock or
investment advice. For any questions related to our products and services, please
feel free to contact us at +100022200 or abc@example.com. I'd be happy to assist
you with those types of inquiries.
Question2: Hi, what are the credit cards available?
Answer: Hello, thank you for your inquiry about ABC Inc.'s credit card offerings.
We currently provide the following credit card products:
- ABC Rewards Card - This card offers 2x points on all purchases and has no
annual fee.
- ABC Premium Card - This card provides 3x points on select purchases, airport
lounge access, and a $100 annual travel credit. It has a $195 annual fee.
- ABC Business Card - Designed for small business owners, this card offers
3x points on business-related expenses and has no annual fee.
For more detailed information on the features and benefits of each card, please
visit our website at abcbankingsolutions.com or contact our customer service team
at +100022200. We'll be happy to assist you in finding the right credit card
solution for your needs.
这种 approach 对少量 restrictions 效果不错,但当 enterprise-grade privacy 和 security controls 需要 model 遵循更多 rules 时,prompts 会很快变得复杂且难以管理。在这些情况下,使用 Amazon Bedrock Guardrails 等 content filtering tools 就变得 essential。
Filtering Tools
Guardrails 对 constraining model behavior 和 enforcing safety policies 至关重要。在 Amazon Bedrock 中,你可以通过 AWS Management Console 或 API 以 programmatic 方式定义 guardrail。图 4-4 和图 4-5 分别展示了 console 中 topic filtering 和 word filtering 的 guardrail configurations。
每个 guardrail 最多可以配置 30 个 topics,使 LLM 能更精准聚焦 AI application 的 specific requirements。
图 4-4:ABC Inc. 的 topic filter configuration
“Filter profanity” checkbox 可以简化对 inputs 和 outputs 中 profane words 的 autodetecting 和 blocking,而不需要你在 prompt 中显式添加它们。你还可以选择添加最多 10k words 或 phrases 进行过滤,例如 competitors 名称,如 XYZ Bank 和 RRRCorp。相比 “Topic Restriction and Word Filtering” 中把所有 rules 显式输入到单一 prompt 的方式,这种 approach 更 modular,也更易管理。
图 4-5:ABC Inc. 的 word filter configuration
下面的 code snippet 可在 GitHub repository 中找到,展示了如何 programmatically 使用 Amazon Bedrock Guardrails:
response = bedrock.converse(
modelId="anthropic.claude-haiku-4-5-20251001-v1",
### You can replace the model with any other preferred option
system=[
{
"text": system_prompt
}
],
messages=[
{
"role": "user",
"content": [
{
"guardContent": {
"text": {
"text": user_input
}
}
}
]
}
],
guardrailConfig={
"guardrailIdentifier": "ABCDEFG", ### Replace with your guardrail ID
"guardrailVersion": "DRAFT", ### Replace with version number if published
"trace": "enabled"
}
)
这里,我们使用标准 Amazon Bedrock Converse API template,并包含 guardrailConfig field,以便将 guardrail 应用于 request。Guardrail identifier 和 version 可以从 AWS Management Console 的 Amazon Bedrock Guardrails section 中获取,也可以通过 Bedrock API programmatically 获取。
End-to-End Data Protection
无论你在哪里 host AI application,它很可能会直接或间接接触多个你应该考虑保护的 components。例如,application 对 foundation model 的 API calls,以及这些 calls 期间交换的 input / output data,都应该被 encrypted。
Generative AI context 下的 data protection 可以通过结合 encryption at rest 和 in transit 来实现。表 4-6 展示了 application 可能遇到的各种 components,并说明每个 component 必须考虑哪种 encryption。
表 4-6:AI applications 的 end-to-end encryption matrix
| Component | Encryption at rest | Encryption in transit | Description |
|---|---|---|---|
| Data storage | Yes | Yes | 保存 training data、prompts 和 outputs 的 databases、data lakes 和 filesystems |
| Model artifacts | Yes | Yes | 用于 deployment 或 reuse 的 trained models、checkpoints 和 weights |
| Input data pipelines | Yes | Yes | 将 data 从 raw sources 移动到 storage 或 model 的 data ingestion 和 preprocessing pipelines |
| Inference and API endpoints | N/A | Yes | User requests 和 AI responses 的 communication channels |
| Internal service communication | N/A | Yes | Application 内部 microservices、compute nodes 或 containers 之间交换的数据 |
| Output data storage | Yes | Yes | Inference 或 generation 后存储的 generated content、logs 和 metadata |
| Backup and archive systems | Yes | N/A | Data 和 models 的 backups |
| Configuration and secrets | Yes | Yes | Application 使用的 API keys、credentials 和 configuration files |
当在 public cloud environment 中运行时,provider 的 shared responsibility model 会部分简化 encryption management,因为 provider 会代表你保护某些 components。然而,理解这些 responsibilities 如何划分,并确保其 implementation 满足 organization 的 security standards 仍然非常重要。
到目前为止,我们已经聚焦于开发 generative AI application 时涉及的 essential governance approaches 和 security considerations。虽然这些 foundational elements 是必要的,但在 production environment 中管理 generative AI system 时,还有另一个关键方面必须处理。下面进一步来看这个重要 component。
LLMOps: AI Workflow Orchestration
LLMOps 指用于管理 large language model applications 完整 lifecycle 的一组 practices、tools 和 methodologies,包括 development、deployment 和 ongoing operations。在这个 context 中,workflow orchestration 涉及协调一系列 tasks,例如 data curation、model training、retrieval、evaluation 和 monitoring,以确保 resources 的 scalability、reproducibility 和 usability。随着基于 LLM 的 systems 变得更复杂,尤其是那些利用 RAG 或 agentic AI 的 systems,robust orchestration 对 application 的 reliability 和 performance 至关重要。
AI workflow orchestration 构成 modern LLMOps 的 backbone,将 data ingestion、retrieval、prompt engineering、model execution、result aggregation、validation 和 feedback loops 连接起来。在 RAG systems 中,它控制 search components 和 generators 之间的 data flow;在 agentic AI systems 中,它协调多个 specialized agents 协作解决 complex tasks。Effective orchestration 不仅 streamline operations,也支持 scaling、rapid iteration,以及符合 enterprise governance 和 monitoring requirements。
Orchestration Patterns for AI Applications
随着 AI systems 从 simple request / response interactions 演进为 autonomous、goal-directed behaviors,几种 distinct orchestration patterns 已经出现。每种 pattern 在 complexity、flexibility 和 control 之间提供不同 trade-offs。理解它们有助于你为 specific use case 选择正确 architecture。
本节会覆盖与 RAG 相关的最常用 patterns。我们会在 “Agentic Patterns” 中讨论 agentic AI 的 orchestration patterns。
Linear(chained)orchestration
在线性编排中,如图 4-6 的 retail use case 示例所示,data retrieval 和 generative steps 按 strict sequence 执行,例如 retrieve relevant passages → pass to LLM for synthesis。这种 pattern 简化了 debugging,并支持 easy monitoring。
图 4-6:User question 的 linear orchestration flow diagram
图 4-6 中的 orchestrator 可以是运行在 Docker container 中的简单 Python application,也可以是部署到 public cloud serverless compute service 的 Python code,例如 AWS 上的 AWS Lambda 或 Microsoft Azure 上的 Azure Functions。
该 diagram 展示了以下 user interaction 的 orchestration flow:customer 想使用 retail company 的 AI chatbot 查询 products 和 warranties 的信息。
User: List condensation pumps and their warranty information
下面是 backend 为回答该 user question 所执行的 step-by-step flow:
- Orchestrator 首先向 Products knowledge store 发送 request。该 knowledge store 通常是 vector store,包含 product documentation。
- Products knowledge store 找到与 condensation pumps 相关的所有 chunks,对它们排名,并连同 product_id 等 metadata 一起发送回 orchestrator。
- Orchestrator 随后向 Warranty knowledge store 发送另一个 request。这个 store 可能是另一个 vector store,也可能是 MongoDB 这样的 columnar store,以获得更高 accuracy。
- Warranty knowledge store 返回 condensation pumps 相关的 warranty information chunks,并带有 product_id 等 metadata。
- Orchestrator 然后向 data processing application 发送 request,以合并 retrieved contexts。
- Data processor 使用 metadata product_id,将两个 knowledge stores 中 retrieved 的 context chunks 合并,并把结果发送回 orchestrator。
- Orchestrator 使用 combined context augment prompt,并将其发送给 LLM。
- LLM 将 response 发送给 user。
这种 pattern 是 sequential 的,不能跳过任何步骤。它 easy to set up,适合 less complex scenarios,也是 beginner-level implementations 的很好选择。不过,添加 functionality 可能会变得 complex 和 risky,可能破坏 existing features,并生成难以在 scale 上管理的 unwieldy prompts。接下来,我们会看另一种可以克服这些 limitations 的 architecture。
Modular and concurrent orchestration
将 retriever、generator 和其他 pipeline steps 解耦,有助于 scaling、添加 new components,并支持每个 component 的 independent updates。它还允许某些 steps 并发运行,并支持 prompt decomposition,从而缓解管理 large prompts 的困难。这个 pattern 在图 4-7 中基于上一节同一个 use case 展示,是构建 maintainable 和 robust RAG solutions 的常见选择。
图 4-7:Modular and concurrent orchestration
主要目标是通过将责任委托给 dedicated orchestrator,将 orchestration logic 与 individual business functions 分离。这种 approach 不仅促进 clear separation of concerns,也增强 system 的 modularity 和 flexibility。将 processing 拆分为离散、可管理的 components,使每个 function 专注于自己的 specific task,而 orchestrator 负责管理这些 components 之间的 sequence、coordination 和 error handling。
想象一个 workflow,user 提交以下问题:
User: Provide the status of my order # 76378299
图 4-7 展示了满足这个 user request 所需遵循的 precise steps。下面拆解中会给出一些 architecture components 示例,但同样任务也可以在任何 public cloud 或 on-premises environment 中完成。
Request 首先发送到 dedicated orchestrator,例如 AWS Step Functions 或 Azure Logic Apps,它在 synchronous design 中管理 step sequence、flow logic 和 state。Workflow 如下:
- Orchestrator 启动 intelligent routing service,通常实现为部署在 serverless platform 上的 Python 或 Java application,例如 AWS Lambda 或 Azure Functions,也可以部署在 containerized infrastructure 上。这个 routing component 充当 system 的 decision hub,为每个 incoming request 决定 appropriate processing path。步骤 2 和 3 描述了如何做出这个 decision。
- User request 可能包含一个或多个 intents,例如 retrieving order status、modifying an order quantity,或 requesting product specifications 和 warranty details。为了确保 query 正确 data sources,router 会将 user query 发送给 LLM 执行 intent detection。在这个示例中,intent 会被检测为
order_status。 - 基于 detected intent,router 的 rules engine 决定 appropriate data source,也就是本例中的 orders database。然后 router 构建一个 database query,包含 deterministic filters,例如 user_id 和 order_id,确保只获取 relevant data。如有必要,这一步也可以并发查询 multiple data stores。
- Router 将 retrieved data 发送给 orchestrator。在我们的案例中,response 会包含 order number 和 status,以及 initial user query。
- Orchestrator 调用 data-processing component,例如运行在 AWS Lambda、Azure Functions 或 Docker container 上的 Python 或 Java code,用于 aggregate retrieved context、augment prompt,并执行 responsible AI guardrail validation。
- Processing 完成后,data processor 将 enriched prompt 返回给 orchestrator。这个 final prompt 不仅包含 original user query,还包含 contextual information、retrieved knowledge 和 structural enhancements,用来引导 language model 生成更 accurate 和 comprehensive response。
- Orchestrator 将 augmented prompt 提交给 large language model 进行 inference。这标志着从 preparation 和 enrichment phases 转向 generation phase,在这个阶段 LLM 基于 RAG pipeline 提供的 expanded context 处理 prompt 并形成 response。
- Generated response 随后传回 orchestrator。此时,在 final response 交付给 user 之前,可以执行 additional guardrail validation step,图 4-7 中未展示。这个 final check 确保 output 在到达 intended recipient 前满足 system 的 safety 和 quality standards。
给 user 的 response 可能如下:
Assistant: The provided order # 76378299 was shipped on April 30, 2026, with an
estimated delivery date of 5/4/2026.
Do you want me to confirm the delivery address?
这种 modular pattern 非常适合那些需要 specialized processing,并在有限 set of tasks 上要求 high precision 的 AI applications。它提供了显著 flexibility,允许 individual components 被修改、更新或替换,而不会破坏 broader system——这在快速演进的 AI environments 中非常重要。与 sequential processing approaches 相比,它也提供更好的 scalability,因为 specialized modules 可以 independent operate,并根据 demand scale。不过,该 pattern 对 intelligent routing component 的依赖也引入了 potential vulnerabilities。随着 system 扩展以支持更广泛的 tasks,router 的 decision-making logic 会变得更复杂,可能导致 response quality degradation,并形成 single point of failure,影响整个 system 的 reliability。
Agentic AI orchestration frameworks 通过让 systems 协调多个 specialized agents,更 autonomously 地执行更广泛 tasks,可以解决这些 limitations 中的一部分。下一节将介绍几种 common agentic patterns,并详细讲解一个 agentic orchestration 示例。
Agentic Patterns
Agentic AI applications 有多种 popular orchestration patterns,包括:
Sequential(pipeline)pattern
Specialized agents 以 fixed order 被调用,每个 agent 在将 data 传给下一个 agent 之前,对其进行 refine 或 transform。适合 multistep reasoning 或 data transformation flows。
Concurrent(fan-out / fan-in)pattern
多个 agents 在同一 input 或 problem 上 independent and parallel 工作,它们的 outputs 被 collected 和 reconciled。促进 speed 和 problem solving diversity。
Supervisor agent with specialized agents
一个 supervisor agent 作为 orchestrator,动态将 tasks 委托给最有能力执行它们的 agents,支持 specialization 和 adaptability。
Planning / adaptive pattern
Agents 使用 planning capabilities 将 complex tasks 分解为 subtasks,并由 system 以 parallel 或 sequential 方式派发解决。这个 pattern 是 agentic design 的基础,HuggingGPT 和 AutoGen 等 frameworks 就体现了这一点。
Swarm of agents
Agents 通过 explicit handoff 或 collaborative group conversations 协调完成 workflows,确保 context 被 preserved,并且 results 被有效 synthesized。
鉴于 agentic systems 演进迅速,整个 landscape 仍然高度 dynamic,目前还没有 single approach 成为 definitive solution。为了提供一个 concrete illustration of orchestration in agentic AI,我们将聚焦一个获得特别关注、并在各种 implementations 中越来越频繁出现的 pattern。
Supervisor agent with specialized agents
这是一种 centralized coordination pattern,其中 supervisor agent 作为 orchestrator 管理多个 specialized agents,每个 agent 处理 specific domains,例如 data analysis、content generation、API calls。Supervisor 会将 complex tasks 分解成 subtasks,并根据 agent capabilities 进行 routing。随后它会 consolidate results,并根据需要组合多个 agents 的 outputs。
今天有大量 orchestration frameworks 可用,每种都有自己的 strengths 和 trade-offs。和 orchestration patterns 一样,需要注意:没有 single framework universally superior;选择正确 solution 取决于你的 specific requirements 和 context。你应该认真评估可用选项,确定哪一个最符合 project needs。写作时,popular frameworks 包括:
Strands Agents
一种 model-driven、open source orchestration framework,支持开发 single-agent 和 multi-agent AI systems。它支持 flexible agent architectures,从 supervisor-specialist hierarchies 到 agent graphs 和 peer-to-peer “swarms”,并提供 robust AWS integration 和 built-in observability。Strands Agents 面向 rapid enterprise deployment 设计,以 minimal code 简化 agents 的 composition 和 coordination,是 production-grade、highly scalable agent workflows 的首选之一。
LangGraph
一种 graph-based framework,用于 multiple agents 的 fine-grained orchestration,支持 explicit multi-agent coordination 的 complex workflows。LangGraph 面向 power users,learning curve 更陡,但在构建 custom pipelines 和 RAG workflows 时提供显著 flexibility。
CrewAI
提供 role-based、high-level abstraction,简化将 agents 组织为 collaborative teams 的过程。它面向 quick prototyping 以及 human–AI 和 multi-agent cooperation,非常适合 early-stage multi-agent projects。
OpenAI Swarm
一种 lightweight、experimental framework,聚焦 routine-based agent orchestration 和 agent-to-agent handoffs。虽然尚不适合 production use,但高度 customizable,适合 experimentation、learning 和 early-stage development。
AutoGen
一种 adaptive、open source framework,支持 agents 之间通过 message passing 进行 asynchronous collaboration。它常用于 research 和 prototyping,尤其当 agent behavior 需要 iteratively refined 时。
下一节将走读一个 example implementation。
Example use case and implementation: ecommerce customer support
我们的示例展示了一个基于 Strands Agents framework 构建的 multi-agent customer support system,通过 simplified hub-and-spoke architecture 展示 intelligent request routing。
该 design 以 Strands supervisor agent 为中心,它作为 system’s orchestrator,分析 incoming customer requests,并将其路由到四个 specialized agents 之一:
- Technical support agent,处理 login issues、password resets 和 technical troubleshooting。
- Billing support agent,管理 refunds、charges 和 invoice inquiries。
- Product information agent,提供 product details 和 recommendations。
- Order status agent,追踪 shipments 和 delivery information。
图 4-8 展示了这个 architecture。
图 4-8:使用 Strands Agents 的 agent orchestration
所有 customer requests 都会经过 central orchestrator,由它决定哪个 specialist agent 负责处理每个 request。Individual agents 使用 Strands 的 built-in 或 custom tools 与 enterprise data sources 交互。
Routing logic 使用 LLM call 执行 initial request classification。例如,包含 “login” 或 “password” 等 terms 的 requests 会路由到 technical support agent;包含 “refund” 或 “charge” 等 keywords 的 requests 会路由到 billing support agent。注意,为了清晰起见,该示例使用 keyword-based routing;更 advanced approaches 可以利用 natural language understanding 和 reasoning-capable models 来判断 intent,并选择 appropriate tools,而不需要 explicit keyword matching。
所有 agents 都继承自 base Strands Agent class,利用 framework 的 built-in capabilities 来进行 tool management 和 execution flow。Enterprise data tools 会根据 detected request types 返回 predefined responses,例如:
- Technical issues:“Try clearing your browser cache and cookies.”
- Billing queries:“Your refund will appear in three to five business days.”
- Product information:“Premium laptop with Intel i7, 16GB RAM - $1,299.”
该 system 也包含 error handling,用于 routing failures、tool execution errors 和 invalid inputs,并记录 errors,以支持 operation 期间 graceful recovery。
完整 implementation code 和 additional documentation 可在本书 companion GitHub repository 中获得。提供的代码包括 individual agent responses 的 comprehensive unit tests,以及 validation 完整 request-to-response flow 的 integration tests。Test scenarios 覆盖四个主要 support categories,并验证 expected routing behavior 和 response。
这个 design 展示了 intelligent agent orchestration 的核心概念,同时保持足够简单,适合 rapid prototyping 和 experimentation。Strands Agents framework 提供了 solid foundation,可将 system 扩展为 production-ready deployment。
Summary
本章覆盖了 responsible 且 effective 部署 generative AI applications 的 essential pillars。我们探索了 AI data governance 如何扩展 traditional frameworks,以涵盖 unstructured data;考察了 data stewardship 和 metadata management 在让 data 同时对 humans 和 AI agents accessible 中的关键作用;并建立了 unstructured data 的 data quality standards。随后,我们考察了 responsible AI principles——fairness、transparency、accountability、privacy、reliability 和 human oversight,并提供了跨主要 cloud platforms 的 practical implementation guidance。最后,本章讨论了 LLMOps orchestration patterns,从 linear RAG pipelines,到 modular concurrent architectures,再到使用 Strands Agents 等 frameworks 的 multi-agent systems。所有这些 practices 共同构成了 AI systems 的 foundation,使其不仅 powerful,而且 secure、compliant 和 trustworthy。