liveBook · Manning

Vector index

As explained in Generative AI in Action

A vector index is a data structure that organizes high-dimensional vectors to support efficient similarity and nearest-neighbor searches.

A vector index is a data structure that organizes high-dimensional embeddings for fast similarity and nearest-neighbor searches. In retrieval-augmented generation (RAG), it helps a retriever find relevant passages without comparing a query against every document vector. section 7.4 section 7.5

A vector database stores embeddings alongside original content and provides database capabilities; the index supports efficient lookup. Documents are typically split into chunks, embedded, and linked to their sources through metadata. A query is embedded and searched against the index, and matching passages can then supply context to an LLM. section 7.4 section 7.5 section 7.5.2

Choose an index and search configuration for the data and workload:

  • Compare exact and approximate nearest-neighbor approaches, including options such as HNSW and IVF. Index choices balance speed, accuracy, and memory consumption. section 7.5.1
  • Select a similarity measure appropriate to the query. Cosine similarity emphasizes vector orientation; Euclidean distance reflects separation in space and can be sensitive to scale. section 7.5.2
  • Consider compression techniques such as quantization or pruning when assessing memory needs. section 7.5.1

Search a collection of blog posts

A chat application chunks blog posts, creates embeddings, and indexes them in a local Redis database. At question time, it embeds the query, retrieves the top five matching results through a hybrid search index, and adds the retrieved chunks to the prompt sent to the LLM. The local setup is illustrative, not a complete enterprise production deployment. section 8.6

Listing 8.9 End-to-end RAG-powered chat
def hybrid_search(query_vector, client, top_k=5, hybrid_fields="*"):
...
    return results

def get_search_results(query:str, max_token=4096, 
                       debug_message=False) -> str:
    query_vector = get_embedding(query)    #1

    query_vector = np.array(query_vector).astype(
        np.float32).tobytes()    #2

    print("Searching for similar posts...")
    results = hybrid_search(query_vector, conn, top_k=5)   #3

    token_budget = max_token - count_tokens(query)        #4
    if debug_message:
        print(f"Token budget: {token_budget}")

    message = 'Use the blog post below to answer the subsequent 
               question. If the answer cannot be found in the 
               articles, write "Sorry, I could not find an answer in 
               the blog posts."'
    question = f"\n\nQuestion: {query}"

    if results:
        for i, post in enumerate(results.docs):          #5
            next_post = f'\n\nBlog post:\n"""\n{post.content}\n"""'
            new_token_usage = count_tokens(message + question + next_post)
            if new_token_usage < token_budget:
                if debug_message:
                    print(f"Token usage: {new_token_usage}")
                message += next_post
            else:
                break
    else:
        print("No results found")

    return message + question

def ask_gpt(query : str, max_token = 4096, debug_message = False) -> str:
    message = get_search_results(                      #6
        query,
        max_token,
        debug_message=debug_message)

    messages = [                                   #7
        {"role": 
         "system", 
         "content": "You answer questions in summary from the [CA]
                     blog posts."},
        {"role":
          "user",
            "content": message},]

    response = openai.ChatCompletion.create(           #8
        model="gpt-3.5-turbo-16k",
        messages=messages,
        temperature=0.7,
        max_tokens=2000,
        top_p=0.95
    )
    response_message = response["choices"][0]["message"]["content"]
    return response_message

if __name__ == "__main__":
    # Enter a query
    while True:
        query = input("Please enter your query: ")
        print(ask_gpt(query, max_token=15000, debug_message=False))
        print("=="*20)

Inspect the retrieval helper and its top-five search call in the end-to-end chat example; the listing omits helper implementation details. section 8.6

Production use requires more than a fast index. Managing and securing embeddings, planning data ingestion, and integrating source systems all require engineering effort. Index performance and cost should be considered alongside the needs of the overall retrieval pipeline. section 7.5 section 8.9

How Generative AI in Action covers it

How deep it goes
Explains index organization and speed, accuracy, and memory trade-offs without deriving the algorithms.
Examples
Demonstrates retrieval over chunked blog posts, returning five matches to augment a chat prompt.
What you can do after
Applies it via Redis to retrieve indexed embeddings for a RAG chat application.
How it connects
Connects vector indexes to embeddings, vector databases, similarity metrics, and retrieval-augmented generation.

Also explained in

Compare how 8 books explain vector index →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Generative AI in Action. The section links point to the parts of the book it draws on.