빠른 시작: 문서 요약 및 대화 요약 사용

Important

미리 보기 지역인 스웨덴 중부에서는 GPT 모델을 기준으로 계속 진화하고 있는 최신 LLM 미세 조정 기술을 선보입니다. 스웨덴 중부 지역의 언어 리소스로 이 기술을 사용해 볼 수 있습니다.

대화 요약은 다음을 통해서만 사용할 수 있습니다.

  • REST API
  • Python
  • C#

이 빠른 시작을 사용하여 .NET용 클라이언트 라이브러리로 텍스트 요약 애플리케이션을 만듭니다. 다음 예제에서는 문서 또는 텍스트 기반 고객 서비스 대화를 요약할 수 있는 C# 애플리케이션을 만듭니다.

Language Studio를 사용하여 코드를 작성할 필요 없이 문서 요약을 시도할 수 있습니다.

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • Visual Studio IDE
  • Azure 구독이 있으면 Azure Portal에서 언어 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.
    • 애플리케이션을 API에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 키와 엔드포인트를 이 빠른 시작의 뒷부분에서 코드에 붙여넣습니다.
    • 평가판 가격 책정 계층(Free F0)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.
  • 분석 기능을 사용하려면 표준(S) 가격 책정 계층을 사용하는 언어 리소스가 필요합니다.

설정

환경 변수 만들기

API 요청을 보내려면 애플리케이션을 인증해야 합니다. 프로덕션의 경우 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.

코드에 키를 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Azure AI 서비스 보안 문서를 참조하세요.

Language 리소스 키에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.

  1. LANGUAGE_KEY 환경 변수를 설정하려면 your-key를 리소스에 대한 키 중 하나로 바꿉니다.
  2. LANGUAGE_ENDPOINT 환경 변수를 설정하려면 your-endpoint를 리소스에 대한 엔드포인트로 바꿉니다.
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

참고 항목

현재 실행 중인 콘솔에서만 환경 변수에 액세스해야 하는 경우 환경 변수를 setx 대신 set으로 설정할 수 있습니다.

환경 변수가 추가되면 콘솔 창을 포함하여 환경 변수를 읽어야 하는 실행 중인 프로그램을 다시 시작해야 할 수 있습니다. 예를 들어 편집기로 Visual Studio를 사용하는 경우 Visual Studio를 다시 시작한 후 예제를 실행합니다.

새 .NET Core 애플리케이션 만들기

Visual Studio IDE를 사용하여 새 .NET Core 콘솔 앱을 만듭니다. 그러면 단일 C# 소스 파일인 program.cs를 사용하여 "Hello World" 프로젝트가 생성됩니다.

솔루션 탐색기에서 솔루션을 마우스 오른쪽 단추로 클릭하고 NuGet 패키지 관리를 선택하여 클라이언트 라이브러리를 설치합니다. 열리는 패키지 관리자에서 찾아보기를 선택하고 Azure.AI.TextAnalytics를 검색합니다. 시험판 포함이 선택되어 있는지 확인합니다. 5.3.0 버전, 설치를 차례로 선택합니다. 패키지 관리자 콘솔을 사용할 수도 있습니다.

코드 예

program.cs 파일에 다음 코드를 복사합니다. 그런 다음 코드를 실행합니다.

Important

Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 언어 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동 단추를 클릭합니다. 리소스 관리에서 리소스의 키 및 엔드포인트 페이지로 이동하여 키와 엔드포인트를 찾을 수 있습니다.

Important

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자세한 내용은 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를 사용하여 코드를 작성할 필요 없이 문서 요약을 시도할 수 있습니다.

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • JDK(Java Development Kit) 버전 8 이상
  • Azure 구독이 있으면 Azure Portal에서 언어 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.
    • 애플리케이션을 API에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 빠른 시작 뒷부분의 아래 코드에 키와 엔드포인트를 붙여넣습니다.
    • 평가판 가격 책정 계층(Free F0)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.
  • 분석 기능을 사용하려면 표준(S) 가격 책정 계층을 사용하는 언어 리소스가 필요합니다.

설정

클라이언트 라이브러리 추가

선호하는 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 서비스 보안 문서를 참조하세요.

Language 리소스 키에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.

  1. LANGUAGE_KEY 환경 변수를 설정하려면 your-key를 리소스에 대한 키 중 하나로 바꿉니다.
  2. LANGUAGE_ENDPOINT 환경 변수를 설정하려면 your-endpoint를 리소스에 대한 엔드포인트로 바꿉니다.
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

참고 항목

현재 실행 중인 콘솔에서만 환경 변수에 액세스해야 하는 경우 환경 변수를 setx 대신 set으로 설정할 수 있습니다.

환경 변수가 추가되면 콘솔 창을 포함하여 환경 변수를 읽어야 하는 실행 중인 프로그램을 다시 시작해야 할 수 있습니다. 예를 들어 편집기로 Visual Studio를 사용하는 경우 Visual Studio를 다시 시작한 후 예제를 실행합니다.

코드 예

Example.java라는 Java 파일을 만듭니다. 파일을 열고 아래 코드를 복사합니다. 그런 다음 코드를 실행합니다.

Important

Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 언어 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동 단추를 클릭합니다. 리소스 관리에서 리소스의 키 및 엔드포인트 페이지로 이동하여 키와 엔드포인트를 찾을 수 있습니다.

