Building Production-Grade Heterogeneous RAG Systems

aws_genaiic · Tech · 2024 · source Agentic: no · promotional bias: med · source-backed · extracted with prompt 0.5.5 (schema v2)

Generated from extraction.json — do not edit by hand. Every claim cites verbatim source evidence; stated means the quote directly asserts the claim, implied means it supports it indirectly.

Problem

Domain: Heterogeneous RAG over text, tables, images, and domain-specific data sources

AWS GenAIIC needed reusable production patterns for RAG systems that answer questions across heterogeneous data formats, including unstructured text, structured tables, images, diagrams, and domain-specific files, while routing queries to the right pipeline, preserving latency, avoiding hallucination, and choosing the right multimodal embedding or captioning strategy.

Constraints:

Architecture

The architecture uses a router as the front door for heterogeneous RAG. An initial LLM call classifies the user query into a data source or asks for clarification. Text questions go to text RAG; quantitative tabular questions go to an LLM code-generation pipeline that writes Python or SQL, executes it, and may return the result directly; multimodal questions go to either a shared multimodal embedding index or an image-captioning plus text-embedding index. OpenSearch vector indexes store embeddings; Amazon Bedrock provides Claude and Titan models; structured XML tags and parsing make LLM outputs machine-readable; and custom code pipelines add sanity checks around generated code.

Diagram confidence: reconstructed (reconstructed from prose).

flowchart LR
  user-query["User query"] --> router-llm["Router LLM"]
  router-llm --> clarification-path["Clarification path"]
  clarification-path --> user-query
  router-llm --> text-rag-pipeline["Text RAG pipeline"]
  router-llm --> structured-data-pipeline["Structured data pipeline"]
  router-llm --> multimodal-rag-pipeline["Multimodal RAG pipeline"]
  text-rag-pipeline --> text-document-index["Text/document index"]
  text-rag-pipeline --> answer-llm["Answer LLM"]
  structured-data-pipeline --> code-generator["Code generator"]
  code-generator --> code-parser["Code parser"]
  code-parser --> code-execution-environment["Code execution environment"]
  code-execution-environment --> answer-llm
  multimodal-rag-pipeline --> multimodal-embedding-index["Multimodal embedding index"]
  multimodal-rag-pipeline --> caption-embedding-index["Caption embedding index"]
  multimodal-embedding-index --> amazon-titan-multimodal-embeddings["Amazon Titan Multimodal Embeddings"]
  caption-embedding-index --> claude-image-captioner["Claude image captioner"]
  caption-embedding-index --> amazon-titan-text-embeddings["Amazon Titan Text Embeddings"]
Drag to pan · scroll or use +/− to zoom · reconstructed from the source's described component topology

Components

Component Role Interacts with
User query Natural-language text or image-plus-text request over heterogeneous data sources. Router LLM
Router LLM Small initial LLM call that performs intent detection and selects a data source or clarification path. Clarification path, Text RAG pipeline, Structured data pipeline, Multimodal RAG pipeline
Clarification path Pseudo-data source for ambiguous queries, returning the router's reason text as a clarification question. User query
Text RAG pipeline Traditional retrieval pipeline over unstructured text documents and knowledge bases. Text/document index, Answer LLM
Structured data pipeline Table-analysis path that prompts an LLM to write Python or SQL for quantitative questions. Code generator, Code execution environment, Answer LLM
Code generator Claude/LLM prompt that writes Python or SQL code and stores the final result in a known variable. Code parser, Code execution environment
Code parser Structured-output parser that extracts generated code from XML-like tags. Code execution environment
Code execution environment Controlled Python or SQL execution layer that runs generated analysis code and returns results or sends them to an LLM. Answer LLM
Multimodal RAG pipeline Routing target for text-to-image, image-to-text, and image-plus-text retrieval use cases. Multimodal embedding index, Caption embedding index
Multimodal embedding index OpenSearch k-NN index where image and/or text queries are embedded into a shared vector space. Amazon Titan Multimodal Embeddings
Caption embedding index OpenSearch index storing images, generated captions, caption embeddings, and metadata. Claude image captioner, Amazon Titan Text Embeddings
Amazon Titan Multimodal Embeddings Embedding model that maps images and text into a shared vector space for direct multimodal retrieval. Multimodal embedding index
Claude image captioner Multimodal foundation model that converts images into detailed captions before text embedding. Caption embedding index
Amazon Titan Text Embeddings Text embedding model that vectorizes generated captions and natural-language queries for caption-based image retrieval. Caption embedding index
Answer LLM LLM that synthesizes retrieved text or code outputs into a final answer when direct result return is not preferable. —
Text/document index Knowledge base over reports, FAQs, technical documents, analyst notes, filings, manuals, and other unstructured sources. Text RAG pipeline

