快速入門:使用文件摘要和交談摘要

重要

我們的預覽區域瑞典中部展示我們以 GPT 模型為基礎的最新且不斷演進的 LLM 微調技術。 歡迎在瑞典中部地區使用語言資源試用。

交談摘要只能使用:

  • REST API
  • Python
  • C#

使用此快速入門,使用適用於 .NET 的用戶端連結庫建立文字摘要應用程式。 在下列範例中,您將建立 C# 應用程式,以摘要文件或文字為基礎的客戶服務交談。

提示

您可以使用 Language Studio 來嘗試文件摘要,而不需要撰寫程式代碼。

必要條件

  • Azure 訂用帳戶 - 免費建立一個訂用帳戶
  • Visual Studio IDE
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立語言資源,以取得您的密鑰和端點。 部署之後,請選取 [移至資源]。
    • 您需要從您建立的資源取得密鑰和端點,才能將應用程式連線到 API。 您稍後會在快速入門中將金鑰和端點貼到程式碼中。
    • 您可以使用免費定價層 (Free F0) 來試用服務,稍後再升級至生產環境的付費層。
  • 若要使用分析功能,您需要具有標準 (S) 定價層的語言資源。

設定

建立環境變數

您的應用程式必須經過驗證,才能傳送 API 要求。 針對生產環境,請使用安全的方式來儲存和存取您的認證。 在此範例中,您會將認證寫入執行應用程式的本機計算機上環境變數。

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

若要設定語言資源密鑰的環境變數,請開啟控制台視窗,並遵循作業系統和開發環境的指示。

  1. 若要設定 LANGUAGE_KEY 環境變數,請將 取代 your-key 為您資源的其中一個密鑰。
  2. 若要設定 LANGUAGE_ENDPOINT 環境變數,請將 取代 your-endpoint 為您資源的端點。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果您只需要存取目前執行控制台中的環境變數,您可以使用 來設定環境變數 set ,而不是 setx

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例之前重新啟動 Visual Studio。

建立新的 .NET Core 應用程式

使用 Visual Studio IDE,建立新的 .NET Core 控制台應用程式。 這會建立 "Hello World" 專案,內含單一 C# 來源檔案:program.cs。

以滑鼠右鍵按兩下 方案總管 中的解決方案,然後選取 [管理 NuGet 套件],以安裝客戶端連結庫。 開啟的套件管理員中,選取 [ 瀏覽 ] 並搜尋 Azure.AI.TextAnalytics。 請確定 已核取 [包含發行前版本 ]。 選取 [版本 5.3.0],然後 選取 [安裝]。 您也可以使用 封裝管理員 主控台

程式碼範例

將下列程式代碼複製到您的 program.cs 檔案。 然後執行程式碼。

重要

前往 Azure 入口網站。 如果您在成功部署必要條件一節中建立的語言資源,請按兩下 [後續步驟] 底下的 [移至資源] 按鈕。 您可以在 [資源管理] 底下瀏覽至資源的 [金鑰和端點] 頁面,以尋找您的金鑰和端點

重要

當您完成時,請記得從程式碼中移除密鑰,且絕不會公開發佈。 針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

