單擊“創(chuàng)建”開始配置新的多服務(wù)帳戶資源。

步驟 3:配置資源設(shè)置

創(chuàng)建 Azure AI 服務(wù)資源時(shí),需要配置以下設(shè)置:

訂閱:

選擇您的 Azure 訂閱。

資源組:

選擇現(xiàn)有資源組或創(chuàng)建新資源組。如果您的權(quán)限受限,請使用提供給您的資源組。

區(qū)域:

選擇適合您需求的可用區(qū)域。

名稱:

為您的資源輸入一個(gè)唯一的名稱。

定價(jià)層:

選擇標(biāo)準(zhǔn) S0作為定價(jià)層。

步驟 4:完成并創(chuàng)建資源

1、通過選擇所需的復(fù)選框來查看條款和條件。

2、單擊“創(chuàng)建”以部署您的資源。

3、等待部署完成。此過程可能需要幾分鐘。

步驟 5:訪問資源詳細(xì)信息

部署完成后,請按照以下步驟查看資源詳細(xì)信息:

1、進(jìn)入資源頁面,查看部署詳情。

2、導(dǎo)航到密鑰和端點(diǎn)頁面。

此頁面包含連接到資源的基本信息,包括:

HTTP 端點(diǎn):客戶端應(yīng)用程序可以發(fā)送請求的端點(diǎn)。
身份驗(yàn)證密鑰:客戶端應(yīng)用程序可用于身份驗(yàn)證的兩個(gè)密鑰。任一密鑰均可用于對請求進(jìn)行身份驗(yàn)證。

Location:資源的托管位置,某些 API 請求需要該位置。

在您的應(yīng)用程序中使用 Azure AI 服務(wù)

設(shè)置 Azure AI 服務(wù)資源后,你現(xiàn)在可以將 AI 功能整合到應(yīng)用程序中。以下是如何使用這些服務(wù)的一般概述:

1、發(fā)出 HTTP 請求:

使用提供的 HTTP 端點(diǎn)從客戶端應(yīng)用程序發(fā)送請求。確保在請求標(biāo)頭中包含其中一個(gè)身份驗(yàn)證密鑰。

2、處理響應(yīng):

處理來自 Azure AI 服務(wù)的響應(yīng),以將 AI 功能(例如自然語言處理、計(jì)算機(jī)視覺或其他功能)合并到您的應(yīng)用程序中。

3、特定區(qū)域的 API:

對于某些 API,您需要在請求中指定資源的位置。

將 REST 接口與 Azure AI 服務(wù)結(jié)合使用

Azure AI 服務(wù) API 基于 REST,允許你通過 HTTP 發(fā)送 JSON 請求來與它們交互。

在本文中,我們將介紹一個(gè)使用控制臺應(yīng)用程序使用語言 REST API 執(zhí)行語言檢測的示例。

此原則適用于 Azure AI 服務(wù)資源支持的所有 API。

先決條件

設(shè)置你的項(xiàng)目

1. 選擇您的首選語言

您可以選擇使用 C# 或 Python 進(jìn)行此練習(xí)。根據(jù)您的偏好,在 Visual Studio Code 中展開相應(yīng)的文件夾:

2.更新配置設(shè)置

導(dǎo)航到rest-client文件夾并打開配置文件:

C#:appsettings.json

Python:.env

更新配置值以反映您的 Azure AI 服務(wù)端點(diǎn)和身份驗(yàn)證密鑰,然后保存更改。

3.檢查客戶端應(yīng)用程序代碼

打開您選擇的語言的主代碼文件:

C#:Program.cs

using System;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;

namespace rest_client
{
class Program
{
private static string AiSvcEndpoint;
private static string AiSvCKey;
static async Task Main(string[] args)
{
try
{
// Get config settings from AppSettings
IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
IConfigurationRoot configuration = builder.Build();
AiSvcEndpoint = configuration["AIServicesEndpoint"];
AiSvCKey = configuration["AIServicesKey"];

// Get user input (until they enter "quit")
string userText = "";
while (userText.ToLower() != "quit")
{
Console.WriteLine("Enter some text ('quit' to stop)");
userText = Console.ReadLine();
if (userText.ToLower() != "quit")
{
// Call function to detect language
await GetLanguage(userText);
}

}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static async Task GetLanguage(string text)
{
// Construct the JSON request body
try
{
JObject jsonBody = new JObject(
// Create a collection of documents (we'll only use one, but you could have more)
new JProperty("documents",
new JArray(
new JObject(
// Each document needs a unique ID and some text
new JProperty("id", 1),
new JProperty("text", text)
))));

// Encode as UTF-8
UTF8Encoding utf8 = new UTF8Encoding(true, true);
byte[] encodedBytes = utf8.GetBytes(jsonBody.ToString());

// Let's take a look at the JSON we'll send to the service
Console.WriteLine(utf8.GetString(encodedBytes, 0, encodedBytes.Length));

// Make an HTTP request to the REST interface
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);

// Add the authentication key to the header
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", AiSvCKey);

// Use the endpoint to access the Text Analytics language API
var uri = AiSvcEndpoint + "text/analytics/v3.1/languages?" + queryString;

// Send the request and get the response
HttpResponseMessage response;
using (var content = new ByteArrayContent(encodedBytes))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
}

// If the call was successful, get the response
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
// Display the JSON response in full (just so we can see it)
string responseContent = await response.Content.ReadAsStringAsync();
JObject results = JObject.Parse(responseContent);
Console.WriteLine(results.ToString());

// Extract the detected language name for each document
foreach (JObject document in results["documents"])
{
Console.WriteLine("\nLanguage: " + (string)document["detectedLanguage"]["name"]);
}
}
else
{
// Something went wrong, write the whole response
Console.WriteLine(response.ToString());
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}

}
}
}