Data flow

A user query enters the router. The router prompt describes available data sources, asks the LLM to reason about the destination, and returns XML-tagged routing output. If the query is ambiguous, the Clarifications pseudo-source returns a clarification question. Text questions go to a document RAG pipeline. Tabular questions go to a code-generation pipeline where Claude writes Pandas or SQL code, the system extracts code from tags, executes it against a dataframe or database, and either returns the code output directly or sends it back to the LLM. Image/text multimodal questions either embed both modalities into a shared vector space with Amazon Titan Multimodal Embeddings, or caption images with Claude and embed captions with Amazon Titan Text Embeddings before storing image, caption, and vector metadata in OpenSearch.

3 supporting quotes
“In RAG systems, a router is a component that directs incoming user queries to the appropriate processing pipeline based on the query’s nature and the required data type.”article, stated
“The router accomplishes this through intent detection, analyzing the query to determine the type of data and analysis required to answer it.”article, stated
“If in the LLM’s response, the data source is Clarifications, we can then directly return the content of the <reason> tags to the user for clarifications.”article, stated

Why this architecture

The architecture breaks heterogeneous RAG into modular pipelines because text documents, large tables, quantitative analysis, images, and diagrams have different failure modes. Routing avoids sending every query through the same retriever. LLM code generation leverages model strengths for structured analysis while allowing direct return of large outputs. Multimodal embeddings are efficient for broad visual similarity, while captioning supports more detailed, prompt-customized image retrieval.

"when dealing with heterogeneous data sources, because different data types often require distinct retrieval and processing strategies. Consider a financial data analysis system. For a qualitative question like “What caused inflation in 2023?”, the router would direct the query to a text-based RAG" — article, stated "LLMs don’t perform well at analyzing tabular data when it’s added directly in the prompt as raw text. A simple way to improve the LLM’s handling of tables is to add it in the prompt in a more structured format, such as markdown or XML. However, this method" — article, stated "analyze tabular data, even when provided as structured format in the prompt. On the other hand, LLMs are notably good at code generation; for instance, Anthropic’s Claude Sonnet 3.5 has 92% accuracy on the" — article, stated "Constructing a multimodal retriever requires having an embedding strategy that can handle this multimodality. There are two main options for this. First, you could use a multimodal embedding model such as [Amazon Titan Multimodal" — article, stated "The key to success lies in breaking down the problem into modular components and using the strengths of FMs for each component." — article, stated

Models used: Anthropic Claude Haiku on Amazon Bedrock · Anthropic Claude Sonnet · Anthropic Claude Sonnet 3.5 · Anthropic Claude Opus · Amazon Titan Multimodal Embeddings · Amazon Titan Embedding Text v2 · OpenSearch k-NN vector search

Scale

Alternatives considered (roads not taken)

Use one text-only RAG pipeline for every query.

Rejected because: Heterogeneous data sources require different handling for text, tables, and multimodal content.

"text-only RAG solutions, from optimizing the retriever to mitigating and detecting hallucinations. This post focuses on doing RAG on heterogeneous data formats. We first introduce routers, and how they can help managing diverse data sources. We then give tips on how to handle tabular" — article, stated "when dealing with heterogeneous data sources, because different data types often require distinct retrieval and processing strategies. Consider a financial data analysis system. For a qualitative question like “What caused inflation in 2023?”, the router would direct the query to a text-based RAG" — article, stated