using Azure;
using System;
using Azure.AI.TextAnalytics;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace Example
{
    class Program
    {
        // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
        static string languageKey = Environment.GetEnvironmentVariable("LANGUAGE_KEY");
        static string languageEndpoint = Environment.GetEnvironmentVariable("LANGUAGE_ENDPOINT");

        private static readonly AzureKeyCredential credentials = new AzureKeyCredential(languageKey);
        private static readonly Uri endpoint = new Uri(languageEndpoint);

        // Example method for summarizing text
        static async Task TextSummarizationExample(TextAnalyticsClient client)
        {
            string document = @"The extractive summarization feature uses natural language processing techniques to locate key sentences in an unstructured text document. 
                These sentences collectively convey the main idea of the document. This feature is provided as an API for developers. 
                They can use it to build intelligent solutions based on the relevant information extracted to support various use cases. 
                Extractive summarization supports several languages. It is based on pretrained multilingual transformer models, part of our quest for holistic representations. 
                It draws its strength from transfer learning across monolingual and harness the shared nature of languages to produce models of improved quality and efficiency." ;
        
            // Prepare analyze operation input. You can add multiple documents to this list and perform the same
            // operation to all of them.
            var batchInput = new List<string>
            {
                document
            };
        
            TextAnalyticsActions actions = new TextAnalyticsActions()
            {
                ExtractSummaryActions = new List<ExtractSummaryAction>() { new ExtractSummaryAction() }
            };
        
            // Start analysis process.
            AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(batchInput, actions);
            await operation.WaitForCompletionAsync();
            // View operation status.
            Console.WriteLine($"AnalyzeActions operation has completed");
            Console.WriteLine();
        
            Console.WriteLine($"Created On   : {operation.CreatedOn}");
            Console.WriteLine($"Expires On   : {operation.ExpiresOn}");
            Console.WriteLine($"Id           : {operation.Id}");
            Console.WriteLine($"Status       : {operation.Status}");
        
            Console.WriteLine();
            // View operation results.
            await foreach (AnalyzeActionsResult documentsInPage in operation.Value)
            {
                IReadOnlyCollection<ExtractSummaryActionResult> summaryResults = documentsInPage.ExtractSummaryResults;
        
                foreach (ExtractSummaryActionResult summaryActionResults in summaryResults)
                {
                    if (summaryActionResults.HasError)
                    {
                        Console.WriteLine($"  Error!");
                        Console.WriteLine($"  Action error code: {summaryActionResults.Error.ErrorCode}.");
                        Console.WriteLine($"  Message: {summaryActionResults.Error.Message}");
                        continue;
                    }
        
                    foreach (ExtractSummaryResult documentResults in summaryActionResults.DocumentsResults)
                    {
                        if (documentResults.HasError)
                        {
                            Console.WriteLine($"  Error!");
                            Console.WriteLine($"  Document error code: {documentResults.Error.ErrorCode}.");
                            Console.WriteLine($"  Message: {documentResults.Error.Message}");
                            continue;
                        }
        
                        Console.WriteLine($"  Extracted the following {documentResults.Sentences.Count} sentence(s):");
                        Console.WriteLine();
        
                        foreach (SummarySentence sentence in documentResults.Sentences)
                        {
                            Console.WriteLine($"  Sentence: {sentence.Text}");
                            Console.WriteLine();
                        }
                    }
                }
            }
        
        }

        static async Task Main(string[] args)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            await TextSummarizationExample(client);
        }
    }
}

輸出

AnalyzeActions operation has completed

Created On   : 9/16/2021 8:04:27 PM +00:00
Expires On   : 9/17/2021 8:04:27 PM +00:00
Id           : 2e63fa58-fbaa-4be9-a700-080cff098f91
Status       : succeeded

Extracted the following 3 sentence(s):

Sentence: The extractive summarization feature in uses natural language processing techniques to locate key sentences in an unstructured text document.

Sentence: This feature is provided as an API for developers.

Sentence: They can use it to build intelligent solutions based on the relevant information extracted to support various use cases.

參考文件 | 更多樣本 | 套件 (Maven) | 程式庫原始程式碼

使用此快速入門,使用適用於 Java 的用戶端連結庫建立文字摘要應用程式。 在下列範例中,您將建立可摘要文件的 JAVA 應用程式。

提示

您可以使用 Language Studio 來嘗試文件摘要,而不需要撰寫程式代碼。

必要條件

設定

新增 用戶端程式庫

在慣用的 IDE 或開發環境中建立 Maven 專案。 然後將下列相依性新增至專案的 pom.xml 檔案。 您可以在在線找到其他建置工具的實作語法

<dependencies>
     <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-textanalytics</artifactId>
        <version>5.3.0</version>
    </dependency>
</dependencies>

建立環境變數

