Velamuvi AIAcademy

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
In this lesson you will learn
  • 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:

  1. An embedding client turns text into numbers that capture its meaning.
  2. A vector store keeps your records with those numbers and finds the closest ones to a question.
  3. 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:

Try it yourselfPython
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())
Output
2 embeddings of 256 numbers each
  • get_embeddings takes a list of texts and returns GeneratedEmbeddings, a list with one Embedding per text. Each Embedding has .vector (the numbers), .dimensions (how many there are) and .model.
  • The model comes from OPENAI_EMBEDDING_MODEL (or OPENAI_MODEL), for example text-embedding-3-small, which returns 1,536 numbers. For Azure OpenAI, set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_EMBEDDING_MODEL instead.
  • options is an OpenAIEmbeddingOptions dictionary: dimensions asks for shorter vectors, and encoding_format and user are passed to OpenAI. The basic EmbeddingGenerationOptions has model and dimensions.

Other providers have their own clients, and they all work the same way:

ClientImport fromWhat you need
OllamaEmbeddingClientagent_framework.ollamaOllama on your own computer, with a model such as nomic-embed-text. Free
FoundryEmbeddingClientagent_framework.foundryA model deployed in Azure AI Foundry (paid)
GeminiEmbeddingClientagent_framework.geminiA Google Gemini API key
MistralEmbeddingClientagent_framework.mistralA Mistral API key
BedrockEmbeddingClientagent_framework.amazonAn 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 collection

Everything 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:

RoleExampleWhat it is
"key"idThe unique ID of a record. Upserting a record with an existing key replaces it
"data"topic, answerOrdinary values you store and get back
"vector"embeddingThe embedding. dimensions is required and must match the model's vector size

More options you can set on a field:

OptionFieldMeaning
is_indexed=TruedataIndex it so you can filter on it. Redis and Azure AI Search refuse filters on fields that aren't indexed
is_full_text_indexed=TruedataKeyword search on this field. Only Azure AI Search supports it
distance_functionvectorHow 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_kindvectorHow the database indexes vectors (IndexKind), such as "hnsw" or "flat"
embedding_generatorvectorA separate embedding client just for this field
storage_nameanyA 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 into embedding, and upsert sends that text to the embedding client and stores the numbers in its place. That's why its type is list[float] | str | None.
  • It needs a default (= None). get and search leave vectors out unless you pass include_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, pass generate_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())
Output
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 most top results as SearchResults. They arrive one by one, so you read them with async for.
  • Each result is a SearchResponse: a dictionary with the "record" (your FaqEntry) 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. top is only a maximum. It doesn't promise good results.
  • get(keys) looks records up by key without any search. The embedding is None because 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())
Output
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())
Output
close: ['2']
warranty: ['3', '4']
money: ['1', '2']
not warranty: ['1', '2']
  • score_threshold=0.5 drops 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_HELPER tells 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 types FilterOperator and FilterGroupOperator list all the operators.
  • get(filter=...) lists every record that matches, with top, skip and order_by for 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())
Output
['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:

  • name and description tell the model what the tool is for. A clear description decides whether the model uses it at the right moments.
  • query is always a parameter. The model writes it, often as a better search phrase than the customer's own words.
  • top and skip are fixed numbers, or a Param the model may set, with a minimum and maximum.
  • filter is fixed, or contains a Param the model fills in. Here topic is optional: with omit_if_none=True, a missing topic drops that filter instead of matching nothing.
  • result_mapper chooses 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_type and embeddings_options work 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 toolContext provider
Who decides to searchThe modelYour code, on every run
Search textWritten by the modelThe customer's message
Extra model callsOne more round trip for the tool callNone
Best forMixed questions, several data sourcesAn 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())
Output
[('upsert', 'always_require'), ('get', 'never_require'), ('search', 'never_require')]
  • Changes need approval by default. upsert and delete use "always_require", so the run stops with an approval request in response.user_input_requests instead of changing the FAQ. The Tool Approval and User Input lesson showed how to answer it. Change this with approval_mode, one mode for all tools or a dictionary per tool.
  • scope_filter is required. Pass None, or a filter such as Filter("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_tool and include_search_tool choose the tools, and additional_search_tools adds your own, such as search_faq above.
  • instructions are 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,
)
CollectionStoreImport fromWhat you need
RedisCollectionRedisStoreagent_framework.redisRedis 8, or Redis Stack, with its query engine. Free to run yourself, for example with Docker
AzureAISearchCollectionAzureAISearchStoreagent_framework.azureAn Azure AI Search service (paid, with a small free tier). Supports "keyword_hybrid" search
CosmosCollectionCosmosStoreagent_framework.azureAn 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=True raises NotImplementedError there.
  • Distance functions differ. Redis supports "cosine_distance" but not "cosine_similarity"; Cosmos DB the other way round. Leaving distance_function out 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 an embedding_function (such as an OpenAIEmbeddingClient), plus semantic re-ranking when you name a semantic_configuration_name.
  • "agentic" uses an Azure AI Search knowledge base, which plans several searches itself, using the last few messages. Give knowledge_base_name, or give index_name, model and azure_openai_resource_url to create one. It's slower and costs more, but handles questions that need several lookups.

Common mistakes

Practice exercise

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.

Your solutionPython
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
Knowledge check

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 own BaseEmbeddingClient) turns text into vectors.
  • @vectorstoremodel and VectorStoreField describe records with a key, data and a vector; upsert embeds the vector field's text, and search returns 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 with VectorCollectionContextProvider, then move from InMemoryCollection to Redis, Azure AI Search or Cosmos DB without changing the rest.

Next: Agent Skills.

Finished reading? Tick it off to track your progress.