Put raw tables directly into the LLM prompt.

Rejected because: That only works for small tables and simple reasoning; complex quantitative questions need code generation and execution.

"this method will only work if the question doesn’t require complex quantitative reasoning and the table is small enough." — article, stated "we can’t reliably use an LLM to analyze tabular data, even when provided as structured format in the prompt. On the other hand, LLMs are notably good at code generation; for instance, [Anthropic’s Claude Sonnet 3.5 has 92%" — article, stated

Always send generated code output back to the LLM for final wording.

Rejected because: For large filtered dataframes, returning the code output directly can be more efficient and avoids hallucination from large inputs/outputs.

"oil on June 1st 2024.” There could be hundreds of entries in the dataframe. In that case, a custom pipeline that directly returns the code output to the UI (the filtered dataframe for the date of June 1st 2024, with oil production greater than 0) would be more efficient than" — article, stated "Directly returning the variable to the user removes the risk of hallucination that can occur with large inputs and outputs." — article, stated

Use direct multimodal embeddings for all visual retrieval.

Rejected because: Multimodal embeddings are faster and cheaper but less customizable; captioning with a multimodal LLM captures finer details and prompt-guided aspects.

"for image captioning, across several key factors. Multimodal embeddings offer faster ingestion and are generally more cost-effective, making them suitable for large-scale applications where speed and efficiency are crucial. On the other hand, using a multimodal LLM for captions, though slower" — article, stated "using a multimodal LLM for captions, though slower and less cost-effective, provides more detailed and customizable results" — article, stated

Use prompt-based routing only.

Rejected because: The article notes that Bedrock Converse API tool use/function calling can define each data source as a tool for routing.

"An alternative approach to routing is to use the native tool use capability (also known as function calling) available within the Bedrock Converse API. In this scenario," — article, stated "each category or data source would be defined as a ‘tool’ within the API, enabling the model to select and use these tools as needed. Refer to this documentation for a detailed" — article, stated

Patterns

model-routing (architecture)

A router LLM performs intent detection and dispatches each query to the correct data-source pipeline or clarification flow.

"The router accomplishes this through intent detection, analyzing the query to determine the type of data and analysis required to answer it." — article, stated "we recommend using a smaller model, such as Anthropic’s Claude Haiku" — article, stated

structured-output-contract (reliability)

Router and code-generation prompts require XML-like tags so the system can parse routing categories, reasons, and code blocks programmatically.

"Asking the LLM to also structure its response with XML tags allows us to parse out the category from the LLM answer" — article, stated "- Put your the code in tags. - The dataframes may contain nans, so make sure you account for those in your code." — article, stated

rag-retrieval (architecture)

The system retrieves from text knowledge bases, structured data, multimodal image indexes, and caption indexes before answering.

"text-based RAG that retrieves relevant documents and uses an LLM to generate an answer based on textual information." — article, stated "As with traditional RAG pipelines, the retrieval component is the basis of these solutions." — article, stated

tool-use-orchestration (architecture)

The article proposes Bedrock tool use/function calling for routing and code-generation pipelines that run Python or SQL against data stores.

"An alternative approach to routing is to use the native tool use capability (also known as function calling) available within the [Bedrock Converse API](https:" — article, stated "asking the LLM to write Python (if the data is stored in a CSV, Excel, or Parquet file) or SQL" — article, stated

guardrails-io-filtering (safety)

Custom code-generation pipelines can sanity-check generated code and avoid sending large code outputs back to the LLM when that would increase latency or hallucination risk.

"Writing your custom pipelines also allows you to perform some sanity checks on the code" — article, stated "Directly returning the variable to the user removes the risk of hallucination" — article, stated

latency-optimization (operations)

The router uses a smaller model to reduce routing latency, and direct code-output return avoids extra LLM calls for large tabular results.

"To avoid adding too much latency with the routing step, we recommend using a smaller model" — article, stated "the additional call might cause high latency and even risks causing hallucinations." — article, stated

