重要
对话摘要仅适用于:
- REST API
- Python
- C#
借助本快速入门,使用 .NET 客户端库创建文本摘要应用程序。 在以下示例中,你将创建一个 C# 应用程序,该应用程序可以汇总文档或基于文本的客户服务对话。
提示
可以使用 Language Studio 体验文本摘要,而无需编写代码。
- Azure 订阅 - 创建试用订阅
- Visual Studio IDE
- 拥有 Azure 订阅后,请创建 AI 服务资源。
- 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 稍后需要在本快速入门中将密钥和终结点粘贴到代码中。
- 可以使用免费定价层 (
Free F0
) 试用该服务,然后再升级到付费层进行生产。
- 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。
应用程序必须经过身份验证才能发送 API 请求。 对于生产,请使用安全的方式存储和访问凭据。 在此示例中,你将凭据写入运行应用程序的本地计算机上的环境变量。
若要为语言资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。
- 若要设置
LANGUAGE_KEY
环境变量,请将your-key
替换为资源的其中一个密钥。 - 若要设置
LANGUAGE_ENDPOINT
环境变量,请将your-endpoint
替换为资源的终结点。
重要
如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。
有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证。
export LANGUAGE_KEY=your-key
export LANGUAGE_ENDPOINT=your-endpoint
添加环境变量后,请从控制台窗口运行 source ~/.bashrc
,使更改生效。
使用 Visual Studio IDE 创建新的 .NET Core 控制台应用。 这会创建包含单个 C# 源文件的“Hello World”项目:program.cs。
右键单击解决方案资源管理器中的解决方案,然后选择“管理 NuGet 包”,以便安装客户端库。 在打开的包管理器中选择“浏览”,搜索 Azure.AI.Language.Conversations
。 请务必选中“包括预发行版”。 选择版本 1.1.0
,然后选择“安装”。 也可使用包管理器控制台。
将以下代码复制到 program.cs 文件。 然后运行代码。
重要
转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。
重要
完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。
using System;
using Azure;
using Azure.Core;
using Azure.AI.Language.Conversations;
using System.Text.Json;
using System.Threading.Tasks;
namespace Example
{
class Program
{
private static readonly AzureKeyCredential credentials = new AzureKeyCredential("replace-with-your-key-here");
private static readonly Uri endpoint = new Uri("replace-with-your-endpoint-here");
static async Task Main(string[] args)
{
ConversationAnalysisClient client = new ConversationAnalysisClient(endpoint, credentials);
await Summarization(client);
}
static async Task Summarization(ConversationAnalysisClient client)
{
var data = new
{
analysisInput = new
{
conversations = new[]
{
new
{
conversationItems = new[]
{
new
{
text = "Hello, you’re chatting with Rene. How may I help you?",
id = "1",
role = "Agent",
participantId = "Agent",
},
new
{
text = "Hi, I tried to set up wifi connection for Smart Brew 300 coffee machine, but it didn’t work.",
id = "2",
role = "Customer",
participantId = "Customer",
},
new
{
text = "I’m sorry to hear that. Let’s see what we can do to fix this issue. Could you please try the following steps for me? First, could you push the wifi connection button, hold for 3 seconds, then let me know if the power light is slowly blinking on and off every second?",
id = "3",
role = "Agent",
participantId = "Agent",
},
new
{
text = "Yes, I pushed the wifi connection button, and now the power light is slowly blinking?",
id = "4",
role = "Customer",
participantId = "Customer",
},
new
{
text = "Great. Thank you! Now, please check in your Contoso Coffee app. Does it prompt to ask you to connect with the machine?",
id = "5",
role = "Agent",
participantId = "Agent",
},
new
{
text = "No. Nothing happened.",
id = "6",
role = "Customer",
participantId = "Customer",
},
new
{
text = "I’m very sorry to hear that. Let me see if there’s another way to fix the issue. Please hold on for a minute.",
id = "7",
role = "Agent",
participantId = "Agent",
}
},
id = "1",
language = "en",
modality = "text",
},
}
},
tasks = new[]
{
new
{
parameters = new
{
summaryAspects = new[]
{
"issue",
"resolution",
}
},
kind = "ConversationalSummarizationTask",
taskName = "1",
},
},
};
Operation<BinaryData> analyzeConversationOperation = await client.AnalyzeConversationsAsync(WaitUntil.Started, RequestContent.Create(data));
analyzeConversationOperation.WaitForCompletion();
using JsonDocument result = JsonDocument.Parse(analyzeConversationOperation.Value.ToStream());
JsonElement jobResults = result.RootElement;
foreach (JsonElement task in jobResults.GetProperty("tasks").GetProperty("items").EnumerateArray())
{
JsonElement results = task.GetProperty("results");
Console.WriteLine("Conversations:");
foreach (JsonElement conversation in results.GetProperty("conversations").EnumerateArray())
{
Console.WriteLine($"Conversation: #{conversation.GetProperty("id").GetString()}");
Console.WriteLine("Summaries:");
foreach (JsonElement summary in conversation.GetProperty("summaries").EnumerateArray())
{
Console.WriteLine($"Text: {summary.GetProperty("text").GetString()}");
Console.WriteLine($"Aspect: {summary.GetProperty("aspect").GetString()}");
}
Console.WriteLine();
}
}
}
}
}
Conversations:
Conversation: #1
Summaries:
Text: Customer is unable to set up wifi connection for Smart Brew 300 coffee machine.
Aspect: issue
Text: The agent instructed the customer to press the wifi connection button, hold for 3 seconds, and check if the power light blinks. The agent also asked the customer to check if the Contoso Coffee app prompts to connect with the machine, but the issue persisted. The agent is looking for another way to fix the issue.
Aspect: resolution
参考文档 | 更多示例 | 包 (Maven) | 库源代码
借助本快速入门,使用 Java 客户端库创建文本摘要应用程序。 在以下示例中,你将创建一个可以汇总文档的 Java 应用程序。
提示
可以使用 Language Studio 体验文本摘要,而无需编写代码。
- Azure 订阅 - 创建试用订阅
- Java 开发工具包 (JDK) 版本 8 或更高版本
- 拥有 Azure 订阅后,请创建 AI 服务资源。
- 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 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 请求。 对于生产,请使用安全的方式存储和访问凭据。 在此示例中,你将凭据写入运行应用程序的本地计算机上的环境变量。
若要为语言资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。
- 若要设置
LANGUAGE_KEY
环境变量,请将your-key
替换为资源的其中一个密钥。 - 若要设置
LANGUAGE_ENDPOINT
环境变量,请将your-endpoint
替换为资源的终结点。
重要
如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。
有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证。
export LANGUAGE_KEY=your-key
export LANGUAGE_ENDPOINT=your-endpoint
添加环境变量后,请从控制台窗口运行 source ~/.bashrc
,使更改生效。
创建名为 Example.java
的 Java 文件。 打开该文件,并复制以下代码。 然后运行代码。
重要
转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。
重要
完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 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.
借助本快速入门,使用 Node.js 客户端库创建文本摘要应用程序。 在下面的示例中,你将创建一个可以汇总文档的 JavaScript 应用程序。
提示
可以使用 Language Studio 体验文本摘要,而无需编写代码。
- Azure 订阅 - 创建试用订阅
- Node.js v16 LTS
- 拥有 Azure 订阅后,请创建 AI 服务资源。
- 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 稍后在快速入门中将密钥和终结点粘贴到下方的代码中。
- 可以使用免费定价层 (
Free F0
) 试用该服务,然后再升级到付费层进行生产。
- 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。
应用程序必须经过身份验证才能发送 API 请求。 对于生产,请使用安全的方式存储和访问凭据。 在此示例中,你将凭据写入运行应用程序的本地计算机上的环境变量。
若要为语言资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。
- 若要设置
LANGUAGE_KEY
环境变量,请将your-key
替换为资源的其中一个密钥。 - 若要设置
LANGUAGE_ENDPOINT
环境变量,请将your-endpoint
替换为资源的终结点。
重要
如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。
有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证。
export LANGUAGE_KEY=your-key
export LANGUAGE_ENDPOINT=your-endpoint
添加环境变量后,请从控制台窗口运行 source ~/.bashrc
,使更改生效。
在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。
mkdir myapp
cd myapp
运行 npm init
命令以使用 package.json
文件创建一个 node 应用程序。
npm init
安装 npm 包:
npm install --save @azure/ai-language-text@1.1.0
打开该文件,并复制以下代码。 然后运行代码。
重要
转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。
重要
完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 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 订阅后,请创建 AI 服务资源。
- 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 稍后在快速入门中将密钥和终结点粘贴到下方的代码中。
- 可以使用免费定价层 (
Free F0
) 试用该服务,然后再升级到付费层进行生产。
- 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。
应用程序必须经过身份验证才能发送 API 请求。 对于生产,请使用安全的方式存储和访问凭据。 在此示例中,你将凭据写入运行应用程序的本地计算机上的环境变量。
若要为语言资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。
- 若要设置
LANGUAGE_KEY
环境变量,请将your-key
替换为资源的其中一个密钥。 - 若要设置
LANGUAGE_ENDPOINT
环境变量,请将your-endpoint
替换为资源的终结点。
重要
如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。
有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证。
export LANGUAGE_KEY=your-key
export LANGUAGE_ENDPOINT=your-endpoint
添加环境变量后,请从控制台窗口运行 source ~/.bashrc
,使更改生效。
在安装 Python 后,可以通过以下命令安装客户端库:
创建新的 Python 文件,并复制以下代码。 然后运行代码。
重要
转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。
重要
完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。
key = "paste-your-key-here"
endpoint = "paste-your-endpoint-here"
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations import ConversationAnalysisClient
client = ConversationAnalysisClient(endpoint, AzureKeyCredential(key))
with client:
poller = client.begin_conversation_analysis(
task={
"displayName": "Analyze conversations from xxx",
"analysisInput": {
"conversations": [
{
"conversationItems": [
{
"text": "Hello, you’re chatting with Rene. How may I help you?",
"id": "1",
"role": "Agent",
"participantId": "Agent_1",
},
{
"text": "Hi, I tried to set up wifi connection for Smart Brew 300 coffee machine, but it didn’t work.",
"id": "2",
"role": "Customer",
"participantId": "Customer_1",
},
{
"text": "I’m sorry to hear that. Let’s see what we can do to fix this issue. Could you please try the following steps for me? First, could you push the wifi connection button, hold for 3 seconds, then let me know if the power light is slowly blinking on and off every second?",
"id": "3",
"role": "Agent",
"participantId": "Agent_1",
},
{
"text": "Yes, I pushed the wifi connection button, and now the power light is slowly blinking.",
"id": "4",
"role": "Customer",
"participantId": "Customer_1",
},
{
"text": "Great. Thank you! Now, please check in your Contoso Coffee app. Does it prompt to ask you to connect with the machine?",
"id": "5",
"role": "Agent",
"participantId": "Agent_1",
},
{
"text": "No. Nothing happened.",
"id": "6",
"role": "Customer",
"participantId": "Customer_1",
},
{
"text": "I’m very sorry to hear that. Let me see if there’s another way to fix the issue. Please hold on for a minute.",
"id": "7",
"role": "Agent",
"participantId": "Agent_1",
},
],
"modality": "text",
"id": "conversation1",
"language": "en",
},
]
},
"tasks": [
{
"taskName": "Issue task",
"kind": "ConversationalSummarizationTask",
"parameters": {"summaryAspects": ["issue"]},
},
{
"taskName": "Resolution task",
"kind": "ConversationalSummarizationTask",
"parameters": {"summaryAspects": ["resolution"]},
},
],
}
)
# view result
result = poller.result()
task_results = result["tasks"]["items"]
for task in task_results:
print(f"\n{task['taskName']} status: {task['status']}")
task_result = task["results"]
if task_result["errors"]:
print("... errors occurred ...")
for error in task_result["errors"]:
print(error)
else:
conversation_result = task_result["conversations"][0]
if conversation_result["warnings"]:
print("... view warnings ...")
for warning in conversation_result["warnings"]:
print(warning)
else:
summaries = conversation_result["summaries"]
for summary in summaries:
print(f"{summary['aspect']}: {summary['text']}")
Issue task status: succeeded
issue: Customer tried to set up wifi connection for Smart Brew 300 coffee machine but it didn't work. No error message.
Resolution task status: succeeded
resolution: Asked customer to check if the Contoso Coffee app prompts to connect with the machine. Customer ended the chat.
借助本快速入门,使用 REST API 发送文本摘要请求。 在以下示例中,你将使用 cURL 来汇总文档或基于文本的客户服务对话。
提示
可以使用 Language Studio 体验文本摘要,而无需编写代码。
- 最新版本的 cURL。
- 拥有 Azure 订阅后,请<创建 AI 服务资源。
- 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
- 可以使用免费定价层 (
Free F0
) 试用该服务,然后再升级到付费层进行生产。
应用程序必须经过身份验证才能发送 API 请求。 对于生产,请使用安全的方式存储和访问凭据。 在此示例中,你将凭据写入运行应用程序的本地计算机上的环境变量。
若要为语言资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。
- 若要设置
LANGUAGE_KEY
环境变量,请将your-key
替换为资源的其中一个密钥。 - 若要设置
LANGUAGE_ENDPOINT
环境变量,请将your-endpoint
替换为资源的终结点。
重要
如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。
有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证。
export LANGUAGE_KEY=your-key
export LANGUAGE_ENDPOINT=your-endpoint
添加环境变量后,请从控制台窗口运行 source ~/.bashrc
,使更改生效。
备注
- 以下 BASH 示例使用
\
行继续符。 如果你的控制台或终端使用不同的行继续符,请使用该字符。 - 可以在 GitHub 上找到特定于语言的示例。 若要调用 API,需要以下信息:
选择要执行的摘要类型,然后选择以下选项卡之一来查看示例 API 调用:
功能 | 说明 |
---|---|
文本摘要 | 使用抽取式文本摘要生成文档中重要或相关信息的摘要。 |
对话摘要 | 使用抽象式文本摘要生成客户服务代理与客户之间的口述文本中的问题和解决方法。 |
借助以下示例,你可以开始了解对话问题和解决方法摘要:
- 将下面的命令复制到文本编辑器中。 BASH 示例使用
\
续行符。 如果你的控制台或终端使用不同的续行符,请改用该续行符。
curl -i -X POST $LANGUAGE_ENDPOINT/language/analyze-conversations/jobs?api-version=2023-04-01 \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY" \
-d \
'
{
"displayName": "Conversation Task Example",
"analysisInput": {
"conversations": [
{
"conversationItems": [
{
"text": "Hello, you’re chatting with Rene. How may I help you?",
"id": "1",
"role": "Agent",
"participantId": "Agent_1"
},
{
"text": "Hi, I tried to set up wifi connection for Smart Brew 300 espresso machine, but it didn’t work.",
"id": "2",
"role": "Customer",
"participantId": "Customer_1"
},
{
"text": "I’m sorry to hear that. Let’s see what we can do to fix this issue. Could you please try the following steps for me? First, could you push the wifi connection button, hold for 3 seconds, then let me know if the power light is slowly blinking on and off every second?",
"id": "3",
"role": "Agent",
"participantId": "Agent_1"
},
{
"text": "Yes, I pushed the wifi connection button, and now the power light is slowly blinking.",
"id": "4",
"role": "Customer",
"participantId": "Customer_1"
},
{
"text": "Great. Thank you! Now, please check in your Contoso Coffee app. Does it prompt to ask you to connect with the machine? ",
"id": "5",
"role": "Agent",
"participantId": "Agent_1"
},
{
"text": "No. Nothing happened.",
"id": "6",
"role": "Customer",
"participantId": "Customer_1"
},
{
"text": "I’m very sorry to hear that. Let me see if there’s another way to fix the issue. Please hold on for a minute.",
"id": "7",
"role": "Agent",
"participantId": "Agent_1"
}
],
"modality": "text",
"id": "conversation1",
"language": "en"
}
]
},
"tasks": [
{
"taskName": "Conversation Task 1",
"kind": "ConversationalSummarizationTask",
"parameters": {
"summaryAspects": ["issue"]
}
},
{
"taskName": "Conversation Task 2",
"kind": "ConversationalSummarizationTask",
"parameters": {
"summaryAspects": ["resolution"],
"sentenceCount": 1
}
}
]
}
'
只有 resolution
纵横比支持 sentenceCount。 如果未指定 sentenceCount
参数,则模型将确定摘要的长度。 请注意,sentenceCount
只是输出摘要的句子计数的近似值,范围为 1 到 7。
打开命令提示符窗口(例如 BASH)。
将文本编辑器中的命令粘贴到命令提示符窗口,然后运行该命令。
从响应头获取
operation-location
。 值将如下 URL 所示:
https://<your-language-resource-endpoint>/language/analyze-conversations/jobs/12345678-1234-1234-1234-12345678?api-version=2023-04-01
- 要获取请求的结果,请使用以下 cURL 命令。 请务必将
<my-job-id>
替换为从之前的operation-location
响应头中收到的数值 ID 值:
curl -X GET $LANGUAGE_ENDPOINT/language/analyze-conversations/jobs/<my-job-id>?api-version=2023-04-01 \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY"
{
"jobId": "02ec5134-78bf-45da-8f63-d7410291ec40",
"lastUpdatedDateTime": "2022-09-29T17:43:02Z",
"createdDateTime": "2022-09-29T17:43:01Z",
"expirationDateTime": "2022-09-30T17:43:01Z",
"status": "succeeded",
"errors": [],
"displayName": "Conversation Task Example",
"tasks": {
"completed": 2,
"failed": 0,
"inProgress": 0,
"total": 2,
"items": [
{
"kind": "conversationalSummarizationResults",
"taskName": "Conversation Task 1",
"lastUpdateDateTime": "2022-09-29T17:43:02.3584219Z",
"status": "succeeded",
"results": {
"conversations": [
{
"summaries": [
{
"aspect": "issue",
"text": "Customer wants to connect their Smart Brew 300 to their Wi-Fi. | The Wi-Fi connection didn't work."
}
],
"id": "conversation1",
"warnings": []
}
],
"errors": [],
"modelVersion": "latest"
}
},
{
"kind": "conversationalSummarizationResults",
"taskName": "Conversation Task 2",
"lastUpdateDateTime": "2022-09-29T17:43:02.2099663Z",
"status": "succeeded",
"results": {
"conversations": [
{
"summaries": [
{
"aspect": "resolution",
"text": "Asked customer to check if the power light is blinking on and off every second."
}
],
"id": "conversation1",
"warnings": []
}
],
"errors": [],
"modelVersion": "latest"
}
}
]
}
}
如果想要清理并移除 Azure AI 服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。