批处理与异步操作
为嵌入生成实现批处理,并对 LLM 应用程序接口执行异步调用,以提升吞吐量。
批处理与异步操作 是 CoddyKit 上的免费 LLM Apps in Production (RAG + Vector DB + Caching) 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 LLM Apps in Production (RAG + Vector DB + Caching) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 LLM Apps in Production (RAG + Vector DB + Caching) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Boosting RAG Performance
Your RAG application is working, but is it fast and cost-effective? As user traffic grows, you'll need to optimize how your app interacts with LLMs and vector databases.
In this lesson, we'll explore two powerful techniques: batching and asynchronous operations. These can significantly improve your RAG system's throughput and reduce operational costs.
One Task at a Time
Imagine you have a list of documents, and you need to get embeddings for each one. In a synchronous approach, your program would process each document one by one.
- It sends a request for Document 1.
- It waits for the embedding to return.
- Then, it sends a request for Document 2.
- It waits again.
This "wait-and-process" model is simple but can be very slow, especially with many I/O operations like API calls.
Doing Things in Parallel
Asynchronous operations allow your program to send multiple requests without waiting for each one to complete before starting the next. Think of it like a restaurant manager taking multiple orders before any food is ready.
- Send request for Document 1.
- Immediately send request for Document 2.
- Immediately send request for Document 3.
- Collect results as they become available.
This approach keeps your program busy, leading to much faster overall completion times for many tasks.
How Async Works (Conceptual)
While the exact implementation varies by language, the core idea is to avoid blocking your main program thread. For example, in Java, you might use CompletableFuture to manage tasks that run in the background.
Here's a conceptual look at how you might call an LLM API asynchronously:
// Conceptual Async Call
CompletableFuture<String> futureResponse1 = llmApi.generateAsync("prompt 1");
CompletableFuture<String> futureResponse2 = llmApi.generateAsync("prompt 2");
// Do other work while responses are being generated
// Get results when ready
String response1 = futureResponse1.join();
String response2 = futureResponse2.join();This allows your application to perform other computations while waiting for I/O-bound LLM responses.
Grouping for Efficiency
Batching is the strategy of grouping several individual items or requests into a single, larger request. Many LLM providers and embedding services support batching.
- Instead of 10 separate API calls for 10 documents, make 1 API call for a "batch" of 10 documents.
- This reduces the overhead of establishing connections and processing each request individually.
- It can also be more cost-effective as some APIs charge less per token for batched requests.
Why Batch Embeddings?
Generating vector embeddings for documents is a perfect use case for batching. When you load a large dataset, you'll have many text chunks that need to be converted into vectors.
Sending these in batches to your embedding model API means:
- Fewer API calls: Reduced network latency and overhead.
- Higher throughput: Process more text in the same amount of time.
- Potential cost savings: Some APIs offer better pricing for larger batches.
Batching Embeddings Code
Let's see how to implement a simple batching mechanism for embedding generation. We'll simulate an embedding service that takes a list of texts.
This example processes a list of documents in chunks (batches) to send to an embedding service. Notice how we group documents before calling the mock service.
public class Main {
// Simulate an embedding client
static class MockEmbeddingClient {
public double[][] getEmbeddings(String[] texts) {
System.out.println("Processing batch of " + texts.length + " texts...");
// Simulate network latency
try {
Thread.sleep(100 * texts.length); // Slower for larger batches
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
double[][] embeddings = new double[texts.length][3]; // 3D for simplicity
for (int i = 0; i < texts.length; i++) {
embeddings[i][0] = texts[i].length() * 0.1;
embeddings[i][1] = texts[i].hashCode() % 100;
embeddings[i][2] = i;
}
return embeddings;
}
}
public static void main(String[] args) {
MockEmbeddingClient client = new MockEmbeddingClient();
String[] documents = {
"The quick brown fox jumps over the lazy dog.",
"Never underestimate the power of a good book.",
"Artificial intelligence is transforming industries.",
"Retrieval Augmented Generation enhances LLM accuracy.",
"Batching improves efficiency for embedding calls.",
"Asynchronous operations prevent blocking.",
"CoddyKit makes learning fun and interactive.",
"Optimizing RAG saves costs and boosts speed."
};
int batchSize = 3;
for (int i = 0; i < documents.length; i += batchSize) {
int endIndex = Math.min(i + batchSize, documents.length);
String[] currentBatch = new String[endIndex - i];
System.arraycopy(documents, i, currentBatch, 0, endIndex - i);
double[][] batchEmbeddings = client.getEmbeddings(currentBatch);
System.out.println("Received " + batchEmbeddings.length + " embeddings for this batch.");
// In a real app, you'd store these embeddings in a vector database
}
System.out.println("All documents processed in batches.");
}
}Async + Batching = Super RAG
The real power comes from combining both techniques. You can make asynchronous calls to batched requests.
- Group your documents into batches.
- Send each batch request to the API asynchronously.
- Your program can then manage multiple concurrent batch requests, maximizing throughput.
This is crucial for ingesting massive amounts of data or handling high-volume real-time embedding lookups.
Batching & Async Pitfalls
While powerful, batching and async operations require careful handling:
- API Rate Limits: Don't send too many requests too quickly, even if they're batched. Respect API limits.
- Memory Usage: Very large batches can consume significant memory. Find an optimal batch size.
- Error Handling: If one item in a batch fails, how do you handle it? Design robust error recovery.
- Latency vs. Throughput: Async improves throughput, but might not reduce the latency of a single request.
Optimize Your Workflow
You're working on a RAG application that needs to process thousands of customer reviews to generate embeddings for a vector database. Which strategies would be most effective to improve the efficiency and speed of this data ingestion process?
Summary: Faster, Cheaper RAG
Great job! You've learned how to supercharge your RAG system's performance and cost-efficiency.
- Asynchronous operations allow concurrent processing, reducing overall wait times for I/O-bound tasks.
- Batching groups multiple small requests into larger ones, cutting down on API overhead and potentially saving costs.
- Combining both techniques provides the most powerful optimization for high-volume data processing in RAG.
These strategies are essential for building scalable and robust LLM applications in production.
常见问题解答
「批处理与异步操作」课时是免费的吗?
是的 — 「批处理与异步操作」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 LLM Apps in Production (RAG + Vector DB + Caching) 课程的其余内容,请升级到 CoddyKit PRO。 LLM Apps in Production (RAG + Vector DB + Caching) 课程共包含 4 节课。
「批处理与异步操作」这节课中我会学到什么?
为嵌入生成实现批处理,并对 LLM 应用程序接口执行异步调用,以提升吞吐量。 你通过在浏览器中直接运行的动手代码来练习 LLM Apps in Production (RAG + Vector DB + Caching),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 LLM Apps in Production (RAG + Vector DB + Caching) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 LLM Apps in Production (RAG + Vector DB + Caching) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「批处理与异步操作」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 LLM Apps in Production (RAG + Vector DB + Caching) 课中编写并运行代码吗?
能。每节 LLM Apps in Production (RAG + Vector DB + Caching) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 提升效率的提示词工程
- 批处理与异步操作
- 监控成本与延迟
- 为任务选择合适的模型