Lesson 16 of 39 · Sessions, Memory and Context
Embeddings, Vector Stores and RAG
Build RAG in Agent Framework: create embeddings, store and search records in vector stores, filter results, and give agents a search tool or provider.
- 24 min read
- Intermediate
- Reviewed
- Explain what embeddings are and how RAG uses them to find relevant text
- Create embeddings with OpenAIEmbeddingClient, or your own BaseEmbeddingClient
- Describe records with @vectorstoremodel and VectorStoreField, then upsert, get and search them
- Narrow a search with Filter, FilterGroup and a score threshold
- Give search to an agent as a tool, as a context provider, or with VectorCollectionContextProvider
- Move from the in-memory store to Redis, Azure AI Search or Cosmos DB
What RAG is
A model knows what it learned in training and what's in its request. It doesn't know your shop's return policy or this week's delivery times. You could paste every FAQ answer into the instructions, but 2,000 answers cost tokens on every call and distract the model. The better way is to send only the few answers that matter for this question.
Agent Framework gives you every part:
- An embedding client turns text into numbers that capture its meaning.
- A vector store keeps your records with those numbers and finds the closest ones to a question.
- A search tool or a context provider passes what was found to the agent.
The Retrieval-Augmented Generation course covers RAG in depth, such as splitting documents into chunks and checking answer quality. This lesson shows how Agent Framework does it.
Embeddings: meaning as numbers
An embedding model reads "Where is my parcel?" and returns, for example, 1,536 numbers. You never read them yourself: you compare them. The usual comparison is cosine similarity, which is 1 for vectors pointing the same way and close to 0 for unrelated ones. Try it with made-up embeddings of three numbers:
import math
# Made-up embeddings with three numbers: [about deliveries, about money back, about bikes]
texts = {
"Where is my parcel?": [0.9, 0.1, 0.0],
"My delivery is late.": [0.8, 0.3, 0.1],
"How do I get my money back?": [0.1, 0.9, 0.1],
"Which bike is best for hills?": [0.0, 0.1, 0.9],
}
def cosine_similarity(a, b):
dot = sum(x * y for x, y in zip(a, b))
length_a = math.sqrt(sum(x * x for x in a))
length_b = math.sqrt(sum(y * y for y in b))
return dot / (length_a * length_b)
question = [0.85, 0.2, 0.05] # the embedding of "Has my order shipped yet?"
for text, vector in texts.items():
print(f"{cosine_similarity(question, vector):.2f} {text}")"Where is my parcel?" and "My delivery is late." share almost no words with the question, yet both score 0.99. That's why RAG searches by meaning instead of by keywords. Some databases report cosine distance instead, which is 1 minus the similarity, so there a smaller number means closer. The Embeddings course explains how embedding models learn these numbers.
Embedding clients
An embedding client sends texts to an embedding model and returns their vectors. OpenAIEmbeddingClient uses OpenAI's embedding models. It needs an OpenAI API key and costs a small amount per token:
import asyncio
from agent_framework.openai import OpenAIEmbeddingClient
async def main():
client = OpenAIEmbeddingClient() # reads OPENAI_API_KEY and OPENAI_EMBEDDING_MODEL
embeddings = await client.get_embeddings(
["Where is my parcel?", "My delivery is late."],
options={"dimensions": 256}, # text-embedding-3 models can return shorter vectors
)
print(len(embeddings), "embeddings of", embeddings[0].dimensions, "numbers each")
asyncio.run(main())2 embeddings of 256 numbers each
get_embeddingstakes a list of texts and returnsGeneratedEmbeddings, a list with oneEmbeddingper text. EachEmbeddinghas.vector(the numbers),.dimensions(how many there are) and.model.- The model comes from
OPENAI_EMBEDDING_MODEL(orOPENAI_MODEL), for exampletext-embedding-3-small, which returns 1,536 numbers. For Azure OpenAI, setAZURE_OPENAI_ENDPOINTandAZURE_OPENAI_EMBEDDING_MODELinstead. optionsis anOpenAIEmbeddingOptionsdictionary:dimensionsasks for shorter vectors, andencoding_formatanduserare passed to OpenAI. The basicEmbeddingGenerationOptionshasmodelanddimensions.
Other providers have their own clients, and they all work the same way:
| Client | Import from | What you need |
|---|---|---|
OllamaEmbeddingClient | agent_framework.ollama | Ollama on your own computer, with a model such as nomic-embed-text. Free |
FoundryEmbeddingClient | agent_framework.foundry | A model deployed in Azure AI Foundry (paid) |
GeminiEmbeddingClient | agent_framework.gemini | A Google Gemini API key |
MistralEmbeddingClient | agent_framework.mistral | A Mistral API key |
BedrockEmbeddingClient | agent_framework.amazon | An AWS account with Amazon Bedrock (paid) |
Each has a matching options type (OllamaEmbeddingOptions, FoundryEmbeddingOptions, GeminiEmbeddingOptions, MistralEmbeddingOptions, BedrockEmbeddingOptions) and a settings type that lists the environment variables it reads, such as OllamaEmbeddingSettings for OLLAMA_HOST and OLLAMA_EMBEDDING_MODEL. Classes starting with Raw, such as RawGeminiEmbeddingClient and RawFoundryEmbeddingClient, are the same clients without the built-in telemetry.
Describe your records
A vector store keeps records, such as one FAQ answer each. You describe their shape once with a class and mark each field with VectorStoreField. Here is a whole file you'll reuse in the rest of the lesson. Save it as faq_store.py:
# faq_store.py
from dataclasses import dataclass
from typing import Annotated
from agent_framework import (
BaseEmbeddingClient, Embedding, GeneratedEmbeddings, InMemoryCollection, VectorStoreField, vectorstoremodel,
)
WORDS = ["refund", "return", "delivery", "parcel", "late", "warranty", "battery", "brake"]
class KeywordEmbeddings(BaseEmbeddingClient):
"""A toy embedding model that counts shop words: free and offline, but it doesn't understand meaning."""
async def get_embeddings(self, values, *, options=None):
return GeneratedEmbeddings([
Embedding(vector=[text.lower().count(word) + 0.01 for word in WORDS]) # + 0.01: never all zeros
for text in values
])
@vectorstoremodel(collection_name="faq")
@dataclass
class FaqEntry:
id: Annotated[str, VectorStoreField("key")]
topic: Annotated[str, VectorStoreField("data", is_indexed=True)]
answer: Annotated[str, VectorStoreField("data")]
embedding: Annotated[list[float] | str | None, VectorStoreField("vector", dimensions=len(WORDS))] = None
def faq(id, topic, answer):
return FaqEntry(id, topic, answer, embedding=answer) # the vector field holds the text to embed
async def build_faq():
collection = InMemoryCollection(FaqEntry, embedding_generator=KeywordEmbeddings())
await collection.ensure_collection_exists()
await collection.upsert([
faq("1", "returns", "Return a bike within 30 days for a full refund."),
faq("2", "delivery", "Parcel delivery takes 2 to 3 days; late deliveries are refunded."),
faq("3", "warranty", "The battery warranty lasts 2 years."),
faq("4", "warranty", "Brake pads are not covered by the warranty."),
])
return collectionEverything in it runs offline and for free, because KeywordEmbeddings is a toy embedding model: it subclasses BaseEmbeddingClient and only counts eight shop words. A real model understands that "parcel" and "package" mean the same thing. To switch, pass OpenAIEmbeddingClient() instead and set dimensions to the model's size.
@vectorstoremodel turns the dataclass into a record type and sets its default collection name. Pydantic models and ordinary classes work too. Each field has one of three roles:
| Role | Example | What it is |
|---|---|---|
"key" | id | The unique ID of a record. Upserting a record with an existing key replaces it |
"data" | topic, answer | Ordinary values you store and get back |
"vector" | embedding | The embedding. dimensions is required and must match the model's vector size |
More options you can set on a field:
| Option | Field | Meaning |
|---|---|---|
is_indexed=True | data | Index it so you can filter on it. Redis and Azure AI Search refuse filters on fields that aren't indexed |
is_full_text_indexed=True | data | Keyword search on this field. Only Azure AI Search supports it |
distance_function | vector | How closeness is measured. The allowed values are listed in DistanceFunction, such as "cosine_similarity", "cosine_distance", "dot_prod" and "euclidean_distance". Leave it out to use the database's cosine default |
index_kind | vector | How the database indexes vectors (IndexKind), such as "hnsw" or "flat" |
embedding_generator | vector | A separate embedding client just for this field |
storage_name | any | A different name for the column in the database |
Two details about the vector field are easy to miss:
- Before upsert it holds the text; afterwards, the vector.
faq()copies the answer intoembedding, andupsertsends that text to the embedding client and stores the numbers in its place. That's why its type islist[float] | str | None. - It needs a default (
= None).getandsearchleave vectors out unless you passinclude_vectors=True, so the field must be able to stay empty.
For plain dictionaries, describe the fields with a VectorStoreCollectionDefinition instead of a class:
from agent_framework import InMemoryCollection, VectorStoreCollectionDefinition, VectorStoreField
from faq_store import KeywordEmbeddings
definition = VectorStoreCollectionDefinition(
[
VectorStoreField("key", name="id"),
VectorStoreField("data", name="topic", is_indexed=True),
VectorStoreField("data", name="answer"),
VectorStoreField("vector", name="embedding", dimensions=8),
],
collection_name="faq",
)
faq = InMemoryCollection(dict, definition=definition, embedding_generator=KeywordEmbeddings())
# Records are now dictionaries, such as {"id": "3", "topic": "warranty", "answer": text, "embedding": text}For a class you can't decorate, such as one from another library, call register_vectorstoremodel(TheClass, definition=...) once.
Store and search in memory
build_faq() in faq_store.py did three things:
InMemoryCollection(FaqEntry, embedding_generator=...)creates a collection: a named set of records, like a table. The in-memory one keeps everything in a Python dictionary. It's for learning and tests, and it's empty again when the program ends.ensure_collection_exists()creates the collection if it doesn't exist yet. With a real database, this creates the index.upsert(records)embeds each record's vector-field text, then inserts it, or replaces the record with the same key. It returns the keys. If your records already hold vectors, passgenerate_vectors=False(its type,GenerateVectors, also accepts a list of vector field names).
Now search it:
import asyncio
from faq_store import build_faq
async def main():
faq = await build_faq()
results = await faq.search("My parcel is late", top=2)
async for result in results:
print(f"{result['score']:.2f} {result['record'].answer}")
print(await faq.get(["3"])) # look records up by key: no search, no embedding
asyncio.run(main())0.29 Parcel delivery takes 2 to 3 days; late deliveries are refunded. 0.98 Return a bike within 30 days for a full refund. [FaqEntry(id='3', topic='warranty', answer='The battery warranty lasts 2 years.', embedding=None)]
How it works:
search(text, top=2)embeds the question with the same embedding client, compares it with every record and returns at mosttopresults asSearchResults. They arrive one by one, so you read them withasync for.- Each result is a
SearchResponse: a dictionary with the"record"(yourFaqEntry) and its"score". - The score here is a cosine distance, the in-memory default, so smaller is closer. The delivery answer (0.29) is a good match; the returns answer (0.98) is almost unrelated.
topis only a maximum. It doesn't promise good results. get(keys)looks records up by key without any search. TheembeddingisNonebecause vectors aren't returned by default.
Other search arguments: skip (for paging), include_vectors=True, vector= (a vector you already computed, instead of text), vector_property_name (which vector field, if a record has several) and search_type. SearchType has two values: "vector" (the default) and "keyword_hybrid", which mixes vector and keyword search and works only with Azure AI Search. To remove records, call delete(keys).
One store, many collections
A store is one connection to a database that hands out collections. Collections from the same store with the same name share their records:
import asyncio
from agent_framework import InMemoryStore
from faq_store import FaqEntry, KeywordEmbeddings, faq
async def main():
store = InMemoryStore(embedding_generator=KeywordEmbeddings()) # one store hands out many collections
shop_faq = store.get_collection(FaqEntry) # named "faq", from the model
old_faq = store.get_collection(FaqEntry, collection_name="faq_2025")
for collection in (shop_faq, old_faq):
await collection.ensure_collection_exists()
await shop_faq.upsert([faq("1", "returns", "Return a bike within 30 days for a full refund.")])
same_faq = store.get_collection(FaqEntry) # same name, same records
print(len(await same_faq.get(["1"])), await store.list_collection_names())
await shop_faq.delete(["1"])
await store.ensure_collection_deleted("faq_2025")
print(len(await same_faq.get(["1"])), await store.list_collection_names())
asyncio.run(main())1 ['faq', 'faq_2025'] 0 ['faq']
InMemoryStore passes its embedding_generator to every collection it creates. list_collection_names(), collection_exists(name) and ensure_collection_deleted(name) manage whole collections.
Filter the results
A filter keeps only the records that match a condition. Pass it to search or to get:
import asyncio
from agent_framework import Filter, FilterGroup
from faq_store import build_faq
async def main():
faq = await build_faq()
close = await faq.search("My parcel is late", top=2, score_threshold=0.5) # in memory: at most 0.5 apart
print("close:", [result["record"].id async for result in close])
warranty = Filter("topic", "eq", "warranty")
results = await faq.search("battery", top=3, filter=warranty)
print("warranty:", [result["record"].id async for result in results])
money = FilterGroup("or", [Filter("topic", "eq", "returns"), Filter("answer", "contains_text", "refund")])
print("money:", [entry.id for entry in await faq.get(filter=money)]) # list matching records
not_warranty = FilterGroup("not", [Filter("topic", "in", ["warranty"])])
print("not warranty:", [entry.id for entry in await faq.get(filter=not_warranty)])
asyncio.run(main())close: ['2'] warranty: ['3', '4'] money: ['1', '2'] not warranty: ['1', '2']
score_threshold=0.5drops results that are too far away, so only the delivery answer is left. Its meaning depends on the database: here it's a maximum distance, but for a similarity score it would be a minimum.DISTANCE_FUNCTION_DIRECTION_HELPERtells you which way each distance function counts.Filter(field, operator, value)is one condition. Operators include"eq","ne","gt","gte","lt","lte","between","in","not_in","contains","contains_any","contains_all","starts_with","ends_with","contains_text","is_null","is_not_null"and"exists".FilterGroup("and" | "or" | "not", [...])combines conditions. A"not"group takes exactly one filter. The typesFilterOperatorandFilterGroupOperatorlist all the operators.get(filter=...)lists every record that matches, withtop,skipandorder_byfor paging and sorting.
Not every database supports every operator. One that isn't supported raises NotImplementedError instead of being silently ignored.
RAG as a tool
The simplest way to give an agent your data is a search tool. The model decides when to search and what to search for:
import asyncio
from agent_framework import Agent, Filter, Param, create_vector_search_tool
from agent_framework.openai import OpenAIChatClient
from faq_store import build_faq
async def main():
search_faq = create_vector_search_tool(
await build_faq(),
name="search_faq",
description="Search the bike shop's FAQ. Use it before answering questions about orders or products.",
top=2, # at most 2 results per search
filter=Filter("topic", "eq", Param(
"topic", str | None, default=None, omit_if_none=True, # optional: no topic means no filter
description="Optional topic: returns, delivery or warranty",
)),
result_mapper=lambda result: result["record"].answer, # send only the answer text to the model
)
print(list(search_faq.parameters()["properties"])) # what the model can fill in
found = await search_faq.invoke(arguments={"query": "battery warranty", "topic": "warranty"})
print([content.text for content in found]) # what the model gets back
agent = Agent(
client=OpenAIChatClient(),
instructions="Answer bike shop questions with the search_faq tool. If it finds nothing useful, say so.",
tools=[search_faq],
)
response = await agent.run("How long is the warranty on my e-bike battery?")
print(response.text)
asyncio.run(main())['query', 'topic'] ['The battery warranty lasts 2 years.', 'Brake pads are not covered by the warranty.']
After these two lines, the agent's answer follows. For the warranty question, the model calls search_faq with a query such as "battery warranty", reads the two answers that come back, and answers from them.
create_vector_search_tool turns any collection into a tool:
nameanddescriptiontell the model what the tool is for. A clear description decides whether the model uses it at the right moments.queryis always a parameter. The model writes it, often as a better search phrase than the customer's own words.topandskipare fixed numbers, or aParamthe model may set, with aminimumandmaximum.filteris fixed, or contains aParamthe model fills in. Heretopicis optional: withomit_if_none=True, a missing topic drops that filter instead of matching nothing.result_mapperchooses what the model receives for each result. Without it, the model gets each record and its score as JSON.approval_mode("never_require"by default),search_typeandembeddings_optionswork as elsewhere.
RAG on every run
A tool only helps if the model decides to call it. If every question should be answered from the FAQ, search before every run instead, with a context provider (you met these in the previous lesson):
import asyncio
from agent_framework import Agent, ContextProvider, Message, SessionContext
from agent_framework.openai import OpenAIChatClient
from faq_store import build_faq
class FaqRetriever(ContextProvider):
"""Always-on RAG: searches the FAQ with the customer's message before every run."""
def __init__(self, collection, top: int = 2):
super().__init__(source_id="faq_retriever")
self.collection = collection
self.top = top
async def before_run(self, *, agent, session, context: SessionContext, state: dict) -> None:
question = " ".join(message.text for message in context.input_messages)
results = await self.collection.search(question, top=self.top, score_threshold=0.5)
answers = [result["record"].answer async for result in results]
if answers:
note = "Relevant FAQ entries:\n" + "\n".join(answers)
context.extend_messages(self.source_id, [Message("user", [note])])
async def main():
agent = Agent(
client=OpenAIChatClient(),
instructions="Answer bike shop questions using the FAQ entries you are given.",
context_providers=[FaqRetriever(await build_faq())],
)
response = await agent.run("My parcel is late. What happens now?")
print(response.text)
asyncio.run(main())Before the model was called, the provider searched for "My parcel is late. What happens now?" and added a message placed before the question: "Relevant FAQ entries:" followed by the delivery answer. The other answers were more than 0.5 away, so they weren't added.
| Search tool | Context provider | |
|---|---|---|
| Who decides to search | The model | Your code, on every run |
| Search text | Written by the model | The customer's message |
| Extra model calls | One more round trip for the tool call | None |
| Best for | Mixed questions, several data sources | An assistant that always answers from your documents |
Let the agent manage a collection
VectorCollectionContextProvider gives an agent a full set of tools for one collection: upsert, get, delete and search. It suits assistants that keep a knowledge base up to date:
import asyncio
from agent_framework import Agent, VectorCollectionContextProvider
from agent_framework.openai import OpenAIChatClient
from faq_store import build_faq
async def main():
faq_tools = VectorCollectionContextProvider(
await build_faq(),
scope_filter=None, # required: None, or a filter that limits which records the tools touch
include_delete_tool=False, # staff may add and change answers, but not delete them
instructions="Use the FAQ tools to look answers up and to add new ones. When adding, also put the answer text in the embedding field.",
)
print([(tool.name, tool.approval_mode) for tool in faq_tools.tools])
agent = Agent(
client=OpenAIChatClient(),
instructions="You help the shop staff keep the FAQ up to date.",
context_providers=[faq_tools],
)
response = await agent.run("Add an FAQ answer: tyres have a 6-month warranty.")
for request in response.user_input_requests: # upsert needs a person's approval first
print("Needs approval:", request.function_call.name, request.function_call.arguments)
asyncio.run(main())[('upsert', 'always_require'), ('get', 'never_require'), ('search', 'never_require')]- Changes need approval by default.
upsertanddeleteuse"always_require", so the run stops with an approval request inresponse.user_input_requestsinstead of changing the FAQ. The Tool Approval and User Input lesson showed how to answer it. Change this withapproval_mode, one mode for all tools or a dictionary per tool. scope_filteris required. PassNone, or a filter such asFilter("topic", "eq", "warranty")to keep the tools to some records. It groups records; it isn't a security boundary.include_upsert_tool,include_get_tool,include_delete_toolandinclude_search_toolchoose the tools, andadditional_search_toolsadds your own, such assearch_faqabove.instructionsare added to every run. Without them, the provider adds short default instructions about its tools.
To build just one of these tools, call create_upsert_tool, create_get_tool or create_delete_tool directly.
Real vector databases
The in-memory store forgets everything when the program stops. For real use, swap in a database. Your model, your filters and your agent code stay the same; only the collection class changes:
from dataclasses import dataclass
from typing import Annotated
from agent_framework import VectorStoreField, vectorstoremodel
from agent_framework.azure import AzureAISearchCollection, CosmosCollection
from agent_framework.openai import OpenAIEmbeddingClient
from agent_framework.redis import RedisCollection
from azure.identity.aio import AzureCliCredential
@vectorstoremodel(collection_name="faq")
@dataclass
class FaqEntry:
id: Annotated[str, VectorStoreField("key")]
topic: Annotated[str, VectorStoreField("data", is_indexed=True)]
answer: Annotated[str, VectorStoreField("data")]
embedding: Annotated[list[float] | str | None, VectorStoreField("vector", dimensions=1536)] = None
embeddings = OpenAIEmbeddingClient() # text-embedding-3-small: 1536 numbers per text
redis_faq = RedisCollection( # free to run yourself: Redis 8 (or Redis Stack)
FaqEntry, redis_url="redis://localhost:6379", embedding_generator=embeddings,
)
search_faq = AzureAISearchCollection( # Azure AI Search (paid, with a small free tier)
FaqEntry, endpoint="https://your-service.search.windows.net",
credential=AzureCliCredential(), embedding_generator=embeddings,
)
cosmos_faq = CosmosCollection( # Azure Cosmos DB for NoSQL with vector search (paid)
FaqEntry, endpoint="https://your-account.documents.azure.com:443/",
database_name="bike_shop", credential=AzureCliCredential(), embedding_generator=embeddings,
)| Collection | Store | Import from | What you need |
|---|---|---|---|
RedisCollection | RedisStore | agent_framework.redis | Redis 8, or Redis Stack, with its query engine. Free to run yourself, for example with Docker |
AzureAISearchCollection | AzureAISearchStore | agent_framework.azure | An Azure AI Search service (paid, with a small free tier). Supports "keyword_hybrid" search |
CosmosCollection | CosmosStore | agent_framework.azure | An Azure Cosmos DB for NoSQL account with vector search (paid) |
Settings can come from environment variables instead of arguments: REDIS_URL, AZURE_SEARCH_ENDPOINT and AZURE_SEARCH_API_KEY, or AZURE_COSMOS_ENDPOINT, AZURE_COSMOS_DATABASE_NAME and AZURE_COSMOS_KEY. To connect a database that has no ready-made class, subclass BaseVectorCollection and BaseVectorSearch (and BaseVectorStore for a store). create_vector_search_tool accepts any object that fits the SupportsVectorSearch protocol; SupportsVectorUpsert describes the upsert, get and delete methods the same way, and SupportsGetEmbeddings describes an embedding client. Differences that matter:
- Each database checks your model when you create the collection. Redis and Cosmos DB have no keyword search, so
is_full_text_indexed=TrueraisesNotImplementedErrorthere. - Distance functions differ. Redis supports
"cosine_distance"but not"cosine_similarity"; Cosmos DB the other way round. Leavingdistance_functionout uses each database's cosine default and works everywhere. - Scores point different ways. The in-memory store and Redis return a distance (smaller is closer); Azure AI Search and Cosmos DB return a similarity (bigger is closer). Check before you pick a
score_threshold.
Azure AI Search as a context provider
If your documents are already in an Azure AI Search index, AzureAISearchContextProvider does the "RAG on every run" part for you:
from agent_framework import Agent
from agent_framework.azure import AzureAISearchContextProvider
from agent_framework.openai import OpenAIChatClient
from azure.identity.aio import AzureCliCredential
manuals = AzureAISearchContextProvider(
endpoint="https://your-service.search.windows.net",
index_name="bike-manuals", # an index you have already filled
credential=AzureCliCredential(),
mode="semantic", # one search per run
semantic_configuration_name="my-semantic-config", # defined on the index
top_k=3, # add at most 3 documents
)
agent = Agent(
client=OpenAIChatClient(),
instructions="Answer questions about our bikes using the manual excerpts you are given.",
context_providers=[manuals],
)Before each run it searches the index with the customer's message and adds the results, after the line "Use the following context to answer the question:" (change it with context_prompt). It reads AZURE_SEARCH_ENDPOINT, AZURE_SEARCH_INDEX_NAME, AZURE_SEARCH_API_KEY and AZURE_SEARCH_KNOWLEDGE_BASE_NAME (listed in AzureAISearchSettings) when you leave those arguments out. It has two modes:
"semantic"(the default) runs one fast search per run: a keyword search, plus a vector search when the index can embed the question itself or you pass anembedding_function(such as anOpenAIEmbeddingClient), plus semantic re-ranking when you name asemantic_configuration_name."agentic"uses an Azure AI Search knowledge base, which plans several searches itself, using the last few messages. Giveknowledge_base_name, or giveindex_name,modelandazure_openai_resource_urlto create one. It's slower and costs more, but handles questions that need several lookups.
Common mistakes
Build the retrieval step of RAG in plain Python: for each question, find the closest FAQ answer by cosine similarity, and only use it when it is close enough.
import math
faq = {
"Return a bike within 30 days for a full refund.": [0.1, 0.9, 0.0],
"Parcel delivery takes 2 to 3 days.": [0.9, 0.1, 0.1],
"The battery warranty lasts 2 years.": [0.0, 0.2, 0.9],
}
questions = {
"How long is my battery covered?": [0.1, 0.1, 0.95],
"Do you sell gift cards?": [0.5, 0.5, 0.5],
}
def cosine_similarity(a, b):
# Return the dot product of a and b divided by the product of their lengths.
return 0.0
# For each question, find the FAQ answer with the highest similarity.
# If that similarity is at least 0.9, print the question, an arrow and the answer, like:
# How long is my battery covered? -> The battery warranty lasts 2 years.
# Otherwise print the question, an arrow and: no good answer
Customers ask the shop's agent about many things, and only some questions need the FAQ. Which setup lets the model decide when to search the FAQ?
Summary
- RAG finds the most relevant pieces of your own data and adds them to the request; embeddings make "relevant" mean "similar in meaning".
- An embedding client (
OpenAIEmbeddingClient, Ollama, Foundry and others, or your ownBaseEmbeddingClient) turns text into vectors. @vectorstoremodelandVectorStoreFielddescribe records with a key, data and a vector;upsertembeds the vector field's text, andsearchreturns records with scores.- Filters (
Filter,FilterGroup) and a score threshold narrow the results; check whether your database's score is a distance or a similarity. - Give search to an agent as a tool (
create_vector_search_tool), as a context provider, or withVectorCollectionContextProvider, then move fromInMemoryCollectionto Redis, Azure AI Search or Cosmos DB without changing the rest.
Next: Agent Skills.
Finished reading? Tick it off to track your progress.