企业级 RAG 圣诞倒计时:24 天打造完美流水线

今年12月,我创建了上方的这座工厂,作为一个交互式 3D 模型来呈现 RAG 流程。借助 AI 助手把它做出来,过程很有趣。而把 RAG 流水线类比为工厂或商店如何按照客户的需求交付合适的产品,也很值得玩味。你可以在这里体验。
从今天开始,贯穿整个假期季,每天(大致)打开一扇门或一扇窗。每一扇门或窗后面,都有一段简短的动画,展示该流程中的某项技术或某个步骤,后面还附有文章链接。
每篇文章都可以独立阅读。但如果你想了解整条流水线的全貌,最好按顺序阅读这些文章。
希望你们会喜欢这份降临节日历,就像我享受它一丝不苟的筹备过程一样。
1. 对 RAG 流水线来说,什么才是重要的?
几年前,一提到搭建 RAG 流水线,每位 AI 工程师都在谈论更好的嵌入模型和向量数据库。而今天,主要话题变成了智能体框架!用智能体框架写几行代码,似乎就能让魔法发生。
一旦实现了通用方案,业务人员就会抱怨“幻觉”、答案缺失(而答案明明存在)、问题被误解、答案不完整……这时 AI 工程师会说:需要更好的嵌入模型,以及更好的 LLM(我们要用最好的!Fable 5.2!)。
根据我的经验,大多数时候,问题并不出在工具上。起点是真正理解业务问题,并在所有可用工具中挑选出合适的工具,来解决这个具体问题。
那么,真正理解问题意味着什么?构建一个能理解问题的检索增强生成(RAG)流水线又意味着什么?
首先,它必须理解用户提出的问题。也就是理解其意图!
“供应商交货太晚会有罚则吗?”
一个回答“有”的流水线理解了问题,却错失了意图。在专业场景中,用户可能想要的是费率、上限,以及写明这一点的条款。这就是领域专业知识。
它还应当能处理翻译、摘要、两个版本的对比,或针对同一主题但结构不同的文档之间的比较这类请求。从技术上讲,这并不算 RAG,但如果我们能回答这类问题,那也挺好的,对吧?
有时,我们还得做一些计算……例如这个问题:“有多少份合同的通知期在 60 天以内?”显然,答案是一个数字,而且它并没有写在任何文档里。这个答案必须靠计算得出!
然后,它必须读取并结构化公司使用的每一种格式:原生 PDF、扫描版 PDF、Excel、Word、幻灯片、网页、电子邮件等。而其中每一种都可能包含图形、图像、表格……结构还很复杂。
此后,它还必须在成千上万份文档中找到正确的那几份:正确的类型、正确的部分、正确的版本。
最终,它必须融入业务流程,并把领域专业知识整合进来。
每一步都是一个设计决策,你不应该依赖 AI。在公司里搭建检索增强生成(RAG)流程时,我们应当记住:我们不是 Anthropic 或 Google。我们的目标不是打造一个通用流程。我们应该和业务人员沟通,把真实的业务需求整合进来。
所以这个日历在 12 月 1 日到 24 日期间每天给出一条建议,讲的正是贯穿 RAG 流程的这些决策。
在此之前,我们先看看本文开头提到的两个假设,一个关于嵌入(embedding),另一个关于智能体。
1. 检索并不总是需要嵌入
第一个假设,我经常听到它:检索 = 嵌入相似度……
我们来看看 Claude Code 是怎么做的。
1.1. Claude Code 在文档中搜索时做了什么
在做 AI 工程这件事上,Claude Code 是你最好的朋友,对吧?
那么,当你在 Claude Code 里提问时,它同样得做检索增强生成(RAG):找到正确的文档、找到正确的代码文件,或者找到正确的图片。
下次你用 Claude Code 找文档时,问问它是怎么找到正确那一份的。如果你把 Claude Code 里各个不同的步骤都读一遍,或者更好的做法是让它自己描述这些步骤,你就能学到不少技巧。
设想我们有一个装满合同文件的文件夹,里面有供货协议、运输合同、保密协议,还有一份供应商评审的会议纪要。
现在,问题是「当供应商交货太晚时,罚则是什么?」
以下就是逐步发生的过程。
第 1 步:提问。首先,问题会被处理。这里不涉及嵌入向量。LLM 试图理解这个问题,并找出两个关键词,也就是「penalty」和「late」。
第 2 步:搜索模式。Claude Code 并没有只搜索问题里的那两个词。它写了一个包含四个词的正则表达式:
$ rg "(?i)late|delay|liquidated|penalt"
没错,关键词搜索!还能有什么?
事实是,自然语言很复杂,但就搜索而言,关键词搜索仍然是一个非常可靠的工具。
但 LLM 真正的强大之处在于:它能够写出正则表达式,并找到更多关键词。
如果我们看看这个正则表达式,就会看到 "penalt",它是 "penalty" 被截短后的形式。为什么要截短?为了覆盖得更宽一些:"penalt" 既能找到 "penalty",也能找到 "penalties"!
还有另外两个词:"delay" 和 "liquidated"。它们并不在最初的问题中:是模型把它们加进去的!
还有这个符号:(?i)。你知道它的含义吗?如果你不知道,可以搜索一下,你就会更明白为什么这是个好主意。
而且实际上,这是一个相当优雅的正则表达式。
第 3 步:答案。Claude Code 读取了上一步搜索得到的结果,然后用一张表格作答:每个供应商一行,列出费率、上限和条款编号。没错,它相当擅长把答案整理成格式。
这个模式中有两个词来自问题,另外两个词由模型补充。仅凭一个补充的词就能找到一份合同。图片由作者提供
如你所见,这个过程里没有向量索引,也没有 embedding。尽管如此,它在规模可能远大于大多数文档集合的代码仓库中依然运行良好!
现在还有一个问题:分块。是的,即使是关键词搜索,我们也需要在搜索之后确定一个分块大小。我们如何对文档分块,并得到包含该关键词的合适分块?
你如何确定分块大小?我知道很多 AI 工程师(实际上往往是前 ML 工程师)会毫不犹豫地回答:用 MLflow 来学习,并用训练数据集来评估!
好吧,这个就留给你当练习:下次去问 Claude Code。而在这个 Advent Calendar 里,我们会做得更好。
1.2. 当关键词搜索在 Claude Code 中失效时
现在问题来了。同一个文件夹里还有另一份合同——运输合同。但这份合同是用承运方自己的词汇写的,用的是别的说法!我们找不到“late”“delay”或“penalty”这类词。它说的是,当“service level”未达成时,承运方会给予“service credit”!
所以这个流水线漏掉了文件!即使使用了 Fable 5.2!
你看,业务人员一开始会很高兴,但直到他们发现答案并不完整。
那么,什么才是好方法?这正是我们将在这次降临节日历中要解决的问题。
一个提示:它并非来自更好的模型。无论如何,截至 2026 年底,你不会轻易找到比 Fable 5.2 更好的模型。
2. 你真的需要一个智能体来控制你整个业务流程吗?
第二个假设:我们正处于 AI 的新时代!让我们打造 AI 智能体吧!
If/Else 流程?不,不再需要了!
工作流?我们可以做得更好!AI 智能体能够选择自己的路径!
现在,我们将以一个简单的游戏为例,分三个层次来构建它。然后我们再看看这对业务流程意味着什么。
如今,连你的面包师都在谈论 AI 智能体了。那么,AI 智能体究竟是什么?
这里我们采用 AI 智能体的技术定义。让我们以 Pydantic AI 框架为例。
import randomfrom pydantic_ai import Agent, RunContextagent = Agent( 'google:gemini-3.8-flash', deps_type=str, instructions=( "You're a dice game, you should roll the die and see if the number " "you get back matches the user's guess. If so, tell them they're a winner. " "Use the player's name in the response." ),)@agent.tool_plaindef roll_dice() -> str: """Roll a six-sided die and return the result.""" return str(random.randint(1, 6))@agent.tooldef get_player_name(ctx: RunContext[str]) -> str: """Get the player's name.""" return ctx.depsdice_result = agent.run_sync('My guess is 4', deps='Anne')print(dice_result.output)#> Congratulations Anne, you guessed correctly! You're a winner!
在这个示例中,智能体进行游戏,并决定使用不同的工具。文档中有一张图可供阅读。
所以,我们不再创建确定性的流程,而是让智能体自行决定。我们可以看到 LLM 在这些步骤上运行的若干次结果:
获取玩家给出的数字
原文较长,译文为节选;译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。
查看英文原文(Enterprise RAG Advent Calendar: 24 Days to Shape a Perfect Pipeline)
This December, I created the factory above as an interactive 3D model to represent the RAG process. It was fun playing with an AI assistant to create it. And it is also interesting to imagine this comparison between a RAG pipeline and how a factory or shop delivers the right product for the customers' requests. You can play with it here.
One door or window opens each day (give or take), starting today and through the holiday season. Behind each of them, there is a short animation that illustrates the technique or step in the process, followed by a link to the article.
Every article can be read independently. But if you want an overview of the whole pipeline, it is better to follow the articles in order.
I hope that you will enjoy this advent calendar as much as I enjoyed its meticulous preparation.
1. What's important for a RAG pipeline?
A few years ago, when it came to creating a RAG pipeline, every AI engineer was talking about better embedding models and vector databases. Today, the main subject is agent frameworks! And a few lines of code with an agentic framework seem to make the magic happen.
Once a generic solution is implemented, business people complain about "hallucinations," missing answers (while the answer does exist), misunderstood questions, incomplete answers... Then AI engineers would say: better embedding models, and better LLMs (we need the best ones! Fable 5.2!).
In my experience, most of the time, the tool is not the problem. The starting point is to truly understand the business problem, and to select suitable tools among all the available ones to solve this specific problem.
So, what does it mean to truly understand the problem? And to make a RAG pipeline that understands the problem?
First, it has to understand the question that the user asks. The intention!
"Is there a penalty when a supplier's delivery is too late?"
A pipeline that answers "yes" has understood the question, but missed the intention. In a professional context, the user may want the rate, the cap, and the clause that says it. This is domain expertise.
It should also handle requests that are translations, summaries, comparisons of two versions, or comparisons of documents with different structure (but on the same subject). Technically, it is not RAG, but if we could answer these kinds of questions, it would still be nice, right?
Sometimes, we have to do some math... For example, this question: "How many contracts have a notice period under 60 days?" Obviously, the answer is a number, and it is not written in any document. The answer has to be calculated!
Then, it has to read and structure every format the company uses: native PDF, scanned PDF, Excel, Word, slides, web pages, emails, etc. And each of them can contain graphics, images, tables... with complex structures.
After that, it has to find the right documents among thousands: the correct type, the correct part, the correct version.
In the end, it has to fit into a business process, with the domain expertise integrated.
Each step is a design decision, and you should not rely on AI. When creating a RAG pipeline in a company, we should bear in mind that we are not Anthropic or Google. Our aim is not to create a generic pipeline. We should talk to business people and integrate the real business need.
So this calendar gives one tip a day, from 1 to 24 December, on these decisions across the RAG pipeline.
Before that, let's look at two assumptions that I mentioned at the beginning of this article, one about embeddings and the other about agents.
1. Retrieval does not always need embeddings
First assumption, and I constantly hear it: retrieval = embedding similarity...
Let's look at what Claude Code does instead.
1.1. What Claude Code does when searching in documents
Claude Code is your best friend when it comes to doing AI engineering, right?
Now, when you ask questions in Claude Code, it also has to do RAG: to find the correct document, to find the correct code file, or to find the correct image.
Next time you use Claude Code to find a document, ask how it finds the right one. If you read all the different steps in Claude Code, or better yet ask it to describe them, you will already learn many tips.
Imagine we have a folder full of contractual documents, with supply agreements, a transport contract, a confidentiality agreement, and the minutes of a supplier review.
Now, the question is "What is the penalty when a supplier delivery is too late?"
Here is what happened, step by step.
Step 1: the question. First of all, the question is processed. No embeddings are involved. The LLM tries to understand the question and find the two keywords, which are "penalty" and "late".
Step 2: the pattern to search. Claude Code did not search for only the two words in the question. It wrote one regular expression with four words:
$ rg "(?i)late|delay|liquidated|penalt"
Yes, keyword search! What else?
The truth is that natural language is complex, but when it comes to searching, keyword search is still a very solid tool.
But here is the true power of an LLM: its ability to write a regex and to find more keywords.
If we have a look at that regex, we see "penalt", which is "penalty" cut short. Why cut it short? To be a bit broader: "penalt" finds "penalty", and also "penalties"!
And there are two more words: "delay" and "liquidated". They are not in the initial question: the model added them!
And there is this symbol: (?i). Do you know its meaning? If you don't know, you can search for it, and you will better understand why it is a good idea.
And actually, this is quite an elegant regex.
Step 3: the answer. Claude Code read the results of the search done in the previous step, and it answered with a table: one row per supplier, with the rate, the cap and the clause number. Yes, it is quite good at formatting the answer.

