Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
In deze snelstart verzendt u vragen naar een chatvoltooiingsmodel voor een zoekervaring met gesprekken binnen uw geïndexeerde inhoud in Azure AI Search. Nadat u Azure OpenAI- en Azure AI Search-resources hebt ingesteld in Azure Portal, voert u code uit om de API's aan te roepen.
Vereisten
Een Azure-account met een actief abonnement. Gratis een account maken
-
- Kies een regio die ondersteuning biedt voor het voltooiingsmodel voor chats (gpt-4o, gpt-4o-mini of een gelijkwaardig model).
- Implementeer het voltooiingsmodel voor chats in Azure AI Foundry of gebruik een andere benadering.
-
- U wordt aangeraden de Basic-laag of hoger te gebruiken.
- Schakel semantische rangschikking in.
.NET 9.0 geïnstalleerd.
Toegang configureren
Aanvragen voor het zoekeindpunt moeten worden geverifieerd en geautoriseerd. U kunt API-sleutels of -rollen voor deze taak gebruiken. Sleutels zijn gemakkelijker te beginnen, maar rollen zijn veiliger. In deze quickstart wordt ervan uitgegaan dat rollen zijn.
U stelt twee clients in, dus u hebt machtigingen nodig voor beide resources.
Azure AI Search ontvangt de queryaanvraag van uw lokale systeem. Wijs uzelf de roltoewijzing gegevenslezer van de zoekindex toe als de voorbeeldindex van hotels al bestaat. Als deze niet bestaat, wijst u uzelf de rollen Inzender voor zoekservice en Inzender voor zoekindexgegevens toe, zodat u de index kunt maken en er query's op kunt uitvoeren.
Azure OpenAI ontvangt de query en de zoekresultaten van uw lokale systeem. Wijs uzelf de Gebruikersrol Cognitive Services OpenAI toe in Azure OpenAI.
Meld u aan bij het Azure-portaal.
Configureer Azure AI Search voor op rollen gebaseerde toegang:
Zoek in Azure Portal uw Azure AI-Search-service.
Selecteer en selecteer vervolgens op > of Beide.
Rollen toewijzen:
Selecteer toegangsbeheer (IAM) in het linkermenu.
Selecteer in Azure AI Search deze rollen om een zoekindex te maken, laden en er query's op uit te voeren en wijs deze vervolgens toe aan uw Microsoft Entra ID-gebruikersidentiteit:
- Inzender voor zoekindexgegevens
- Inzender voor zoekservice
Selecteer in Azure OpenAI toegangsbeheer (IAM) om deze rol aan uzelf toe te wijzen in Azure OpenAI:
- Cognitive Services OpenAI-gebruiker
Het kan enkele minuten duren voordat machtigingen van kracht worden.
Een index maken
Een zoekindex biedt grondgegevens voor het chatmodel. We raden de hotels-sample-index aan, die in enkele minuten kan worden gemaakt en uitgevoerd op elke zoekservicelaag. Deze index wordt gemaakt met behulp van ingebouwde voorbeeldgegevens.
Zoek uw zoekservice in Azure Portal.
Selecteer op de startpagina Overzicht de optie Gegevens importeren om de wizard te starten.
Selecteer op de pagina Verbinding maken met uw gegevens voorbeelden in de vervolgkeuzelijst.
Kies het hotelvoorbeeld.
Selecteer Volgende via de resterende pagina's en accepteer de standaardwaarden.
Nadat de index is gemaakt, selecteert u Zoekbeheerindexen> in het linkermenu om de index te openen.
Selecteer JSON bewerken.
Schuif naar het einde van de index, waar u tijdelijke aanduidingen kunt vinden voor constructies die aan een index kunnen worden toegevoegd.
"analyzers": [], "tokenizers": [], "tokenFilters": [], "charFilters": [], "normalizers": [],
Plak op een nieuwe regel na normalizers de volgende semantische configuratie. In dit voorbeeld wordt een
"defaultConfiguration"
, wat belangrijk is voor het uitvoeren van deze quickstart."semantic":{ "defaultConfiguration":"semantic-config", "configurations":[ { "name":"semantic-config", "prioritizedFields":{ "titleField":{ "fieldName":"HotelName" }, "prioritizedContentFields":[ { "fieldName":"Description" } ], "prioritizedKeywordsFields":[ { "fieldName":"Category" }, { "fieldName":"Tags" } ] } } ] },
Sla uw wijzigingen op.
Voer de volgende query uit in Search Explorer om uw index te testen:
complimentary breakfast
Uitvoer moet er ongeveer uitzien als in het volgende voorbeeld. Resultaten die rechtstreeks vanuit de zoekmachine worden geretourneerd, bestaan uit velden en hun exacte waarden, samen met metagegevens zoals een zoekscore en een semantische classificatiescore en bijschrift als u semantische rangschikking gebruikt. We hebben een select-instructie gebruikt om alleen de velden HotelName, Description en Tags te retourneren.
{ "@odata.count": 18, "@search.answers": [], "value": [ { "@search.score": 2.2896252, "@search.rerankerScore": 2.506816864013672, "@search.captions": [ { "text": "Head Wind Resort. Suite. coffee in lobby\r\nfree wifi\r\nview. The best of old town hospitality combined with views of the river and cool breezes off the prairie. Our penthouse suites offer views for miles and the rooftop plaza is open to all guests from sunset to 10 p.m. Enjoy a **complimentary continental breakfast** in the lobby, and free Wi-Fi throughout the hotel..", "highlights": "" } ], "HotelName": "Head Wind Resort", "Description": "The best of old town hospitality combined with views of the river and cool breezes off the prairie. Our penthouse suites offer views for miles and the rooftop plaza is open to all guests from sunset to 10 p.m. Enjoy a complimentary continental breakfast in the lobby, and free Wi-Fi throughout the hotel.", "Tags": [ "coffee in lobby", "free wifi", "view" ] }, { "@search.score": 2.2158256, "@search.rerankerScore": 2.288334846496582, "@search.captions": [ { "text": "Swan Bird Lake Inn. Budget. continental breakfast\r\nfree wifi\r\n24-hour front desk service. We serve a continental-style breakfast each morning, featuring a variety of food and drinks. Our locally made, oh-so-soft, caramel cinnamon rolls are a favorite with our guests. Other breakfast items include coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins..", "highlights": "" } ], "HotelName": "Swan Bird Lake Inn", "Description": "We serve a continental-style breakfast each morning, featuring a variety of food and drinks. Our locally made, oh-so-soft, caramel cinnamon rolls are a favorite with our guests. Other breakfast items include coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins.", "Tags": [ "continental breakfast", "free wifi", "24-hour front desk service" ] }, { "@search.score": 0.92481667, "@search.rerankerScore": 2.221315860748291, "@search.captions": [ { "text": "White Mountain Lodge & Suites. Resort and Spa. continental breakfast\r\npool\r\nrestaurant. Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings..", "highlights": "" } ], "HotelName": "White Mountain Lodge & Suites", "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.", "Tags": [ "continental breakfast", "pool", "restaurant" ] }, . . . ]}
Service-eindpunten ophalen
In de resterende secties stelt u API-aanroepen in op Azure OpenAI en Azure AI Search. Haal de service-eindpunten op, zodat u ze kunt opgeven als variabelen in uw code.
Meld u aan bij het Azure-portaal.
Kopieer de URL op de startpagina Overzicht . Een eindpunt ziet er bijvoorbeeld uit als
https://example.search.windows.net
.Selecteer op de startpagina Overzicht de koppeling om de eindpunten weer te geven. Kopieer de URL. Een eindpunt ziet er bijvoorbeeld uit als
https://example.openai.azure.com/
.
Aanmelden bij Azure
U gebruikt Microsoft Entra-id en roltoewijzingen voor de verbinding. Zorg ervoor dat u bent aangemeld bij dezelfde tenant en hetzelfde abonnement als Azure AI Search en Azure OpenAI. U kunt de Azure CLI op de opdrachtregel gebruiken om de huidige eigenschappen weer te geven, eigenschappen te wijzigen en u aan te melden. Zie Verbinding maken zonder sleutels voor meer informatie.
Voer elk van de volgende opdrachten op volgorde uit.
az account show
az account set --subscription <PUT YOUR SUBSCRIPTION ID HERE>
az login --tenant <PUT YOUR TENANT ID HERE>
U moet nu vanaf uw lokale apparaat zijn aangemeld bij Azure.
De .NET-app instellen
Als u de stappen vooruit wilt volgen, kunt u de voltooide voorbeeld-app klonen vanuit GitHub of zelf de app maken.
De voorbeeld-app klonen
Ga als volgt te werk om toegang te krijgen tot de voltooide voorbeeld-app voor dit artikel:
Kloon de opslagplaats azure-search-dotnet-samples van GitHub.
git clone https://github.com/Azure-Samples/azure-search-dotnet-samples
Navigeer naar de
quickstart-rag
map.Open de
quickstart-rag
map in Visual Studio Code of open het oplossingsbestand met Visual Studio.
De voorbeeld-app maken
Voer de volgende stappen uit om een .NET-console-app te maken om verbinding te maken met een AI-model.
Gebruik in een lege map op uw computer de opdracht
dotnet new
om een nieuwe console-app te maken:dotnet new console -o AISearchRag
Wijzig de map in de app-map:
cd AISearchRag
Installeer de vereiste pakketten:
dotnet add package Azure.AI.OpenAI dotnet add package Azure.Identity dotnet add package Azure.Search.Documents
Open de app in Visual Studio Code (of uw editor naar keuze).
code .
De query- en chatthread instellen
In het volgende voorbeeld ziet u hoe u een minimaal RAG-scenario instelt met behulp van Azure AI Search om een OpenAI-model te bieden met contextuele resources om de gegenereerde antwoorden te verbeteren.
Open in het
minimal-query
project van de voorbeeldopslagplaats hetProgram.cs
bestand om het eerste voorbeeld weer te geven. Als u het project zelf hebt gemaakt, voegt u de volgende code toe om verbinding te maken met de Azure AI Search- en Azure OpenAI-services en er query's op uit te voeren.Opmerking
Zorg ervoor dat u de tijdelijke aanduidingen vervangt voor het Azure OpenAI-eindpunt en de modelnaam, evenals het Azure AI Search-eindpunt en de indexnaam.
using System; using System.Collections.Generic; using System.Threading.Tasks; using Azure.Identity; using Azure.Search.Documents; using Azure.Search.Documents.Models; using Azure.AI.OpenAI; using OpenAI.Chat; using System.Text.Json; using Microsoft.Extensions.Logging; // Azure resource endpoints and deployment info string azureSearchServiceEndpoint = "azure-ai-search-endpoint"; string azureOpenAIEndpoint = "azure-ai-openai-endpoint"; string azureDeploymentModel = "azure-ai-deployment-name"; string indexName = "hotels-sample-index"; // Set up Azure credentials and clients var credential = new DefaultAzureCredential(); var searchClient = new SearchClient(new Uri(azureSearchServiceEndpoint), indexName, credential); var openAIClient = new AzureOpenAIClient(new Uri(azureOpenAIEndpoint), credential); // Prompt template for grounding the LLM response in search results string GROUNDED_PROMPT = @"You are a friendly assistant that recommends hotels based on activities and amenities. Answer the query using only the sources provided below in a friendly and concise bulleted manner Answer ONLY with the facts listed in the list of sources below. If there isn't enough information below, say you don't know. Do not generate answers that don't use the sources below. Query: {0} Sources: {1}"; // The user's query string query = "Can you recommend a few hotels with complimentary breakfast?"; // Configure search options: top 5 results, select relevant fields var options = new SearchOptions { Size = 5 }; options.Select.Add("Description"); options.Select.Add("HotelName"); options.Select.Add("Tags"); // Execute the search var searchResults = await searchClient.SearchAsync<SearchDocument>(query, options); var sources = new List<string>(); await foreach (var result in searchResults.Value.GetResultsAsync()) { var doc = result.Document; // Format each result as: HotelName:Description:Tags sources.Add($"{doc["HotelName"]}:{doc["Description"]}:{doc["Tags"]}"); } string sourcesFormatted = string.Join("\n", sources); // Format the prompt with the query and sources string formattedPrompt = string.Format(GROUNDED_PROMPT, query, sourcesFormatted); // Create a chat client for the specified deployment/model ChatClient chatClient = openAIClient.GetChatClient(azureDeploymentModel); // Send the prompt to the LLM and stream the response var chatUpdates = chatClient.CompleteChatStreamingAsync( [ new UserChatMessage(formattedPrompt) ] ); // Print the streaming response to the console await foreach (var chatUpdate in chatUpdates) { if (chatUpdate.Role.HasValue) { Console.Write($"{chatUpdate.Role} : "); } foreach (var contentPart in chatUpdate.ContentUpdate) { Console.Write(contentPart.Text); } }
De voorgaande code bereikt het volgende:
- Zoekt in een Azure Search-index naar hotels die overeenkomen met een gebruikersquery over gratis ontbijt, het ophalen van de hotelnaam, beschrijving en tags.
- Hiermee worden de zoekresultaten opgemaakt in een gestructureerde lijst om te fungeren als contextuele bronnen voor het generatieve AI-model.
- Hiermee wordt een prompt samengesteld waarin het Azure OpenAI-model wordt geïnstrueerd om alleen te beantwoorden met behulp van de opgegeven bronnen.
- Hiermee wordt de prompt verzonden naar het AI-model en wordt het gegenereerde antwoord gestreamd.
- Het antwoord van de AI wordt naar de console weergegeven, waarbij zowel de rol als de inhoud worden getoond tijdens het streamen.
Voer het project uit om een eenvoudig RAG-scenario te starten. De uitvoer van Azure OpenAI bestaat uit aanbevelingen voor verschillende hotels, zoals het volgende voorbeeld:
Sure! Here are a few hotels that offer complimentary breakfast: - **Head Wind Resort** - Complimentary continental breakfast in the lobby - Free Wi-Fi throughout the hotel - **Double Sanctuary Resort** - Continental breakfast included - **White Mountain Lodge & Suites** - Continental breakfast available - **Swan Bird Lake Inn** - Continental-style breakfast each morning with a variety of food and drinks such as caramel cinnamon rolls, coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins
Als u verder wilt experimenteren, wijzigt u de query en voert u de laatste stap opnieuw uit om beter te begrijpen hoe het model werkt met de grondgegevens. U kunt ook de prompt wijzigen om de toon of structuur van de uitvoer te wijzigen.
Probleemoplossingsproces
Mogelijk ontvangt u een van de volgende fouten tijdens het testen:
- Verboden: controleer de Configuratie van Azure AI Search om ervoor te zorgen dat op rollen gebaseerde toegang is ingeschakeld.
- Autorisatie is mislukt: wacht enkele minuten en probeer het opnieuw. Het kan enkele minuten duren voordat roltoewijzingen operationeel worden.
- De resource is niet gevonden: controleer de resource-URI's en controleer of de API-versie in het chatmodel geldig is.
Een complexe RAG-query verzenden
Azure AI Search ondersteunt complexe typen voor geneste JSON-structuren. In de hotels-sample-index Address
is een voorbeeld van een complex type, bestaande uit Address.StreetAddress
, Address.City
, Address.StateProvince
, en Address.PostalCode
.Address.Country
De index heeft ook een complexe verzameling van Rooms
elk hotel. Als uw index complexe typen heeft, kan uw query deze velden leveren als u eerst de uitvoer van zoekresultaten converteert naar JSON en vervolgens de JSON doorgeeft aan het chatmodel.
Open het
complex-query
bestand in hetProgram.cs
project van de voorbeeldopslagplaats. Als u het project zelf hebt gemaakt, vervangt u de code door het volgende:using System; using System.Collections.Generic; using System.Threading.Tasks; using Azure.Identity; using Azure.Search.Documents; using Azure.Search.Documents.Models; using Azure.AI.OpenAI; using OpenAI.Chat; using System.Text.Json; using Microsoft.Extensions.Logging; // Azure resource endpoints and deployment info string azureSearchServiceEndpoint = "azure-ai-search-endpoint"; string azureOpenAIEndpoint = "azure-ai-openai-endpoint"; string azureDeploymentModel = "azure-ai-deployment-name"; string indexName = "hotels-sample-index"; // Set up Azure credentials and clients var credential = new DefaultAzureCredential(); var searchClient = new SearchClient(new Uri(azureSearchServiceEndpoint), indexName, credential); var openAIClient = new AzureOpenAIClient(new Uri(azureOpenAIEndpoint), credential); // Prompt template for the OpenAI model string groundedPrompt = @"You are a friendly assistant that recommends hotels based on activities and amenities. Answer the query using only the sources provided below in a friendly and concise bulleted manner. Answer ONLY with the facts listed in the list of sources below. If there isn't enough information below, say you don't know. Do not generate answers that don't use the sources below. Query: {0} Sources: {1}"; // The user query and fields to select from search var query = "Can you recommend a few hotels that offer complimentary breakfast? Tell me their description, address, tags, and the rate for one room that sleeps 4 people."; var selectedFields = new[] { "HotelName", "Description", "Address", "Rooms", "Tags" }; // Configure search options var options = new SearchOptions { Size = 5 }; foreach (var field in selectedFields) { options.Select.Add(field); } // Run Azure Cognitive Search var searchResults = await searchClient.SearchAsync<SearchDocument>(query, options); // Filter and format search results var sourcesFiltered = new List<Dictionary<string, object>>(); await foreach (var result in searchResults.Value.GetResultsAsync()) { sourcesFiltered.Add( selectedFields .Where(f => result.Document.TryGetValue(f, out _)) .ToDictionary(f => f, f => result.Document[f]) ); } var sourcesFormatted = string.Join("\n", sourcesFiltered.ConvertAll(source => JsonSerializer.Serialize(source))); // Format the prompt for OpenAI string formattedPrompt = string.Format(groundedPrompt, query, sourcesFormatted); // Get a chat client for the OpenAI deployment ChatClient chatClient = openAIClient.GetChatClient(azureDeploymentModel); // Send the prompt to Azure OpenAI and stream the response var chatUpdates = chatClient.CompleteChatStreamingAsync( new[] { new UserChatMessage(formattedPrompt) } ); // Output the streamed chat response await foreach (var chatUpdate in chatUpdates) { if (chatUpdate.Role.HasValue) { Console.Write($"{chatUpdate.Role} : "); } foreach (var contentPart in chatUpdate.ContentUpdate) { Console.Write(contentPart.Text); } }
Voer het project uit om een eenvoudig RAG-scenario te starten. De uitvoer van Azure OpenAI bestaat uit aanbevelingen voor verschillende hotels, zoals het volgende voorbeeld:
1. **Double Sanctuary Resort** - **Description**: 5-star luxury hotel with the biggest rooms in the city. Recognized as the #1 hotel in the area by Traveler magazine. Features include free WiFi, flexible check-in/out, a fitness center, and in-room espresso. - **Address**: 2211 Elliott Ave, Seattle, WA, 98121, USA - **Tags**: view, pool, restaurant, bar, continental breakfast - **Room Rate for 4 People**: - Suite, 2 Queen Beds: $254.99 per night 2. **Starlight Suites** - **Description**: Spacious all-suite hotel with complimentary airport shuttle and WiFi. Facilities include an indoor/outdoor pool, fitness center, and Florida Green certification. Complimentary coffee and HDTV are also available. - **Address**: 19575 Biscayne Blvd, Aventura, FL, 33180, USA - **Tags**: pool, coffee in lobby, free wifi - **Room Rate for 4 People**: - Suite, 2 Queen Beds (Cityside): $231.99 per night - Deluxe Room, 2 Queen Beds (Waterfront View): $148.99 per night 3. **Good Business Hotel** - **Description**: Located one mile from the airport with free WiFi, an outdoor pool, and a complimentary airport shuttle. Close proximity to Lake Lanier and downtown. The business center includes printers, a copy machine, fax, and a work area. - **Address**: 4400 Ashford Dunwoody Rd NE, Atlanta, GA, 30346, USA - **Tags**: pool, continental breakfast, free parking - **Room Rate for 4 People**: - Budget Room, 2 Queen Beds (Amenities): $60.99 per night - Deluxe Room, 2 Queen Beds (Amenities): $139.99 per night
Probleemoplossingsproces
Als u uitvoerberichten ziet tijdens foutopsporing met betrekking tot ManagedIdentityCredential
en fouten bij het verkrijgen van tokens, kan het zijn dat u meerdere tenants hebt en dat uw Azure-aanmelding een tenant gebruikt die niet over uw zoekservice beschikt. Als u uw tenant-id wilt ophalen, zoekt u in Azure Portal naar 'tenanteigenschappen' of voert u deze uit az login tenant list
.
Zodra u uw tenant-id hebt, voert u deze uit az login --tenant <YOUR-TENANT-ID>
bij een opdrachtprompt en voert u het script opnieuw uit.
U kunt ook fouten in uw code registreren door een instantie van ILogger
te maken:
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
});
ILogger logger = loggerFactory.CreateLogger<Program>();
Opschonen
Wanneer u in uw eigen abonnement werkt, is het een goed idee om aan het einde van een project te bepalen of u de gemaakte resources nog nodig hebt. Resources die actief blijven, kunnen u geld kosten. U kunt resources afzonderlijk verwijderen, maar u kunt ook de resourcegroep verwijderen als u de volledige resourceset wilt verwijderen.
U kunt resources vinden en beheren in Azure Portal met behulp van de koppeling Alle resources of resourcegroepen in het meest linkse deelvenster.
Vereisten
Een Azure-account met een actief abonnement. Gratis een account maken
-
- Kies een regio die ondersteuning biedt voor het voltooiingsmodel voor chats (gpt-4o, gpt-4o-mini of een gelijkwaardig model).
- Implementeer het voltooiingsmodel voor chats in Azure AI Foundry of gebruik een andere benadering.
-
- U wordt aangeraden de Basic-laag of hoger te gebruiken.
- Schakel semantische rangschikking in.
Toegang configureren
Aanvragen voor het zoekeindpunt moeten worden geverifieerd en geautoriseerd. U kunt API-sleutels of -rollen voor deze taak gebruiken. Sleutels zijn gemakkelijker te beginnen, maar rollen zijn veiliger. In deze quickstart wordt ervan uitgegaan dat rollen zijn.
U stelt twee clients in, dus u hebt machtigingen nodig voor beide resources.
Azure AI Search ontvangt de queryaanvraag van uw lokale systeem. Wijs uzelf de roltoewijzing gegevenslezer van de zoekindex toe als de voorbeeldindex van hotels al bestaat. Als deze niet bestaat, wijst u uzelf de rollen Inzender voor zoekservice en Inzender voor zoekindexgegevens toe, zodat u de index kunt maken en er query's op kunt uitvoeren.
Azure OpenAI ontvangt de query en de zoekresultaten van uw lokale systeem. Wijs uzelf de Gebruikersrol Cognitive Services OpenAI toe in Azure OpenAI.
Meld u aan bij het Azure-portaal.
Configureer Azure AI Search voor op rollen gebaseerde toegang:
Zoek in Azure Portal uw Azure AI-Search-service.
Selecteer en selecteer vervolgens op > of Beide.
Rollen toewijzen:
Selecteer toegangsbeheer (IAM) in het linkermenu.
Selecteer in Azure AI Search deze rollen om een zoekindex te maken, laden en er query's op uit te voeren en wijs deze vervolgens toe aan uw Microsoft Entra ID-gebruikersidentiteit:
- Inzender voor zoekindexgegevens
- Inzender voor zoekservice
Selecteer in Azure OpenAI toegangsbeheer (IAM) om deze rol aan uzelf toe te wijzen in Azure OpenAI:
- Cognitive Services OpenAI-gebruiker
Het kan enkele minuten duren voordat machtigingen van kracht worden.
Een index maken
Een zoekindex biedt grondgegevens voor het chatmodel. We raden de hotels-sample-index aan, die in enkele minuten kan worden gemaakt en uitgevoerd op elke zoekservicelaag. Deze index wordt gemaakt met behulp van ingebouwde voorbeeldgegevens.
Zoek uw zoekservice in Azure Portal.
Selecteer op de startpagina Overzicht de optie Gegevens importeren om de wizard te starten.
Selecteer op de pagina Verbinding maken met uw gegevens voorbeelden in de vervolgkeuzelijst.
Kies het hotelvoorbeeld.
Selecteer Volgende via de resterende pagina's en accepteer de standaardwaarden.
Nadat de index is gemaakt, selecteert u Zoekbeheerindexen> in het linkermenu om de index te openen.
Selecteer JSON bewerken.
Schuif naar het einde van de index, waar u tijdelijke aanduidingen kunt vinden voor constructies die aan een index kunnen worden toegevoegd.
"analyzers": [], "tokenizers": [], "tokenFilters": [], "charFilters": [], "normalizers": [],
Plak op een nieuwe regel na normalizers de volgende semantische configuratie. In dit voorbeeld wordt een
"defaultConfiguration"
, wat belangrijk is voor het uitvoeren van deze quickstart."semantic":{ "defaultConfiguration":"semantic-config", "configurations":[ { "name":"semantic-config", "prioritizedFields":{ "titleField":{ "fieldName":"HotelName" }, "prioritizedContentFields":[ { "fieldName":"Description" } ], "prioritizedKeywordsFields":[ { "fieldName":"Category" }, { "fieldName":"Tags" } ] } } ] },
Sla uw wijzigingen op.
Voer de volgende query uit in Search Explorer om uw index te testen:
complimentary breakfast
Uitvoer moet er ongeveer uitzien als in het volgende voorbeeld. Resultaten die rechtstreeks vanuit de zoekmachine worden geretourneerd, bestaan uit velden en hun exacte waarden, samen met metagegevens zoals een zoekscore en een semantische classificatiescore en bijschrift als u semantische rangschikking gebruikt. We hebben een select-instructie gebruikt om alleen de velden HotelName, Description en Tags te retourneren.
{ "@odata.count": 18, "@search.answers": [], "value": [ { "@search.score": 2.2896252, "@search.rerankerScore": 2.506816864013672, "@search.captions": [ { "text": "Head Wind Resort. Suite. coffee in lobby\r\nfree wifi\r\nview. The best of old town hospitality combined with views of the river and cool breezes off the prairie. Our penthouse suites offer views for miles and the rooftop plaza is open to all guests from sunset to 10 p.m. Enjoy a **complimentary continental breakfast** in the lobby, and free Wi-Fi throughout the hotel..", "highlights": "" } ], "HotelName": "Head Wind Resort", "Description": "The best of old town hospitality combined with views of the river and cool breezes off the prairie. Our penthouse suites offer views for miles and the rooftop plaza is open to all guests from sunset to 10 p.m. Enjoy a complimentary continental breakfast in the lobby, and free Wi-Fi throughout the hotel.", "Tags": [ "coffee in lobby", "free wifi", "view" ] }, { "@search.score": 2.2158256, "@search.rerankerScore": 2.288334846496582, "@search.captions": [ { "text": "Swan Bird Lake Inn. Budget. continental breakfast\r\nfree wifi\r\n24-hour front desk service. We serve a continental-style breakfast each morning, featuring a variety of food and drinks. Our locally made, oh-so-soft, caramel cinnamon rolls are a favorite with our guests. Other breakfast items include coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins..", "highlights": "" } ], "HotelName": "Swan Bird Lake Inn", "Description": "We serve a continental-style breakfast each morning, featuring a variety of food and drinks. Our locally made, oh-so-soft, caramel cinnamon rolls are a favorite with our guests. Other breakfast items include coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins.", "Tags": [ "continental breakfast", "free wifi", "24-hour front desk service" ] }, { "@search.score": 0.92481667, "@search.rerankerScore": 2.221315860748291, "@search.captions": [ { "text": "White Mountain Lodge & Suites. Resort and Spa. continental breakfast\r\npool\r\nrestaurant. Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings..", "highlights": "" } ], "HotelName": "White Mountain Lodge & Suites", "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.", "Tags": [ "continental breakfast", "pool", "restaurant" ] }, . . . ]}
Service-eindpunten ophalen
In de resterende secties stelt u API-aanroepen in op Azure OpenAI en Azure AI Search. Haal de service-eindpunten op, zodat u ze kunt opgeven als variabelen in uw code.
Meld u aan bij het Azure-portaal.
Kopieer de URL op de startpagina Overzicht . Een eindpunt ziet er bijvoorbeeld uit als
https://example.search.windows.net
.Selecteer op de startpagina Overzicht de koppeling om de eindpunten weer te geven. Kopieer de URL. Een eindpunt ziet er bijvoorbeeld uit als
https://example.openai.azure.com/
.
Omgevingsvariabelen instellen voor lokale ontwikkeling
Maak een
.env
-bestand.Voeg de volgende omgevingsvariabelen toe aan het
.env
bestand en vervang de waarden door uw eigen service-eindpunten en -sleutels.AZURE_SEARCH_ENDPOINT=<YOUR AZURE AI SEARCH ENDPOINT> AZURE_SEARCH_INDEX_NAME=hotels-sample-index AZURE_OPENAI_ENDPOINT=<YOUR AZURE OPENAI ENDPOINT> AZURE_OPENAI_VERSION=<YOUR AZURE OPENAI API VERSION> AZURE_DEPLOYMENT_MODEL=<YOUR DEPLOYMENT NAME>
Het Node.JS-project instellen
Stel een project in met Visual Studio Code en TypeScript.
Start Visual Studio Code in een nieuwe map.
mkdir rag-quickstart && cd rag-quickstart code .
Maak een nieuw pakket voor ESM-modules in uw projectmap.
npm init -y npm pkg set type=module
Hiermee maakt u een
package.json
bestand met standaardwaarden.Installeer de volgende npm-pakketten.
npm install @azure/identity @azure/search-documents openai dotenv
Maak een
src
map in uw projectmap.mkdir src
Aanmelden bij Azure
U gebruikt Microsoft Entra-id en roltoewijzingen voor de verbinding. Zorg ervoor dat u bent aangemeld bij dezelfde tenant en hetzelfde abonnement als Azure AI Search en Azure OpenAI. U kunt de Azure CLI op de opdrachtregel gebruiken om de huidige eigenschappen weer te geven, eigenschappen te wijzigen en u aan te melden. Zie Verbinding maken zonder sleutels voor meer informatie.
Voer elk van de volgende opdrachten op volgorde uit.
az account show
az account set --subscription <PUT YOUR SUBSCRIPTION ID HERE>
az login --tenant <PUT YOUR TENANT ID HERE>
U moet nu vanaf uw lokale apparaat zijn aangemeld bij Azure.
Query- en chatthread instellen
Maak een queryscript dat gebruikmaakt van de Azure AI Search-index en het chatmodel om antwoorden te genereren op basis van grondgegevens. De volgende stappen helpen u bij het instellen van het queryscript.
Maak een
query.js
bestand in desrc
map met de volgende code.// This is a RAG (Retrieval Augmented Generation) implementation that: // 1. Takes a user query about hotels // 2. Searches a hotel database using Azure AI Search // 3. Formats the search results for the LLM // 4. Sends the query and formatted results to Azure OpenAI // 5. Returns a grounded response based only on the retrieved information import { SearchClient } from "@azure/search-documents"; import { AzureOpenAI } from "openai"; import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity"; function getClients() { const credential = new DefaultAzureCredential(); // Search const azureSearchEndpoint = process.env.AZURE_SEARCH_ENDPOINT; const azureSearchIndexName = process.env.AZURE_SEARCH_INDEX_NAME; const searchClient = new SearchClient( azureSearchEndpoint, azureSearchIndexName, credential ); // OpenAI const azureOpenAiEndpoint = process.env.AZURE_OPENAI_ENDPOINT; const azureOpenAiApiVersion = process.env.AZURE_OPENAI_VERSION; const azureOpenAiDeploymentName = process.env.AZURE_DEPLOYMENT_MODEL; const scope = "https://cognitiveservices.azure.com/.default"; const azureADTokenProvider = getBearerTokenProvider(credential, scope); const options = { azureADTokenProvider, deployment: azureOpenAiDeploymentName, apiVersion: azureOpenAiApiVersion, endpoint: azureOpenAiEndpoint } const openaiClient = new AzureOpenAI(options); return { openaiClient, searchClient, modelName: azureOpenAiDeploymentName }; } async function queryAISearchForSources(searchClient, query) { console.log(`Searching for: "${query}"\n`); const searchResults = await searchClient.search(query, { top: 5, select: ["Description", "HotelName", "Tags"] }); const sources = []; for await (const result of searchResults.results) { const doc = result.document; sources.push( `Hotel: ${doc.HotelName}\n` + `Description: ${doc.Description}\n` + `Tags: ${Array.isArray(doc.Tags) ? doc.Tags.join(', ') : doc.Tags}\n` ); } const sourcesFormatted = sources.join("\n---\n"); return sourcesFormatted; } async function queryOpenAIForResponse(openaiClient, query, sourcesFormatted, modelName) { const GROUNDED_PROMPT = ` You are a friendly assistant that recommends hotels based on activities and amenities. Answer the query using only the sources provided below in a friendly and concise bulleted manner. Answer ONLY with the facts listed in the list of sources below. If there isn't enough information below, say you don't know. Do not generate answers that don't use the sources below. Query: {query} Sources: {sources} `; return openaiClient.chat.completions.create({ model: modelName, messages: [ { role: "user", content: GROUNDED_PROMPT.replace("{query}", query).replace("{sources}", sourcesFormatted), } ], temperature: 0.7, max_tokens: 800, }); } async function main() { const { openaiClient, searchClient, modelName } = getClients(); const query = "Can you recommend a few hotels with complimentary breakfast?"; const sources = await queryAISearchForSources(searchClient, query); const response = await queryOpenAIForResponse(openaiClient, query, sources, modelName); // Print the response from the chat model const content = response.choices[0].message.content; if (content) { console.log(content); } else { console.log("No content available in the response."); } } main().catch((error) => { console.error("An error occurred:", error); process.exit(1); });
De voorgaande code doet het volgende:
- Hiermee importeert u de benodigde bibliotheken voor Azure AI Search en Azure OpenAI.
- Maakt gebruik van omgevingsvariabelen om de Azure AI Search- en Azure OpenAI-clients te configureren.
- Definieert een functie voor het ophalen van de clients voor Azure AI Search en Azure OpenAI, met behulp van omgevingsvariabelen voor configuratie.
- Hiermee definieert u een functie om een query uit te voeren op Azure AI Search naar bronnen op basis van de gebruikersquery.
- Definieert een functie om een query uit te voeren op Azure OpenAI voor een antwoord op basis van de gebruikersquery en de bronnen die zijn opgehaald uit Azure AI Search.
- De
main
functie organiseert de stroom door de zoek- en OpenAI-functies aan te roepen en vervolgens het antwoord af te drukken.
Voer de volgende opdracht uit in een terminal om het queryscript uit te voeren:
node -r dotenv/config query.js
De
.env
wordt doorgegeven aan de runtime met behulp van de-r dotenv/config
.Bekijk de uitvoer, die bestaat uit aanbevelingen voor verschillende hotels. Hier volgt een voorbeeld van hoe de uitvoer eruit kan zien:
Sure! Here are a few hotels that offer complimentary breakfast: - **Head Wind Resort** - Complimentary continental breakfast in the lobby - Free Wi-Fi throughout the hotel - **Double Sanctuary Resort** - Continental breakfast included - **White Mountain Lodge & Suites** - Continental breakfast available - **Swan Bird Lake Inn** - Continental-style breakfast each morning with a variety of food and drinks such as caramel cinnamon rolls, coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins
Probleemoplossingsproces
Als u een foutbericht Verboden krijgt, controleert u de Configuratie van Azure AI Search om ervoor te zorgen dat op rollen gebaseerde toegang is ingeschakeld.
Als er een foutbericht met autorisatie is mislukt , wacht u enkele minuten en probeert u het opnieuw. Het kan enkele minuten duren voordat roltoewijzingen operationeel worden.
Als er een foutbericht wordt weergegeven dat een resource niet is gevonden , controleert u de resource-URI's en controleert u of de API-versie van het chatmodel geldig is.
Als u verder wilt experimenteren, wijzigt u de query en voert u de laatste stap opnieuw uit om beter te begrijpen hoe het model werkt met de grondgegevens.
U kunt ook de prompt wijzigen om de toon of structuur van de uitvoer te wijzigen.
U kunt de query ook proberen zonder semantische classificatie door in te stellen use_semantic_reranker=False
in de stap queryparameters. Semantische classificatie kan de relevantie van queryresultaten en de mogelijkheid van de LLM om nuttige informatie te retourneren, aanzienlijk verbeteren. Met experimenten kunt u bepalen of dit een verschil maakt voor uw inhoud.
Een complexe RAG-query verzenden
Azure AI Search ondersteunt complexe typen voor geneste JSON-structuren. In de hotels-sample-index Address
is een voorbeeld van een complex type, bestaande uit Address.StreetAddress
, Address.City
, Address.StateProvince
, en Address.PostalCode
.Address.Country
De index heeft ook een complexe verzameling van Rooms
elk hotel.
Als uw index complexe typen heeft, wijzigt u de prompt om opmaakinstructies op te nemen:
Can you recommend a few hotels that offer complimentary breakfast?
Tell me their description, address, tags, and the rate for one room that sleeps 4 people.
Maak een nieuw bestand
queryComplex.js
.Kopieer de volgende code naar het bestand:
// This is a RAG (Retrieval Augmented Generation) implementation that: // 1. Takes a user query about hotels // 2. Searches a hotel database using Azure AI Search // 3. Formats the search results for the LLM // 4. Sends the query and formatted results to Azure OpenAI // 5. Returns a grounded response based only on the retrieved information import { SearchClient } from "@azure/search-documents"; import { AzureOpenAI } from "openai"; import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity"; function getClients() { const credential = new DefaultAzureCredential(); // Search const azureSearchEndpoint = process.env.AZURE_SEARCH_ENDPOINT; const azureSearchIndexName = process.env.AZURE_SEARCH_INDEX_NAME; const searchClient = new SearchClient( azureSearchEndpoint, azureSearchIndexName, credential ); // OpenAI const azureOpenAiEndpoint = process.env.AZURE_OPENAI_ENDPOINT; const azureOpenAiApiVersion = process.env.AZURE_OPENAI_VERSION; const azureOpenAiDeploymentName = process.env.AZURE_DEPLOYMENT_MODEL; const scope = "https://cognitiveservices.azure.com/.default"; const azureADTokenProvider = getBearerTokenProvider(credential, scope); const options = { azureADTokenProvider, deployment: azureOpenAiDeploymentName, apiVersion: azureOpenAiApiVersion, endpoint: azureOpenAiEndpoint } const openaiClient = new AzureOpenAI(options); return { openaiClient, searchClient, modelName: azureOpenAiDeploymentName }; } async function queryAISearchForSources( searchClient, query ) { console.log(`Searching for: "${query}"\n`); const selectedFields = ["HotelName", "Description", "Address", "Rooms", "Tags"]; const searchResults = await searchClient.search(query, { top: 5, select: selectedFields, queryType: "semantic", semanticSearchOptions: {}, }); return searchResults; } async function queryOpenAIForResponse( openaiClient, query, sourcesFormatted, modelName ){ const GROUNDED_PROMPT = ` You are a friendly assistant that recommends hotels based on activities and amenities. Answer the query using only the sources provided below in a friendly and concise bulleted manner. Answer ONLY with the facts listed in the list of sources below. If there isn't enough information below, say you don't know. Do not generate answers that don't use the sources below. Query: {query} Sources: {sources} `; return openaiClient.chat.completions.create({ model: modelName, messages: [ { role: "user", content: GROUNDED_PROMPT.replace("{query}", query).replace("{sources}", sourcesFormatted), } ], temperature: 0.7, max_tokens: 800, }); } async function main() { const { openaiClient, searchClient, modelName } = getClients(); const query = ` Can you recommend a few hotels that offer complimentary breakfast? Tell me their description, address, tags, and the rate for one room that sleeps 4 people. `; const sourcesResult = await queryAISearchForSources(searchClient, query); let sourcesFormatted = ""; for await (const result of sourcesResult.results) { // Explicitly typing result to ensure compatibility sourcesFormatted += JSON.stringify(result.document) + "\n"; } const response = await queryOpenAIForResponse(openaiClient, query, sourcesFormatted.trim(), modelName); // Print the response from the chat model const content = response.choices[0].message.content; if (content) { console.log(content); } else { console.log("No content available in the response."); } } main().catch((error) => { console.error("An error occurred:", error); process.exit(1); });
Voer de volgende opdracht uit in een terminal om het queryscript uit te voeren:
node -r dotenv/config queryComplex.js
De
.env
wordt doorgegeven aan de runtime met behulp van de-r dotenv/config
.Bekijk de uitvoer van Azure OpenAI; het voegt inhoud toe van complexe typen.
Here are a few hotels that offer complimentary breakfast and have rooms that sleep 4 people: 1. **Head Wind Resort** - **Description:** The best of old town hospitality combined with views of the river and cool breezes off the prairie. Enjoy a complimentary continental breakfast in the lobby, and free Wi-Fi throughout the hotel. - **Address:** 7633 E 63rd Pl, Tulsa, OK 74133, USA - **Tags:** Coffee in lobby, free Wi-Fi, view - **Room for 4:** Suite, 2 Queen Beds (Amenities) - $254.99 2. **Double Sanctuary Resort** - **Description:** 5-star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room. Offers continental breakfast. - **Address:** 2211 Elliott Ave, Seattle, WA 98121, USA - **Tags:** View, pool, restaurant, bar, continental breakfast - **Room for 4:** Suite, 2 Queen Beds (Amenities) - $254.99 3. **Swan Bird Lake Inn** - **Description:** Continental-style breakfast featuring a variety of food and drinks. Locally made caramel cinnamon rolls are a favorite. - **Address:** 1 Memorial Dr, Cambridge, MA 02142, USA - **Tags:** Continental breakfast, free Wi-Fi, 24-hour front desk service - **Room for 4:** Budget Room, 2 Queen Beds (City View) - $85.99 4. **Gastronomic Landscape Hotel** - **Description:** Known for its culinary excellence under the management of William Dough, offers continental breakfast. - **Address:** 3393 Peachtree Rd, Atlanta, GA 30326, USA - **Tags:** Restaurant, bar, continental breakfast - **Room for 4:** Budget Room, 2 Queen Beds (Amenities) - $66.99 ... - **Tags:** Pool, continental breakfast, free parking - **Room for 4:** Budget Room, 2 Queen Beds (Amenities) - $60.99 Enjoy your stay! Let me know if you need any more information.
Fouten oplossen
Als u fouten in Azure SDK wilt opsporen, stelt u de omgevingsvariabele AZURE_LOG_LEVEL
in op een van de volgende: verbose
, info
, warning
, . error
Hiermee schakelt u gedetailleerde logboekregistratie in voor de Azure SDK, die kan helpen bij het identificeren van problemen met verificatie, netwerkconnectiviteit of andere problemen.
Voer het queryscript opnieuw uit. U krijgt nu informatieve verklaringen van de SDK's in de uitvoer die gedetailleerdere informatie verstrekken over mogelijke problemen.
Als er uitvoerberichten worden weergegeven met betrekking tot managedIdentityCredential- en tokenverwervingsfouten, kan het zijn dat u meerdere tenants hebt en dat uw Azure-aanmelding gebruikmaakt van een tenant die niet over uw zoekservice beschikt. Als u uw tenant-id wilt ophalen, zoekt u in Azure Portal naar 'tenanteigenschappen' of voert u deze uit az login tenant list
.
Zodra u uw tenant-id hebt, voert u deze uit az login --tenant <YOUR-TENANT-ID>
bij een opdrachtprompt en voert u het script opnieuw uit.
Opschonen
Wanneer u in uw eigen abonnement werkt, is het een goed idee om aan het einde van een project te bepalen of u de gemaakte resources nog nodig hebt. Resources die actief blijven, kunnen u geld kosten. U kunt resources afzonderlijk verwijderen, maar u kunt ook de resourcegroep verwijderen als u de volledige resourceset wilt verwijderen.
U kunt resources vinden en beheren in Azure Portal met behulp van de koppeling Alle resources of resourcegroepen in het meest linkse deelvenster.
Vereisten
Een Azure-account met een actief abonnement. Gratis een account maken
-
- Kies een regio die ondersteuning biedt voor het voltooiingsmodel voor chats (gpt-4o, gpt-4o-mini of een gelijkwaardig model).
- Implementeer het voltooiingsmodel voor chats in Azure AI Foundry of gebruik een andere benadering.
-
- U wordt aangeraden de Basic-laag of hoger te gebruiken.
- Schakel semantische rangschikking in.
Visual Studio Code met de Python-extensie en het Jupyter-pakket. Zie Python in Visual Studio Code voor meer informatie.
Bestand downloaden
Download een Jupyter-notebook van GitHub om de aanvragen in deze quickstart te verzenden. Zie Bestanden downloaden van GitHub voor meer informatie.
U kunt ook een nieuw bestand op uw lokale systeem starten en handmatig aanvragen maken met behulp van de instructies in dit artikel.
Toegang configureren
Aanvragen voor het zoekeindpunt moeten worden geverifieerd en geautoriseerd. U kunt API-sleutels of -rollen voor deze taak gebruiken. Sleutels zijn gemakkelijker te beginnen, maar rollen zijn veiliger. In deze quickstart wordt ervan uitgegaan dat rollen zijn.
U stelt twee clients in, dus u hebt machtigingen nodig voor beide resources.
Azure AI Search ontvangt de queryaanvraag van uw lokale systeem. Wijs uzelf de roltoewijzing gegevenslezer van de zoekindex toe als de voorbeeldindex van hotels al bestaat. Als deze niet bestaat, wijst u uzelf de rollen Inzender voor zoekservice en Inzender voor zoekindexgegevens toe, zodat u de index kunt maken en er query's op kunt uitvoeren.
Azure OpenAI ontvangt de query en de zoekresultaten van uw lokale systeem. Wijs uzelf de Gebruikersrol Cognitive Services OpenAI toe in Azure OpenAI.
Meld u aan bij het Azure-portaal.
Configureer Azure AI Search voor op rollen gebaseerde toegang:
Zoek in Azure Portal uw Azure AI-Search-service.
Selecteer en selecteer vervolgens op > of Beide.
Rollen toewijzen:
Selecteer toegangsbeheer (IAM) in het linkermenu.
Selecteer in Azure AI Search deze rollen om een zoekindex te maken, laden en er query's op uit te voeren en wijs deze vervolgens toe aan uw Microsoft Entra ID-gebruikersidentiteit:
- Inzender voor zoekindexgegevens
- Inzender voor zoekservice
Selecteer in Azure OpenAI toegangsbeheer (IAM) om deze rol aan uzelf toe te wijzen in Azure OpenAI:
- Cognitive Services OpenAI-gebruiker
Het kan enkele minuten duren voordat machtigingen van kracht worden.
De hotels-sample-index bijwerken
Een zoekindex biedt grondgegevens voor het chatmodel. We raden de hotels-sample-index aan, die in enkele minuten kan worden gemaakt en uitgevoerd op elke zoekservicelaag. Deze index wordt gemaakt met behulp van ingebouwde voorbeeldgegevens.
Zoek uw zoekservice in Azure Portal.
Selecteer op de startpagina Overzicht de optie Gegevens importeren om de wizard te starten.
Selecteer op de pagina Verbinding maken met uw gegevens voorbeelden in de vervolgkeuzelijst.
Kies het hotelvoorbeeld.
Selecteer Volgende via de resterende pagina's en accepteer de standaardwaarden.
Nadat de index is gemaakt, selecteert u Zoekbeheerindexen> in het linkermenu om de index te openen.
Selecteer JSON bewerken.
Schuif naar het einde van de index, waar u tijdelijke aanduidingen kunt vinden voor constructies die aan een index kunnen worden toegevoegd.
"analyzers": [], "tokenizers": [], "tokenFilters": [], "charFilters": [], "normalizers": [],
Plak op een nieuwe regel na normalizers de volgende semantische configuratie. In dit voorbeeld wordt een
"defaultConfiguration"
, wat belangrijk is voor het uitvoeren van deze quickstart."semantic":{ "defaultConfiguration":"semantic-config", "configurations":[ { "name":"semantic-config", "prioritizedFields":{ "titleField":{ "fieldName":"HotelName" }, "prioritizedContentFields":[ { "fieldName":"Description" } ], "prioritizedKeywordsFields":[ { "fieldName":"Category" }, { "fieldName":"Tags" } ] } } ] },
Sla uw wijzigingen op.
Voer de volgende query uit in Search Explorer om uw index te testen:
complimentary breakfast
Uitvoer moet er ongeveer uitzien als in het volgende voorbeeld. Resultaten die rechtstreeks vanuit de zoekmachine worden geretourneerd, bestaan uit velden en hun exacte waarden, samen met metagegevens zoals een zoekscore en een semantische classificatiescore en bijschrift als u semantische rangschikking gebruikt. We hebben een select-instructie gebruikt om alleen de velden HotelName, Description en Tags te retourneren.
{ "@odata.count": 18, "@search.answers": [], "value": [ { "@search.score": 2.2896252, "@search.rerankerScore": 2.506816864013672, "@search.captions": [ { "text": "Head Wind Resort. Suite. coffee in lobby\r\nfree wifi\r\nview. The best of old town hospitality combined with views of the river and cool breezes off the prairie. Our penthouse suites offer views for miles and the rooftop plaza is open to all guests from sunset to 10 p.m. Enjoy a **complimentary continental breakfast** in the lobby, and free Wi-Fi throughout the hotel..", "highlights": "" } ], "HotelName": "Head Wind Resort", "Description": "The best of old town hospitality combined with views of the river and cool breezes off the prairie. Our penthouse suites offer views for miles and the rooftop plaza is open to all guests from sunset to 10 p.m. Enjoy a complimentary continental breakfast in the lobby, and free Wi-Fi throughout the hotel.", "Tags": [ "coffee in lobby", "free wifi", "view" ] }, { "@search.score": 2.2158256, "@search.rerankerScore": 2.288334846496582, "@search.captions": [ { "text": "Swan Bird Lake Inn. Budget. continental breakfast\r\nfree wifi\r\n24-hour front desk service. We serve a continental-style breakfast each morning, featuring a variety of food and drinks. Our locally made, oh-so-soft, caramel cinnamon rolls are a favorite with our guests. Other breakfast items include coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins..", "highlights": "" } ], "HotelName": "Swan Bird Lake Inn", "Description": "We serve a continental-style breakfast each morning, featuring a variety of food and drinks. Our locally made, oh-so-soft, caramel cinnamon rolls are a favorite with our guests. Other breakfast items include coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins.", "Tags": [ "continental breakfast", "free wifi", "24-hour front desk service" ] }, { "@search.score": 0.92481667, "@search.rerankerScore": 2.221315860748291, "@search.captions": [ { "text": "White Mountain Lodge & Suites. Resort and Spa. continental breakfast\r\npool\r\nrestaurant. Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings..", "highlights": "" } ], "HotelName": "White Mountain Lodge & Suites", "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.", "Tags": [ "continental breakfast", "pool", "restaurant" ] }, . . . ]}
Service-eindpunten ophalen
In de resterende secties stelt u API-aanroepen in op Azure OpenAI en Azure AI Search. Haal de service-eindpunten op, zodat u ze kunt opgeven als variabelen in uw code.
Meld u aan bij het Azure-portaal.
Kopieer de URL op de startpagina Overzicht . Een eindpunt ziet er bijvoorbeeld uit als
https://example.search.windows.net
.Selecteer op de startpagina Overzicht de koppeling om de eindpunten weer te geven. Kopieer de URL. Een eindpunt ziet er bijvoorbeeld uit als
https://example.openai.azure.com/
.
Een virtuele omgeving maken
In deze stap gaat u terug naar uw lokale systeem en Visual Studio Code. U wordt aangeraden een virtuele omgeving te maken, zodat u de afhankelijkheden geïsoleerd kunt installeren.
Open in Visual Studio Code de map met Quickstart-RAG.ipynb.
Druk op Ctrl-shift-P om het opdrachtenpalet te openen, zoek naar Python: Omgeving maken en selecteer
Venv
vervolgens om een virtuele omgeving te maken in de huidige werkruimte.Selecteer Quickstart-RAG\requirements.txt voor de afhankelijkheden.
Het duurt enkele minuten om de omgeving te maken. Wanneer de omgeving gereed is, gaat u verder met de volgende stap.
Aanmelden bij Azure
U gebruikt Microsoft Entra-id en roltoewijzingen voor de verbinding. Zorg ervoor dat u bent aangemeld bij dezelfde tenant en hetzelfde abonnement als Azure AI Search en Azure OpenAI. U kunt de Azure CLI op de opdrachtregel gebruiken om de huidige eigenschappen weer te geven, eigenschappen te wijzigen en u aan te melden. Zie Verbinding maken zonder sleutels voor meer informatie.
Voer elk van de volgende opdrachten op volgorde uit.
az account show
az account set --subscription <PUT YOUR SUBSCRIPTION ID HERE>
az login --tenant <PUT YOUR TENANT ID HERE>
U moet nu vanaf uw lokale apparaat zijn aangemeld bij Azure.
De query- en chatthread instellen
In deze sectie worden Visual Studio Code en Python gebruikt om de API's voor chatvoltooiing aan te roepen in Azure OpenAI.
Start Visual Studio Code en open het .ipynb-bestand of maak een nieuw Python-bestand.
Installeer de volgende Python-pakketten.
! pip install azure-search-documents==11.6.0b5 --quiet ! pip install azure-identity==1.16.1 --quiet ! pip install openai --quiet ! pip install aiohttp --quiet ! pip install ipykernel --quiet
Stel de volgende variabelen in, waarbij u tijdelijke aanduidingen vervangt door de eindpunten die u in de vorige stap hebt verzameld.
AZURE_SEARCH_SERVICE: str = "PUT YOUR SEARCH SERVICE ENDPOINT HERE" AZURE_OPENAI_ACCOUNT: str = "PUT YOUR AZURE OPENAI ENDPOINT HERE" AZURE_DEPLOYMENT_MODEL: str = "gpt-4o"
Stel clients, de prompt, query en het antwoord in.
Wijzig voor de Azure Government-cloud het API-eindpunt van de tokenprovider in
"https://cognitiveservices.azure.us/.default"
.# Set up the query for generating responses from azure.identity import DefaultAzureCredential from azure.identity import get_bearer_token_provider from azure.search.documents import SearchClient from openai import AzureOpenAI credential = DefaultAzureCredential() token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default") openai_client = AzureOpenAI( api_version="2024-06-01", azure_endpoint=AZURE_OPENAI_ACCOUNT, azure_ad_token_provider=token_provider ) search_client = SearchClient( endpoint=AZURE_SEARCH_SERVICE, index_name="hotels-sample-index", credential=credential ) # This prompt provides instructions to the model GROUNDED_PROMPT=""" You are a friendly assistant that recommends hotels based on activities and amenities. Answer the query using only the sources provided below in a friendly and concise bulleted manner. Answer ONLY with the facts listed in the list of sources below. If there isn't enough information below, say you don't know. Do not generate answers that don't use the sources below. Query: {query} Sources:\n{sources} """ # Query is the question being asked. It's sent to the search engine and the chat model query="Can you recommend a few hotels with complimentary breakfast?" # Search results are created by the search client # Search results are composed of the top 5 results and the fields selected from the search index # Search results include the top 5 matches to your query search_results = search_client.search( search_text=query, top=5, select="Description,HotelName,Tags" ) sources_formatted = "\n".join([f'{document["HotelName"]}:{document["Description"]}:{document["Tags"]}' for document in search_results]) # Send the search results and the query to the LLM to generate a response based on the prompt. response = openai_client.chat.completions.create( messages=[ { "role": "user", "content": GROUNDED_PROMPT.format(query=query, sources=sources_formatted) } ], model=AZURE_DEPLOYMENT_MODEL ) # Here is the response from the chat model. print(response.choices[0].message.content)
De uitvoer is afkomstig van Azure OpenAI en bestaat uit aanbevelingen voor verschillende hotels. Hier volgt een voorbeeld van hoe de uitvoer eruit kan zien:
Sure! Here are a few hotels that offer complimentary breakfast: - **Head Wind Resort** - Complimentary continental breakfast in the lobby - Free Wi-Fi throughout the hotel - **Double Sanctuary Resort** - Continental breakfast included - **White Mountain Lodge & Suites** - Continental breakfast available - **Swan Bird Lake Inn** - Continental-style breakfast each morning with a variety of food and drinks such as caramel cinnamon rolls, coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins
Als u een foutbericht Verboden krijgt, controleert u de Configuratie van Azure AI Search om ervoor te zorgen dat op rollen gebaseerde toegang is ingeschakeld.
Als er een foutbericht met autorisatie is mislukt , wacht u enkele minuten en probeert u het opnieuw. Het kan enkele minuten duren voordat roltoewijzingen operationeel worden.
Als er een foutbericht wordt weergegeven dat een resource niet is gevonden , controleert u de resource-URI's en controleert u of de API-versie van het chatmodel geldig is.
Als u verder wilt experimenteren, wijzigt u de query en voert u de laatste stap opnieuw uit om beter te begrijpen hoe het model werkt met de grondgegevens.
U kunt ook de prompt wijzigen om de toon of structuur van de uitvoer te wijzigen.
U kunt de query ook proberen zonder semantische classificatie door in te stellen
use_semantic_reranker=False
in de stap queryparameters. Semantische classificatie kan de relevantie van queryresultaten en de mogelijkheid van de LLM om nuttige informatie te retourneren, aanzienlijk verbeteren. Met experimenten kunt u bepalen of dit een verschil maakt voor uw inhoud.
Een complexe RAG-query verzenden
Azure AI Search ondersteunt complexe typen voor geneste JSON-structuren. In de hotels-sample-index Address
is een voorbeeld van een complex type, bestaande uit Address.StreetAddress
, Address.City
, Address.StateProvince
, en Address.PostalCode
.Address.Country
De index heeft ook een complexe verzameling van Rooms
elk hotel.
Als uw index complexe typen heeft, kan uw query deze velden leveren als u eerst de uitvoer van zoekresultaten converteert naar JSON en vervolgens de JSON doorgeeft aan het chatmodel. In het volgende voorbeeld worden complexe typen aan de aanvraag toegevoegd. De opmaakinstructies bevatten een JSON-specificatie.
import json
# Query is the question being asked. It's sent to the search engine and the LLM.
query="Can you recommend a few hotels that offer complimentary breakfast?
Tell me their description, address, tags, and the rate for one room that sleeps 4 people."
# Set up the search results and the chat thread.
# Retrieve the selected fields from the search index related to the question.
selected_fields = ["HotelName","Description","Address","Rooms","Tags"]
search_results = search_client.search(
search_text=query,
top=5,
select=selected_fields,
query_type="semantic"
)
sources_filtered = [{field: result[field] for field in selected_fields} for result in search_results]
sources_formatted = "\n".join([json.dumps(source) for source in sources_filtered])
response = openai_client.chat.completions.create(
messages=[
{
"role": "user",
"content": GROUNDED_PROMPT.format(query=query, sources=sources_formatted)
}
],
model=AZURE_DEPLOYMENT_MODEL
)
print(response.choices[0].message.content)
De uitvoer is afkomstig van Azure OpenAI en voegt inhoud van complexe typen toe.
Here are a few hotels that offer complimentary breakfast and have rooms that sleep 4 people:
1. **Head Wind Resort**
- **Description:** The best of old town hospitality combined with views of the river and
cool breezes off the prairie. Enjoy a complimentary continental breakfast in the lobby,
and free Wi-Fi throughout the hotel.
- **Address:** 7633 E 63rd Pl, Tulsa, OK 74133, USA
- **Tags:** Coffee in lobby, free Wi-Fi, view
- **Room for 4:** Suite, 2 Queen Beds (Amenities) - $254.99
2. **Double Sanctuary Resort**
- **Description:** 5-star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area
listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso
in room. Offers continental breakfast.
- **Address:** 2211 Elliott Ave, Seattle, WA 98121, USA
- **Tags:** View, pool, restaurant, bar, continental breakfast
- **Room for 4:** Suite, 2 Queen Beds (Amenities) - $254.99
3. **Swan Bird Lake Inn**
- **Description:** Continental-style breakfast featuring a variety of food and drinks.
Locally made caramel cinnamon rolls are a favorite.
- **Address:** 1 Memorial Dr, Cambridge, MA 02142, USA
- **Tags:** Continental breakfast, free Wi-Fi, 24-hour front desk service
- **Room for 4:** Budget Room, 2 Queen Beds (City View) - $85.99
4. **Gastronomic Landscape Hotel**
- **Description:** Known for its culinary excellence under the management of William Dough,
offers continental breakfast.
- **Address:** 3393 Peachtree Rd, Atlanta, GA 30326, USA
- **Tags:** Restaurant, bar, continental breakfast
- **Room for 4:** Budget Room, 2 Queen Beds (Amenities) - $66.99
...
- **Tags:** Pool, continental breakfast, free parking
- **Room for 4:** Budget Room, 2 Queen Beds (Amenities) - $60.99
Enjoy your stay! Let me know if you need any more information.
Fouten oplossen
Als u verificatiefouten wilt opsporen, voegt u de volgende code in vóór de stap die de zoekmachine en de LLM aanroept.
import sys
import logging # Set the logging level for all azure-storage-* libraries
logger = logging.getLogger('azure.identity')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter('[%(levelname)s %(name)s] %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
Voer het queryscript opnieuw uit. U krijgt nu INFO- en DEBUG-instructies in de uitvoer die meer informatie geven over het probleem.
Als er uitvoerberichten worden weergegeven met betrekking tot managedIdentityCredential- en tokenverwervingsfouten, kan het zijn dat u meerdere tenants hebt en dat uw Azure-aanmelding gebruikmaakt van een tenant die niet over uw zoekservice beschikt. Als u uw tenant-id wilt ophalen, zoekt u in Azure Portal naar 'tenanteigenschappen' of voert u deze uit az login tenant list
.
Zodra u uw tenant-id hebt, voert u deze uit az login --tenant <YOUR-TENANT-ID>
bij een opdrachtprompt en voert u het script opnieuw uit.
Opschonen
Wanneer u in uw eigen abonnement werkt, is het een goed idee om aan het einde van een project te bepalen of u de gemaakte resources nog nodig hebt. Resources die actief blijven, kunnen u geld kosten. U kunt resources afzonderlijk verwijderen, maar u kunt ook de resourcegroep verwijderen als u de volledige resourceset wilt verwijderen.
U kunt resources vinden en beheren in Azure Portal met behulp van de koppeling Alle resources of resourcegroepen in het meest linkse deelvenster.
Vereisten
Een Azure-account met een actief abonnement. Gratis een account maken
-
- Kies een regio die ondersteuning biedt voor het voltooiingsmodel voor chats (gpt-4o, gpt-4o-mini of een gelijkwaardig model).
- Implementeer het voltooiingsmodel voor chats in Azure AI Foundry of gebruik een andere benadering.
-
- U wordt aangeraden de Basic-laag of hoger te gebruiken.
- Schakel semantische rangschikking in.
Een nieuwe of bestaande index met beschrijvende of uitgebreide tekstvelden, gemarkeerd als op te halen in uw index. In deze quickstart wordt ervan uitgegaan dat de hotels-sample-index wordt gebruikt.
De Azure CLI voor sleutelloze verificatie met Microsoft Entra-id.
Visual Studio Code met de REST-clientextensie .
Bestand downloaden
Download een .rest-bestand van GitHub om de aanvragen in deze quickstart te verzenden. Zie Bestanden downloaden van GitHub voor meer informatie.
U kunt ook een nieuw bestand op uw lokale systeem starten en handmatig aanvragen maken met behulp van de instructies in dit artikel.
Toegang configureren
Aanvragen voor het zoekeindpunt moeten worden geverifieerd en geautoriseerd. U kunt API-sleutels of -rollen voor deze taak gebruiken. Sleutels zijn gemakkelijker te beginnen, maar rollen zijn veiliger. In deze quickstart wordt ervan uitgegaan dat rollen zijn.
U stelt twee clients in, dus u hebt machtigingen nodig voor beide resources.
Azure AI Search ontvangt de queryaanvraag van uw lokale systeem. Wijs uzelf de roltoewijzing gegevenslezer van de zoekindex toe als de voorbeeldindex van hotels al bestaat. Als deze niet bestaat, wijst u uzelf de rollen Inzender voor zoekservice en Inzender voor zoekindexgegevens toe, zodat u de index kunt maken en er query's op kunt uitvoeren.
Azure OpenAI ontvangt de query en de zoekresultaten van uw lokale systeem. Wijs uzelf de Gebruikersrol Cognitive Services OpenAI toe in Azure OpenAI.
Meld u aan bij het Azure-portaal.
Configureer Azure AI Search voor op rollen gebaseerde toegang:
Zoek in Azure Portal uw Azure AI-Search-service.
Selecteer en selecteer vervolgens op > of Beide.
Rollen toewijzen:
Selecteer toegangsbeheer (IAM) in het linkermenu.
Selecteer in Azure AI Search deze rollen om een zoekindex te maken, laden en er query's op uit te voeren en wijs deze vervolgens toe aan uw Microsoft Entra ID-gebruikersidentiteit:
- Inzender voor zoekindexgegevens
- Inzender voor zoekservice
Selecteer in Azure OpenAI toegangsbeheer (IAM) om deze rol aan uzelf toe te wijzen in Azure OpenAI:
- Cognitive Services OpenAI-gebruiker
Het kan enkele minuten duren voordat machtigingen van kracht worden.
Service-eindpunten en -tokens ophalen
In de resterende secties stelt u API-aanroepen in op Azure OpenAI en Azure AI Search. Haal de service-eindpunten en -tokens op, zodat u ze kunt opgeven als variabelen in uw code.
Meld u aan bij het Azure-portaal.
Kopieer de URL op de startpagina Overzicht . Een eindpunt ziet er bijvoorbeeld uit als
https://example.search.windows.net
.Selecteer op de startpagina Overzicht de koppeling om de eindpunten weer te geven. Kopieer de URL. Een eindpunt ziet er bijvoorbeeld uit als
https://example.openai.azure.com/
.Persoonlijke toegangstokens ophalen uit de Azure CLI via een opdrachtprompt. Dit zijn de opdrachten voor elke resource:
az account get-access-token --resource https://search.azure.com --query "accessToken" -o tsv
az account get-access-token --resource https://cognitiveservices.azure.com --query "accessToken" -o tsv
De client instellen
In deze quickstart gebruikt u een REST-client en de Azure AI Search REST API's om het RAG-patroon te implementeren.
We raden Visual Studio Code aan met een REST-clientextensie voor deze quickstart.
Aanbeveling
U kunt de broncode downloaden om te beginnen met een voltooid project of deze stappen volgen om uw eigen project te maken.
Start Visual Studio Code en open het quickstart-rag.rest-bestand of maak een nieuw bestand.
Stel bovenaan omgevingsvariabelen in voor uw zoekservice, autorisatie en indexnaam.
- Plak het zoekeindpunt in @searchUrl.
- Voor @aoaiUrl het Azure OpenAI-eindpunt plakken.
- Gebruik voor @searchAccessToken het toegangstoken dat beperkt is tot
https://search.azure.com
. - Voor @aoaiAccessToken plakt u het toegangstoken met het bereik
https://cognitiveservices.azure.com
.
Als u de verbinding wilt testen, verzendt u uw eerste aanvraag.
### List existing indexes by name (verify the connection) GET {{searchUrl}}/indexes?api-version=2025-05-01-preview&$select=name HTTP/1.1 Authorization: Bearer {{personalAccessToken}}
Selecteer Verzonden aanvraag.
Uitvoer voor deze GET-aanvraag moet een lijst met indexen zijn. Je zou de hotels-sample-index tussen hen moeten zien.
De query- en chatthread instellen
In deze sectie worden Visual Studio Code en REST gebruikt om de API's voor chatvoltooiing aan te roepen in Azure OpenAI.
Stel een queryaanvraag in op de zin 'Kunt u een paar hotels aanbevelen met gratis ontbijt?'. Deze query maakt gebruik van semantische classificatie om relevante overeenkomsten te retourneren, zelfs als de exacte tekst geen exacte overeenkomst is. De resultaten worden bewaard in de variabele searchRequest voor hergebruik bij de volgende aanvraag.
# @name searchRequest POST {{searchUrl}}/indexes/{{index-name}}/docs/search?api-version={{api-version}} HTTP/1.1 Content-Type: application/json Authorization: Bearer {{searchAccessToken}} { "search": "Can you recommend a few hotels with complimentary breakfast?", "queryType": "semantic", "semanticConfiguration": "semantic-config", "select": "Description,HotelName,Tags", "top": 5 } ### 3 - Use search results in Azure OpenAI call to a chat completion model POST {{aoaiUrl}}/openai/deployments/{{aoaiGptDeployment}}/chat/completions?api-version=2024-08-01-preview HTTP/1.1 Content-Type: application/json Authorization: Bearer {{aoaiAccessToken}} { "messages": [ { "role": "system", "content": "You recommend hotels based on activities and amenities. Answer the query using only the search result. Answer in a friendly and concise manner. Answer ONLY with the facts provided. If there isn't enough information below, say you don't know." }, { "role": "user", "content": "Based on the hotel search results, can you recommend hotels with breakfast? Here are all the hotels I found:\n\nHotel 1: {{searchRequest.response.body.value[0].HotelName}}\nDescription: {{searchRequest.response.body.value[0].Description}}\n\nHotel 2: {{searchRequest.response.body.value[1].HotelName}}\nDescription: {{searchRequest.response.body.value[1].Description}}\n\nHotel 3: {{searchRequest.response.body.value[2].HotelName}}\nDescription: {{searchRequest.response.body.value[2].Description}}\n\nHotel 4: {{searchRequest.response.body.value[3].HotelName}}\nDescription: {{searchRequest.response.body.value[3].Description}}\n\nHotel 5: {{searchRequest.response.body.value[4].HotelName}}\nDescription: {{searchRequest.response.body.value[4].Description}}\n\nPlease recommend which hotels offer breakfast based on their descriptions." } ], "max_tokens": 1000, "temperature": 0.7 }`
Verzend de aanvraag.
Uitvoer moet er ongeveer uitzien als in het volgende voorbeeld:
"value": [ { "@search.score": 3.9269178, "@search.rerankerScore": 2.380699872970581, "HotelName": "Head Wind Resort", "Description": "The best of old town hospitality combined with views of the river and cool breezes off the prairie. Our penthouse suites offer views for miles and the rooftop plaza is open to all guests from sunset to 10 p.m. Enjoy a complimentary continental breakfast in the lobby, and free Wi-Fi throughout the hotel.", "Tags": [ "coffee in lobby", "free wifi", "view" ] }, { "@search.score": 1.5450059, "@search.rerankerScore": 2.1258809566497803, "HotelName": "Thunderbird Motel", "Description": "Book Now & Save. Clean, Comfortable rooms at the lowest price. Enjoy complimentary coffee and tea in common areas.", "Tags": [ "coffee in lobby", "free parking", "free wifi" ] }, { "@search.score": 2.2158256, "@search.rerankerScore": 2.121671438217163, "HotelName": "Swan Bird Lake Inn", "Description": "We serve a continental-style breakfast each morning, featuring a variety of food and drinks. Our locally made, oh-so-soft, caramel cinnamon rolls are a favorite with our guests. Other breakfast items include coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins.", "Tags": [ "continental breakfast", "free wifi", "24-hour front desk service" ] }, { "@search.score": 0.6395861, "@search.rerankerScore": 2.116753339767456, "HotelName": "Waterfront Scottish Inn", "Description": "Newly Redesigned Rooms & airport shuttle. Minutes from the airport, enjoy lakeside amenities, a resort-style pool & stylish new guestrooms with Internet TVs.", "Tags": [ "24-hour front desk service", "continental breakfast", "free wifi" ] }, { "@search.score": 4.885111, "@search.rerankerScore": 2.0008862018585205, "HotelName": "Double Sanctuary Resort", "Description": "5 star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso in room.", "Tags": [ "view", "pool", "restaurant", "bar", "continental breakfast" ] } ]
Stel een gesprekswisseling in met een voltooiingsmodel voor chats. Deze aanvraag bevat een prompt met instructies voor het antwoord. De
max_tokens
waarde is groot genoeg voor de zoekresultaten van de vorige query.POST {{aoaiUrl}}/openai/deployments/{{aoaiGptDeployment}}/chat/completions?api-version=2024-08-01-preview HTTP/1.1 Content-Type: application/json Authorization: Bearer {{aoaiAccessToken}} { "messages": [ { "role": "system", "content": "You are a friendly assistant that recommends hotels based on activities and amenities. Answer the query using only the search result. Answer in a friendly and concise manner. Answer ONLY with the facts provided. If there isn't enough information below, say you don't know." }, { "role": "user", "content": "Based on the hotel search results, can you recommend hotels with breakfast? Here are all the hotels I found:\n\nHotel 1: {{searchRequest.response.body.value[0].HotelName}}\nDescription: {{searchRequest.response.body.value[0].Description}}\n\nHotel 2: {{searchRequest.response.body.value[1].HotelName}}\nDescription: {{searchRequest.response.body.value[1].Description}}\n\nHotel 3: {{searchRequest.response.body.value[2].HotelName}}\nDescription: {{searchRequest.response.body.value[2].Description}}\n\nHotel 4: {{searchRequest.response.body.value[3].HotelName}}\nDescription: {{searchRequest.response.body.value[3].Description}}\n\nHotel 5: {{searchRequest.response.body.value[4].HotelName}}\nDescription: {{searchRequest.response.body.value[4].Description}}\n\nPlease recommend which hotels offer breakfast based on their descriptions." } ], "max_tokens": 1000, "temperature": 0.7 }
Verzend de aanvraag.
Uitvoer moet een HTTP 200 Success statusbericht zijn. Opgenomen in de uitvoer is inhoud die antwoord geeft op de vraag:
"message": { "annotations": [], "content": "I recommend the following hotels that offer breakfast:\n\n1. **Head Wind Resort** - Offers a complimentary continental breakfast in the lobby.\n2. **Swan Bird Lake Inn** - Serves a continental-style breakfast each morning, including a variety of food and drinks. \n\nEnjoy your stay!", "refusal": null, "role": "assistant" }
U ziet dat de uitvoer verschillende hotels mist die ontbijt vermelden in het veld Tags. Het veld Tags is een matrix en met dit veld wordt de JSON-structuur in de resultaten verbroken. Omdat er geen mogelijkheden voor tekenreeksconversie in de REST-client zijn, is extra code voor het handmatig converteren van de JSON naar een tekenreeks vereist als matrices moeten worden opgenomen. Voor deze snelle opstartgids slaan we deze stap over.
Opschonen
Wanneer u in uw eigen abonnement werkt, is het een goed idee om aan het einde van een project te bepalen of u de gemaakte resources nog nodig hebt. Resources die actief blijven, kunnen u geld kosten. U kunt resources afzonderlijk verwijderen, maar u kunt ook de resourcegroep verwijderen als u de volledige resourceset wilt verwijderen.
U kunt resources vinden en beheren in Azure Portal met behulp van de koppeling Alle resources of resourcegroepen in het meest linkse deelvenster.
Vereisten
Een Azure-account met een actief abonnement. Gratis een account maken
Een Azure AI Search-service, elke laag en regio.
-
- Kies een regio die ondersteuning biedt voor het voltooiingsmodel voor chats (gpt-4o, gpt-4o-mini of een gelijkwaardig model).
- Implementeer het voltooiingsmodel voor chats in Azure AI Foundry of gebruik een andere benadering.
-
- U wordt aangeraden de Basic-laag of hoger te gebruiken.
- Schakel semantische rangschikking in.
TypeScript. U kunt TypeScript globaal installeren met behulp van npm:
npm install -g typescript
Toegang configureren
Aanvragen voor het zoekeindpunt moeten worden geverifieerd en geautoriseerd. U kunt API-sleutels of -rollen voor deze taak gebruiken. Sleutels zijn gemakkelijker te beginnen, maar rollen zijn veiliger. In deze quickstart wordt ervan uitgegaan dat rollen zijn.
U stelt twee clients in, dus u hebt machtigingen nodig voor beide resources.
Azure AI Search ontvangt de queryaanvraag van uw lokale systeem. Wijs uzelf de roltoewijzing gegevenslezer van de zoekindex toe als de voorbeeldindex van hotels al bestaat. Als deze niet bestaat, wijst u uzelf de rollen Inzender voor zoekservice en Inzender voor zoekindexgegevens toe, zodat u de index kunt maken en er query's op kunt uitvoeren.
Azure OpenAI ontvangt de query en de zoekresultaten van uw lokale systeem. Wijs uzelf de Gebruikersrol Cognitive Services OpenAI toe in Azure OpenAI.
Meld u aan bij het Azure-portaal.
Configureer Azure AI Search voor op rollen gebaseerde toegang:
Zoek in Azure Portal uw Azure AI-Search-service.
Selecteer en selecteer vervolgens op > of Beide.
Rollen toewijzen:
Selecteer toegangsbeheer (IAM) in het linkermenu.
Selecteer in Azure AI Search deze rollen om een zoekindex te maken, laden en er query's op uit te voeren en wijs deze vervolgens toe aan uw Microsoft Entra ID-gebruikersidentiteit:
- Inzender voor zoekindexgegevens
- Inzender voor zoekservice
Selecteer in Azure OpenAI toegangsbeheer (IAM) om deze rol aan uzelf toe te wijzen in Azure OpenAI:
- Cognitive Services OpenAI-gebruiker
Het kan enkele minuten duren voordat machtigingen van kracht worden.
Een index maken
Een zoekindex biedt grondgegevens voor het chatmodel. We raden de hotels-sample-index aan, die in enkele minuten kan worden gemaakt en uitgevoerd op elke zoekservicelaag. Deze index wordt gemaakt met behulp van ingebouwde voorbeeldgegevens.
Zoek uw zoekservice in Azure Portal.
Selecteer op de startpagina Overzicht de optie Gegevens importeren om de wizard te starten.
Selecteer op de pagina Verbinding maken met uw gegevens voorbeelden in de vervolgkeuzelijst.
Kies het hotelvoorbeeld.
Selecteer Volgende via de resterende pagina's en accepteer de standaardwaarden.
Nadat de index is gemaakt, selecteert u Zoekbeheerindexen> in het linkermenu om de index te openen.
Selecteer JSON bewerken.
Schuif naar het einde van de index, waar u tijdelijke aanduidingen kunt vinden voor constructies die aan een index kunnen worden toegevoegd.
"analyzers": [], "tokenizers": [], "tokenFilters": [], "charFilters": [], "normalizers": [],
Plak op een nieuwe regel na normalizers de volgende semantische configuratie. In dit voorbeeld wordt een
"defaultConfiguration"
, wat belangrijk is voor het uitvoeren van deze quickstart."semantic":{ "defaultConfiguration":"semantic-config", "configurations":[ { "name":"semantic-config", "prioritizedFields":{ "titleField":{ "fieldName":"HotelName" }, "prioritizedContentFields":[ { "fieldName":"Description" } ], "prioritizedKeywordsFields":[ { "fieldName":"Category" }, { "fieldName":"Tags" } ] } } ] },
Sla uw wijzigingen op.
Voer de volgende query uit in Search Explorer om uw index te testen:
complimentary breakfast
Uitvoer moet er ongeveer uitzien als in het volgende voorbeeld. Resultaten die rechtstreeks vanuit de zoekmachine worden geretourneerd, bestaan uit velden en hun exacte waarden, samen met metagegevens zoals een zoekscore en een semantische classificatiescore en bijschrift als u semantische rangschikking gebruikt. We hebben een select-instructie gebruikt om alleen de velden HotelName, Description en Tags te retourneren.
{ "@odata.count": 18, "@search.answers": [], "value": [ { "@search.score": 2.2896252, "@search.rerankerScore": 2.506816864013672, "@search.captions": [ { "text": "Head Wind Resort. Suite. coffee in lobby\r\nfree wifi\r\nview. The best of old town hospitality combined with views of the river and cool breezes off the prairie. Our penthouse suites offer views for miles and the rooftop plaza is open to all guests from sunset to 10 p.m. Enjoy a **complimentary continental breakfast** in the lobby, and free Wi-Fi throughout the hotel..", "highlights": "" } ], "HotelName": "Head Wind Resort", "Description": "The best of old town hospitality combined with views of the river and cool breezes off the prairie. Our penthouse suites offer views for miles and the rooftop plaza is open to all guests from sunset to 10 p.m. Enjoy a complimentary continental breakfast in the lobby, and free Wi-Fi throughout the hotel.", "Tags": [ "coffee in lobby", "free wifi", "view" ] }, { "@search.score": 2.2158256, "@search.rerankerScore": 2.288334846496582, "@search.captions": [ { "text": "Swan Bird Lake Inn. Budget. continental breakfast\r\nfree wifi\r\n24-hour front desk service. We serve a continental-style breakfast each morning, featuring a variety of food and drinks. Our locally made, oh-so-soft, caramel cinnamon rolls are a favorite with our guests. Other breakfast items include coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins..", "highlights": "" } ], "HotelName": "Swan Bird Lake Inn", "Description": "We serve a continental-style breakfast each morning, featuring a variety of food and drinks. Our locally made, oh-so-soft, caramel cinnamon rolls are a favorite with our guests. Other breakfast items include coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins.", "Tags": [ "continental breakfast", "free wifi", "24-hour front desk service" ] }, { "@search.score": 0.92481667, "@search.rerankerScore": 2.221315860748291, "@search.captions": [ { "text": "White Mountain Lodge & Suites. Resort and Spa. continental breakfast\r\npool\r\nrestaurant. Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings..", "highlights": "" } ], "HotelName": "White Mountain Lodge & Suites", "Description": "Live amongst the trees in the heart of the forest. Hike along our extensive trail system. Visit the Natural Hot Springs, or enjoy our signature hot stone massage in the Cathedral of Firs. Relax in the meditation gardens, or join new friends around the communal firepit. Weekend evening entertainment on the patio features special guest musicians or poetry readings.", "Tags": [ "continental breakfast", "pool", "restaurant" ] }, . . . ]}
Service-eindpunten ophalen
In de resterende secties stelt u API-aanroepen in op Azure OpenAI en Azure AI Search. Haal de service-eindpunten op, zodat u ze kunt opgeven als variabelen in uw code.
Meld u aan bij het Azure-portaal.
Kopieer de URL op de startpagina Overzicht . Een eindpunt ziet er bijvoorbeeld uit als
https://example.search.windows.net
.Selecteer op de startpagina Overzicht de koppeling om de eindpunten weer te geven. Kopieer de URL. Een eindpunt ziet er bijvoorbeeld uit als
https://example.openai.azure.com/
.
Omgevingsvariabelen instellen voor lokale ontwikkeling
Maak een
.env
-bestand.Voeg de volgende omgevingsvariabelen toe aan het
.env
bestand en vervang de waarden door uw eigen service-eindpunten en -sleutels.AZURE_SEARCH_ENDPOINT=<YOUR AZURE AI SEARCH ENDPOINT> AZURE_SEARCH_INDEX_NAME=hotels-sample-index AZURE_OPENAI_ENDPOINT=<YOUR AZURE OPENAI ENDPOINT> AZURE_OPENAI_VERSION=<YOUR AZURE OPENAI API VERSION> AZURE_DEPLOYMENT_MODEL=<YOUR DEPLOYMENT NAME>
Het Node.JS-project instellen
Stel een project in met Visual Studio Code en TypeScript.
Start Visual Studio Code in een nieuwe map.
mkdir rag-quickstart && cd rag-quickstart code .
Maak een nieuw pakket voor ESM-modules in uw projectmap.
npm init -y npm pkg set type=module
Hiermee maakt u een
package.json
bestand met standaardwaarden.Installeer de volgende npm-pakketten.
npm install @azure/identity @azure/search-documents openai dotenv @types/node
Maak een
src
map in uw projectmap.mkdir src
Maak een
tsconfig.json
bestand in de projectmap voor ESM met de volgende inhoud.{ "compilerOptions": { "target": "esnext", "module": "NodeNext", "moduleResolution": "nodenext", "rootDir": "./src", "outDir": "./dist/", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "declaration": true, "sourceMap": true, "resolveJsonModule": true, "moduleDetection": "force", // Add this for ESM "allowSyntheticDefaultImports": true // Helpful for ESM interop }, "include": [ "src/**/*.ts" ] }
Aanmelden bij Azure
U gebruikt Microsoft Entra-id en roltoewijzingen voor de verbinding. Zorg ervoor dat u bent aangemeld bij dezelfde tenant en hetzelfde abonnement als Azure AI Search en Azure OpenAI. U kunt de Azure CLI op de opdrachtregel gebruiken om de huidige eigenschappen weer te geven, eigenschappen te wijzigen en u aan te melden. Zie Verbinding maken zonder sleutels voor meer informatie.
Voer elk van de volgende opdrachten op volgorde uit.
az account show
az account set --subscription <PUT YOUR SUBSCRIPTION ID HERE>
az login --tenant <PUT YOUR TENANT ID HERE>
U moet nu vanaf uw lokale apparaat zijn aangemeld bij Azure.
Query- en chatthread instellen
Maak een queryscript dat gebruikmaakt van de Azure AI Search-index en het chatmodel om antwoorden te genereren op basis van grondgegevens. De volgende stappen helpen u bij het instellen van het queryscript.
Maak een
query.ts
bestand in desrc
map met de volgende code.// This is a RAG (Retrieval Augmented Generation) implementation that: // 1. Takes a user query about hotels // 2. Searches a hotel database using Azure AI Search // 3. Formats the search results for the LLM // 4. Sends the query and formatted results to Azure OpenAI // 5. Returns a grounded response based only on the retrieved information import { SearchClient, AzureKeyCredential, SearchDocumentsResult } from "@azure/search-documents"; import { AzureOpenAI } from "openai"; import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity"; function getClients(): { openaiClient: AzureOpenAI, searchClient: SearchClient<{ HotelName: string; Description: string; Tags: string[] | string }>, modelName: string } { const credential = new DefaultAzureCredential(); // Search const azureSearchEndpoint = process.env.AZURE_SEARCH_ENDPOINT!; const azureSearchIndexName = process.env.AZURE_SEARCH_INDEX_NAME!; const searchClient = new SearchClient<{ HotelName: string; Description: string; Tags: string[] | string }>( azureSearchEndpoint, azureSearchIndexName, credential ); // OpenAI const azureOpenAiEndpoint = process.env.AZURE_OPENAI_ENDPOINT!; const azureOpenAiApiVersion = process.env.AZURE_OPENAI_VERSION!; const azureOpenAiDeploymentName = process.env.AZURE_DEPLOYMENT_MODEL!; const scope = "https://cognitiveservices.azure.com/.default"; const azureADTokenProvider = getBearerTokenProvider(credential, scope); const options = { azureADTokenProvider, deployment: azureOpenAiDeploymentName, apiVersion: azureOpenAiApiVersion, endpoint: azureOpenAiEndpoint } const openaiClient = new AzureOpenAI(options); return { openaiClient, searchClient, modelName: azureOpenAiDeploymentName }; } async function queryAISearchForSources(searchClient: SearchClient<{ HotelName: string; Description: string; Tags: string[] | string }>, query: string): Promise<string> { console.log(`Searching for: "${query}"\n`); const searchResults: SearchDocumentsResult<{ HotelName: string; Description: string; Tags: string[] | string }> = await searchClient.search(query, { top: 5, select: ["Description", "HotelName", "Tags"] }); const sources: string[] = []; for await (const result of searchResults.results) { const doc = result.document; sources.push( `Hotel: ${doc.HotelName}\n` + `Description: ${doc.Description}\n` + `Tags: ${Array.isArray(doc.Tags) ? doc.Tags.join(', ') : doc.Tags}\n` ); } const sourcesFormatted = sources.join("\n---\n"); return sourcesFormatted; } async function queryOpenAIForResponse( openaiClient: AzureOpenAI, query: string, sourcesFormatted: string, modelName: string ): Promise<{ choices: { message: { content: string | null } }[] }> { const GROUNDED_PROMPT = ` You are a friendly assistant that recommends hotels based on activities and amenities. Answer the query using only the sources provided below in a friendly and concise bulleted manner. Answer ONLY with the facts listed in the list of sources below. If there isn't enough information below, say you don't know. Do not generate answers that don't use the sources below. Query: {query} Sources: {sources} `; return openaiClient.chat.completions.create({ model: modelName, messages: [ { role: "user", content: GROUNDED_PROMPT.replace("{query}", query).replace("{sources}", sourcesFormatted), } ], temperature: 0.7, max_tokens: 800, }); } async function main():Promise<void> { const { openaiClient, searchClient, modelName } = getClients(); const query = "Can you recommend a few hotels with complimentary breakfast?"; const sources = await queryAISearchForSources(searchClient, query); const response = await queryOpenAIForResponse(openaiClient, query, sources, modelName); // Print the response from the chat model const content = response.choices[0].message.content; if (content) { console.log(content); } else { console.log("No content available in the response."); } } main().catch((error) => { console.error("An error occurred:", error); process.exit(1); });
De voorgaande code doet het volgende:
- Hiermee importeert u de benodigde bibliotheken voor Azure AI Search en Azure OpenAI.
- Maakt gebruik van omgevingsvariabelen om de Azure AI Search- en Azure OpenAI-clients te configureren.
- Definieert een functie voor het ophalen van de clients voor Azure AI Search en Azure OpenAI, met behulp van omgevingsvariabelen voor configuratie.
- Hiermee definieert u een functie om een query uit te voeren op Azure AI Search naar bronnen op basis van de gebruikersquery.
- Definieert een functie om een query uit te voeren op Azure OpenAI voor een antwoord op basis van de gebruikersquery en de bronnen die zijn opgehaald uit Azure AI Search.
- De
main
functie organiseert de stroom door de zoek- en OpenAI-functies aan te roepen en vervolgens het antwoord af te drukken.
Vertaal de TypeScript-code naar JavaScript.
tsc
Met deze opdracht wordt de TypeScript-code in de
src
map gecompileerd en worden de JavaScript-bestanden in dedist
map uitgevoerd.Voer de volgende opdracht uit in een terminal om het queryscript uit te voeren:
node -r dotenv/config dist/query.js
De
.env
wordt doorgegeven aan de runtime met behulp van de-r dotenv/config
.Bekijk de uitvoer die bestaat uit aanbevelingen voor verschillende hotels. Hier volgt een voorbeeld van hoe de uitvoer eruit kan zien:
Sure! Here are a few hotels that offer complimentary breakfast: - **Head Wind Resort** - Complimentary continental breakfast in the lobby - Free Wi-Fi throughout the hotel - **Double Sanctuary Resort** - Continental breakfast included - **White Mountain Lodge & Suites** - Continental breakfast available - **Swan Bird Lake Inn** - Continental-style breakfast each morning with a variety of food and drinks such as caramel cinnamon rolls, coffee, orange juice, milk, cereal, instant oatmeal, bagels, and muffins
Probleemoplossingsproces
Als u een foutbericht Verboden krijgt, controleert u de Configuratie van Azure AI Search om ervoor te zorgen dat op rollen gebaseerde toegang is ingeschakeld.
Als er een foutbericht met autorisatie is mislukt , wacht u enkele minuten en probeert u het opnieuw. Het kan enkele minuten duren voordat roltoewijzingen operationeel worden.
Als er een foutbericht wordt weergegeven dat een resource niet is gevonden , controleert u de resource-URI's en controleert u of de API-versie van het chatmodel geldig is.
Als u verder wilt experimenteren, wijzigt u de query en voert u de laatste stap opnieuw uit om beter te begrijpen hoe het model werkt met de grondgegevens.
U kunt ook de prompt wijzigen om de toon of structuur van de uitvoer te wijzigen.
U kunt de query ook proberen zonder semantische classificatie door in te stellen use_semantic_reranker=False
in de stap queryparameters. Semantische classificatie kan de relevantie van queryresultaten en de mogelijkheid van de LLM om nuttige informatie te retourneren, aanzienlijk verbeteren. Met experimenten kunt u bepalen of dit een verschil maakt voor uw inhoud.
Een complexe RAG-query verzenden
Azure AI Search ondersteunt complexe typen voor geneste JSON-structuren. In de hotels-sample-index Address
is een voorbeeld van een complex type, bestaande uit Address.StreetAddress
, Address.City
, Address.StateProvince
, en Address.PostalCode
.Address.Country
De index heeft ook een complexe verzameling van Rooms
elk hotel.
Als uw index complexe typen heeft, wijzigt u de prompt om opmaakinstructies op te nemen:
Can you recommend a few hotels that offer complimentary breakfast?
Tell me their description, address, tags, and the rate for one room that sleeps 4 people.
Maak een nieuw bestand
queryComplex.ts
in desrc
map.Kopieer de volgende code naar het bestand:
// This is a RAG (Retrieval Augmented Generation) implementation that: // 1. Takes a user query about hotels // 2. Searches a hotel database using Azure AI Search // 3. Formats the search results for the LLM // 4. Sends the query and formatted results to Azure OpenAI // 5. Returns a grounded response based only on the retrieved information import { SearchClient, SearchDocumentsResult } from "@azure/search-documents"; import { AzureOpenAI } from "openai"; import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity"; function getClients(): { openaiClient: AzureOpenAI; searchClient: SearchClient<{ HotelName: string; Description: string; Tags: string[] | string; Address: string; Rooms: string }>; modelName: string } { const credential = new DefaultAzureCredential(); // Search const azureSearchEndpoint = process.env.AZURE_SEARCH_ENDPOINT!; const azureSearchIndexName = process.env.AZURE_SEARCH_INDEX_NAME!; const searchClient = new SearchClient<{ HotelName: string; Description: string; Tags: string[] | string; Address: string; Rooms: string }>( azureSearchEndpoint, azureSearchIndexName, credential ); // OpenAI const azureOpenAiEndpoint = process.env.AZURE_OPENAI_ENDPOINT!; const azureOpenAiApiVersion = process.env.AZURE_OPENAI_VERSION!; const azureOpenAiDeploymentName = process.env.AZURE_DEPLOYMENT_MODEL!; const scope = "https://cognitiveservices.azure.com/.default"; const azureADTokenProvider = getBearerTokenProvider(credential, scope); const options = { azureADTokenProvider, deployment: azureOpenAiDeploymentName, apiVersion: azureOpenAiApiVersion, endpoint: azureOpenAiEndpoint } const openaiClient = new AzureOpenAI(options); return { openaiClient, searchClient, modelName: azureOpenAiDeploymentName }; } async function queryAISearchForSources( searchClient: SearchClient<{ HotelName: string; Description: string; Tags: string[] | string; Address: string; Rooms: string }>, query: string ): Promise<SearchDocumentsResult<{ HotelName: string; Description: string; Tags: string[] | string; Address: string; Rooms: string }>> { console.log(`Searching for: "${query}"\n`); const selectedFields: readonly ["HotelName", "Description", "Address", "Rooms", "Tags"] = ["HotelName", "Description", "Address", "Rooms", "Tags"]; const searchResults = await searchClient.search(query, { top: 5, select: selectedFields, queryType: "semantic", semanticSearchOptions: {}, }); return searchResults; } async function queryOpenAIForResponse( openaiClient: AzureOpenAI, query: string, sourcesFormatted: string, modelName: string ): Promise<{ choices: { message: { content: string | null } }[] }> { const GROUNDED_PROMPT = ` You are a friendly assistant that recommends hotels based on activities and amenities. Answer the query using only the sources provided below in a friendly and concise bulleted manner. Answer ONLY with the facts listed in the list of sources below. If there isn't enough information below, say you don't know. Do not generate answers that don't use the sources below. Query: {query} Sources: {sources} `; return openaiClient.chat.completions.create({ model: modelName, messages: [ { role: "user", content: GROUNDED_PROMPT.replace("{query}", query).replace("{sources}", sourcesFormatted), } ], temperature: 0.7, max_tokens: 800, }); } async function main(): Promise<void> { const { openaiClient, searchClient, modelName } = getClients(); const query = ` Can you recommend a few hotels that offer complimentary breakfast? Tell me their description, address, tags, and the rate for one room that sleeps 4 people. `; const sourcesResult = await queryAISearchForSources(searchClient, query); let sourcesFormatted = ""; for await (const result of sourcesResult.results) { // Explicitly typing result to ensure compatibility sourcesFormatted += JSON.stringify(result.document) + "\n"; } const response = await queryOpenAIForResponse(openaiClient, query, sourcesFormatted.trim(), modelName); // Print the response from the chat model const content = response.choices[0].message.content; if (content) { console.log(content); } else { console.log("No content available in the response."); } } main().catch((error) => { console.error("An error occurred:", error); process.exit(1); });
Vertaal de TypeScript-code naar JavaScript.
tsc
Met deze opdracht wordt de TypeScript-code in de
src
map gecompileerd en worden de JavaScript-bestanden in dedist
map uitgevoerd.Voer de volgende opdracht uit in een terminal om het queryscript uit te voeren:
node -r dotenv/config dist/queryComplex.js
De
.env
wordt doorgegeven aan de runtime met behulp van de-r dotenv/config
.Bekijk de uitvoer van Azure OpenAI; het voegt inhoud toe van complexe typen.
Here are a few hotels that offer complimentary breakfast and have rooms that sleep 4 people:
1. **Head Wind Resort**
- **Description:** The best of old town hospitality combined with views of the river and
cool breezes off the prairie. Enjoy a complimentary continental breakfast in the lobby,
and free Wi-Fi throughout the hotel.
- **Address:** 7633 E 63rd Pl, Tulsa, OK 74133, USA
- **Tags:** Coffee in lobby, free Wi-Fi, view
- **Room for 4:** Suite, 2 Queen Beds (Amenities) - $254.99
2. **Double Sanctuary Resort**
- **Description:** 5-star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area
listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso
in room. Offers continental breakfast.
- **Address:** 2211 Elliott Ave, Seattle, WA 98121, USA
- **Tags:** View, pool, restaurant, bar, continental breakfast
- **Room for 4:** Suite, 2 Queen Beds (Amenities) - $254.99
3. **Swan Bird Lake Inn**
- **Description:** Continental-style breakfast featuring a variety of food and drinks.
Locally made caramel cinnamon rolls are a favorite.
- **Address:** 1 Memorial Dr, Cambridge, MA 02142, USA
- **Tags:** Continental breakfast, free Wi-Fi, 24-hour front desk service
- **Room for 4:** Budget Room, 2 Queen Beds (City View) - $85.99
4. **Gastronomic Landscape Hotel**
- **Description:** Known for its culinary excellence under the management of William Dough,
offers continental breakfast.
- **Address:** 3393 Peachtree Rd, Atlanta, GA 30326, USA
- **Tags:** Restaurant, bar, continental breakfast
- **Room for 4:** Budget Room, 2 Queen Beds (Amenities) - $66.99
...
- **Tags:** Pool, continental breakfast, free parking
- **Room for 4:** Budget Room, 2 Queen Beds (Amenities) - $60.99
Enjoy your stay! Let me know if you need any more information.
Fouten oplossen
Als u fouten in Azure SDK wilt opsporen, stelt u de omgevingsvariabele AZURE_LOG_LEVEL
in op een van de volgende: verbose
, info
, warning
, . error
Hiermee schakelt u gedetailleerde logboekregistratie in voor de Azure SDK, die kan helpen bij het identificeren van problemen met verificatie, netwerkconnectiviteit of andere problemen.
Voer het queryscript opnieuw uit. U krijgt nu informatieve verklaringen van de SDK's in de uitvoer die gedetailleerdere informatie verstrekken over mogelijke problemen.
Als er uitvoerberichten worden weergegeven met betrekking tot managedIdentityCredential- en tokenverwervingsfouten, kan het zijn dat u meerdere tenants hebt en dat uw Azure-aanmelding gebruikmaakt van een tenant die niet over uw zoekservice beschikt. Als u uw tenant-id wilt ophalen, zoekt u in Azure Portal naar 'tenanteigenschappen' of voert u deze uit az login tenant list
.
Zodra u uw tenant-id hebt, voert u deze uit az login --tenant <YOUR-TENANT-ID>
bij een opdrachtprompt en voert u het script opnieuw uit.
Opschonen
Wanneer u in uw eigen abonnement werkt, is het een goed idee om aan het einde van een project te bepalen of u de gemaakte resources nog nodig hebt. Resources die actief blijven, kunnen u geld kosten. U kunt resources afzonderlijk verwijderen, maar u kunt ook de resourcegroep verwijderen als u de volledige resourceset wilt verwijderen.
U kunt resources vinden en beheren in Azure Portal met behulp van de koppeling Alle resources of resourcegroepen in het meest linkse deelvenster.