cost-aware-routing (operations)

The multimodal strategy weighs direct multimodal embeddings against multimodal LLM captioning based on speed, cost, detail, and customization needs.

"Multimodal embeddings offer faster ingestion and are generally more cost-effective" — article, stated "though slower and less cost-effective, provides more detailed and customizable results" — article, stated

Tradeoffs

Use an LLM router before retrieval.

Chose Intent detection with a small routing model over Sending all queries to one retrieval pipeline.

Rationale: The router makes sure each data type is processed appropriately, but the routing step must use a small model to avoid adding too much latency.

"In systems with heterogeneous data, this process makes sure each data type is processed appropriately, whether it’s unstructured text, structured tables, or multimodal content." — article, stated "To avoid adding too much latency with the routing step, we recommend using a smaller model" — article, stated

Use generated code for structured data analysis.

Chose Python or SQL generation plus execution over Putting the whole table into the prompt.

Rationale: Code execution handles quantitative filtering, aggregation, and plotting better than raw table prompting for complex or large data.

"On the other hand, LLMs are notably good at code generation; for instance, [Anthropic’s Claude Sonnet 3.5 has 92% accuracy](https:" — article, stated "we can’t reliably use an LLM to analyze tabular data, even when provided as structured format in the prompt." — article, stated

Return some code outputs directly instead of asking the LLM to narrate them.

Chose Direct UI return for large filtered dataframe results over Always sending code output back to the LLM.

Rationale: Direct return is more efficient and avoids hallucination risk when the result is already the requested data.

"In that case, a custom pipeline that directly returns the code output to the UI (the filtered dataframe for the date of June 1st 2024, with oil production greater than 0) would be more efficient than sending it to the LLM for a final answer." — article, stated "Directly returning the variable to the user removes the risk of hallucination" — article, stated

Choose multimodal embeddings for broad visual similarity.

Chose Amazon Titan Multimodal Embeddings in a shared vector space over Caption-first retrieval for every image.

Rationale: Direct multimodal embeddings are faster and more cost-effective for high-level image/text matching.

"Titan Multimodal Embeddings](https://docs.aws.amazon.com/bedrock/latest/userguide/titan-multiemb-models.html), which can embed both images and text into a shared vector space. This allows for direct comparison and retrieval of text and images based on semantic similarity. This simple approach" — article, stated "This simple approach is effective for finding images that match a high-level description" — article, stated

Use caption-first retrieval for detailed visual understanding.

Chose Claude image captions plus Titan Text Embeddings over Only comparing raw image/text embeddings.

Rationale: Generated captions can focus on specific visual attributes and capture diagram complexity, at the cost of an extra LLM call and slower ingestion.

"generated image description is embedded using a traditional text embedding" — article, stated "This would also work better to capture the complexity of diagrams in industrial maintenance." — article, stated

Gotchas (what bit them)

A single retriever will mis-handle heterogeneous data.

Root cause: Tables, documents, images, and multimodal questions require different retrieval and processing logic.

Resolution: Use a router to dispatch to specialized pipelines for text RAG, structured data/code generation, and multimodal retrieval.

"different data types often require distinct retrieval and processing strategies." — article, stated "whether it’s unstructured text, structured tables, or multimodal content." — article, stated

Prompting directly over tables breaks down for complex quantitative analysis.

Root cause: LLMs do not reliably analyze raw tables in prompts unless the data is small and reasoning is simple.

Resolution: Ask the LLM to generate Python or SQL, execute the code, and return the computed result.

"LLMs don’t perform well at analyzing tabular data when it’s added directly in the prompt as raw text." — article, stated "asking the LLM to write Python (if the data is stored in a CSV, Excel, or Parquet file) or SQL" — article, stated

Large tabular outputs can create latency and hallucination risk when re-fed to the LLM.

Root cause: A large filtered dataframe adds another LLM call and large input/output surface.

Resolution: Return code output directly to the UI for large filtering tasks when a natural-language final answer is unnecessary.