Python: rest-client.py

from dotenv import load_dotenv
import os
import http.client, base64, json, urllib
from urllib import request, parse, error

def main():
global ai_endpoint
global ai_key

try:
# Get Configuration Settings
load_dotenv()
ai_endpoint = os.getenv('AI_SERVICE_ENDPOINT')
ai_key = os.getenv('AI_SERVICE_KEY')

# Get user input (until they enter "quit")
userText =''
while userText.lower() != 'quit':
userText = input('Enter some text ("quit" to stop)\n')
if userText.lower() != 'quit':
GetLanguage(userText)

except Exception as ex:
print(ex)

def GetLanguage(text):
try:
# Construct the JSON request body (a collection of documents, each with an ID and text)
jsonBody = {
"documents":[
{"id": 1,
"text": text}
]
}

# Let's take a look at the JSON we'll send to the service
print(json.dumps(jsonBody, indent=2))

# Make an HTTP request to the REST interface
uri = ai_endpoint.rstrip('/').replace('https://', '')
conn = http.client.HTTPSConnection(uri)

# Add the authentication key to the request header
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': ai_key
}

# Use the Text Analytics language API
conn.request("POST", "/text/analytics/v3.1/languages?", str(jsonBody).encode('utf-8'), headers)

# Send the request
response = conn.getresponse()
data = response.read().decode("UTF-8")

# If the call was successful, get the response
if response.status == 200:

# Display the JSON response in full (just so we can see it)
results = json.loads(data)
print(json.dumps(results, indent=2))

# Extract the detected language name for each document
for document in results["documents"]:
print("\nLanguage:", document["detectedLanguage"]["name"])

else:
# Something went wrong, write the whole response
print(data)

conn.close()

except Exception as ex:
print(ex)

if __name__ == "__main__":
main()

檢查代碼,注意以下細(xì)節(jié):

命名空間和導(dǎo)入:導(dǎo)入各種命名空間以啟用 HTTP 通信。

主要函數(shù):主要函數(shù)檢索 Azure AI 服務(wù)資源的端點(diǎn)和密鑰,用于向文本分析服務(wù)發(fā)送 REST 請求。

用戶輸入:該程序接受用戶輸入并使用該GetLanguage函數(shù)為您的端點(diǎn)調(diào)用文本分析語言檢測 REST API。

JSON 請求:發(fā)送到 API 的請求由包含輸入數(shù)據(jù)的 JSON 對象組成,其中包括文檔對象的集合,每個(gè)對象都有一個(gè) id 和文本。

身份驗(yàn)證:您的服務(wù)的密鑰包含在請求標(biāo)頭中,用于驗(yàn)證您的客戶端應(yīng)用程序。

JSON 響應(yīng):來自服務(wù)的響應(yīng)是客戶端應(yīng)用程序可以解析的 JSON 對象。

4. 運(yùn)行客戶端應(yīng)用程序

右鍵單擊rest-client文件夾,選擇在集成終端中打開,然后運(yùn)行適合您的語言的命令:

Python

C#

5.測試應(yīng)用程序

出現(xiàn)提示時(shí),輸入一些文本來測試語言檢測服務(wù)。例如,您可以嘗試輸入“Hello”、“Bonjour”或“Gracias”。檢測到的語言將在 JSON 響應(yīng)中返回。

6.停止程序

當(dāng)您完成應(yīng)用程序測試后,輸入“quit”以停止該程序。

Azure AI 服務(wù)簡化了向應(yīng)用程序添加復(fù)雜 AI 功能的過程。

通過遵循本指南中概述的步驟,您可以快速配置 Azure AI 服務(wù)資源并開始利用人工智能的強(qiáng)大功能。

無論您構(gòu)建的是需要語言理解、圖像識別還是其他 AI 功能的應(yīng)用程序,Azure AI 服務(wù)都可以提供創(chuàng)新和增強(qiáng)解決方案所需的工具。

文章轉(zhuǎn)自微信公眾號@PikeTalk

上一篇:

文心一言的三種使用方式(附api接入方式)

下一篇:

在.NET?API中使用內(nèi)存中緩存時(shí),性能提高了90%!
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場景實(shí)測,選對API

#AI文本生成大模型API

對比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對比試用API 限時(shí)免費(fèi)