鍵.png)
GraphRAG:基于PolarDB+通義千問api+LangChain的知識圖譜定制實(shí)踐
單擊“創(chuàng)建”開始配置新的多服務(wù)帳戶資源。
創(chuàng)建 Azure AI 服務(wù)資源時(shí),需要配置以下設(shè)置:
選擇您的 Azure 訂閱。
選擇現(xiàn)有資源組或創(chuàng)建新資源組。如果您的權(quán)限受限,請使用提供給您的資源組。
選擇適合您需求的可用區(qū)域。
為您的資源輸入一個(gè)唯一的名稱。
選擇標(biāo)準(zhǔn) S0作為定價(jià)層。
部署完成后,請按照以下步驟查看資源詳細(xì)信息:
此頁面包含連接到資源的基本信息,包括:
HTTP 端點(diǎn):客戶端應(yīng)用程序可以發(fā)送請求的端點(diǎn)。
身份驗(yàn)證密鑰:客戶端應(yīng)用程序可用于身份驗(yàn)證的兩個(gè)密鑰。任一密鑰均可用于對請求進(jìn)行身份驗(yàn)證。
Location:資源的托管位置,某些 API 請求需要該位置。
設(shè)置 Azure AI 服務(wù)資源后,你現(xiàn)在可以將 AI 功能整合到應(yīng)用程序中。以下是如何使用這些服務(wù)的一般概述:
使用提供的 HTTP 端點(diǎn)從客戶端應(yīng)用程序發(fā)送請求。確保在請求標(biāo)頭中包含其中一個(gè)身份驗(yàn)證密鑰。
處理來自 Azure AI 服務(wù)的響應(yīng),以將 AI 功能(例如自然語言處理、計(jì)算機(jī)視覺或其他功能)合并到您的應(yīng)用程序中。
對于某些 API,您需要在請求中指定資源的位置。
將 REST 接口與 Azure AI 服務(wù)結(jié)合使用
Azure AI 服務(wù) API 基于 REST,允許你通過 HTTP 發(fā)送 JSON 請求來與它們交互。
在本文中,我們將介紹一個(gè)使用控制臺應(yīng)用程序使用語言 REST API 執(zhí)行語言檢測的示例。
此原則適用于 Azure AI 服務(wù)資源支持的所有 API。
先決條件
您可以選擇使用 C# 或 Python 進(jìn)行此練習(xí)。根據(jù)您的偏好,在 Visual Studio Code 中展開相應(yīng)的文件夾:
導(dǎo)航到rest-client文件夾并打開配置文件:
C#:appsettings.json
Python:.env
更新配置值以反映您的 Azure AI 服務(wù)端點(diǎn)和身份驗(yàn)證密鑰,然后保存更改。
打開您選擇的語言的主代碼文件:
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 對象。
右鍵單擊rest-client文件夾,選擇在集成終端中打開,然后運(yùn)行適合您的語言的命令:
Python
C#
出現(xiàn)提示時(shí),輸入一些文本來測試語言檢測服務(wù)。例如,您可以嘗試輸入“Hello”、“Bonjour”或“Gracias”。檢測到的語言將在 JSON 響應(yīng)中返回。
當(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
GraphRAG:基于PolarDB+通義千問api+LangChain的知識圖譜定制實(shí)踐
使用Node.js、Express和MySQL構(gòu)建REST API
天氣API推薦:精準(zhǔn)獲取氣象數(shù)據(jù)的首選
基于自定義數(shù)據(jù)集的微調(diào):Alpaca與LLaMA模型的訓(xùn)練
OAuth和OpenID Connect圖解指南
有哪些新聞媒體提供Open API?
現(xiàn)在做大模型,還有靠譜且免費(fèi)的API接口嗎?
如何運(yùn)用AI提高自己的工作效率?
區(qū)塊鏈API推薦,快速開發(fā)去中心化應(yīng)用