在本快速入門中,您會使用自己的資料搭配 Azure OpenAI 模型來建立強大的交談式 AI 平台,以實現更快、更準確的通訊。
這很重要
有新方法可以使用您自己的資料建置對話式解決方案。 如需最新的建議方法,請參閱 快速入門:在 Azure AI 搜尋服務中使用代理程式擷取。
先決條件
- 如果您沒有自己的數據,請從 GitHub 下載範例數據。
使用 Microsoft Foundry 入口網站新增您的資料
小提示
或者,您可以使用 Azure 開發人員 CLI 以程式設計方式建立 Azure OpenAI On Your Data 所需的資源。
若要使用入口網站新增資料:
-
登入 Microsoft Foundry。 確定新鑄造廠的開關是關閉的。 這些步驟指的是 Foundry (傳統版)。
選取您的 Azure OpenAI 資源。 如果你有 Foundry 資源,你可以 建立一個 Foundry 專案。
從左窗格中,選取 [Playgrounds>聊天]。
在 [設定] 窗格中,選取您的模型部署。
選取 新增您的資料> 新增資料來源。
在 資料來源 頁面上:
在 [選取資料來源] 底下,選取 [上傳檔案 (預覽版)]。
小提示
- 此選項需要 Azure Blob 儲存體資源和 Azure AI 搜尋服務資源,才能存取和編製資料索引。 如需詳細資訊,請參閱資料來源 選項 和 支援的檔案類型和格式。
- 對於具有長文字的文件和資料集,建議您使用 資料準備指令碼。
Azure OpenAI 需要跨來源資源共用 (CORS) 才能存取您的儲存體帳戶。 如果您的 Azure Blob 儲存體資源尚未啟用 CORS,請選取 [開啟 CORS]。
選取您的 Azure AI 搜尋服務資源。
輸入新索引的名稱。
選取確認使用 Azure AI 搜尋服務的計費效果的複選框。
選取 下一步。
在 [上傳檔案 ] 頁面上:
選取 [瀏覽] 以取得檔案,然後選取您自己的資料或您從 必要條件下載的範例資料。
選取 [上傳檔案]。
選取 下一步。
在 資料管理 頁面上:
選擇是否要為索引啟用 語意搜尋或向量搜尋 。
選取 下一步。
在 [資料連線 ] 頁面上:
選擇是否要使用 系統指派的受控識別 或 API 金鑰進行驗證。
選取 下一步。
檢閱您的設定,然後選取 儲存並關閉。
您現在可以與模型聊天,模型會使用您的資料來建構回應。
聊天遊樂場
透過聊天遊樂場以無程式碼方法開始探索 Azure OpenAI 功能。 這只是一個文字方塊,您可以在其中提交提示來產生完成。 您可以透過此頁面,快速逐一查看並實驗各種功能。
遊樂場為您提供了量身打造聊天體驗的選項。 在頂端功能表上,您可以選取 [ 部署 ] 來判斷哪個模型會使用索引中的搜尋結果來產生回應。 您可以選擇過去訊息的數目,以作為未來所產生回應的交談記錄。 交談歷程記錄 提供背景來產生相關的回應,但也會消耗 令牌用量。 輸入語彙基元進度指示器會追蹤您提交問題的語彙基元計數。
左側的進 階設定 是 運行時間參數,可讓您控制從數據擷取和搜尋相關信息。 良好的使用案例是當您想要確定只會根據您的資料產生回應,或您發現模型無法根據資料上存在的資訊產生回應時。
嚴謹度會根據系統的相似度分數來決定篩選搜尋文件的積極度。 將嚴謹度設定為 5 表示系統會積極篩選出文件,並套用非常高的相似度閾值。 在此案例中,語意搜尋很有用,因為排名模型會更妥善地推斷查詢的意圖。 如果嚴格度降低,產生的答案會更詳細,但也可能包含索引中未出現的資訊。 依預設,這會設定為 3。
擷取的檔 是一個整數,可以設定為 3、5、10 或 20,並控制提供給大型語言模型的檔區塊數目,以制定最終回應。 根據預設,這項設定為 5。
啟用 [限制對您資料的回應] 時,模型會嘗試只依賴您的文件進行回應。 根據預設,這會設定為 true。
傳送第一個查詢。 聊天模型在問答練習中表現最佳。 例如,「我的可用健康方案為何?」或「什麼是健康加號選項?」。
需要數據分析的查詢可能會失敗,例如「哪個健康計劃最受歡迎?」。 需要所有數據相關信息的查詢也可能會失敗,例如「我上傳了多少份檔?」。 請記住,搜尋引擎會尋找包含與查詢完全相同或類似字詞、片語或建構的區塊。 雖然模型可能理解了問題,但如果搜尋結果是來自資料集的區塊,那麼這些搜尋結果也不適合回答這類問題。
聊天受限於回應中回傳的文件(區塊數量)(在 Foundry 入口遊樂場中限制為 3 至 20 個)。 您可以想象到,如果是提出有關「所有標題」這樣的問題,則需要完整掃描整個向量存放區。
部署模型
一旦您對體驗感到滿意,您可以選取 [ 部署至 ] 按鈕,直接從入口網站部署Web應用程式。
這可讓您選擇將模型部署至獨立的 Web 應用程式,或部署為 Copilot Studio (預覽) 中的一個副手 (若您在模型上使用自己的資料)。
例如,如果您選擇部署 Web 應用程式:
第一次部署 Web 應用程式時,您應該選取 [建立新的 Web 應用程式]。 選擇應用程式的名稱,這會成為應用程式 URL 的一部分。 例如: https://<appname>.azurewebsites.net 。
選取已發佈的應用程式的訂用帳戶、資源群組、位置和定價方案。 若要更新現有的應用程式,請選取 [發佈到現有的 Web 應用程式],然後從下拉式功能表中選擇先前應用程式的名稱。
如果您選擇部署 Web 應用程式,請參閱使用它 的重要考慮 。
先決條件
- Azure 訂用帳戶 - 建立免費帳戶。
- 如果您沒有自己的數據,請從 GitHub 下載範例數據。
- .NET 8 SDK
使用 Microsoft Foundry 入口網站新增您的資料
小提示
或者,您可以使用 Azure 開發人員 CLI 以程式設計方式建立 Azure OpenAI On Your Data 所需的資源。
若要使用入口網站新增資料:
-
登入 Microsoft Foundry。 確定新鑄造廠的開關是關閉的。 這些步驟指的是 Foundry (傳統版)。
選取您的 Azure OpenAI 資源。 如果你有 Foundry 資源,你可以 建立一個 Foundry 專案。
從左窗格中,選取 [Playgrounds>聊天]。
在 [設定] 窗格中,選取您的模型部署。
選取 新增您的資料> 新增資料來源。
在 資料來源 頁面上:
在 [選取資料來源] 底下,選取 [上傳檔案 (預覽版)]。
小提示
- 此選項需要 Azure Blob 儲存體資源和 Azure AI 搜尋服務資源,才能存取和編製資料索引。 如需詳細資訊,請參閱資料來源 選項 和 支援的檔案類型和格式。
- 對於具有長文字的文件和資料集,建議您使用 資料準備指令碼。
Azure OpenAI 需要跨來源資源共用 (CORS) 才能存取您的儲存體帳戶。 如果您的 Azure Blob 儲存體資源尚未啟用 CORS,請選取 [開啟 CORS]。
選取您的 Azure AI 搜尋服務資源。
輸入新索引的名稱。
選取確認使用 Azure AI 搜尋服務的計費效果的複選框。
選取 下一步。
在 [上傳檔案 ] 頁面上:
選取 [瀏覽] 以取得檔案,然後選取您自己的資料或您從 必要條件下載的範例資料。
選取 [上傳檔案]。
選取 下一步。
在 資料管理 頁面上:
選擇是否要為索引啟用 語意搜尋或向量搜尋 。
選取 下一步。
在 [資料連線 ] 頁面上:
選擇是否要使用 系統指派的受控識別 或 API 金鑰進行驗證。
選取 下一步。
檢閱您的設定,然後選取 儲存並關閉。
您現在可以與模型聊天,模型會使用您的資料來建構回應。
擷取資源資訊
您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式。 本快速入門假設您已將資料上傳至 Azure Blob 儲存體帳戶,並已建立 Azure AI 搜尋服務索引。 請參閱使用 Microsoft Foundry 入口新增您的資料。
| 變數名稱 | 價值觀 |
|---|---|
AZURE_OPENAI_ENDPOINT |
從 Azure 入口網站查看您的 Azure OpenAI 資源時,可以在 [金鑰與端點] 區段中找到此值。 範例端點為:https://my-resource.openai.azure.com。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 此值可在 Azure 入口網站的 [資源管理>部署 ] 下找到。 |
AZURE_AI_SEARCH_ENDPOINT |
從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
AZURE_AI_SEARCH_INDEX |
此值會對應至您建立來儲存資料的索引名稱。 從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
從項目目錄中,開啟 Program.cs 檔案,並以下列程序代碼取代其內容:
using System;
using Azure.AI.OpenAI;
using System.ClientModel;
using Azure.AI.OpenAI.Chat;
using OpenAI.Chat;
using static System.Environment;
string azureOpenAIEndpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
string azureOpenAIKey = GetEnvironmentVariable("AZURE_OPENAI_API_KEY");
string deploymentName = GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME");
string searchEndpoint = GetEnvironmentVariable("AZURE_AI_SEARCH_ENDPOINT");
string searchKey = GetEnvironmentVariable("AZURE_AI_SEARCH_API_KEY");
string searchIndex = GetEnvironmentVariable("AZURE_AI_SEARCH_INDEX");
AzureOpenAIClient openAIClient = new(
new Uri(azureOpenAIEndpoint),
new ApiKeyCredential(azureOpenAIKey));
ChatClient chatClient = openAIClient.GetChatClient(deploymentName);
// Extension methods to use data sources with options are subject to SDK surface changes. Suppress the
// warning to acknowledge and this and use the subject-to-change AddDataSource method.
#pragma warning disable AOAI001
ChatCompletionOptions options = new();
options.AddDataSource(new AzureSearchChatDataSource()
{
Endpoint = new Uri(searchEndpoint),
IndexName = searchIndex,
Authentication = DataSourceAuthentication.FromApiKey(searchKey),
});
ChatCompletion completion = chatClient.CompleteChat(
[
new UserChatMessage("What health plans are available?"),
],
options);
ChatMessageContext onYourDataContext = completion.GetMessageContext();
if (onYourDataContext?.Intent is not null)
{
Console.WriteLine($"Intent: {onYourDataContext.Intent}");
}
foreach (ChatCitation citation in onYourDataContext?.Citations ?? [])
{
Console.WriteLine($"Citation: {citation.Content}");
}
這很重要
在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需認證安全性的詳細資訊,請參閱此 安全性 文章。
dotnet run Program.cs
輸出
Contoso Electronics offers two health plans: Northwind Health Plus and Northwind Standard [doc1]. Northwind Health Plus is a comprehensive plan that provides coverage for medical, vision, and dental services, prescription drug coverage, mental health and substance abuse coverage, and coverage for preventive care services. It also offers coverage for emergency services, both in-network and out-of-network. On the other hand, Northwind Standard is a basic plan that provides coverage for medical, vision, and dental services, prescription drug coverage, and coverage for preventive care services. However, it does not offer coverage for emergency services, mental health and substance abuse coverage, or out-of-network services [doc1].
Intent: ["What are the available health plans?", "List of health plans available", "Health insurance options", "Types of health plans offered"]
Citation:
Contoso Electronics plan and benefit packages
Thank you for your interest in the Contoso electronics plan and benefit packages. Use this document to
learn more about the various options available to you...// Omitted for brevity
這會等到模型產生整個回應,才會列印結果。
| 原始程式碼 | 原始程式碼樣本
先決條件
- Azure OpenAI
- Azure Blob 儲存服務
- Azure AI 搜尋服務
- 部署在支援的區域並具有支援的模型的 Azure OpenAI。
- 請確定您已至少獲派 Azure OpenAI 資源的 認知服務參與者 角色。
- 如果您沒有自己的數據,請從 GitHub 下載範例數據。
使用 Microsoft Foundry 入口網站新增您的資料
小提示
或者,您可以使用 Azure 開發人員 CLI 以程式設計方式建立 Azure OpenAI On Your Data 所需的資源。
若要使用入口網站新增資料:
-
登入 Microsoft Foundry。 確定新鑄造廠的開關是關閉的。 這些步驟指的是 Foundry (傳統版)。
選取您的 Azure OpenAI 資源。 如果你有 Foundry 資源,你可以 建立一個 Foundry 專案。
從左窗格中,選取 [Playgrounds>聊天]。
在 [設定] 窗格中,選取您的模型部署。
選取 新增您的資料> 新增資料來源。
在 資料來源 頁面上:
在 [選取資料來源] 底下,選取 [上傳檔案 (預覽版)]。
小提示
- 此選項需要 Azure Blob 儲存體資源和 Azure AI 搜尋服務資源,才能存取和編製資料索引。 如需詳細資訊,請參閱資料來源 選項 和 支援的檔案類型和格式。
- 對於具有長文字的文件和資料集,建議您使用 資料準備指令碼。
Azure OpenAI 需要跨來源資源共用 (CORS) 才能存取您的儲存體帳戶。 如果您的 Azure Blob 儲存體資源尚未啟用 CORS,請選取 [開啟 CORS]。
選取您的 Azure AI 搜尋服務資源。
輸入新索引的名稱。
選取確認使用 Azure AI 搜尋服務的計費效果的複選框。
選取 下一步。
在 [上傳檔案 ] 頁面上:
選取 [瀏覽] 以取得檔案,然後選取您自己的資料或您從 必要條件下載的範例資料。
選取 [上傳檔案]。
選取 下一步。
在 資料管理 頁面上:
選擇是否要為索引啟用 語意搜尋或向量搜尋 。
選取 下一步。
在 [資料連線 ] 頁面上:
選擇是否要使用 系統指派的受控識別 或 API 金鑰進行驗證。
選取 下一步。
檢閱您的設定,然後選取 儲存並關閉。
您現在可以與模型聊天,模型會使用您的資料來建構回應。
擷取必要的變數
若要成功對 Azure OpenAI 發出呼叫,您將需要下列變數。 本快速入門假設您已將資料上傳至 Azure Blob 儲存體帳戶,並已建立 Azure AI 搜尋服務索引。 欲了解更多資訊,請參閱使用 Microsoft Foundry 新增您的資料。
| 變數名稱 | 價值觀 |
|---|---|
AZURE_OPENAI_ENDPOINT |
您可以在從 Azure 入口網站查看您的 Azure OpenAI 資源時,在 [金鑰與端點] 區段中找到此值。 或者,你也可以在 Foundry>聊天遊樂場>程式碼檢視中找到這個數值。 範例端點為:https://my-resource.openai.azure.com。 |
AZURE_OPENAI_API_KEY |
您可以在從 Azure 入口網站查看您的 Azure OpenAI 資源時,在 [資源管理]> [金鑰與端點] 區段中找到此值。 您可以使用 KEY1 或 KEY2。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。 |
AZURE_OPEN_AI_DEPLOYMENT_ID |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 你可以在 Azure 入口網站的 資源管理>部署 中找到這個值,或在 Foundry 入口網站的 管理>部署 中查詢。 |
AZURE_AI_SEARCH_ENDPOINT |
您可以在從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,在 [概觀] 區段中找到此值。 |
AZURE_AI_SEARCH_API_KEY |
您可以在從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,在 [設定]> [金鑰] 區段中找到此值。 您可以使用主要系統管理金鑰或次要系統管理金鑰。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。 |
AZURE_AI_SEARCH_INDEX |
此值會對應至您建立來儲存資料的索引名稱。 從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
環境變數
為您的金鑰和端點建立及指派永續性環境變數。
這很重要
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果您使用 API 金鑰,請安全地將其儲存在 Azure 金鑰保存庫。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱 使用 Azure Key Vault 的 API 金鑰。
如需 AI 服務安全性的詳細資訊,請參閱驗證對 Azure AI 服務的要求。
備註
Spring AI 會將模型名稱預設為 gpt-35-turbo。 只有在您使用了不同名稱部署模型時,才需要提供 SPRING_AI_AZURE_OPENAI_MODEL 值。
export SPRING_AI_AZURE_OPENAI_ENDPOINT=REPLACE_WITH_YOUR_AOAI_ENDPOINT_VALUE_HERE
export SPRING_AI_AZURE_OPENAI_API_KEY=REPLACE_WITH_YOUR_AOAI_KEY_VALUE_HERE
export SPRING_AI_AZURE_COGNITIVE_SEARCH_ENDPOINT=REPLACE_WITH_YOUR_AZURE_SEARCH_RESOURCE_VALUE_HERE
export SPRING_AI_AZURE_COGNITIVE_SEARCH_API_KEY=REPLACE_WITH_YOUR_AZURE_SEARCH_RESOURCE_KEY_VALUE_HERE
export SPRING_AI_AZURE_COGNITIVE_SEARCH_INDEX=REPLACE_WITH_YOUR_INDEX_NAME_HERE
export SPRING_AI_AZURE_OPENAI_MODEL=REPLACE_WITH_YOUR_MODEL_NAME_HERE
建立新的 Spring 應用程式
Spring AI 目前不支援允許 Azure AI 查詢封裝AzureCognitiveSearchChatExtensionConfiguration 方法,並隱藏使用者詳細資料的 選項。 作為替代方法,您仍然可以在應用程式中直接叫用 RAG 方法來查詢 Azure AI Search 索引中的資料,並使用所擷取的文件來增強您的查詢。
Spring AI 支援 VectorStore 抽象概念,而且您可以將 Azure AI 搜尋封裝在 Spring AI VectorStore 實作中,以便查詢自訂資料。 下列專案會實作 Azure AI 搜尋服務所支援的自訂 VectorStore,並直接執行 RAG 作業。
在 Bash 視窗中,為您的應用程式建立新目錄,並瀏覽至其中。
mkdir ai-custom-data-demo && cd ai-custom-data-demo
從您的工作目錄執行 spring init 命令。 此命令會為您的 Spring 專案建立標準目錄結構,包括主要 Java 類別來源檔案,以及用於管理 Maven 型專案的 pom.xml 檔案。
spring init -a ai-custom-data-demo -n AICustomData --force --build maven -x
產生的檔案與資料夾類似下列結構:
ai-custom-data-demo/
|-- pom.xml
|-- mvn
|-- mvn.cmd
|-- HELP.md
|-- src/
|-- main/
| |-- resources/
| | |-- application.properties
| |-- java/
| |-- com/
| |-- example/
| |-- aicustomdatademo/
| |-- AiCustomDataApplication.java
|-- test/
|-- java/
|-- com/
|-- example/
|-- aicustomdatademo/
|-- AiCustomDataApplicationTests.java
編輯 Spring 應用程式
編輯 pom.xml 檔案。
從項目目錄的根目錄中,開啟慣用編輯器或 IDE 中的 pom.xml 檔案,並以下列內容覆寫檔案:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>ai-custom-data-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>AICustomData</name> <description>Demo project for Spring Boot</description> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.experimental.ai</groupId> <artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId> <version>0.7.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.azure</groupId> <artifactId>azure-search-documents</artifactId> <version>11.6.0-beta.10</version> <exclusions> <!-- exclude this to avoid changing the default serializer and the null-value behavior --> <exclusion> <groupId>com.azure</groupId> <artifactId>azure-core-serializer-json-jackson</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </repository> </repositories> </project>從 src/main/java/com/example/aicustomdatademo 資料夾,開啟慣用編輯器或 IDE 中的AiCustomDataApplication.java ,並貼上下列程式代碼:
package com.example.aicustomdatademo; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.ai.client.AiClient; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.prompt.Prompt; import org.springframework.ai.prompt.SystemPromptTemplate; import org.springframework.ai.prompt.messages.MessageType; import org.springframework.ai.prompt.messages.UserMessage; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.util.Context; import com.azure.search.documents.SearchClient; import com.azure.search.documents.SearchClientBuilder; import com.azure.search.documents.models.IndexingResult; import com.azure.search.documents.models.SearchOptions; import com.azure.search.documents.models.RawVectorQuery; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.extern.jackson.Jacksonized; @SpringBootApplication public class AiCustomDataApplication implements CommandLineRunner { private static final String ROLE_INFO_KEY = "role"; private static final String template = """ You are a helpful assistant. Use the information from the DOCUMENTS section to augment answers. DOCUMENTS: {documents} """; @Value("${spring.ai.azure.cognitive-search.endpoint}") private String acsEndpoint; @Value("${spring.ai.azure.cognitive-search.api-key}") private String acsApiKey; @Value("${spring.ai.azure.cognitive-search.index}") private String acsIndexName; @Autowired private AiClient aiClient; @Autowired private EmbeddingClient embeddingClient; public static void main(String[] args) { SpringApplication.run(AiCustomDataApplication.class, args); } @Override public void run(String... args) throws Exception { System.out.println(String.format("Sending custom data prompt to Foundry Tool. One moment please...\r\n")); final var store = vectorStore(embeddingClient); final String question = "What are my available health plans?"; final var candidateDocs = store.similaritySearch(question); final var userMessage = new UserMessage(question); final String docPrompts = candidateDocs.stream().map(entry -> entry.getContent()).collect(Collectors.joining("\n")); final SystemPromptTemplate promptTemplate = new SystemPromptTemplate(template); final var systemMessage = promptTemplate.createMessage(Map.of("documents", docPrompts)); final var prompt = new Prompt(List.of(systemMessage, userMessage)); final var resps = aiClient.generate(prompt); System.out.println(String.format("Prompt created %d generated response(s).", resps.getGenerations().size())); resps.getGenerations().stream() .forEach(gen -> { final var role = gen.getInfo().getOrDefault(ROLE_INFO_KEY, MessageType.ASSISTANT.getValue()); System.out.println(String.format("Generated respose from \"%s\": %s", role, gen.getText())); }); } @Bean public VectorStore vectorStore(EmbeddingClient embeddingClient) { final SearchClient searchClient = new SearchClientBuilder() .endpoint(acsEndpoint) .credential(new AzureKeyCredential(acsApiKey)) .indexName(acsIndexName) .buildClient(); return new AzureCognitiveSearchVectorStore(searchClient, embeddingClient); } public static class AzureCognitiveSearchVectorStore implements VectorStore { private static final int DEFAULT_TOP_K = 4; private static final Double DEFAULT_SIMILARITY_THRESHOLD = 0.0; private SearchClient searchClient; private final EmbeddingClient embeddingClient; public AzureCognitiveSearchVectorStore(SearchClient searchClient, EmbeddingClient embeddingClient) { this.searchClient = searchClient; this.embeddingClient = embeddingClient; } @Override public void add(List<Document> documents) { final var docs = documents.stream().map(document -> { final var embeddings = embeddingClient.embed(document); return new DocEntry(document.getId(), "", document.getContent(), embeddings); }).toList(); searchClient.uploadDocuments(docs); } @Override public Optional<Boolean> delete(List<String> idList) { final List<DocEntry> docIds = idList.stream().map(id -> DocEntry.builder().id(id).build()) .toList(); var results = searchClient.deleteDocuments(docIds); boolean resSuccess = true; for (IndexingResult result : results.getResults()) if (!result.isSucceeded()) { resSuccess = false; break; } return Optional.of(resSuccess); } @Override public List<Document> similaritySearch(String query) { return similaritySearch(query, DEFAULT_TOP_K); } @Override public List<Document> similaritySearch(String query, int k) { return similaritySearch(query, k, DEFAULT_SIMILARITY_THRESHOLD); } @Override public List<Document> similaritySearch(String query, int k, double threshold) { final var searchQueryVector = new RawVectorQuery() .setVector(toFloatList(embeddingClient.embed(query))) .setKNearestNeighborsCount(k) .setFields("contentVector"); final var searchResults = searchClient.search(null, new SearchOptions().setVectorQueries(searchQueryVector), Context.NONE); return searchResults.stream() .filter(r -> r.getScore() >= threshold) .map(r -> { final DocEntry entry = r.getDocument(DocEntry.class); final Document doc = new Document(entry.getId(), entry.getContent(), Collections.emptyMap()); doc.setEmbedding(entry.getContentVector()); return doc; }) .collect(Collectors.toList()); } private List<Float> toFloatList(List<Double> doubleList) { return doubleList.stream().map(Double::floatValue).toList(); } } @Data @Builder @Jacksonized @AllArgsConstructor @NoArgsConstructor static class DocEntry { private String id; private String hash; private String content; private List<Double> contentVector; } }這很重要
在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需認證安全性的詳細資訊,請參閱此 安全性 文章。
瀏覽回專案根資料夾,並使用下列命令執行應用程式:
./mvnw spring-boot:run
輸出
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.1.5)
2023-11-07T14:40:45.250-06:00 INFO 18557 --- [ main] c.e.a.AiCustomDataApplication : No active profile set, falling back to 1 default profile: "default"
2023-11-07T14:40:46.035-06:00 INFO 18557 --- [ main] c.e.a.AiCustomDataApplication : Started AiCustomDataApplication in 1.095 seconds (process running for 1.397)
Sending custom data prompt to Foundry Tool. One moment please...
Prompt created 1 generated response(s).
Generated response from "assistant": The available health plans in the Contoso Electronics plan and benefit packages are the Northwind Health Plus and Northwind Standard plans.
先決條件
Azure 訂用帳戶 - 建立免費帳戶。
在本地開發環境中,Azure CLI 用於無密碼驗證,使用 Azure CLI 登入以建立必要的情境。
部署在 支持區域中且具有支援模型的 Azure OpenAI 資源。
請確定您已至少獲派 Azure OpenAI 資源的 認知服務參與者 角色。
如果您沒有自己的數據,請從 GitHub 下載範例數據。
Microsoft Entra ID 必要條件
針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:
- 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
- 將
Cognitive Services User角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。
使用 Microsoft Foundry 入口網站新增您的資料
小提示
或者,您可以使用 Azure 開發人員 CLI 以程式設計方式建立 Azure OpenAI On Your Data 所需的資源。
若要使用入口網站新增資料:
-
登入 Microsoft Foundry。 確定新鑄造廠的開關是關閉的。 這些步驟指的是 Foundry (傳統版)。
選取您的 Azure OpenAI 資源。 如果你有 Foundry 資源,你可以 建立一個 Foundry 專案。
從左窗格中,選取 [Playgrounds>聊天]。
在 [設定] 窗格中,選取您的模型部署。
選取 新增您的資料> 新增資料來源。
在 資料來源 頁面上:
在 [選取資料來源] 底下,選取 [上傳檔案 (預覽版)]。
小提示
- 此選項需要 Azure Blob 儲存體資源和 Azure AI 搜尋服務資源,才能存取和編製資料索引。 如需詳細資訊,請參閱資料來源 選項 和 支援的檔案類型和格式。
- 對於具有長文字的文件和資料集,建議您使用 資料準備指令碼。
Azure OpenAI 需要跨來源資源共用 (CORS) 才能存取您的儲存體帳戶。 如果您的 Azure Blob 儲存體資源尚未啟用 CORS,請選取 [開啟 CORS]。
選取您的 Azure AI 搜尋服務資源。
輸入新索引的名稱。
選取確認使用 Azure AI 搜尋服務的計費效果的複選框。
選取 下一步。
在 [上傳檔案 ] 頁面上:
選取 [瀏覽] 以取得檔案,然後選取您自己的資料或您從 必要條件下載的範例資料。
選取 [上傳檔案]。
選取 下一步。
在 資料管理 頁面上:
選擇是否要為索引啟用 語意搜尋或向量搜尋 。
選取 下一步。
在 [資料連線 ] 頁面上:
選擇是否要使用 系統指派的受控識別 或 API 金鑰進行驗證。
選取 下一步。
檢閱您的設定,然後選取 儲存並關閉。
您現在可以與模型聊天,模型會使用您的資料來建構回應。
擷取資源資訊
您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式。 本快速入門假設您已將資料上傳至 Azure Blob 儲存體帳戶,並已建立 Azure AI 搜尋服務索引。 請參閱使用 Microsoft Foundry 入口新增您的資料。
| 變數名稱 | 價值觀 |
|---|---|
AZURE_OPENAI_ENDPOINT |
從 Azure 入口網站查看您的 Azure OpenAI 資源時,可以在 [金鑰與端點] 區段中找到此值。 範例端點為:https://my-resource.openai.azure.com。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 此值可在 Azure 入口網站的 [資源管理>部署 ] 下找到。 |
AZURE_AI_SEARCH_ENDPOINT |
從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
AZURE_AI_SEARCH_INDEX |
此值會對應至您建立來儲存資料的索引名稱。 從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
設定
建立新的資料夾
use-data-quickstart,並使用下列命令移至快速入門資料夾:mkdir use-data-quickstart && cd use-data-quickstart使用下列命令建立
package.json:npm init -y使用以下指令安裝適用於 JavaScript 的 OpenAI 客戶端庫:
npm install openai若要設定建議的無密碼驗證:
npm install @azure/identity
新增 JavaScript 程式碼
使用下列程式代碼,建立
index.js檔案。const { DefaultAzureCredential, getBearerTokenProvider } = require("@azure/identity"); const { AzureOpenAI } = require("openai"); // Set the Azure and AI Search values from environment variables const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint"; const searchEndpoint = process.env.AZURE_AI_SEARCH_ENDPOINT || "Your search endpoint"; const searchIndex = process.env.AZURE_AI_SEARCH_INDEX || "Your search index"; // keyless authentication const credential = new DefaultAzureCredential(); const scope = "https://cognitiveservices.azure.com/.default"; const azureADTokenProvider = getBearerTokenProvider(credential, scope); // Required Azure OpenAI deployment name and API version const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "gpt-4"; const apiVersion = process.env.OPENAI_API_VERSION || "2024-10-21"; function getClient() { return new AzureOpenAI({ endpoint, azureADTokenProvider, deployment: deploymentName, apiVersion, }); } async function main() { const client = getClient(); const messages = [ { role: "user", content: "What are my available health plans?" }, ]; console.log(`Message: ${messages.map((m) => m.content).join("\n")}`); const events = await client.chat.completions.create({ stream: true, messages: [ { role: "user", content: "What's the most common feedback we received from our customers about the product?", }, ], max_tokens: 128, model: "", data_sources: [ { type: "azure_search", parameters: { endpoint: searchEndpoint, index_name: searchIndex, authentication: { type: "api_key", key: searchKey, }, }, }, ], }); let response = ""; for await (const event of events) { for (const choice of event.choices) { const newText = choice.delta?.content; if (newText) { response += newText; // To see streaming results as they arrive, uncomment line below // console.log(newText); } } } console.log(response); } main().catch((err) => { console.error("The sample encountered an error:", err); });使用下列命令登入 Azure:
az login執行 JavaScript 檔案。
node index.js
輸出
Message: What are my available health plans?
The available health plans in the Contoso Electronics plan and benefit packages are the Northwind Health Plus and Northwind Standard plans.
先決條件
Azure 訂用帳戶 - 建立免費帳戶。
在本地開發環境中,Azure CLI 用於無密碼驗證,使用 Azure CLI 登入以建立必要的情境。
部署在 支持區域中且具有支援模型的 Azure OpenAI 資源。
請確定您已至少獲派 Azure OpenAI 資源的 認知服務參與者 角色。
如果您沒有自己的數據,請從 GitHub 下載範例數據。
Microsoft Entra ID 必要條件
針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:
- 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
- 將
Cognitive Services User角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。
使用 Microsoft Foundry 入口網站新增您的資料
小提示
或者,您可以使用 Azure 開發人員 CLI 以程式設計方式建立 Azure OpenAI On Your Data 所需的資源。
若要使用入口網站新增資料:
-
登入 Microsoft Foundry。 確定新鑄造廠的開關是關閉的。 這些步驟指的是 Foundry (傳統版)。
選取您的 Azure OpenAI 資源。 如果你有 Foundry 資源,你可以 建立一個 Foundry 專案。
從左窗格中,選取 [Playgrounds>聊天]。
在 [設定] 窗格中,選取您的模型部署。
選取 新增您的資料> 新增資料來源。
在 資料來源 頁面上:
在 [選取資料來源] 底下,選取 [上傳檔案 (預覽版)]。
小提示
- 此選項需要 Azure Blob 儲存體資源和 Azure AI 搜尋服務資源,才能存取和編製資料索引。 如需詳細資訊,請參閱資料來源 選項 和 支援的檔案類型和格式。
- 對於具有長文字的文件和資料集,建議您使用 資料準備指令碼。
Azure OpenAI 需要跨來源資源共用 (CORS) 才能存取您的儲存體帳戶。 如果您的 Azure Blob 儲存體資源尚未啟用 CORS,請選取 [開啟 CORS]。
選取您的 Azure AI 搜尋服務資源。
輸入新索引的名稱。
選取確認使用 Azure AI 搜尋服務的計費效果的複選框。
選取 下一步。
在 [上傳檔案 ] 頁面上:
選取 [瀏覽] 以取得檔案,然後選取您自己的資料或您從 必要條件下載的範例資料。
選取 [上傳檔案]。
選取 下一步。
在 資料管理 頁面上:
選擇是否要為索引啟用 語意搜尋或向量搜尋 。
選取 下一步。
在 [資料連線 ] 頁面上:
選擇是否要使用 系統指派的受控識別 或 API 金鑰進行驗證。
選取 下一步。
檢閱您的設定,然後選取 儲存並關閉。
您現在可以與模型聊天,模型會使用您的資料來建構回應。
擷取資源資訊
您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式。 本快速入門假設您已將資料上傳至 Azure Blob 儲存體帳戶,並已建立 Azure AI 搜尋服務索引。 請參閱使用 Microsoft Foundry 入口新增您的資料。
| 變數名稱 | 價值觀 |
|---|---|
AZURE_OPENAI_ENDPOINT |
從 Azure 入口網站查看您的 Azure OpenAI 資源時,可以在 [金鑰與端點] 區段中找到此值。 範例端點為:https://my-resource.openai.azure.com。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 此值可在 Azure 入口網站的 [資源管理>部署 ] 下找到。 |
AZURE_AI_SEARCH_ENDPOINT |
從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
AZURE_AI_SEARCH_INDEX |
此值會對應至您建立來儲存資料的索引名稱。 從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
設定
建立新的資料夾
use-data-quickstart,並使用下列命令移至快速入門資料夾:mkdir use-data-quickstart && cd use-data-quickstart使用下列命令建立
package.json:npm init -y請使用下列命令將
package.json更新為 ECMAScript。npm pkg set type=module使用以下指令安裝適用於 JavaScript 的 OpenAI 客戶端庫:
npm install openai若要設定建議的無密碼驗證:
npm install @azure/identity
新增 TypeScript 程式碼
使用下列程式代碼,建立
index.ts檔案。import { AzureOpenAI } from "openai"; import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity"; import "@azure/openai/types"; // Set the Azure and AI Search values from environment variables const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint"; const searchEndpoint = process.env.AZURE_AI_SEARCH_ENDPOINT || "Your search endpoint"; const searchIndex = process.env.AZURE_AI_SEARCH_INDEX || "Your search index"; // keyless authentication const credential = new DefaultAzureCredential(); const scope = "https://cognitiveservices.azure.com/.default"; const azureADTokenProvider = getBearerTokenProvider(credential, scope); // Required Azure OpenAI deployment name and API version const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "gpt-4"; const apiVersion = process.env.OPENAI_API_VERSION || "2024-07-01-preview"; function getClient(): AzureOpenAI { return new AzureOpenAI({ endpoint, azureADTokenProvider, deployment: deploymentName, apiVersion, }); } async function main() { const client = getClient(); const messages = [ { role: "user", content: "What are my available health plans?" }, ]; console.log(`Message: ${messages.map((m) => m.content).join("\n")}`); const events = await client.chat.completions.create({ stream: true, messages: [ { role: "user", content: "What's the most common feedback we received from our customers about the product?", }, ], max_tokens: 128, model: "", data_sources: [ { type: "azure_search", parameters: { endpoint: searchEndpoint, index_name: searchIndex, authentication: { type: "api_key", key: searchKey, }, }, }, ], }); let response = ""; for await (const event of events) { for (const choice of event.choices) { const newText = choice.delta?.content; if (newText) { response += newText; // To see streaming results as they arrive, uncomment line below // console.log(newText); } } } console.log(response); } main().catch((err) => { console.error("The sample encountered an error:", err); });建立檔案
tsconfig.json以轉譯 TypeScript 程式代碼,並複製 ECMAScript 的下列程式代碼。{ "compilerOptions": { "module": "NodeNext", "target": "ES2022", // Supports top-level await "moduleResolution": "NodeNext", "skipLibCheck": true, // Avoid type errors from node_modules "strict": true // Enable strict type-checking options }, "include": ["*.ts"] }從 TypeScript 轉譯為 JavaScript。
tsc使用下列命令登入 Azure:
az login使用下列命令執行程式碼:
node index.js
這很重要
在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需認證安全性的詳細資訊,請參閱此 安全性 文章。
輸出
Message: What are my available health plans?
The available health plans in the Contoso Electronics plan and benefit packages are the Northwind Health Plus and Northwind Standard plans.
先決條件
- Azure OpenAI
- Azure Blob 儲存服務
- Azure AI 搜尋服務
- 部署在支持區域中且具有支援模型的Azure OpenAI 資源。
- 請確定您已至少獲派 Azure OpenAI 資源的 認知服務參與者 角色。
- 如果您沒有自己的數據,請從 GitHub 下載範例數據。
這些連結會參考適用於 Python 的 OpenAI API。 目前還沒有針對 Azure 的 OpenAI Python SDK。 學習如何在 OpenAI 服務與 Azure OpenAI 之間切換。
使用 Microsoft Foundry 入口網站新增您的資料
小提示
或者,您可以使用 Azure 開發人員 CLI 以程式設計方式建立 Azure OpenAI On Your Data 所需的資源。
若要使用入口網站新增資料:
-
登入 Microsoft Foundry。 確定新鑄造廠的開關是關閉的。 這些步驟指的是 Foundry (傳統版)。
選取您的 Azure OpenAI 資源。 如果你有 Foundry 資源,你可以 建立一個 Foundry 專案。
從左窗格中,選取 [Playgrounds>聊天]。
在 [設定] 窗格中,選取您的模型部署。
選取 新增您的資料> 新增資料來源。
在 資料來源 頁面上:
在 [選取資料來源] 底下,選取 [上傳檔案 (預覽版)]。
小提示
- 此選項需要 Azure Blob 儲存體資源和 Azure AI 搜尋服務資源,才能存取和編製資料索引。 如需詳細資訊,請參閱資料來源 選項 和 支援的檔案類型和格式。
- 對於具有長文字的文件和資料集,建議您使用 資料準備指令碼。
Azure OpenAI 需要跨來源資源共用 (CORS) 才能存取您的儲存體帳戶。 如果您的 Azure Blob 儲存體資源尚未啟用 CORS,請選取 [開啟 CORS]。
選取您的 Azure AI 搜尋服務資源。
輸入新索引的名稱。
選取確認使用 Azure AI 搜尋服務的計費效果的複選框。
選取 下一步。
在 [上傳檔案 ] 頁面上:
選取 [瀏覽] 以取得檔案,然後選取您自己的資料或您從 必要條件下載的範例資料。
選取 [上傳檔案]。
選取 下一步。
在 資料管理 頁面上:
選擇是否要為索引啟用 語意搜尋或向量搜尋 。
選取 下一步。
在 [資料連線 ] 頁面上:
選擇是否要使用 系統指派的受控識別 或 API 金鑰進行驗證。
選取 下一步。
檢閱您的設定,然後選取 儲存並關閉。
您現在可以與模型聊天,模型會使用您的資料來建構回應。
擷取資源資訊
您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式。 本快速入門假設您已將資料上傳至 Azure Blob 儲存體帳戶,並已建立 Azure AI 搜尋服務索引。 請參閱使用 Microsoft Foundry 入口新增您的資料。
| 變數名稱 | 價值觀 |
|---|---|
AZURE_OPENAI_ENDPOINT |
從 Azure 入口網站查看您的 Azure OpenAI 資源時,可以在 [金鑰與端點] 區段中找到此值。 範例端點為:https://my-resource.openai.azure.com。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 此值可在 Azure 入口網站的 [資源管理>部署 ] 下找到。 |
AZURE_AI_SEARCH_ENDPOINT |
從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
AZURE_AI_SEARCH_INDEX |
此值會對應至您建立來儲存資料的索引名稱。 從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
建立 Python 環境
- 為您的專案建立名為 openai-python 的新資料夾,以及名為 main.py 的新 Python 程式代碼檔案。 變更為該目錄:
mkdir openai-python
cd openai-python
- 安裝下列 Python 程式庫:
pip install openai
pip install python-dotenv
建立 Python 應用程式
- 從項目目錄中,開啟 main.py 檔案,然後新增下列程序代碼:
import os
import openai
import dotenv
dotenv.load_dotenv()
endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
api_key = os.environ.get("AZURE_OPENAI_API_KEY")
deployment = os.environ.get("AZURE_OPENAI_DEPLOYMENT_NAME")
client = openai.AzureOpenAI(
azure_endpoint=endpoint,
api_key=api_key,
api_version="2024-10-21",
)
completion = client.chat.completions.create(
model=deployment,
messages=[
{
"role": "user",
"content": "What are my available health plans?",
},
],
extra_body={
"data_sources":[
{
"type": "azure_search",
"parameters": {
"endpoint": os.environ["AZURE_AI_SEARCH_ENDPOINT"],
"index_name": os.environ["AZURE_AI_SEARCH_INDEX"],
"authentication": {
"type": "api_key",
"key": os.environ["AZURE_AI_SEARCH_API_KEY"],
}
}
}
],
}
)
print(f"{completion.choices[0].message.role}: {completion.choices[0].message.content}")
這很重要
在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需認證安全性的詳細資訊,請參閱此 安全性 文章。
- 執行以下 命令:
python main.py
應用程式會以 JSON 格式列印適用於許多案例的回應。 其中包含來自所上傳檔案之查詢和引文的解答。
先決條件
- Azure OpenAI
- Azure Blob 儲存服務
- Azure AI 搜尋服務
- 部署在支持區域中且具有支援模型的Azure OpenAI 資源。
- 請確定您已至少獲派 Azure OpenAI 資源的 認知服務參與者 角色。
- 如果您沒有自己的數據,請從 GitHub 下載範例數據。
使用 Microsoft Foundry 入口網站新增您的資料
小提示
或者,您可以使用 Azure 開發人員 CLI 以程式設計方式建立 Azure OpenAI On Your Data 所需的資源。
若要使用入口網站新增資料:
-
登入 Microsoft Foundry。 確定新鑄造廠的開關是關閉的。 這些步驟指的是 Foundry (傳統版)。
選取您的 Azure OpenAI 資源。 如果你有 Foundry 資源,你可以 建立一個 Foundry 專案。
從左窗格中,選取 [Playgrounds>聊天]。
在 [設定] 窗格中,選取您的模型部署。
選取 新增您的資料> 新增資料來源。
在 資料來源 頁面上:
在 [選取資料來源] 底下,選取 [上傳檔案 (預覽版)]。
小提示
- 此選項需要 Azure Blob 儲存體資源和 Azure AI 搜尋服務資源,才能存取和編製資料索引。 如需詳細資訊,請參閱資料來源 選項 和 支援的檔案類型和格式。
- 對於具有長文字的文件和資料集,建議您使用 資料準備指令碼。
Azure OpenAI 需要跨來源資源共用 (CORS) 才能存取您的儲存體帳戶。 如果您的 Azure Blob 儲存體資源尚未啟用 CORS,請選取 [開啟 CORS]。
選取您的 Azure AI 搜尋服務資源。
輸入新索引的名稱。
選取確認使用 Azure AI 搜尋服務的計費效果的複選框。
選取 下一步。
在 [上傳檔案 ] 頁面上:
選取 [瀏覽] 以取得檔案,然後選取您自己的資料或您從 必要條件下載的範例資料。
選取 [上傳檔案]。
選取 下一步。
在 資料管理 頁面上:
選擇是否要為索引啟用 語意搜尋或向量搜尋 。
選取 下一步。
在 [資料連線 ] 頁面上:
選擇是否要使用 系統指派的受控識別 或 API 金鑰進行驗證。
選取 下一步。
檢閱您的設定,然後選取 儲存並關閉。
您現在可以與模型聊天,模型會使用您的資料來建構回應。
擷取資源資訊
您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式。 本快速入門假設您已將資料上傳至 Azure Blob 儲存體帳戶,並已建立 Azure AI 搜尋服務索引。 請參閱使用 Microsoft Foundry 入口新增您的資料。
| 變數名稱 | 價值觀 |
|---|---|
AZURE_OPENAI_ENDPOINT |
從 Azure 入口網站查看您的 Azure OpenAI 資源時,可以在 [金鑰與端點] 區段中找到此值。 範例端點為:https://my-resource.openai.azure.com。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 此值可在 Azure 入口網站的 [資源管理>部署 ] 下找到。 |
AZURE_AI_SEARCH_ENDPOINT |
從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
AZURE_AI_SEARCH_INDEX |
此值會對應至您建立來儲存資料的索引名稱。 從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
範例 PowerShell 命令
Azure OpenAI 聊天模型已最佳化,以使用格式化為交談的輸入。
messages 變數會在系統、使用者、工具和助理所描述的交談中傳遞具有不同角色的字典陣列。
dataSources 變數會連線到您的 Azure 認知搜尋索引,並讓 Azure OpenAI 模型使用您的資料回應。
若要觸發模型的回應,您應該以使用者訊息結尾,指出輪到助理回應。
小提示
您可以使用數個參數來變更模型的回應,例如 temperature 或 top_p。 如需詳細資訊,請參閱 參考檔 。
# Azure OpenAI metadata variables
$openai = @{
api_key = $Env:AZURE_OPENAI_API_KEY
api_base = $Env:AZURE_OPENAI_ENDPOINT # your endpoint should look like the following https://YOUR_RESOURCE_NAME.openai.azure.com/
api_version = '2023-07-01-preview' # this may change in the future
name = 'YOUR-DEPLOYMENT-NAME-HERE' #This will correspond to the custom name you chose for your deployment when you deployed a model.
}
$acs = @{
search_endpoint = 'YOUR ACS ENDPOINT' # your endpoint should look like the following https://YOUR_RESOURCE_NAME.search.windows.net/
search_key = 'YOUR-ACS-KEY-HERE' # or use the Get-Secret cmdlet to retrieve the value
search_index = 'YOUR-INDEX-NAME-HERE' # the name of your ACS index
}
# Completion text
$body = @{
dataSources = @(
@{
type = 'AzureCognitiveSearch'
parameters = @{
endpoint = $acs.search_endpoint
key = $acs.search_key
indexName = $acs.search_index
}
}
)
messages = @(
@{
role = 'user'
content = 'What are my available health plans?'
}
)
} | convertto-json -depth 5
# Header for authentication
$headers = [ordered]@{
'api-key' = $openai.api_key
}
# Send a completion call to generate an answer
$url = "$($openai.api_base)/openai/deployments/$($openai.name)/extensions/chat/completions?api-version=$($openai.api_version)"
$response = Invoke-RestMethod -Uri $url -Headers $headers -Body $body -Method Post -ContentType 'application/json'
return $response.choices.messages[1].content
範例輸出
The available health plans in the Contoso Electronics plan and benefit packages are the Northwind Health Plus and Northwind Standard plans.
這很重要
針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 使用 Azure Key Vault 的 PowerShell 秘密管理。 如需認證安全性的詳細資訊,請參閱此 安全性 文章。
使用 Web 應用程式與模型聊天
要開始與使用 Azure OpenAI 模型的互動,你可以使用 Microsoft Foundry 入口網站 或我們在 GitHub 提供的範例程式碼部署網頁應用程式。 此應用程式會使用 Azure 應用程式服務進行部署,並提供用來傳送查詢的使用者介面。 此應用程式可由使用您的資料的 Azure OpenAI 模型,或不使用您的資料的模型使用。 如需需求、設定和部署的指示,請參閱存放庫中的讀我檔案。 您可以選擇性地自定義 Web 應用程式的 前端和後端邏輯 ,方法是對原始程式碼進行變更。
先決條件
- Azure OpenAI
- Azure Blob 儲存服務
- Azure AI 搜尋服務
- 部署在支持區域中且具有支援模型的Azure OpenAI 資源。
- 請確定您已至少獲派 Azure OpenAI 資源的 認知服務參與者 角色。
- 如果您沒有自己的數據,請從 GitHub 下載範例數據。
使用 Microsoft Foundry 入口網站新增您的資料
小提示
或者,您可以使用 Azure 開發人員 CLI 以程式設計方式建立 Azure OpenAI On Your Data 所需的資源。
若要使用入口網站新增資料:
-
登入 Microsoft Foundry。 確定新鑄造廠的開關是關閉的。 這些步驟指的是 Foundry (傳統版)。
選取您的 Azure OpenAI 資源。 如果你有 Foundry 資源,你可以 建立一個 Foundry 專案。
從左窗格中,選取 [Playgrounds>聊天]。
在 [設定] 窗格中,選取您的模型部署。
選取 新增您的資料> 新增資料來源。
在 資料來源 頁面上:
在 [選取資料來源] 底下,選取 [上傳檔案 (預覽版)]。
小提示
- 此選項需要 Azure Blob 儲存體資源和 Azure AI 搜尋服務資源,才能存取和編製資料索引。 如需詳細資訊,請參閱資料來源 選項 和 支援的檔案類型和格式。
- 對於具有長文字的文件和資料集,建議您使用 資料準備指令碼。
Azure OpenAI 需要跨來源資源共用 (CORS) 才能存取您的儲存體帳戶。 如果您的 Azure Blob 儲存體資源尚未啟用 CORS,請選取 [開啟 CORS]。
選取您的 Azure AI 搜尋服務資源。
輸入新索引的名稱。
選取確認使用 Azure AI 搜尋服務的計費效果的複選框。
選取 下一步。
在 [上傳檔案 ] 頁面上:
選取 [瀏覽] 以取得檔案,然後選取您自己的資料或您從 必要條件下載的範例資料。
選取 [上傳檔案]。
選取 下一步。
在 資料管理 頁面上:
選擇是否要為索引啟用 語意搜尋或向量搜尋 。
選取 下一步。
在 [資料連線 ] 頁面上:
選擇是否要使用 系統指派的受控識別 或 API 金鑰進行驗證。
選取 下一步。
檢閱您的設定,然後選取 儲存並關閉。
您現在可以與模型聊天,模型會使用您的資料來建構回應。
Microsoft Entra ID 必要條件
針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:
- 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
- 將
Cognitive Services User角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。
設定
建立新的資料夾
dall-e-quickstart,並使用下列命令移至快速入門資料夾:mkdir dall-e-quickstart && cd dall-e-quickstart如需使用 Microsoft Entra ID 的建議 無密鑰驗證,請使用下列命令登入 Azure:
az login
擷取資源資訊
您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式。 本快速入門假設您已將資料上傳至 Azure Blob 儲存體帳戶,並已建立 Azure AI 搜尋服務索引。 請參閱使用 Microsoft Foundry 入口新增您的資料。
| 變數名稱 | 價值觀 |
|---|---|
AZURE_OPENAI_ENDPOINT |
從 Azure 入口網站查看您的 Azure OpenAI 資源時,可以在 [金鑰與端點] 區段中找到此值。 範例端點為:https://my-resource.openai.azure.com。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 此值可在 Azure 入口網站的 [資源管理>部署 ] 下找到。 |
AZURE_AI_SEARCH_ENDPOINT |
從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
AZURE_AI_SEARCH_INDEX |
此值會對應至您建立來儲存資料的索引名稱。 從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
執行快速入門
本快速入門中的範例程式代碼會針對建議的無密鑰驗證使用 Microsoft Entra 識別碼。 如果您要使用 API 金鑰,可以將 實作 NewDefaultAzureCredential 取代為 NewKeyCredential。
azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")
credential, err := azidentity.NewDefaultAzureCredential(nil)
client, err := azopenai.NewClient(azureOpenAIEndpoint, credential, nil)
若要執行範例:
建立名為 quickstart.go 的新檔案。 將下列程式代碼複製到 quickstart.go 檔案。
package main import ( "context" "fmt" "log" "os" "github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" ) func main() { azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT") credential, err := azidentity.NewDefaultAzureCredential(nil) client, err := azopenai.NewClient(azureOpenAIEndpoint, credential, nil) modelDeploymentID := os.Getenv("AZURE_OPENAI_DEPLOYMENT_NAME") // Azure AI Search configuration searchIndex := os.Getenv("AZURE_AI_SEARCH_INDEX") searchEndpoint := os.Getenv("AZURE_AI_SEARCH_ENDPOINT") searchAPIKey := os.Getenv("AZURE_AI_SEARCH_API_KEY") if modelDeploymentID == "" || azureOpenAIEndpoint == "" || searchIndex == "" || searchEndpoint == "" || searchAPIKey == "" { fmt.Fprintf(os.Stderr, "Skipping example, environment variables missing\n") return } client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, credential, nil) if err != nil { // Implement application specific error handling logic. log.Printf("ERROR: %s", err) return } resp, err := client.GetChatCompletions(context.TODO(), azopenai.ChatCompletionsOptions{ Messages: []azopenai.ChatRequestMessageClassification{ &azopenai.ChatRequestUserMessage{Content: azopenai.NewChatRequestUserMessageContent("What are my available health plans?")}, }, MaxTokens: to.Ptr[int32](512), AzureExtensionsOptions: []azopenai.AzureChatExtensionConfigurationClassification{ &azopenai.AzureSearchChatExtensionConfiguration{ // This allows Azure OpenAI to use an Azure AI Search index. // Answers are based on the model's pretrained knowledge // and the latest information available in the designated data source. Parameters: &azopenai.AzureSearchChatExtensionParameters{ Endpoint: &searchEndpoint, IndexName: &searchIndex, Authentication: &azopenai.OnYourDataAPIKeyAuthenticationOptions{ Key: &searchAPIKey, }, }, }, }, DeploymentName: &modelDeploymentID, }, nil) if err != nil { // Implement application specific error handling logic. log.Printf("ERROR: %s", err) return } fmt.Fprintf(os.Stderr, "Extensions Context Role: %s\nExtensions Context (length): %d\n", *resp.Choices[0].Message.Role, len(*resp.Choices[0].Message.Content)) fmt.Fprintf(os.Stderr, "ChatRole: %s\nChat content: %s\n", *resp.Choices[0].Message.Role, *resp.Choices[0].Message.Content, ) }執行下列命令以建立新的 Go 模組:
go mod init quickstart.go執行
go mod tidy以安裝必要的相依性:go mod tidy執行下列命令以執行範例:
go run quickstart.go
應用程式會列印回應,包括來自所上傳檔案的查詢和引文答案。
先決條件
- Azure OpenAI
- Azure Blob 儲存服務
- Azure AI 搜尋服務
- 部署在支持區域中且具有支援模型的Azure OpenAI 資源。
- 請確定您已至少獲派 Azure OpenAI 資源的 認知服務參與者 角色。
- 如果您沒有自己的數據,請從 GitHub 下載範例數據。
使用 Microsoft Foundry 入口網站新增您的資料
小提示
或者,您可以使用 Azure 開發人員 CLI 以程式設計方式建立 Azure OpenAI On Your Data 所需的資源。
若要使用入口網站新增資料:
-
登入 Microsoft Foundry。 確定新鑄造廠的開關是關閉的。 這些步驟指的是 Foundry (傳統版)。
選取您的 Azure OpenAI 資源。 如果你有 Foundry 資源,你可以 建立一個 Foundry 專案。
從左窗格中,選取 [Playgrounds>聊天]。
在 [設定] 窗格中,選取您的模型部署。
選取 新增您的資料> 新增資料來源。
在 資料來源 頁面上:
在 [選取資料來源] 底下,選取 [上傳檔案 (預覽版)]。
小提示
- 此選項需要 Azure Blob 儲存體資源和 Azure AI 搜尋服務資源,才能存取和編製資料索引。 如需詳細資訊,請參閱資料來源 選項 和 支援的檔案類型和格式。
- 對於具有長文字的文件和資料集,建議您使用 資料準備指令碼。
Azure OpenAI 需要跨來源資源共用 (CORS) 才能存取您的儲存體帳戶。 如果您的 Azure Blob 儲存體資源尚未啟用 CORS,請選取 [開啟 CORS]。
選取您的 Azure AI 搜尋服務資源。
輸入新索引的名稱。
選取確認使用 Azure AI 搜尋服務的計費效果的複選框。
選取 下一步。
在 [上傳檔案 ] 頁面上:
選取 [瀏覽] 以取得檔案,然後選取您自己的資料或您從 必要條件下載的範例資料。
選取 [上傳檔案]。
選取 下一步。
在 資料管理 頁面上:
選擇是否要為索引啟用 語意搜尋或向量搜尋 。
選取 下一步。
在 [資料連線 ] 頁面上:
選擇是否要使用 系統指派的受控識別 或 API 金鑰進行驗證。
選取 下一步。
檢閱您的設定,然後選取 儲存並關閉。
您現在可以與模型聊天,模型會使用您的資料來建構回應。
擷取資源資訊
您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式。 本快速入門假設您已將資料上傳至 Azure Blob 儲存體帳戶,並已建立 Azure AI 搜尋服務索引。 請參閱使用 Microsoft Foundry 入口新增您的資料。
| 變數名稱 | 價值觀 |
|---|---|
AZURE_OPENAI_ENDPOINT |
從 Azure 入口網站查看您的 Azure OpenAI 資源時,可以在 [金鑰與端點] 區段中找到此值。 範例端點為:https://my-resource.openai.azure.com。 |
AZURE_OPENAI_DEPLOYMENT_NAME |
此值會對應至您在部署模型時為部署選擇的自訂名稱。 此值可在 Azure 入口網站的 [資源管理>部署 ] 下找到。 |
AZURE_AI_SEARCH_ENDPOINT |
從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
AZURE_AI_SEARCH_INDEX |
此值會對應至您建立來儲存資料的索引名稱。 從 Azure 入口網站查看您的 Azure AI 搜尋服務資源時,可以在 [概觀] 區段中找到此值。 |
範例 cURL 命令
Azure OpenAI 聊天模型已最佳化,以使用格式化為交談的輸入。
messages 變數會在系統、使用者、工具和助理所描述的交談中傳遞具有不同角色的字典陣列。
dataSources 變數會連線到您的 Azure AI 搜尋服務索引,並讓 Azure OpenAI 模型使用您的資料回應。
若要觸發模型的回應,您應該以使用者訊息結尾,指出輪到助理回應。
小提示
您可以使用數個參數來變更模型的回應,例如 temperature 或 top_p。 如需詳細資訊,請參閱 參考檔 。
curl -i -X POST $AZURE_OPENAI_ENDPOINT/openai/deployments/$AZURE_OPENAI_DEPLOYMENT_NAME/chat/completions?api-version=2024-10-21 \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d \
'
{
"data_sources": [
{
"type": "azure_search",
"parameters": {
"endpoint": "'$AZURE_AI_SEARCH_ENDPOINT'",
"index_name": "'$AZURE_AI_SEARCH_INDEX'",
"authentication": {
"type": "api_key",
"key": "'$AZURE_AI_SEARCH_API_KEY'"
}
}
}
],
"messages": [
{
"role": "user",
"content": "What are my available health plans?"
}
]
}
'
範例輸出
{
"id": "12345678-1a2b-3c4e5f-a123-12345678abcd",
"model": "gpt-4",
"created": 1709835345,
"object": "extensions.chat.completion",
"choices": [
{
"index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "The available health plans in the Contoso Electronics plan and benefit packages are the Northwind Health Plus and Northwind Standard plans. [doc1].",
"end_turn": true,
"context": {
"citations": [
{
"content": "...",
"title": "...",
"url": "https://mysearch.blob.core.windows.net/xyz/001.txt",
"filepath": "001.txt",
"chunk_id": "0"
}
],
"intent": "[\"Available health plans\"]"
}
}
}
],
"usage": {
"prompt_tokens": 3779,
"completion_tokens": 105,
"total_tokens": 3884
},
"system_fingerprint": "fp_65792305e4"
}
使用 Web 應用程式與模型聊天
要開始與使用 Azure OpenAI 模型的互動,你可以使用 Microsoft Foundry 入口網站 或我們在 GitHub 提供的範例程式碼部署網頁應用程式。 此應用程式會使用 Azure 應用程式服務進行部署,並提供用來傳送查詢的使用者介面。 此應用程式可由使用您的資料的 Azure OpenAI 模型,或不使用您的資料的模型使用。 如需需求、設定和部署的指示,請參閱存放庫中的讀我檔案。 您可以選擇性地自定義 Web 應用程式的 前端和後端邏輯 ,方法是對原始程式碼進行變更。
清理資源
如果您想要清除和移除 Azure OpenAI 或 Azure AI 搜尋服務資源,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。