"If the filtered dataframe is large, the additional call might cause high latency and even risks causing hallucinations." — article, stated "Directly returning the variable to the user removes the risk of hallucination that can occur with large inputs and outputs." — article, stated

Generated code can damage files or databases if executed blindly.

Root cause: LLM-written Python or SQL may contain operations that modify existing files or databases.

Resolution: Build custom pipelines with code sanity checks before execution.

"perform some sanity checks on the code, to verify, for instance, that the code generated by the LLM will not create issues" — article, stated "Writing your custom pipelines also allows you to perform some sanity checks on the code, to verify, for instance, that the code generated by the LLM will not create issues (such as modify existing files or data bases)." — article, stated

Multimodal embedding and captioning approaches optimize for different things.

Root cause: Direct multimodal embeddings are efficient but less customizable; captions add an LLM call but capture finer, prompted details.

Resolution: Choose direct multimodal embeddings for quick broad matching, and caption-based retrieval for detailed or aspect-specific searches.

"Captions can capture finer details in images, and can be guided to focus on specific aspects such as color, fabric, pattern, shape, and more." — article, stated "Considerations such as latency for different input types, customization needs, and the level of detail required in the output should guide the decision-making process" — article, stated

Evaluation

The article evaluates by decomposing known customer-use-case classes and comparing design choices rather than reporting benchmark results for a deployed system. Its evaluation guidance is qualitative and architectural: route correctness, parseable structured outputs, code sanity, latency, hallucination risk, retrieval fit for each modality, and the comparative cost/speed/detail tradeoffs of multimodal embeddings versus caption-based retrieval.

Metrics: Router category accuracy and debuggability through explanation tags · Clarification rate for ambiguous queries · Latency added by the routing step · Correctness of generated Python or SQL analysis code · Hallucination risk when large code outputs are sent back to the LLM · k-NN retrieval results in OpenSearch · Multimodal embedding ingestion speed and cost · Captioning detail and customization quality · Image-input latency with or without extra caption-generation calls · Suitability for text-to-image, image-to-text, and image-plus-text retrieval

"Prompting the LLM to explain the routing logic may help with accuracy, by forcing the LLM to “think” about its answer, and also for debugging purposes" — article, stated "ask for clarifications in the router, if the LLM finds that the query is too ambiguous." — article, stated "The closest images are then returned. ![This diagram shows the retrieval of images from a user query in a vector database using a multimodal embedding." — article, stated "Multimodal embeddings offer faster ingestion and are generally more cost-effective" — article, stated "as multimodal LLM Same as multimodal embeddings Image Input Latency Faster, no extra processing required Slower, requires extra LLM call to generate image caption Best Use Case General use, quick and efficient data handling Precise searches needing detailed image descriptions ##" — article, stated

Outcomes

  • AWS GenAIIC reports building heterogeneous RAG systems across field engineering, oil and gas, financial analysis, industrial maintenance, and ecommerce product search.
  • The guide establishes a modular router pattern for routing queries to text, structured data, multimodal, or clarification pipelines.
  • The structured-data pattern uses LLM-generated Python/SQL plus execution, with optional direct result return to avoid latency and hallucination.
  • The multimodal pattern offers two production options: direct multimodal embeddings or multimodal-caption plus text-embedding retrieval.
  • The article does not disclose named customer deployments or quantitative production outcomes.

Concrete scale signals include five use-case families, hundreds of dataframe entries in the oil-and-gas example, 92% HumanEval cited for Claude Sonnet 3.5 code generation, k=5 nearest-neighbor retrieval examples, and three multimodal question categories.

"Use cases we have worked on include: * Technical assistance for field engineers – We built a system that aggregates information about a company’s specific products and field expertise." — article, stated "Building real-world RAG systems with heterogeneous data formats presents unique challenges" — article, stated "By employing techniques like intent detection, code generation, and multimodal embeddings, you can create intelligent systems" — article, stated "enabling seamless integration of images and other media into your knowledge bases." — article, stated "specific company names and quantitative results are not disclosed, which limits the ability to verify claims independently." — summary, stated