您的應用程式必須經過驗證,才能傳送 API 要求。 針對生產環境,請使用安全的方式來儲存和存取您的認證。 在此範例中,您會將認證寫入執行應用程式的本機計算機上環境變數。

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

若要設定語言資源密鑰的環境變數,請開啟控制台視窗,並遵循作業系統和開發環境的指示。

  1. 若要設定 LANGUAGE_KEY 環境變數,請將 取代 your-key 為您資源的其中一個密鑰。
  2. 若要設定 LANGUAGE_ENDPOINT 環境變數,請將 取代 your-endpoint 為您資源的端點。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果您只需要存取目前執行控制台中的環境變數,您可以使用 來設定環境變數 set ,而不是 setx

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例之前重新啟動 Visual Studio。

程式碼範例

建立名為 Example.java的 Java 檔案。 開啟檔案並複製下列程序代碼。 然後執行程式碼。

重要

前往 Azure 入口網站。 如果您在成功部署必要條件一節中建立的語言資源,請按兩下 [後續步驟] 底下的 [移至資源] 按鈕。 您可以在 [資源管理] 底下瀏覽至資源的 [金鑰和端點] 頁面,以尋找您的金鑰和端點

重要

當您完成時,請記得從程式碼中移除密鑰,且絕不會公開發佈。 針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

import com.azure.core.credential.AzureKeyCredential;
import com.azure.ai.textanalytics.models.*;
import com.azure.ai.textanalytics.TextAnalyticsClientBuilder;
import com.azure.ai.textanalytics.TextAnalyticsClient;
import java.util.ArrayList;
import java.util.List;
import com.azure.core.util.polling.SyncPoller;
import com.azure.ai.textanalytics.util.*;

public class Example {

    // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
    private static String languageKey = System.getenv("LANGUAGE_KEY");
    private static String languageEndpoint = System.getenv("LANGUAGE_ENDPOINT");

    public static void main(String[] args) {
        TextAnalyticsClient client = authenticateClient(languageKey, languageEndpoint);
        summarizationExample(client);
    }
    // Method to authenticate the client object with your key and endpoint
    static TextAnalyticsClient authenticateClient(String key, String endpoint) {
        return new TextAnalyticsClientBuilder()
                .credential(new AzureKeyCredential(key))
                .endpoint(endpoint)
                .buildClient();
    }
    // Example method for summarizing text
    static void summarizationExample(TextAnalyticsClient client) {
        List<String> documents = new ArrayList<>();
        documents.add(
                "The extractive summarization feature uses natural language processing techniques "
                + "to locate key sentences in an unstructured text document. "
                + "These sentences collectively convey the main idea of the document. This feature is provided as an API for developers. "
                + "They can use it to build intelligent solutions based on the relevant information extracted to support various use cases. "
                + "Extractive summarization supports several languages. "
                + "It is based on pretrained multilingual transformer models, part of our quest for holistic representations. "
                + "It draws its strength from transfer learning across monolingual and harness the shared nature of languages "
                + "to produce models of improved quality and efficiency.");
    
        SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> syncPoller =
                client.beginAnalyzeActions(documents,
                        new TextAnalyticsActions().setDisplayName("{tasks_display_name}")
                                .setExtractSummaryActions(
                                        new ExtractSummaryAction()),
                        "en",
                        new AnalyzeActionsOptions());
    
        syncPoller.waitForCompletion();
    
        syncPoller.getFinalResult().forEach(actionsResult -> {
            System.out.println("Extractive Summarization action results:");
            for (ExtractSummaryActionResult actionResult : actionsResult.getExtractSummaryResults()) {
                if (!actionResult.isError()) {
                    for (ExtractSummaryResult documentResult : actionResult.getDocumentsResults()) {
                        if (!documentResult.isError()) {
                            System.out.println("\tExtracted summary sentences:");
                            for (SummarySentence summarySentence : documentResult.getSentences()) {
                                System.out.printf(
                                        "\t\t Sentence text: %s, length: %d, offset: %d, rank score: %f.%n",
                                        summarySentence.getText(), summarySentence.getLength(),
                                        summarySentence.getOffset(), summarySentence.getRankScore());
                            }
                        } else {
                            System.out.printf("\tCannot extract summary sentences. Error: %s%n",
                                    documentResult.getError().getMessage());
                        }
                    }
                } else {
                    System.out.printf("\tCannot execute Extractive Summarization action. Error: %s%n",
                            actionResult.getError().getMessage());
                }
            }
        });
    }
}