Important

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자세한 내용은 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 Portal에서 언어 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.
    • 애플리케이션을 API에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 이 빠른 시작의 뒷부분에 나오는 코드에 키와 엔드포인트를 붙여넣습니다.
    • 평가판 가격 책정 계층(Free F0)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.
  • 분석 기능을 사용하려면 표준(S) 가격 책정 계층을 사용하는 언어 리소스가 필요합니다.

설정

환경 변수 만들기

API 요청을 보내려면 애플리케이션을 인증해야 합니다. 프로덕션의 경우 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.

코드에 키를 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Azure AI 서비스 보안 문서를 참조하세요.

Language 리소스 키에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.

  1. LANGUAGE_KEY 환경 변수를 설정하려면 your-key를 리소스에 대한 키 중 하나로 바꿉니다.
  2. LANGUAGE_ENDPOINT 환경 변수를 설정하려면 your-endpoint를 리소스에 대한 엔드포인트로 바꿉니다.
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

참고 항목

현재 실행 중인 콘솔에서만 환경 변수에 액세스해야 하는 경우 환경 변수를 setx 대신 set으로 설정할 수 있습니다.

환경 변수가 추가되면 콘솔 창을 포함하여 환경 변수를 읽어야 하는 실행 중인 프로그램을 다시 시작해야 할 수 있습니다. 예를 들어 편집기로 Visual Studio를 사용하는 경우 Visual Studio를 다시 시작한 후 예제를 실행합니다.

새 Node.js 애플리케이션 만들기

콘솔 창(예: cmd, PowerShell 또는 Bash)에서 앱에 대한 새 디렉터리를 만들고 이 디렉터리로 이동합니다.

mkdir myapp 

cd myapp

package.json 파일을 사용하여 노드 애플리케이션을 만들려면 npm init 명령을 실행합니다.

npm init

클라이언트 라이브러리 설치

npm 패키지를 설치합니다.

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

코드 예

파일을 열고 아래 코드를 복사합니다. 그런 다음 코드를 실행합니다.

Important

Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 언어 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동 단추를 클릭합니다. 리소스 관리에서 리소스의 키 및 엔드포인트 페이지로 이동하여 키와 엔드포인트를 찾을 수 있습니다.

Important

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자세한 내용은 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 Portal에서 언어 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.
    • 애플리케이션을 API에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 빠른 시작 뒷부분의 아래 코드에 키와 엔드포인트를 붙여넣습니다.
    • 평가판 가격 책정 계층(Free F0)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.
  • 분석 기능을 사용하려면 표준(S) 가격 책정 계층을 사용하는 언어 리소스가 필요합니다.

설정

환경 변수 만들기

API 요청을 보내려면 애플리케이션을 인증해야 합니다. 프로덕션의 경우 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.

코드에 키를 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Azure AI 서비스 보안 문서를 참조하세요.

Language 리소스 키에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.

  1. LANGUAGE_KEY 환경 변수를 설정하려면 your-key를 리소스에 대한 키 중 하나로 바꿉니다.
  2. LANGUAGE_ENDPOINT 환경 변수를 설정하려면 your-endpoint를 리소스에 대한 엔드포인트로 바꿉니다.
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

참고 항목

현재 실행 중인 콘솔에서만 환경 변수에 액세스해야 하는 경우 환경 변수를 setx 대신 set으로 설정할 수 있습니다.

환경 변수가 추가되면 콘솔 창을 포함하여 환경 변수를 읽어야 하는 실행 중인 프로그램을 다시 시작해야 할 수 있습니다. 예를 들어 편집기로 Visual Studio를 사용하는 경우 Visual Studio를 다시 시작한 후 예제를 실행합니다.

클라이언트 라이브러리 설치

Python을 설치한 후, 다음을 사용하여 클라이언트 라이브러리를 설치할 수 있습니다.

pip install azure-ai-textanalytics==5.3.0

코드 예

새 Python 파일을 만들고 아래 코드를 복사합니다. 그런 다음 코드를 실행합니다.

Important

Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 언어 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동 단추를 클릭합니다. 리소스 관리에서 리소스의 키 및 엔드포인트 페이지로 이동하여 키와 엔드포인트를 찾을 수 있습니다.

Important

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자세한 내용은 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 Portal에서 언어 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.
    • 애플리케이션을 API에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 이 빠른 시작의 뒷부분에 나오는 코드에 키와 엔드포인트를 붙여넣습니다.
    • 평가판 가격 책정 계층(Free F0)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.

설정

환경 변수 만들기

API 요청을 보내려면 애플리케이션을 인증해야 합니다. 프로덕션의 경우 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.

코드에 키를 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Azure AI 서비스 보안 문서를 참조하세요.

Language 리소스 키에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.

  1. LANGUAGE_KEY 환경 변수를 설정하려면 your-key를 리소스에 대한 키 중 하나로 바꿉니다.
  2. LANGUAGE_ENDPOINT 환경 변수를 설정하려면 your-endpoint를 리소스에 대한 엔드포인트로 바꿉니다.
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

참고 항목

현재 실행 중인 콘솔에서만 환경 변수에 액세스해야 하는 경우 환경 변수를 setx 대신 set으로 설정할 수 있습니다.

환경 변수가 추가되면 콘솔 창을 포함하여 환경 변수를 읽어야 하는 실행 중인 프로그램을 다시 시작해야 할 수 있습니다. 예를 들어 편집기로 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 응답 헤더에서 받은 숫자 ID 값으로 바꾸어야 합니다.
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 서비스 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.

다음 단계