### Install Azure Search and Identity Packages Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Installs necessary NuGet packages for Azure AI Search and Azure Identity. Ensure you have the correct versions specified. ```python #r "nuget: Azure.Search.Documents, 12.1.0-beta.1" #r "nuget: Azure.Identity, 1.21.0" #r "nuget: dotenv.net, 4.0.0" ``` -------------------------------- ### Define System Message for Q&A Agent Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Sets up the initial system message that guides the Q&A agent's behavior and constraints. This is the first message in the conversation history. ```csharp string instructions = @" A Q&A agent that can answer questions about the Earth at night. If you don't have the answer, respond with \"I don't know\". "; var messages = new List> { new Dictionary { { "role", "system" }, { "content", instructions } } }; ``` -------------------------------- ### Create a Knowledge Base with Answer Synthesis Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb This snippet shows how to create a knowledge base, which acts as a wrapper for a knowledge source and an LLM deployment. It configures the knowledge base to use Answer Synthesis for LLM-generated answers with citations. ```csharp using Azure.Search.Documents.Indexes.Models; using Azure.Search.Documents.KnowledgeBases.Models; var openAiParameters = new AzureOpenAIVectorizerParameters { ResourceUri = new Uri(aoaiEndpoint), DeploymentName = aoaiGptDeployment, ModelName = aoaiGptModel }; var model = new KnowledgeBaseAzureOpenAIModel(azureOpenAIParameters: openAiParameters); // Create the knowledge base var knowledgeBase = new KnowledgeBase( name: knowledgeBaseName, knowledgeSources: new KnowledgeSourceReference[] { new KnowledgeSourceReference(knowledgeSourceName) } ) { RetrievalReasoningEffort = new KnowledgeRetrievalLowReasoningEffort(), OutputMode = KnowledgeRetrievalOutputMode.AnswerSynthesis, Models = { model } }; await indexClient.CreateOrUpdateKnowledgeBaseAsync(knowledgeBase); Console.WriteLine($"Knowledge base '{knowledgeBaseName}' created or updated successfully."); ``` -------------------------------- ### Initialize KnowledgeBaseRetrievalClient Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Initializes the client for interacting with Azure Search's knowledge base retrieval. Ensure you have your search endpoint, knowledge base name, and Azure credentials configured. ```csharp using Azure.Search.Documents.KnowledgeBases; using Azure.Search.Documents.KnowledgeBases.Models; var baseClient = new KnowledgeBaseRetrievalClient( endpoint: new Uri(searchEndpoint), knowledgeBaseName: knowledgeBaseName, tokenCredential: new DefaultAzureCredential() ); ``` -------------------------------- ### Upload Sample Documents to Azure Search Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Uploads sample documents from a GitHub URL to an Azure Cognitive Search index. Requires setting up the search endpoint, index name, and credentials. ```csharp using System.Net.Http; using System.Text.Json; using Azure.Search.Documents; using Azure.Search.Documents.Indexes; using Azure.Search.Documents.Models; // Upload sample documents from the GitHub URL string url = "https://raw.githubusercontent.com/Azure-Samples/azure-search-sample-data/refs/heads/main/nasa-e-book/earth-at-night-json/documents.json"; var httpClient = new HttpClient(); var response = await httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); var documents = JsonSerializer.Deserialize>>(json); var searchClient = new SearchClient(new Uri(searchEndpoint), indexName, credential); var searchIndexingBufferedSender = new SearchIndexingBufferedSender>( searchClient, new SearchIndexingBufferedSenderOptions> { KeyFieldAccessor = doc => doc["id"].ToString(), } ); await searchIndexingBufferedSender.UploadDocumentsAsync(documents); await searchIndexingBufferedSender.FlushAsync(); Console.WriteLine($"Documents uploaded to index '{indexName}' successfully."); ``` -------------------------------- ### Create a Knowledge Source in Azure AI Search Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb This snippet demonstrates how to create a knowledge source that targets an existing Azure AI Search index. It specifies the index name and the fields to be used as data sources. ```csharp using Azure.Search.Documents.Indexes.Models; // Create the knowledge source var indexKnowledgeSource = new SearchIndexKnowledgeSource( name: knowledgeSourceName, searchIndexParameters: new SearchIndexKnowledgeSourceParameters(searchIndexName: indexName) { SourceDataFields = { new SearchIndexFieldReference(name: "id"), new SearchIndexFieldReference(name: "page_chunk"), new SearchIndexFieldReference(name: "page_number") } } ); await indexClient.CreateOrUpdateKnowledgeSourceAsync(indexKnowledgeSource); Console.WriteLine($"Knowledge source '{knowledgeSourceName}' created or updated successfully."); ``` -------------------------------- ### Load Environment Variables and Initialize Connections Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Loads environment variables from a .env file for Azure AI Search and Azure OpenAI endpoints and models. It uses DefaultAzureCredential for authentication. ```csharp using dotenv.net; using Azure.Identity; // .env should be in the same directory as this notebook DotEnv.Load(options: new DotEnvOptions(envFilePaths: new[] { ".env" }, ignoreExceptions: false)); // Get environment variables with defaults where appropriate string searchEndpoint = Environment.GetEnvironmentVariable("SEARCH_ENDPOINT") ?? throw new InvalidOperationException("SEARCH_ENDPOINT isn't set."); string aoaiEndpoint = Environment.GetEnvironmentVariable("AOAI_ENDPOINT") ?? throw new InvalidOperationException("AOAI_ENDPOINT isn't set."); string aoaiEmbeddingModel = "text-embedding-3-large"; string aoaiEmbeddingDeployment = "text-embedding-3-large"; string aoaiGptModel = Environment.GetEnvironmentVariable("AOAI_GPT_MODEL") ?? "gpt-5-mini"; string aoaiGptDeployment = Environment.GetEnvironmentVariable("AOAI_GPT_DEPLOYMENT") ?? "gpt-5-mini"; string indexName = "earth-at-night"; string knowledgeSourceName = "earth-knowledge-source"; string knowledgeBaseName = "earth-knowledge-base"; var credential = new DefaultAzureCredential(); ``` -------------------------------- ### Index Creation Output Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb This is the expected output message upon successful creation or update of the search index. ```text Index 'earth-at-night' created or updated successfully. ``` -------------------------------- ### Continue Conversation with Knowledge Agent Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb This snippet shows how to add a user message, construct a retrieval request with conversation history, set reasoning effort, and retrieve information from the knowledge base. ```csharp messages.Add(new Dictionary { { "role", "user" }, { "content", "How do I find lava at night?" } }); var retrievalRequest = new KnowledgeBaseRetrievalRequest(); foreach (Dictionary message in messages) { if (message["role"] != "system") { retrievalRequest.Messages.Add(new KnowledgeBaseMessage(content: new[] { new KnowledgeBaseMessageTextContent(message["content"]) }) { Role = message["role"] }); } } retrievalRequest.RetrievalReasoningEffort = new KnowledgeRetrievalLowReasoningEffort(); var retrievalResult = await baseClient.RetrieveAsync(retrievalRequest); messages.Add(new Dictionary { { "role", "assistant" }, { "content", (retrievalResult.Value.Response[0].Content[0] as KnowledgeBaseMessageTextContent).Text } }); ``` -------------------------------- ### Review Azure AI Search Retrieval Activity and Results Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Iterates through the activity and reference results from a retrieval operation. Use this to understand the steps taken by the retrieval process and the data sources that were relevant. ```csharp Console.WriteLine("Activity:"); foreach (var activity in retrievalResult.Value.Activity) { Console.WriteLine($"Activity Type: {activity.GetType().Name}"); string json = JsonSerializer.Serialize( activity, activity.GetType(), new JsonSerializerOptions { WriteIndented = true } ); Console.WriteLine(json); } Console.WriteLine("Results"); foreach (var reference in retrievalResult.Value.References) { Console.WriteLine($"Reference Type: {reference.GetType().Name}"); string json = JsonSerializer.Serialize( reference, reference.GetType(), new JsonSerializerOptions { WriteIndented = true } ); Console.WriteLine(json); } ``` -------------------------------- ### Add User Message and Perform Retrieval Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Adds a user's question to the conversation history and initiates the agentic retrieval process. The retrieval request is configured with low reasoning effort. ```csharp messages.Add(new Dictionary { { "role", "user" }, { "content", @" Why do suburban belts display larger December brightening than urban cores even though absolute light levels are higher downtown? Why is the Phoenix nighttime street grid is so sharply visible from space, whereas large stretches of the interstate between midwestern cities remain comparatively dim? " } }); var retrievalRequest = new KnowledgeBaseRetrievalRequest(); foreach (Dictionary message in messages) { if (message["role"] != "system") { retrievalRequest.Messages.Add(new KnowledgeBaseMessage(content: new[] { new KnowledgeBaseMessageTextContent(message["content"]) }) { Role = message["role"] }); } } retrievalRequest.RetrievalReasoningEffort = new KnowledgeRetrievalLowReasoningEffort(); var retrievalResult = await baseClient.RetrieveAsync(retrievalRequest); messages.Add(new Dictionary { { "role", "assistant" }, { "content", (retrievalResult.Value.Response[0].Content[0] as KnowledgeBaseMessageTextContent).Text } }); ``` -------------------------------- ### Define and Create Azure Cognitive Search Index Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Use this C# code to define the schema for a search index, including text fields, vector fields, vectorizers, and semantic configurations. It then creates or updates the index in Azure Cognitive Search. ```csharp using Azure.Search.Documents.Indexes; using Azure.Search.Documents.Indexes.Models; // Define fields for the index var fields = new List { new SimpleField("id", SearchFieldDataType.String) { IsKey = true, IsFilterable = true, IsSortable = true, IsFacetable = true }, new SearchField("page_chunk", SearchFieldDataType.String) { IsFilterable = false, IsSortable = false, IsFacetable = false }, new SearchField("page_embedding_text_3_large", SearchFieldDataType.Collection(SearchFieldDataType.Single)) { VectorSearchDimensions = 3072, VectorSearchProfileName = "hnsw_text_3_large" }, new SimpleField("page_number", SearchFieldDataType.Int32) { IsFilterable = true, IsSortable = true, IsFacetable = true } }; // Define a vectorizer var vectorizer = new AzureOpenAIVectorizer(vectorizerName: "azure_openai_text_3_large") { Parameters = new AzureOpenAIVectorizerParameters { ResourceUri = new Uri(aoaiEndpoint), DeploymentName = aoaiEmbeddingDeployment, ModelName = aoaiEmbeddingModel } }; // Define a vector search profile and algorithm var vectorSearch = new VectorSearch() { Profiles = { new VectorSearchProfile( name: "hnsw_text_3_large", algorithmConfigurationName: "alg" ) { VectorizerName = "azure_openai_text_3_large" } }, Algorithms = { new HnswAlgorithmConfiguration(name: "alg") }, Vectorizers = { vectorizer } }; // Define a semantic configuration var semanticConfig = new SemanticConfiguration( name: "semantic_config", prioritizedFields: new SemanticPrioritizedFields { ContentFields = { new SemanticField("page_chunk") } } ); var semanticSearch = new SemanticSearch() { DefaultConfigurationName = "semantic_config", Configurations = { semanticConfig } }; // Create the index var index = new SearchIndex(indexName) { Fields = fields, VectorSearch = vectorSearch, SemanticSearch = semanticSearch }; // Create the index client and create or update the index var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential); await indexClient.CreateOrUpdateIndexAsync(index); Console.WriteLine($"Index '{indexName}' created or updated successfully."); ``` -------------------------------- ### Extract Answer Text from Retrieval Response Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Accesses the synthesized answer from the retrieval result. This code snippet shows how to cast the content to extract the text. ```csharp (retrievalResult.Value.Response[0].Content[0] as KnowledgeBaseMessageTextContent).Text ``` -------------------------------- ### Delete Knowledge Base in Azure AI Search Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Use this C# snippet to delete a knowledge base from Azure AI Search. Ensure you have the SearchIndexClient initialized with your search endpoint and credentials. ```csharp using Azure.Search.Documents.Indexes; var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential); await indexClient.DeleteKnowledgeBaseAsync(knowledgeBaseName); System.Console.WriteLine($"Knowledge base '{knowledgeBaseName}' deleted successfully."); ``` -------------------------------- ### Delete Knowledge Source in Azure AI Search Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb This C# code deletes a specific knowledge source from your Azure AI Search service. It requires an initialized SearchIndexClient. ```csharp await indexClient.DeleteKnowledgeSourceAsync(knowledgeSourceName); System.Console.WriteLine($"Knowledge source '{knowledgeSourceName}' deleted successfully."); ``` -------------------------------- ### Delete Search Index in Azure AI Search Source: https://github.com/azure-samples/azure-search-dotnet-samples/blob/main/quickstart-agentic-retrieval/quickstart.ipynb Use this C# snippet to delete a search index from Azure AI Search. This operation requires an initialized SearchIndexClient and the name of the index to be deleted. ```csharp await indexClient.DeleteIndexAsync(indexName); System.Console.WriteLine($"Index '{indexName}' deleted successfully."); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.