輸出

Extractive Summarization action results:
	Extracted summary sentences:
		 Sentence text: The extractive summarization feature uses natural language processing techniques to locate key sentences in an unstructured text document., length: 138, offset: 0, rank score: 1.000000.
		 Sentence text: This feature is provided as an API for developers., length: 50, offset: 206, rank score: 0.510000.
		 Sentence text: Extractive summarization supports several languages., length: 52, offset: 378, rank score: 0.410000.

參考檔 | 其他範例 | 套件 (npm) | 連結庫原始程式碼

使用本快速入門,建立具有用戶端連結庫的文字摘要應用程式以進行Node.js。 在下列範例中,您將建立可摘要文件的 JavaScript 應用程式。

提示

您可以使用 Language Studio 來嘗試文件摘要,而不需要撰寫程式代碼。

必要條件

  • Azure 訂用帳戶 - 免費建立一個訂用帳戶
  • Node.js v16 LTS
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立語言資源,以取得您的密鑰和端點。 部署之後,請選取 [移至資源]。
    • 您需要從您建立的資源取得密鑰和端點,才能將應用程式連線到 API。 您稍後會在快速入門中將金鑰和端點貼到下列程式代碼中。
    • 您可以使用免費定價層 (Free F0) 來試用服務,稍後再升級至生產環境的付費層。
  • 若要使用分析功能,您需要具有標準 (S) 定價層的語言資源。

設定

建立環境變數

您的應用程式必須經過驗證,才能傳送 API 要求。 針對生產環境,請使用安全的方式來儲存和存取您的認證。 在此範例中,您會將認證寫入執行應用程式的本機計算機上環境變數。

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

若要設定語言資源密鑰的環境變數,請開啟控制台視窗,並遵循作業系統和開發環境的指示。

  1. 若要設定 LANGUAGE_KEY 環境變數,請將 取代 your-key 為您資源的其中一個密鑰。
  2. 若要設定 LANGUAGE_ENDPOINT 環境變數,請將 取代 your-endpoint 為您資源的端點。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果您只需要存取目前執行控制台中的環境變數,您可以使用 來設定環境變數 set ,而不是 setx

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例之前重新啟動 Visual Studio。

建立新的Node.js應用程式

在主控台視窗中(例如 cmd、PowerShell 或 Bash),為您的應用程式建立新的目錄,然後流覽至它。

mkdir myapp 

cd myapp

npm init執行 命令以使用 package.json 檔案建立節點應用程式。

npm init

安裝客戶端連結庫

安裝 npm 套件:

npm install --save @azure/ai-language-text@1.1.0

程式碼範例

開啟檔案並複製下列程序代碼。 然後執行程式碼。

重要

前往 Azure 入口網站。 如果您在成功部署必要條件一節中建立的語言資源,請按兩下 [後續步驟] 底下的 [移至資源] 按鈕。 您可以在 [資源管理] 底下瀏覽至資源的 [金鑰和端點] 頁面,以尋找您的金鑰和端點

重要

當您完成時,請記得從程式碼中移除密鑰,且絕不會公開發佈。 針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

/**
 * This sample program extracts a summary of two sentences at max from an article.
 * For more information, see the feature documentation: {@link https://learn.microsoft.com/azure/ai-services/language-service/summarization/overview}
 *
 * @summary extracts a summary from an article
 */

const { AzureKeyCredential, TextAnalysisClient } = require("@azure/ai-language-text");

// Load the .env file if it exists
require("dotenv").config();

