Retrieval-augmented generation (RAG)
Genkit provides abstractions that help you build retrieval-augmented generation (RAG) flows, as well as plugins that provide integrations with related tools.
What is RAG?
Section titled “What is RAG?”Retrieval-augmented generation is a technique used to incorporate external sources of information into an LLM’s responses. It’s important to be able to do so because, while LLMs are typically trained on a broad body of material, practical use of LLMs often requires specific domain knowledge (for example, you might want to use an LLM to answer customers’ questions about your company’s products).
One solution is to fine-tune the model using more specific data. However, this can be expensive both in terms of compute cost and in terms of the effort needed to prepare adequate training data.
In contrast, RAG works by incorporating external data sources into a prompt at the time it’s passed to the model. For example, you could imagine the prompt, “What is Bart’s relationship to Lisa?” might be expanded (“augmented”) by prepending some relevant information, resulting in the prompt, “Homer and Marge’s children are named Bart, Lisa, and Maggie. What is Bart’s relationship to Lisa?”
This approach has several advantages:
- It can be more cost-effective because you don’t have to retrain the model.
- You can continuously update your data source and the LLM can immediately make use of the updated information.
- You now have the potential to cite references in your LLM’s responses.
On the other hand, using RAG naturally means longer prompts, and some LLM API services charge for each input token you send. Ultimately, you must evaluate the cost tradeoffs for your applications.
Genkit’s RAG support centers on the shared Document model and embedders: use ai.embed and ai.embed_many with typed EmbedderRef helpers (such as GoogleAI.embedder(...) or VertexAI.embedder(...)) or 'provider/embedder' strings to produce vectors. Combine those embeddings with your ingestion, storage, and search code, then pass retrieved documents into ai.generate(..., docs=...) to ground answers.
Most RAG pipelines cover four steps:
- Indexing: chunk documents, compute vectors, and upsert them into your store.
- Embedders: convert text or multimodal content into vectors via a Genkit embedder action.
- Retrieval: query your vector database or search layer for matching chunks.
- Generation: call the model with the user question and retrieved
docs.
Ingestion
Section titled “Ingestion”Chunk source text, compute embeddings with ai.embed or ai.embed_many, and write text, vectors, and metadata to your database. Pass embedder-specific settings with config=, such as EmbeddingConfig(output_dimensionality=768) from genkit_google_genai. The storage call below is a placeholder for your client library:
from genkit import Document, Genkitfrom genkit_google_genai import EmbeddingConfig, GoogleAI
ai = Genkit(plugins=[GoogleAI()])
menu_embedder = GoogleAI.embedder( 'gemini-embedding-001', config=EmbeddingConfig(output_dimensionality=768),)
async def ingest_menu(chunks: list[Document]) -> None: embeddings = await ai.embed_many(embedder=menu_embedder, content=chunks) for doc, item in zip(chunks, embeddings, strict=True): # Replace with your store's client print(doc.metadata['dish'], len(item.embedding)) # => fruit tart 768 # sorbet 768
await ingest_menu([ Document.from_text('Fruit tart: shortcrust, custard, berries. Contains dairy and eggs.', {'dish': 'fruit tart'}), Document.from_text('Raspberry sorbet: raspberries, sugar, lemon. Dairy-free and nut-free.', {'dish': 'sorbet'}),])Embedders
Section titled “Embedders”Reference embedders with plugin helpers such as GoogleAI.embedder('gemini-embedding-001') or VertexAI.embedder('text-embedding-005'), or pass a registered name string ('vertexai/text-embedding-005'). Use the same embedder and dimensionality at index time and query time. To register a custom embedder, implement an async function over EmbedRequest (from genkit.embedder) and register it with ai.define_embedder(...).
Generation with docs
Section titled “Generation with docs”Run your search query to produce a list[Document], then pass that list as docs to ai.generate. Embed the query with the same embedder and config you used at ingestion:
from genkit import Document, Genkitfrom genkit_google_genai import EmbeddingConfig, GoogleAI
ai = Genkit( plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'),)
menu_embedder = GoogleAI.embedder( 'gemini-embedding-001', config=EmbeddingConfig(output_dimensionality=768),)
async def fetch_menu_context(question: str, limit: int = 3) -> list[Document]: """Embed the query, search your vector store, map hits to Documents.""" embeddings = await ai.embed(embedder=menu_embedder, content=question) rows = await my_vector_db.search(embeddings[0].embedding, limit=limit) # your client return [Document.from_text(row.text, row.metadata) for row in rows]
@ai.flow()async def menu_qa_flow(question: str) -> str: docs = await fetch_menu_context(question) response = await ai.generate( prompt=question, docs=docs, ) return response.textRun the flow
Section titled “Run the flow”result = await menu_qa_flow('Recommend a dessert while avoiding dairy and nuts')print(result)# => I recommend the Raspberry sorbet. It contains raspberries, sugar, and lemon,# and is both dairy-free and nut-free. (The fruit tart contains dairy.)Composing search and prompts
Section titled “Composing search and prompts”Genkit Python has no retriever or indexer action types. Any async function returning list[Document] can supply context: query databases, call search APIs, or rerank results in ordinary Python code before passing docs to ai.generate(...).
Next steps
Section titled “Next steps”- Learn about tool calling to give your RAG system access to external APIs and functions
- Explore full-stack agents for coordinating multiple AI agents with RAG capabilities
- See the evaluation guide for testing and improving your RAG system’s performance