Two words of the pattern come from the question, and two are added by the model. One contract is found by an added word alone. Image by author
As you can see, there is no vector index and no embedding in this process. Still, it works fine in repositories that can be much larger than most document collections!
Now, there is one more question: the chunk. Yes, even for keyword search, we need a chunk size after the search. How do we chunk the document and get a suitable chunk that contains the keyword?
How do you find the chunk size? I know many AI engineers (actually often former ML engineers) would answer without hesitating: use MLflow to learn and evaluate with a training dataset!
Well, I leave this one to you as an exercise: next time, ask Claude Code. And in this Advent Calendar, we will do better.
1.2. When keyword search fails in Claude Code
Now the problem. In the same folder there is another contract, the transport contract. But this contract is written in the carrier's own vocabulary, using other words! We can't find any words like "late", "delay" or "penalty". It says that the carrier grants a "service credit" when a "service level" isn't met!
So this pipeline misses the file! Even with Fable 5.2!
You see, business people would be happy at the beginning, but only until they found out that the answers were not complete.
Now, what would be a good approach? This is exactly the kind of question we will tackle in this advent calendar.
One hint: it doesn't come from a better model. Anyway, you will not easily find a better model than Fable 5.2 as of the end of 2026.
2. Do you really need an agent to control your whole business process?
Second assumption: we are in a new era of AI! Let's make AI agents!
If/Else procedure? No, not anymore!
Workflows? We can do better! AI agents are capable of choosing their own path!
Now, we will use a simple game as an example, and build it at three levels. Then we'll look at what this means for a business process.
Even your baker is talking about AI agents nowadays. So, what actually is an AI agent?
Here we will use the technical definition of an AI agent. Let's take the example of the Pydantic AI framework.
import randomfrom pydantic_ai import Agent, RunContextagent = Agent( 'google:gemini-3.8-flash', deps_type=str, instructions=( "You're a dice game, you should roll the die and see if the number " "you get back matches the user's guess. If so, tell them they're a winner. " "Use the player's name in the response." ),)@agent.tool_plaindef roll_dice() -> str: """Roll a six-sided die and return the result.""" return str(random.randint(1, 6))@agent.tooldef get_player_name(ctx: RunContext[str]) -> str: """Get the player's name.""" return ctx.depsdice_result = agent.run_sync('My guess is 4', deps='Anne')print(dice_result.output)#> Congratulations Anne, you guessed correctly! You're a winner!
In this example, the agent plays the game and decides to use different tools. There is a diagram that you can read in the documentation.
So, instead of creating a deterministic process, we let the agent decide. And we can see several runs of the LLM working on these steps:
Get the number that the player gives
Compare the result and conclude
This agent is capable of using natural language instructions, both as input (user prompt) and as game instructions (system prompt) to play this game. So we don't have to clearly define order and the objective (the mathematical objective, which is the equality of the two numbers); the LLM decides.
Some would even ask: why even use a Python function to get a random number? Why not use the LLM?
And some would say: bad question! Because the LLM doesn't know how to truly choose a random number. And we should use a Python function for mathematical operations!
Now, don't you see a little problem here? Checking if the random number is equal to the number given by the player is also a mathematical operation!
So here are the important questions that we should raise: in the era of AI agents, when should we choose to use an LLM?
2.2. One game, three levels
Now, let's analyze the previous game. There are three ways of doing it. The agentic way is the third and highest level. But hey, why would we use a cannon to kill a fly?
And of course, the frontier between the three levels can be blurred. This is only conceptual.
Level 1: deterministic process.
For this simple game, we can define the exact order of these steps:
First, the input of the player can only be a number (between 1 and 6). No natural language input.
Then we roll the dice. And it is important to roll the dice after getting the guess; otherwise, the player could cheat.
Finally, a simple equality check will give the final result.
import randomPLAYER = 'Anne'def ask_for_guess() -> int: """Ask the player for a number, and accept it only if it is a whole number from 1 to 6.""" while True: typed = input('Your guess, from 1 to 6: ') if typed.isdigit() and 1 <= int(typed) <= 6: return int(typed) print('This is not a number from 1 to 6. Try again.')guess = ask_for_guess()roll = random.randint(1, 6)if roll == guess: print(f'Congratulations {PLAYER}, you guessed {guess} and the die shows {roll}. You win!')else: print(f'Sorry {PLAYER}, you guessed {guess} and the die shows {roll}. Try again!')
Of course, it does only one thing, and the interface is very fixed. And it is not comparable to the agentic framework, but I am still giving this example because in real life, I have already seen developers create a chatbot for a single use!
Level 2: controlled workflow with AI integration. We enter one sentence, the LLM parses it, then we use the tools that are detected.
Here the interface is also a chatbot. The only step that needs a model is reading the player's message: one call returns what we need in a typed template. After that, we use a simple function to check the result. At the end, we can either use a deterministic message or the LLM to generate the final message.
Here, we use the LLM for what it is good at: understanding natural language.
So the player doesn't have to type a number. They can write "My guess is 4".
They can make mistakes: "i gess foor" or "oneis my guess".
Or they can also write in French: "je joue le 4", "le quatre".
The LLM will easily get the number.
For this example, the interest may be limited. But you see the potential.
import randomfrom openai import OpenAIfrom pydantic import BaseModel, FieldPLAYER = 'Anne'class Turn(BaseModel): guess: int = Field(ge=1, le=6, description='The number the player guessed, from 1 to 6')response = OpenAI().responses.parse( # the only call to the model: it reads the sentence model='gpt-4.1', instructions="Read the player's message and return the number they guessed.", input='My guess is 4', text_format=Turn,)turn = response.output_parsedroll = random.randint(1, 6) # code rolls the dieif roll == turn.guess: # code applies the rule of the game print(f'Congratulations {PLAYER}, you guessed {turn.guess} and the die shows {roll}. You win!')else: print(f'Sorry {PLAYER}, you guessed {turn.guess} and the die shows {roll}. Try again!')
Once we have the number, the model's work is over. We use a simple Python function to roll the die, and the comparison is math: roll == turn.guess.
Maybe you have seen these posts saying that an LLM doesn't know which one is larger, 9.11 or 9.9. Newer, better models get it right. The principle remains: if you can do something without an LLM, do it without it!
Level 3: AI agents. This is the example from Pydantic AI that I showed before. For many, this is the future of programming: instead of programming code in a traditional way, we can write skills and instructions directly in natural language.
But as we discussed before, in practice, we should ask:
Which tools can we create with classic programming?
Which steps could we control?
Which tasks can we delegate to LLMs?
When I say THREE levels, the frontier between them can be blurred. And here is a recap for the game:
The same dice game at three levels, measured on twelve games with gpt-4.1 for levels 2 and 3. Image by author
2.3. Workflows vs Agents
In many companies, a huge gap is observed between the two worlds:
On one hand, many people still use classic tools to do manual work: extracting information from documents into a system or even Excel, routing a request received by email, verifying information from documents... This is level 1.
On the other, AI agents can automate complex tasks, even without human intervention. All the tasks above can be done, from end to end: let's put all the documents in a server that AI agents can access. Creating skills is the only thing to be done. This is level 3.
And of course, level 3 is very much desired. But in practice, I would suggest that we begin with Level 2: workflow with AI integrated into the different steps. Here is why.
First, it costs too much and it is slower. Let's take the guessing game as an example again.
I ran the game 12 times at levels 2 and 3:
Result: Every answer was right.
Number of LLM calls: Level 3 makes two calls to the model. Level 2 makes one.
Run time: Level 3 takes 4.8 seconds instead of 1.9, and uses about four times the tokens.
Levels 2 and 3 on the same twelve games with gpt-4.1: both are right every time, and level 3 costs about four times the tokens. Image by author
Second, it doesn't scale for the choice of tools. At every call, the model reads the description of every tool, whether it uses the tool or not. If we have more tools, this choosing process is the main job! Yes, an agentic framework is good for demos. And in real life, one of the difficult jobs is not to use or create an agentic framework, but to create the process of choosing tools.
Third, and the most important reason for me: explainability and control of the agents in a business process.
Yes, Claude Code is a level 3: the model chooses its own tools. It fits there, because the task is open and a person is watching, and it is a process to create. But a business process is a known path.
You will say that level 2 isn't generic anymore, and that's true. But in a company, this is usually the situation: the process is known, and it's exactly what has to be done. An agent for a company isn't a generic agent, and it doesn't have to be.
If you already know the process, why would you let the AI agent decide?
I often hear certain consultants say: with AI agents, you don't need to create complex workflows anymore. AI agents will help you!
This is the kind of consultants who don't know the business, try to help, and say that AI will replace humans.
This is exactly the same symptom as when AI engineers say: "oh no, not keyword search, this is too archaic. We make AI agents now!"
You know what? If you want real results, you have to get your hands dirty! Not dirty hands from training models, but dirty hands from knowing the business problem.
Once the overall process is defined, we should use an LLM in each step depending on whether it is useful.
3. Four parts for a complete RAG pipeline
The month follows the order in which a RAG system can be built with real-life constraints.
Part 1 is about document parsing and indexing: reading the formats a company really has, from scanned files to spreadsheets and emails (that also have attached files). And then, we will use a common database structure to store the content of all these files, so that the following steps will be identical. Remember: structure is important, hierarchical structure is important.
Part 2 is about question parsing and document retrieval. Creating an embedding of the question is not an optimal way to understand it. There are multiple ways to analyze the question: as we saw, extracting keywords is an efficient way as we saw, and we will do a deeper analysis. And for each method of question parsing, we also have the corresponding way of retrieving the passage.
Part 3 is about generation with validation, and the tools. It is important to check the answer and to distinguish different types of answers: quotes, reformulations, interpretations, calculations. And for each type, tools may be used.
Part 4 is about the usage of agents in the whole business process. Agents are specialized for specific tasks and steps. The loop is important and it is very much under control, across all the steps, from reading the document to checking the answer. We will also trace an answer step by step, give the process a memory and reference data, and count what one case costs.
To illustrate how the whole RAG pipeline works, I created this magnificent factory, which you can see at the beginning of this article. There are different workshops, each with its own job, and a store where what one workshop makes is kept for the others.
Each part has its own building, in the order of a build: read, retrieve, control and run.
RAG is often treated as an IT project, without business people involved. The whole technical stack is usually implemented without asking any questions: standard PDF reading, classic OCR, embeddings stored in a vector database, similarity search, reranking, and a chatbot to generate with the whole context in bulk...
In this advent calendar for enterprise RAG, I want to show some rarely taught techniques with a reflection on how these techniques should be understood from a human point of view. What would a human expert do in these cases? This is an important guideline that I always have in mind.
The first door opens with the first step of the pipeline: parsing a PDF. Stay tuned, and wnjoy!
An overview of popular techniques to confine LLMs' output to a predefined schema
August 8, 202511 min read
If you have both unique domain expertise and know how to make it usable to your AI systems, you’ll be hard to beat.
March 1, 202611 min read
Key steps to using RAG for generating MCQs from Wikipedia articles based on user-defined context
May 30, 202511 min read
Three Python classes, an OpenRouter key, and gpt-4.1-mini give the agent a calculator, a stub web search, and conversation recall that survives restarts.
November 6, 202617 min read
Learn how to optimize your CI/CD pipeline for coding agents
August 10, 20267 min read
Why the future of AI memory relies on persistent neural state, not vector databases.
July 10, 20267 min read
What practitioners need to know about this LLM agent benchmark
Practical field notes on workflows, structure, and evaluation from two years of building with engineering domain experts.
November 25, 202518 min read
A quick-start guide to using open-source LLMs
August 5, 202310 min read
原文为英文,正文由自动抓取并保留原文。
原文发布于 Towards Data Science(Enterprise RAG Advent Calendar: 24 Days to Shape a Perfect Pipeline),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。