// This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
const endpoint = process.env.LANGUAGE_ENDPOINT;
const apiKey = process.env.LANGUAGE_KEY;

const documents = [
  `
           Windows 365 was in the works before COVID-19 sent companies around the world on a scramble to secure solutions to support employees suddenly forced to work from home, but “what really put the firecracker behind it was the pandemic, it accelerated everything,” McKelvey said. She explained that customers were asking, “’How do we create an experience for people that makes them still feel connected to the company without the physical presence of being there?”
           In this new world of Windows 365, remote workers flip the lid on their laptop, bootup the family workstation or clip a keyboard onto a tablet, launch a native app or modern web browser and login to their Windows 365 account. From there, their Cloud PC appears with their background, apps, settings and content just as they left it when they last were last there – in the office, at home or a coffee shop.
           “And then, when you’re done, you’re done. You won’t have any issues around security because you’re not saving anything on your device,” McKelvey said, noting that all the data is stored in the cloud.
           The ability to login to a Cloud PC from anywhere on any device is part of Microsoft’s larger strategy around tailoring products such as Microsoft Teams and Microsoft 365 for the post-pandemic hybrid workforce of the future, she added. It enables employees accustomed to working from home to continue working from home; it enables companies to hire interns from halfway around the world; it allows startups to scale without requiring IT expertise.
           “I think this will be interesting for those organizations who, for whatever reason, have shied away from virtualization. This is giving them an opportunity to try it in a way that their regular, everyday endpoint admin could manage,” McKelvey said.
           The simplicity of Windows 365 won over Dean Wells, the corporate chief information officer for the Government of Nunavut. His team previously attempted to deploy a traditional virtual desktop infrastructure and found it inefficient and unsustainable given the limitations of low-bandwidth satellite internet and the constant need for IT staff to manage the network and infrastructure.
           We didn’t run it for very long,” he said. “It didn’t turn out the way we had hoped. So, we actually had terminated the project and rolled back out to just regular PCs.”
           He re-evaluated this decision after the Government of Nunavut was hit by a ransomware attack in November 2019 that took down everything from the phone system to the government’s servers. Microsoft helped rebuild the system, moving the government to Teams, SharePoint, OneDrive and Microsoft 365. Manchester’s team recruited the Government of Nunavut to pilot Windows 365. Wells was intrigued, especially by the ability to manage the elastic workforce securely and seamlessly.
           “The impact that I believe we are finding, and the impact that we’re going to find going forward, is being able to access specialists from outside the territory and organizations outside the territory to come in and help us with our projects, being able to get people on staff with us to help us deliver the day-to-day expertise that we need to run the government,” he said.
           “Being able to improve healthcare, being able to improve education, economic development is going to improve the quality of life in the communities.”`,
];

