Skip to content

Commit b902aae

Browse files
committed
initial version of java include, copied from JS unchanged (for diff purposes)
1 parent e25ac7a commit b902aae

File tree

1 file changed

+395
-0
lines changed

1 file changed

+395
-0
lines changed
Lines changed: 395 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,395 @@
1+
---
2+
manager: nitinme
3+
author: haileytap
4+
ms.author: haileytapia
5+
ms.service: azure-ai-search
6+
ms.topic: include
7+
ms.date: 06/05/2025
8+
---
9+
## Prerequisites
10+
11+
- An Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F).
12+
13+
- An [Azure OpenAI resource](/azure/ai-services/openai/how-to/create-resource).
14+
- [Choose a region](/azure/ai-services/openai/concepts/models?tabs=global-standard%2Cstandard-chat-completions#global-standard-model-availability) that supports the chat completion model you want to use (gpt-4o, gpt-4o-mini, or an equivalent model).
15+
- [Deploy the chat completion model](/azure/ai-foundry/how-to/deploy-models-openai) in Azure AI Foundry or [use another approach](/azure/ai-services/openai/how-to/working-with-models).
16+
- An [Azure AI Search resource](../../search-create-service-portal.md).
17+
- We recommend using the Basic tier or higher.
18+
- [Enable semantic ranking](../../semantic-how-to-enable-disable.md).
19+
- [Visual Studio Code](https://code.visualstudio.com/download).
20+
- [Node.JS with LTS](https://nodejs.org/en/download/).
21+
22+
23+
## Configure access
24+
25+
Requests to the search endpoint must be authenticated and authorized. You can use API keys or roles for this task. Keys are easier to start with, but roles are more secure. This quickstart assumes roles.
26+
27+
You're setting up two clients, so you need permissions on both resources.
28+
29+
Azure AI Search is receiving the query request from your local system. Assign yourself the **Search Index Data Reader** role assignment if the hotels sample index already exists. If it doesn't exist, assign yourself **Search Service Contributor** and **Search Index Data Contributor** roles so that you can create and query the index.
30+
31+
Azure OpenAI is receiving the query and the search results from your local system. Assign yourself the **Cognitive Services OpenAI User** role on Azure OpenAI.
32+
33+
1. Sign in to the [Azure portal](https://portal.azure.com).
34+
35+
1. Configure Azure AI Search for role-based access:
36+
37+
1. In the Azure portal, find your Azure AI Search service.
38+
39+
1. On the left menu, select **Settings** > **Keys**, and then select either **Role-based access control** or **Both**.
40+
41+
1. Assign roles:
42+
43+
1. On the left menu, select **Access control (IAM)**.
44+
45+
1. On Azure AI Search, select these roles to create, load, and query a search index, and then assign them to your Microsoft Entra ID user identity:
46+
47+
- **Search Index Data Contributor**
48+
- **Search Service Contributor**
49+
50+
1. On Azure OpenAI, select **Access control (IAM)** to assign this role to yourself on Azure OpenAI:
51+
52+
- **Cognitive Services OpenAI User**
53+
54+
It can take several minutes for permissions to take effect.
55+
56+
## Create an index
57+
58+
A search index provides grounding data for the chat model. We recommend the hotels-sample-index, which can be created in minutes and runs on any search service tier. This index is created using built-in sample data.
59+
60+
1. In the Azure portal, [find your search service](https://portal.azure.com/#blade/HubsExtension/BrowseResourceBlade/resourceType/Microsoft.Search%2FsearchServices).
61+
62+
1. On the **Overview** home page, select [**Import data**](../../search-get-started-portal.md) to start the wizard.
63+
64+
1. On the **Connect to your data** page, select **Samples** from the dropdown list.
65+
66+
1. Choose the **hotels-sample**.
67+
68+
1. Select **Next** through the remaining pages, accepting the default values.
69+
70+
1. Once the index is created, select **Search management** > **Indexes** from the left menu to open the index.
71+
72+
1. Select **Edit JSON**.
73+
74+
1. Scroll to the end of the index, where you can find placeholders for constructs that can be added to an index.
75+
76+
```json
77+
"analyzers": [],
78+
"tokenizers": [],
79+
"tokenFilters": [],
80+
"charFilters": [],
81+
"normalizers": [],
82+
```
83+
84+
1. On a new line after "normalizers", paste in the following semantic configuration. This example specifies a `"defaultConfiguration"`, which is important to the running of this quickstart.
85+
86+
```json
87+
"semantic":{
88+
"defaultConfiguration":"semantic-config",
89+
"configurations":[
90+
{
91+
"name":"semantic-config",
92+
"prioritizedFields":{
93+
"titleField":{
94+
"fieldName":"HotelName"
95+
},
96+
"prioritizedContentFields":[
97+
{
98+
"fieldName":"Description"
99+
}
100+
],
101+
"prioritizedKeywordsFields":[
102+
{
103+
"fieldName":"Category"
104+
},
105+
{
106+
"fieldName":"Tags"
107+
}
108+
]
109+
}
110+
}
111+
]
112+
},
113+
```
114+
115+
1. **Save** your changes.
116+
117+
1. Run the following query in [Search Explorer](../../search-explorer.md) to test your index: `complimentary breakfast`.
118+
119+
Output should look similar to the following example. Results that are returned directly from the search engine consist of fields and their verbatim values, along with metadata like a search score and a semantic ranking score and caption if you use semantic ranker. We used a [select statement](../../search-query-odata-select.md) to return just the HotelName, Description, and Tags fields.
120+
121+
```
122+
{
123+
"@odata.count": 18,
124+
"@search.answers": [],
125+
"value": [
126+
{
127+
"@search.score": 2.2896252,
128+
"@search.rerankerScore": 2.506816864013672,
129+
"@search.captions": [
130+
{
131+
"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..",
132+
"highlights": ""
133+
}
134+
],
135+
"HotelName": "Head Wind Resort",
136+
"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.",
137+
"Tags": [
138+
"coffee in lobby",
139+
"free wifi",
140+
"view"
141+
]
142+
},
143+
{
144+
"@search.score": 2.2158256,
145+
"@search.rerankerScore": 2.288334846496582,
146+
"@search.captions": [
147+
{
148+
"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..",
149+
"highlights": ""
150+
}
151+
],
152+
"HotelName": "Swan Bird Lake Inn",
153+
"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.",
154+
"Tags": [
155+
"continental breakfast",
156+
"free wifi",
157+
"24-hour front desk service"
158+
]
159+
},
160+
{
161+
"@search.score": 0.92481667,
162+
"@search.rerankerScore": 2.221315860748291,
163+
"@search.captions": [
164+
{
165+
"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..",
166+
"highlights": ""
167+
}
168+
],
169+
"HotelName": "White Mountain Lodge & Suites",
170+
"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.",
171+
"Tags": [
172+
"continental breakfast",
173+
"pool",
174+
"restaurant"
175+
]
176+
},
177+
. . .
178+
]}
179+
```
180+
181+
## Get service endpoints
182+
183+
In the remaining sections, you set up API calls to Azure OpenAI and Azure AI Search. Get the service endpoints so that you can provide them as variables in your code.
184+
185+
1. Sign in to the [Azure portal](https://portal.azure.com).
186+
187+
1. [Find your search service](https://portal.azure.com/#blade/HubsExtension/BrowseResourceBlade/resourceType/Microsoft.Search%2FsearchServices).
188+
189+
1. On the **Overview** home page, copy the URL. An example endpoint might look like `https://example.search.windows.net`.
190+
191+
1. [Find your Azure OpenAI service](https://portal.azure.com/#blade/HubsExtension/BrowseResourceBlade/resourceType/Microsoft.CognitiveServices%2Faccounts).
192+
193+
1. On the **Overview** home page, select the link to view the endpoints. Copy the URL. An example endpoint might look like `https://example.openai.azure.com/`.
194+
195+
## Set up environment variables for local development
196+
197+
1. Create a `.env` file.
198+
1. Add the following environment variables to the `.env` file, replacing the values with your own service endpoints and keys.
199+
200+
```plaintext
201+
AZURE_SEARCH_ENDPOINT=<YOUR AZURE AI SEARCH ENDPOINT>
202+
AZURE_SEARCH_INDEX_NAME=hotels-sample-index
203+
204+
AZURE_OPENAI_ENDPOINT=<YOUR AZURE OPENAI ENDPOINT>
205+
AZURE_OPENAI_VERSION=<YOUR AZURE OPENAI API VERSION>
206+
AZURE_DEPLOYMENT_MODEL=<YOUR DEPLOYMENT NAME>
207+
```
208+
209+
## Set up the Node.JS project
210+
211+
Set up project with Visual Studio Code and TypeScript.
212+
213+
1. Start Visual Studio Code in a new directory.
214+
215+
```bash
216+
mkdir rag-quickstart && cd rag-quickstart
217+
code .
218+
```
219+
1. Create a new package for ESM modules in your project directory.
220+
221+
```bash
222+
npm init -y
223+
npm pkg set type=module
224+
```
225+
226+
This creates a `package.json` file with default values.
227+
228+
1. Install the following npm packages.
229+
230+
```bash
231+
npm install @azure/identity @azure/search-documents openai dotenv
232+
```
233+
234+
1. Create a `src` directory in your project directory.
235+
236+
```bash
237+
mkdir src
238+
```
239+
240+
## Sign in to Azure
241+
242+
You're using Microsoft Entra ID and role assignments for the connection. Make sure you're logged in to the same tenant and subscription as Azure AI Search and Azure OpenAI. You can use the Azure CLI on the command line to show current properties, change properties, and to sign in. For more information, see [Connect without keys](../../search-get-started-rbac.md).
243+
244+
Run each of the following commands in sequence.
245+
246+
```azure-cli
247+
az account show
248+
249+
az account set --subscription <PUT YOUR SUBSCRIPTION ID HERE>
250+
251+
az login --tenant <PUT YOUR TENANT ID HERE>
252+
```
253+
254+
You should now be logged in to Azure from your local device.
255+
256+
## Set up query and chat thread
257+
258+
Create a query script that uses the Azure AI Search index and the chat model to generate responses based on grounding data. The following steps guide you through setting up the query script.
259+
260+
1. Create a `query.js` file in the `src` directory with the following code.
261+
262+
:::code language="javascript" source="~/azure-search-javascript-samples/quickstart-rag-js/src/query.js" :::
263+
264+
The preceding code does the following:
265+
- Imports the necessary libraries for Azure AI Search and Azure OpenAI.
266+
- Uses environment variables to configure the Azure AI Search and Azure OpenAI clients.
267+
- Defines a function to get the clients for Azure AI Search and Azure OpenAI, using environment variables for configuration.
268+
- Defines a function to query Azure AI Search for sources based on the user query.
269+
- Defines a function to query Azure OpenAI for a response based on the user query and the sources retrieved from Azure AI Search.
270+
- The `main` function orchestrates the flow by calling the search and OpenAI functions, and then prints the response.
271+
272+
1. Run the following command in a terminal to execute the query script:
273+
274+
```bash
275+
node -r dotenv/config query.js
276+
```
277+
278+
The `.env` is passed into the runtime using the `-r dotenv/config`.
279+
280+
1. View the output, which consists of recommendations for several hotels. Here's an example of what the output might look like:
281+
282+
```
283+
Sure! Here are a few hotels that offer complimentary breakfast:
284+
285+
- **Head Wind Resort**
286+
- Complimentary continental breakfast in the lobby
287+
- Free Wi-Fi throughout the hotel
288+
289+
- **Double Sanctuary Resort**
290+
- Continental breakfast included
291+
292+
- **White Mountain Lodge & Suites**
293+
- Continental breakfast available
294+
295+
- **Swan Bird Lake Inn**
296+
- Continental-style breakfast each morning with a variety of food and drinks
297+
such as caramel cinnamon rolls, coffee, orange juice, milk, cereal,
298+
instant oatmeal, bagels, and muffins
299+
```
300+
301+
## Troubleshooting
302+
303+
If you get a **Forbidden** error message, check Azure AI Search configuration to make sure role-based access is enabled.
304+
305+
If you get an **Authorization failed** error message, wait a few minutes and try again. It can take several minutes for role assignments to become operational.
306+
307+
If you get a **Resource not found** error message, check the resource URIs and make sure the API version on the chat model is valid.
308+
309+
Otherwise, to experiment further, change the query and rerun the last step to better understand how the model works with the grounding data.
310+
311+
You can also modify the prompt to change the tone or structure of the output.
312+
313+
You might also try the query without semantic ranking by setting `use_semantic_reranker=False` in the query parameters step. Semantic ranking can noticably improve the relevance of query results and the ability of the LLM to return useful information. Experimentation can help you decide whether it makes a difference for your content.
314+
315+
## Send a complex RAG query
316+
317+
Azure AI Search supports [complex types](../../search-howto-complex-data-types.md) for nested JSON structures. In the hotels-sample-index, `Address` is an example of a complex type, consisting of `Address.StreetAddress`, `Address.City`, `Address.StateProvince`, `Address.PostalCode`, and `Address.Country`. The index also has complex collection of `Rooms` for each hotel.
318+
319+
If your index has complex types, change your prompt to include formatting instructions:
320+
321+
```text
322+
Can you recommend a few hotels that offer complimentary breakfast?
323+
Tell me their description, address, tags, and the rate for one room that sleeps 4 people.
324+
```
325+
326+
1. Create a new file `queryComplex.js`.
327+
1. Copy the following code to the file:
328+
329+
:::code language="javascript" source="~/azure-search-javascript-samples/quickstart-rag-js/src/queryComplex.js" :::
330+
331+
332+
1. Run the following command in a terminal to execute the query script:
333+
334+
```bash
335+
node -r dotenv/config queryComplex.js
336+
```
337+
338+
The `.env` is passed into the runtime using the `-r dotenv/config`.
339+
340+
1. View the output from Azure OpenAI, and it adds content from complex types.
341+
342+
```
343+
Here are a few hotels that offer complimentary breakfast and have rooms that sleep 4 people:
344+
345+
1. **Head Wind Resort**
346+
- **Description:** The best of old town hospitality combined with views of the river and
347+
cool breezes off the prairie. Enjoy a complimentary continental breakfast in the lobby,
348+
and free Wi-Fi throughout the hotel.
349+
- **Address:** 7633 E 63rd Pl, Tulsa, OK 74133, USA
350+
- **Tags:** Coffee in lobby, free Wi-Fi, view
351+
- **Room for 4:** Suite, 2 Queen Beds (Amenities) - $254.99
352+
353+
2. **Double Sanctuary Resort**
354+
- **Description:** 5-star Luxury Hotel - Biggest Rooms in the city. #1 Hotel in the area
355+
listed by Traveler magazine. Free WiFi, Flexible check in/out, Fitness Center & espresso
356+
in room. Offers continental breakfast.
357+
- **Address:** 2211 Elliott Ave, Seattle, WA 98121, USA
358+
- **Tags:** View, pool, restaurant, bar, continental breakfast
359+
- **Room for 4:** Suite, 2 Queen Beds (Amenities) - $254.99
360+
361+
3. **Swan Bird Lake Inn**
362+
- **Description:** Continental-style breakfast featuring a variety of food and drinks.
363+
Locally made caramel cinnamon rolls are a favorite.
364+
- **Address:** 1 Memorial Dr, Cambridge, MA 02142, USA
365+
- **Tags:** Continental breakfast, free Wi-Fi, 24-hour front desk service
366+
- **Room for 4:** Budget Room, 2 Queen Beds (City View) - $85.99
367+
368+
4. **Gastronomic Landscape Hotel**
369+
- **Description:** Known for its culinary excellence under the management of William Dough,
370+
offers continental breakfast.
371+
- **Address:** 3393 Peachtree Rd, Atlanta, GA 30326, USA
372+
- **Tags:** Restaurant, bar, continental breakfast
373+
- **Room for 4:** Budget Room, 2 Queen Beds (Amenities) - $66.99
374+
...
375+
- **Tags:** Pool, continental breakfast, free parking
376+
- **Room for 4:** Budget Room, 2 Queen Beds (Amenities) - $60.99
377+
378+
Enjoy your stay! Let me know if you need any more information.
379+
```
380+
381+
## Troubleshooting errors
382+
383+
To debug Azure SDK errors, set the environment variable `AZURE_LOG_LEVEL` to one of the following: `verbose`, `info`, `warning`, `error`. This will enable detailed logging for the Azure SDK, which can help identify [issues with authentication](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/TROUBLESHOOTING.md#enable-and-configure-logging), network connectivity, or other problems.
384+
385+
Rerun the query script. You should now get informational statements from the SDKs in the output that provide more detail about any issues.
386+
387+
If you see output messages related to ManagedIdentityCredential and token acquisition failures, it could be that you have multiple tenants, and your Azure sign-in is using a tenant that doesn't have your search service. To get your tenant ID, search the Azure portal for "tenant properties" or run `az login tenant list`.
388+
389+
Once you have your tenant ID, run `az login --tenant <YOUR-TENANT-ID>` at a command prompt, and then rerun the script.
390+
391+
## Clean up
392+
393+
When you're working in your own subscription, it's a good idea at the end of a project to identify whether you still need the resources you created. Resources left running can cost you money. You can delete resources individually or delete the resource group to delete the entire set of resources.
394+
395+
You can find and manage resources in the Azure portal by using the **All resources** or **Resource groups** link in the leftmost pane.

0 commit comments

Comments
 (0)