單擊“創建”開始配置新的多服務帳戶資源。

步驟 3:配置資源設置

創建 Azure AI 服務資源時,需要配置以下設置:

訂閱:

選擇您的 Azure 訂閱。

資源組:

選擇現有資源組或創建新資源組。如果您的權限受限,請使用提供給您的資源組。

區域:

選擇適合您需求的可用區域。

名稱:

為您的資源輸入一個唯一的名稱。

定價層:

選擇標準 S0作為定價層。

步驟 4:完成并創建資源

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

2、單擊“創建”以部署您的資源。

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

步驟 5:訪問資源詳細信息

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

1、進入資源頁面,查看部署詳情。

2、導航到密鑰和端點頁面。

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

HTTP 端點:客戶端應用程序可以發送請求的端點。
身份驗證密鑰:客戶端應用程序可用于身份驗證的兩個密鑰。任一密鑰均可用于對請求進行身份驗證。

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

在您的應用程序中使用 Azure AI 服務

設置 Azure AI 服務資源后,你現在可以將 AI 功能整合到應用程序中。以下是如何使用這些服務的一般概述:

1、發出 HTTP 請求:

使用提供的 HTTP 端點從客戶端應用程序發送請求。確保在請求標頭中包含其中一個身份驗證密鑰。

2、處理響應:

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

3、特定區域的 API:

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

將 REST 接口與 Azure AI 服務結合使用

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

在本文中,我們將介紹一個使用控制臺應用程序使用語言 REST API 執行語言檢測的示例。

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

先決條件

設置你的項目

1. 選擇您的首選語言

您可以選擇使用 C# 或 Python 進行此練習。根據您的偏好,在 Visual Studio Code 中展開相應的文件夾:

2.更新配置設置

導航到rest-client文件夾并打開配置文件:

C#:appsettings.json

Python:.env

更新配置值以反映您的 Azure AI 服務端點和身份驗證密鑰,然后保存更改。

3.檢查客戶端應用程序代碼

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

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()

檢查代碼,注意以下細節:

命名空間和導入:導入各種命名空間以啟用 HTTP 通信。

主要函數:主要函數檢索 Azure AI 服務資源的端點和密鑰,用于向文本分析服務發送 REST 請求。

用戶輸入:該程序接受用戶輸入并使用該GetLanguage函數為您的端點調用文本分析語言檢測 REST API。

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

身份驗證:您的服務的密鑰包含在請求標頭中,用于驗證您的客戶端應用程序。

JSON 響應:來自服務的響應是客戶端應用程序可以解析的 JSON 對象。

4. 運行客戶端應用程序

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

Python

C#

5.測試應用程序

出現提示時,輸入一些文本來測試語言檢測服務。例如,您可以嘗試輸入“Hello”、“Bonjour”或“Gracias”。檢測到的語言將在 JSON 響應中返回。

6.停止程序

當您完成應用程序測試后,輸入“quit”以停止該程序。

Azure AI 服務簡化了向應用程序添加復雜 AI 功能的過程。

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

無論您構建的是需要語言理解、圖像識別還是其他 AI 功能的應用程序,Azure AI 服務都可以提供創新和增強解決方案所需的工具。

文章轉自微信公眾號@PikeTalk

上一篇:

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

下一篇:

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

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

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

10個渠道
一鍵對比試用API 限時免費