async function main() {
  console.log("== Extractive Summarization Sample ==");

  const client = new TextAnalysisClient(endpoint, new AzureKeyCredential(apiKey));
  const actions = [
    {
      kind: "ExtractiveSummarization",
      maxSentenceCount: 2,
    },
  ];
  const poller = await client.beginAnalyzeBatch(actions, documents, "en");

  poller.onProgress(() => {
    console.log(
      `Last time the operation was updated was on: ${poller.getOperationState().modifiedOn}`
    );
  });
  console.log(`The operation was created on ${poller.getOperationState().createdOn}`);
  console.log(`The operation results will expire on ${poller.getOperationState().expiresOn}`);

  const results = await poller.pollUntilDone();

  for await (const actionResult of results) {
    if (actionResult.kind !== "ExtractiveSummarization") {
      throw new Error(`Expected extractive summarization results but got: ${actionResult.kind}`);
    }
    if (actionResult.error) {
      const { code, message } = actionResult.error;
      throw new Error(`Unexpected error (${code}): ${message}`);
    }
    for (const result of actionResult.results) {
      console.log(`- Document ${result.id}`);
      if (result.error) {
        const { code, message } = result.error;
        throw new Error(`Unexpected error (${code}): ${message}`);
      }
      console.log("Summary:");
      console.log(result.sentences.map((sentence) => sentence.text).join("\n"));
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

module.exports = { main };

使用本快速入門,使用適用於 Python 的用戶端連結庫建立文字摘要應用程式。 在下列範例中,您將建立 Python 應用程式,摘要以文件或文字為基礎的客戶服務交談。

提示

您可以使用 Language Studio 來嘗試文件摘要,而不需要撰寫程式代碼。

必要條件

  • Azure 訂用帳戶 - 免費建立一個訂用帳戶
  • Python 3.x
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立語言資源,以取得您的密鑰和端點。 部署之後,請選取 [移至資源]。
    • 您需要從您建立的資源取得密鑰和端點,才能將應用程式連線到 API。 您稍後會在快速入門中將金鑰和端點貼到下列程式碼中。
    • 您可以使用免費定價層 (Free F0) 來試用服務,稍後再升級至生產環境的付費層。
  • 若要使用分析功能,您需要具有標準 (S) 定價層的語言資源。

設定

建立環境變數

您的應用程式必須經過驗證,才能傳送 API 要求。 針對生產環境,請使用安全的方式來儲存和存取您的認證。 在此範例中,您會將認證寫入執行應用程式的本機計算機上環境變數。

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

若要設定語言資源密鑰的環境變數,請開啟控制台視窗,並遵循作業系統和開發環境的指示。

  1. 若要設定 LANGUAGE_KEY 環境變數,請將 取代 your-key 為您資源的其中一個密鑰。
  2. 若要設定 LANGUAGE_ENDPOINT 環境變數,請將 取代 your-endpoint 為您資源的端點。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果您只需要存取目前執行控制台中的環境變數,您可以使用 來設定環境變數 set ,而不是 setx

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例之前重新啟動 Visual Studio。

安裝客戶端連結庫

安裝 Python 之後,您可以使用下列項目來安裝用戶端連結庫:

pip install azure-ai-textanalytics==5.3.0

程式碼範例

建立新的 Python 檔案,並複製下列程式代碼。 然後執行程式碼。

重要

前往 Azure 入口網站。 如果您在成功部署必要條件一節中建立的語言資源,請按兩下 [後續步驟] 底下的 [移至資源] 按鈕。 您可以在 [資源管理] 底下瀏覽至資源的 [金鑰和端點] 頁面,以尋找您的金鑰和端點

重要

當您完成時,請記得從程式碼中移除密鑰,且絕不會公開發佈。 針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

# This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
key = os.environ.get('LANGUAGE_KEY')
endpoint = os.environ.get('LANGUAGE_ENDPOINT')

from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# Authenticate the client using your key and endpoint 
def authenticate_client():
    ta_credential = AzureKeyCredential(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint, 
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

# Example method for summarizing text
def sample_extractive_summarization(client):
    from azure.core.credentials import AzureKeyCredential
    from azure.ai.textanalytics import (
        TextAnalyticsClient,
        ExtractiveSummaryAction
    ) 

    document = [
        "The extractive summarization feature uses natural language processing techniques to locate key sentences in an unstructured text document. "
        "These sentences collectively convey the main idea of the document. This feature is provided as an API for developers. " 
        "They can use it to build intelligent solutions based on the relevant information extracted to support various use cases. "
        "Extractive summarization supports several languages. It is based on pretrained multilingual transformer models, part of our quest for holistic representations. "
        "It draws its strength from transfer learning across monolingual and harness the shared nature of languages to produce models of improved quality and efficiency. "
    ]

    poller = client.begin_analyze_actions(
        document,
        actions=[
            ExtractiveSummaryAction(max_sentence_count=4)
        ],
    )

    document_results = poller.result()
    for result in document_results:
        extract_summary_result = result[0]  # first document, first result
        if extract_summary_result.is_error:
            print("...Is an error with code '{}' and message '{}'".format(
                extract_summary_result.code, extract_summary_result.message
            ))
        else:
            print("Summary extracted: \n{}".format(
                " ".join([sentence.text for sentence in extract_summary_result.sentences]))
            )

sample_extractive_summarization(client)

輸出

Summary extracted: 
The extractive summarization feature uses natural language processing techniques to locate key sentences in an unstructured text document. This feature is provided as an API for developers. They can use it to build intelligent solutions based on the relevant information extracted to support various use cases.

使用此快速入門,使用 REST API 傳送文字摘要要求。 在下列範例中,您將使用 cURL 來摘要檔或以文字為基礎的客戶服務交談。

提示

您可以使用 Language Studio 來嘗試文件摘要,而不需要撰寫程式代碼。

必要條件

  • cURL目前版本。
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立語言資源,以取得您的密鑰和端點。 部署之後,請選取 [移至資源]。
    • 您需要從您建立的資源取得密鑰和端點,才能將應用程式連線到 API。 您稍後會在快速入門中將金鑰和端點貼到下列程式代碼中。
    • 您可以使用免費定價層 (Free F0) 來試用服務,稍後再升級至生產環境的付費層。

設定

建立環境變數

您的應用程式必須經過驗證,才能傳送 API 要求。 針對生產環境,請使用安全的方式來儲存和存取您的認證。 在此範例中,您會將認證寫入執行應用程式的本機計算機上環境變數。

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 Azure Key Vault),請參閱 Azure AI 服務安全性文章。

若要設定語言資源密鑰的環境變數,請開啟控制台視窗,並遵循作業系統和開發環境的指示。

  1. 若要設定 LANGUAGE_KEY 環境變數,請將 取代 your-key 為您資源的其中一個密鑰。
  2. 若要設定 LANGUAGE_ENDPOINT 環境變數,請將 取代 your-endpoint 為您資源的端點。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果您只需要存取目前執行控制台中的環境變數,您可以使用 來設定環境變數 set ,而不是 setx

新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例之前重新啟動 Visual Studio。

範例要求

注意

  • 下列BASH範例使用 \ 行接續字元。 如果您的主控台或終端機使用不同的行接續字元,請使用該字元。
  • 您可以在 GitHub找到語言特定範例。 若要呼叫 API,您需要下列資訊:

選擇您要執行的摘要類型,然後選取下列其中一個索引標籤,以查看範例 API 呼叫:

功能 描述
文件摘要 使用擷取文字摘要,在文件中產生重要或相關信息的摘要。
交談摘要 使用抽象文字摘要,在客戶服務代理程式和客戶之間的文字記錄中產生問題和解決方式的摘要。
parameter 描述
-X POST <endpoint> 指定用於存取 API 的端點。
-H Content-Type: application/json 傳送 JSON 資料的內容類型。
-H "Ocp-Apim-Subscription-Key:<key> 指定用來存取 API 的金鑰。
-d <documents> 包含您要傳送之檔的 JSON。

下列 cURL 命令是從 BASH 殼層執行。 用自己的 JSON 值編輯這些命令。

文件摘要

檔擷取摘要範例

下列範例會讓您開始使用檔案擷取摘要:

  1. 將下列命令複製到文字編輯器。 BASH 範例會使用 \ 行接續字元。 如果您的主控台或終端機使用不同的行接續字元,請改用該字元。
curl -i -X POST $LANGUAGE_ENDPOINT/language/analyze-text/jobs?api-version=2023-04-01 \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY" \
-d \
' 
{
  "displayName": "Document ext Summarization Task Example",
  "analysisInput": {
    "documents": [
      {
        "id": "1",
        "language": "en",
        "text": "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic, human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI services, I have been working with a team of amazing scientists and engineers to turn this quest into a reality. In my role, I enjoy a unique perspective in viewing the relationship among three attributes of human cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z). At the intersection of all three, there’s magic—what we call XYZ-code as illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear, see, and understand humans better. We believe XYZ-code will enable us to fulfill our long-term vision: cross-domain transfer learning, spanning modalities and languages. The goal is to have pre-trained models that can jointly learn representations to support a broad range of downstream AI tasks, much in the way humans do today. Over the past five years, we have achieved human performance on benchmarks in conversational speech recognition, machine translation, conversational question answering, machine reading comprehension, and image captioning. These five breakthroughs provided us with strong signals toward our more ambitious aspiration to produce a leap in AI capabilities, achieving multi-sensory and multilingual learning that is closer in line with how humans learn and understand. I believe the joint XYZ-code is a foundational component of this aspiration, if grounded with external knowledge sources in the downstream AI tasks."
      }
    ]
  },
  "tasks": [
    {
      "kind": "ExtractiveSummarization",
      "taskName": "Document Extractive Summarization Task 1",
      "parameters": {
        "sentenceCount": 6
      }
    }
  ]
}
'
  1. 開啟命令提示字元視窗(例如:BASH)。

  2. 將命令從文字編輯器貼到命令提示字元視窗中,然後執行 命令。

  3. operation-location從回應標頭取得 。 此值看起來會類似下列 URL:

https://<your-language-resource-endpoint>/language/analyze-text/jobs/12345678-1234-1234-1234-12345678?api-version=2023-04-01
  1. 若要取得要求的結果,請使用下列 cURL 命令。 請務必將 取代 <my-job-id> 為您從上 operation-location 一個回應標頭收到的數值識別碼值:
curl -X GET $LANGUAGE_ENDPOINT/language/analyze-text/jobs/<my-job-id>?api-version=2023-04-01 \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY"

檔擷取摘要範例 JSON 回應

{
    "jobId": "56e43bcf-70d8-44d2-a7a7-131f3dff069f",
    "lastUpdateDateTime": "2022-09-28T19:33:43Z",
    "createdDateTime": "2022-09-28T19:33:42Z",
    "expirationDateTime": "2022-09-29T19:33:42Z",
    "status": "succeeded",
    "errors": [],
    "displayName": "Document ext Summarization Task Example",
    "tasks": {
        "completed": 1,
        "failed": 0,
        "inProgress": 0,
        "total": 1,
        "items": [
            {
                "kind": "ExtractiveSummarizationLROResults",
                "taskName": "Document Extractive Summarization Task 1",
                "lastUpdateDateTime": "2022-09-28T19:33:43.6712507Z",
                "status": "succeeded",
                "results": {
                    "documents": [
                        {
                            "id": "1",
                            "sentences": [
                                {
                                    "text": "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic, human-centric approach to learning and understanding.",
                                    "rankScore": 0.69,
                                    "offset": 0,
                                    "length": 160
                                },
                                {
                                    "text": "In my role, I enjoy a unique perspective in viewing the relationship among three attributes of human cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z).",
                                    "rankScore": 0.66,
                                    "offset": 324,
                                    "length": 192
                                },
                                {
                                    "text": "At the intersection of all three, there’s magic—what we call XYZ-code as illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear, see, and understand humans better.",
                                    "rankScore": 0.63,
                                    "offset": 517,
                                    "length": 203
                                },
                                {
                                    "text": "We believe XYZ-code will enable us to fulfill our long-term vision: cross-domain transfer learning, spanning modalities and languages.",
                                    "rankScore": 1.0,
                                    "offset": 721,
                                    "length": 134
                                },
                                {
                                    "text": "The goal is to have pre-trained models that can jointly learn representations to support a broad range of downstream AI tasks, much in the way humans do today.",
                                    "rankScore": 0.74,
                                    "offset": 856,
                                    "length": 159
                                },
                                {
                                    "text": "I believe the joint XYZ-code is a foundational component of this aspiration, if grounded with external knowledge sources in the downstream AI tasks.",
                                    "rankScore": 0.49,
                                    "offset": 1481,
                                    "length": 148
                                }
                            ],
                            "warnings": []
                        }
                    ],
                    "errors": [],
                    "modelVersion": "latest"
                }
            }
        ]
    }
}

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

下一步