|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +// This sample shows how to use TextSearchProvider to add retrieval augmented generation (RAG) capabilities to an AI agent. |
| 4 | +// The sample uses an In-Memory vector store, which can easily be replaced with any other vector store that implements the Microsoft.Extensions.VectorData abstractions. |
| 5 | +// The TextSearchProvider runs a search against the vector store via the TextSearchStore before each model invocation and injects the results into the model context. |
| 6 | +// The TextSearchStore is a sample store implementation that hardcodes a storage schema and uses the vector store to store and retrieve documents. |
| 7 | + |
| 8 | +using Azure.AI.OpenAI; |
| 9 | +using Azure.Identity; |
| 10 | +using Microsoft.Agents.AI; |
| 11 | +using Microsoft.Agents.AI.Data; |
| 12 | +using Microsoft.Agents.AI.Samples; |
| 13 | +using Microsoft.Extensions.AI; |
| 14 | +using Microsoft.Extensions.VectorData; |
| 15 | +using Microsoft.SemanticKernel.Connectors.InMemory; |
| 16 | +using OpenAI; |
| 17 | + |
| 18 | +var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set."); |
| 19 | +var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; |
| 20 | +var embeddingDeploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME") ?? "text-embedding-3-large"; |
| 21 | + |
| 22 | +AzureOpenAIClient azureOpenAIClient = new( |
| 23 | + new Uri(endpoint), |
| 24 | + new AzureCliCredential()); |
| 25 | + |
| 26 | +// Create an In-Memory vector store that uses the Azure OpenAI embedding model to generate embeddings. |
| 27 | +VectorStore vectorStore = new InMemoryVectorStore(new() |
| 28 | +{ |
| 29 | + EmbeddingGenerator = azureOpenAIClient.GetEmbeddingClient(embeddingDeploymentName).AsIEmbeddingGenerator() |
| 30 | +}); |
| 31 | + |
| 32 | +// Create a store that defines a storage schema, and uses the vector store to store and retrieve documents. |
| 33 | +TextSearchStore textSearchStore = new(vectorStore, "product-and-policy-info", 3072); |
| 34 | + |
| 35 | +// Upload sample documents into the store. |
| 36 | +await textSearchStore.UpsertDocumentsAsync(GetSampleDocuments()); |
| 37 | + |
| 38 | +// Create an adapter function that the TextSearchProvider can use to run searches against the TextSearchStore. |
| 39 | +Func<string, CancellationToken, Task<IEnumerable<TextSearchProvider.TextSearchResult>>> SearchAdapter = async (text, ct) => |
| 40 | +{ |
| 41 | + // Here we are limiting the search results to the single top result to demonstrate that we are accurately matching |
| 42 | + // specific search results for each question, but in a real world case, more results should be used. |
| 43 | + var searchResults = await textSearchStore.SearchAsync(text, 1, ct); |
| 44 | + return searchResults.Select(r => new TextSearchProvider.TextSearchResult |
| 45 | + { |
| 46 | + SourceName = r.SourceName, |
| 47 | + SourceLink = r.SourceLink, |
| 48 | + Text = r.Text ?? string.Empty, |
| 49 | + RawRepresentation = r |
| 50 | + }); |
| 51 | +}; |
| 52 | + |
| 53 | +// Configure the options for the TextSearchProvider. |
| 54 | +TextSearchProviderOptions textSearchOptions = new() |
| 55 | +{ |
| 56 | + // Run the search prior to every model invocation. |
| 57 | + SearchTime = TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke, |
| 58 | +}; |
| 59 | + |
| 60 | +// Create the AI agent with the TextSearchProvider as the AI context provider. |
| 61 | +AIAgent agent = azureOpenAIClient |
| 62 | + .GetChatClient(deploymentName) |
| 63 | + .CreateAIAgent(new ChatClientAgentOptions |
| 64 | + { |
| 65 | + Instructions = "You are a helpful support specialist for Contoso Outdoors. Answer questions using the provided context and cite the source document when available.", |
| 66 | + AIContextProviderFactory = ctx => ctx.SerializedState.ValueKind is not System.Text.Json.JsonValueKind.Null and not System.Text.Json.JsonValueKind.Undefined |
| 67 | + ? new TextSearchProvider(SearchAdapter, ctx.SerializedState, ctx.JsonSerializerOptions, textSearchOptions) |
| 68 | + : new TextSearchProvider(SearchAdapter, textSearchOptions) |
| 69 | + }); |
| 70 | + |
| 71 | +AgentThread thread = agent.GetNewThread(); |
| 72 | + |
| 73 | +Console.WriteLine(">> Asking about returns\n"); |
| 74 | +Console.WriteLine(await agent.RunAsync("Hi! I need help understanding the return policy.", thread)); |
| 75 | + |
| 76 | +Console.WriteLine("\n>> Asking about shipping\n"); |
| 77 | +Console.WriteLine(await agent.RunAsync("How long does standard shipping usually take?", thread)); |
| 78 | + |
| 79 | +Console.WriteLine("\n>> Asking about product care\n"); |
| 80 | +Console.WriteLine(await agent.RunAsync("What is the best way to maintain the TrailRunner tent fabric?", thread)); |
| 81 | + |
| 82 | +// Produces some sample search documents. |
| 83 | +// Each one contains a source name and link, which the agent can use to cite sources in its responses. |
| 84 | +static IEnumerable<TextSearchDocument> GetSampleDocuments() |
| 85 | +{ |
| 86 | + yield return new TextSearchDocument |
| 87 | + { |
| 88 | + SourceId = "return-policy-001", |
| 89 | + SourceName = "Contoso Outdoors Return Policy", |
| 90 | + SourceLink = "https://contoso.com/policies/returns", |
| 91 | + Text = "Customers may return any item within 30 days of delivery. Items should be unused and include original packaging. Refunds are issued to the original payment method within 5 business days of inspection." |
| 92 | + }; |
| 93 | + yield return new TextSearchDocument |
| 94 | + { |
| 95 | + SourceId = "shipping-guide-001", |
| 96 | + SourceName = "Contoso Outdoors Shipping Guide", |
| 97 | + SourceLink = "https://contoso.com/help/shipping", |
| 98 | + Text = "Standard shipping is free on orders over $50 and typically arrives in 3-5 business days within the continental United States. Expedited options are available at checkout." |
| 99 | + }; |
| 100 | + yield return new TextSearchDocument |
| 101 | + { |
| 102 | + SourceId = "tent-care-001", |
| 103 | + SourceName = "TrailRunner Tent Care Instructions", |
| 104 | + SourceLink = "https://contoso.com/manuals/trailrunner-tent", |
| 105 | + Text = "Clean the tent fabric with lukewarm water and a non-detergent soap. Allow it to air dry completely before storage and avoid prolonged UV exposure to extend the lifespan of the waterproof coating." |
| 106 | + }; |
| 107 | +} |
0 commit comments