|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using Azure; |
| 4 | +using Azure.Identity; |
| 5 | +using Azure.Search.Documents.Indexes; |
| 6 | +using Microsoft.Extensions.VectorData; |
| 7 | +using Microsoft.SemanticKernel.Connectors.AzureAISearch; |
| 8 | +using Microsoft.SemanticKernel.Connectors.AzureOpenAI; |
| 9 | +using Microsoft.SemanticKernel.Embeddings; |
| 10 | + |
| 11 | +namespace Memory; |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// A simple example showing how to ingest data into a vector store and then use hybrid search to find related records to a given string and set of keywords. |
| 15 | +/// |
| 16 | +/// The example shows the following steps: |
| 17 | +/// 1. Create an embedding generator. |
| 18 | +/// 2. Create an AzureAISearch Vector Store. |
| 19 | +/// 3. Ingest some data into the vector store. |
| 20 | +/// 4. Do a hybrid search on the vector store with various text+keyword and filtering options. |
| 21 | +/// </summary> |
| 22 | +public class VectorStore_HybridSearch_Simple_AzureAISearch(ITestOutputHelper output) : BaseTest(output) |
| 23 | +{ |
| 24 | + [Fact] |
| 25 | + public async Task IngestDataAndUseHybridSearch() |
| 26 | + { |
| 27 | + // Create an embedding generation service. |
| 28 | + var textEmbeddingGenerationService = new AzureOpenAITextEmbeddingGenerationService( |
| 29 | + TestConfiguration.AzureOpenAIEmbeddings.DeploymentName, |
| 30 | + TestConfiguration.AzureOpenAIEmbeddings.Endpoint, |
| 31 | + new AzureCliCredential()); |
| 32 | + |
| 33 | + // Construct the AzureAISearch VectorStore. |
| 34 | + var searchIndexClient = new SearchIndexClient( |
| 35 | + new Uri(TestConfiguration.AzureAISearch.Endpoint), |
| 36 | + new AzureKeyCredential(TestConfiguration.AzureAISearch.ApiKey)); |
| 37 | + var vectorStore = new AzureAISearchVectorStore(searchIndexClient); |
| 38 | + |
| 39 | + // Get and create collection if it doesn't exist. |
| 40 | + var collection = vectorStore.GetCollection<string, Glossary>("skglossary"); |
| 41 | + await collection.CreateCollectionIfNotExistsAsync(); |
| 42 | + var hybridSearchCollection = (IKeywordHybridSearch<Glossary>)collection; |
| 43 | + |
| 44 | + // Create glossary entries and generate embeddings for them. |
| 45 | + var glossaryEntries = CreateGlossaryEntries().ToList(); |
| 46 | + var tasks = glossaryEntries.Select(entry => Task.Run(async () => |
| 47 | + { |
| 48 | + entry.DefinitionEmbedding = await textEmbeddingGenerationService.GenerateEmbeddingAsync(entry.Definition); |
| 49 | + })); |
| 50 | + await Task.WhenAll(tasks); |
| 51 | + |
| 52 | + // Upsert the glossary entries into the collection and return their keys. |
| 53 | + var upsertedKeysTasks = glossaryEntries.Select(x => collection.UpsertAsync(x)); |
| 54 | + var upsertedKeys = await Task.WhenAll(upsertedKeysTasks); |
| 55 | + |
| 56 | + // Search the collection using a vector search. |
| 57 | + var searchString = "What is an Application Programming Interface"; |
| 58 | + var searchVector = await textEmbeddingGenerationService.GenerateEmbeddingAsync(searchString); |
| 59 | + var searchResult = await hybridSearchCollection.HybridSearchAsync(searchVector, ["Application", "Programming", "Interface"], new() { Top = 1 }); |
| 60 | + var resultRecords = await searchResult.Results.ToListAsync(); |
| 61 | + |
| 62 | + Console.WriteLine("Search string: " + searchString); |
| 63 | + Console.WriteLine("Result: " + resultRecords.First().Record.Definition); |
| 64 | + Console.WriteLine(); |
| 65 | + |
| 66 | + // Search the collection using a vector search. |
| 67 | + searchString = "What is Retrieval Augmented Generation"; |
| 68 | + searchVector = await textEmbeddingGenerationService.GenerateEmbeddingAsync(searchString); |
| 69 | + searchResult = await hybridSearchCollection.HybridSearchAsync(searchVector, ["Retrieval", "Augmented", "Generation"], new() { Top = 1 }); |
| 70 | + resultRecords = await searchResult.Results.ToListAsync(); |
| 71 | + |
| 72 | + Console.WriteLine("Search string: " + searchString); |
| 73 | + Console.WriteLine("Result: " + resultRecords.First().Record.Definition); |
| 74 | + Console.WriteLine(); |
| 75 | + |
| 76 | + // Search the collection using a vector search with pre-filtering. |
| 77 | + searchString = "What is Retrieval Augmented Generation"; |
| 78 | + searchVector = await textEmbeddingGenerationService.GenerateEmbeddingAsync(searchString); |
| 79 | + searchResult = await hybridSearchCollection.HybridSearchAsync(searchVector, ["Retrieval", "Augmented", "Generation"], new() { Top = 3, Filter = g => g.Category == "External Definitions" }); |
| 80 | + resultRecords = await searchResult.Results.ToListAsync(); |
| 81 | + |
| 82 | + Console.WriteLine("Search string: " + searchString); |
| 83 | + Console.WriteLine("Number of results: " + resultRecords.Count); |
| 84 | + Console.WriteLine("Result 1 Score: " + resultRecords[0].Score); |
| 85 | + Console.WriteLine("Result 1: " + resultRecords[0].Record.Definition); |
| 86 | + Console.WriteLine("Result 2 Score: " + resultRecords[1].Score); |
| 87 | + Console.WriteLine("Result 2: " + resultRecords[1].Record.Definition); |
| 88 | + } |
| 89 | + |
| 90 | + /// <summary> |
| 91 | + /// Sample model class that represents a glossary entry. |
| 92 | + /// </summary> |
| 93 | + /// <remarks> |
| 94 | + /// Note that each property is decorated with an attribute that specifies how the property should be treated by the vector store. |
| 95 | + /// This allows us to create a collection in the vector store and upsert and retrieve instances of this class without any further configuration. |
| 96 | + /// </remarks> |
| 97 | + private sealed class Glossary |
| 98 | + { |
| 99 | + [VectorStoreRecordKey] |
| 100 | + public string Key { get; set; } |
| 101 | + |
| 102 | + [VectorStoreRecordData(IsFilterable = true)] |
| 103 | + public string Category { get; set; } |
| 104 | + |
| 105 | + [VectorStoreRecordData] |
| 106 | + public string Term { get; set; } |
| 107 | + |
| 108 | + [VectorStoreRecordData(IsFullTextSearchable = true)] |
| 109 | + public string Definition { get; set; } |
| 110 | + |
| 111 | + [VectorStoreRecordVector(1536)] |
| 112 | + public ReadOnlyMemory<float> DefinitionEmbedding { get; set; } |
| 113 | + } |
| 114 | + |
| 115 | + /// <summary> |
| 116 | + /// Create some sample glossary entries. |
| 117 | + /// </summary> |
| 118 | + /// <returns>A list of sample glossary entries.</returns> |
| 119 | + private static IEnumerable<Glossary> CreateGlossaryEntries() |
| 120 | + { |
| 121 | + yield return new Glossary |
| 122 | + { |
| 123 | + Key = "1", |
| 124 | + Category = "External Definitions", |
| 125 | + Term = "API", |
| 126 | + Definition = "Application Programming Interface. A set of rules and specifications that allow software components to communicate and exchange data." |
| 127 | + }; |
| 128 | + |
| 129 | + yield return new Glossary |
| 130 | + { |
| 131 | + Key = "2", |
| 132 | + Category = "Core Definitions", |
| 133 | + Term = "Connectors", |
| 134 | + Definition = "Connectors allow you to integrate with various services provide AI capabilities, including LLM, AudioToText, TextToAudio, Embedding generation, etc." |
| 135 | + }; |
| 136 | + |
| 137 | + yield return new Glossary |
| 138 | + { |
| 139 | + Key = "3", |
| 140 | + Category = "External Definitions", |
| 141 | + Term = "RAG", |
| 142 | + Definition = "Retrieval Augmented Generation - a term that refers to the process of retrieving additional data to provide as context to an LLM to use when generating a response (completion) to a user’s question (prompt)." |
| 143 | + }; |
| 144 | + } |
| 145 | +} |
0 commit comments