共用方式為


The Azure AI Foundry SDK

Azure AI Foundry SDK 是一個全方位的工具鏈,旨在簡化 Azure 上的 AI 應用程式開發。 它可讓開發人員:

  • 透過單一介面從各種模型提供者存取熱門模型
  • 輕鬆地將模型、數據和 AI 服務結合在一起,以建置 AI 支援的應用程式
  • 跨開發、測試和生產環境評估、偵錯及改善應用程式品質與安全性

Azure AI Foundry SDK 是一組套件和服務,其設計目的是一起運作。 您可以使用 Azure AI Projects 用戶端連結庫,透過單一專案用戶端和 連接字串 輕鬆地使用多個服務。 您也可以自行使用服務和 SDK,並直接連線到您的服務。

如果您要直接進入並開始建置應用程式,請參閱:

開始使用專案

開始使用 Azure AI Foundry SDK 的最佳方式是使用專案。 AI 專案會將建置 AI 應用程式所需的不同數據、資產和服務連接在一起。 AI 專案用戶端可讓您使用單一 連接字串,輕鬆地從程式代碼存取這些項目元件。

如果您還沒有 AI 專案,請先遵循步驟來 建立 AI 專案

使用您用來存取 AI 專案的相同帳戶來登入 Azure CLI:

az login

安裝 Azure AI 專案用戶端連結庫:

pip install azure-ai-projects azure-identity

在程式代碼建立專案用戶端:

from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient

project_connection_string="your_connection_string"

project = AIProjectClient.from_connection_string(
  conn_str=project_connection_string,
  credential=DefaultAzureCredential())
dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity

新增 using 語句:

using Azure.Identity;
using Azure.AI.Projects;

在程式代碼建立專案用戶端:

var connectionString = "<your_connection_string>";
var projectClient = new AIProjectClient(connectionString, new DefaultAzureCredential());

專案的 [概觀] 頁面複製 Project 連接字串,並更新上述的連接字串值。

建立專案客戶端之後,您可以使用用戶端來取得下列各節中的功能。

請務必查看 參考範例

請務必查看 參考範例

Azure OpenAI 服務

Azure OpenAI 服務可讓您存取 OpenAI 的模型,包括 GPT-4o、GPT-4o mini、GPT-4、GPT-4 Turbo with Vision、DALLE-3、Whisper 和 Embeddings 模型系列,以及 Azure 的數據落地、延展性、安全性、安全性和企業功能。

如果您有使用 OpenAI SDK 的程式碼,您可以輕鬆地將程式代碼設為使用 Azure OpenAI 服務的目標。 首先,安裝 OpenAI SDK:

pip install openai

如果您有使用 OpenAI SDK 的現有程式代碼,您可以使用專案用戶端來建立 AzureOpenAI 使用您專案 Azure OpenAI 連線的用戶端:

openai = project.inference.get_azure_openai_client(api_version="2024-06-01")
response = openai.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful writing assistant"},
        {"role": "user", "content": "Write me a poem about flowers"},
    ]
)

print(response.choices[0].message.content)
dotnet add package Azure.AI.OpenAI

新增 using 語句:

using OpenAI.Chat;
using Azure.AI.OpenAI;

如果您有使用 OpenAI SDK 的現有程式代碼,您可以使用專案用戶端來建立 AzureOpenAI 使用您專案 Azure OpenAI 連線的用戶端:

var connections = projectClient.GetConnectionsClient();
ConnectionResponse connection = connections.GetDefaultConnection(ConnectionType.AzureOpenAI, withCredential: true);
var properties = connection.Properties as ConnectionPropertiesApiKeyAuth;

if (properties == null) {
    throw new Exception("Invalid auth type, expected API key auth");
}

// Create and use an Azure OpenAI client
AzureOpenAIClient azureOpenAIClient = new(
    new Uri(properties.Target),
    new AzureKeyCredential(properties.Credentials.Key));

// This must match the custom deployment name you chose for your model
ChatClient chatClient = azureOpenAIClient.GetChatClient("gpt-4o-mini");

ChatCompletion completion = chatClient.CompleteChat(
    [
        new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
        new UserChatMessage("Does Azure OpenAI support customer managed keys?"),
        new AssistantChatMessage("Yes, customer managed keys are supported by Azure OpenAI"),
        new UserChatMessage("Do other Azure AI services support this too?")
    ]);

Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");

如果您已經直接對 Azure OpenAI 服務使用 Azure OpenAI SDK ,專案會提供方便的方式,將 Azure OpenAI 服務功能與其餘的 Azure AI Foundry 功能搭配使用。

Azure AI 模型推斷服務

Azure AI 模型推斷服務可讓您從 OpenAI、Microsoft、Meta 等領先提供者存取功能強大的模型。 這些模型支援工作,例如內容產生、摘要和程式代碼產生。

若要使用模型推斷服務,請先確定您的專案具有 AI 服務連線(在管理中心)。

安裝客戶端連結 azure-ai-inference 庫:

pip install azure-ai-inference

您可以使用專案用戶端來取得已設定與驗證 ChatCompletionsClient 的或 EmbeddingsClient

# get an chat inferencing client using the project's default model inferencing endpoint
chat = project.inference.get_chat_completions_client()

# run a chat completion using the inferencing client
response = chat.complete(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful writing assistant"},
        {"role": "user", "content": "Write me a poem about flowers"},
    ]
)

print(response.choices[0].message.content)
dotnet add package Azure.AI.Inference

新增 using 語句:

using Azure.AI.Inference;

您可以使用專案用戶端來取得已設定與驗證 ChatCompletionsClient 的或 EmbeddingsClient

var connectionString = Environment.GetEnvironmentVariable("AIPROJECT_CONNECTION_STRING");
var projectClient = new AIProjectClient(connectionString, new DefaultAzureCredential());

ChatCompletionsClient chatClient = projectClient.GetChatCompletionsClient();

var requestOptions = new ChatCompletionsOptions()
{
    Messages =
        {
            new ChatRequestSystemMessage("You are a helpful assistant."),
            new ChatRequestUserMessage("How many feet are in a mile?"),
        },
    Model = "gpt-4o-mini"
};

Response<ChatCompletions> response = chatClient.Complete(requestOptions);
Console.WriteLine(response.Value.Content);

您可以將模型名稱變更為部署至推斷服務或 Azure OpenAI 服務的任何模型。

若要深入瞭解如何使用 Azure AI 推斷用戶端,請參閱 Azure AI 模型推斷參考

提示範本

推斷客戶端支援從範本建立提示訊息。 範本可讓您使用運行時間可用的輸入,動態產生提示。

若要使用提示範本,請安裝 azure-ai-inference 套件:

pip install azure-ai-inference

您可以從內嵌字串轉譯提示樣本:

from azure.ai.inference.prompts import PromptTemplate

# create a prompt template from an inline string (using mustache syntax)
prompt_template = PromptTemplate.from_string(prompt_template="""
    system:
    You are a helpful writing assistant.
    The user's first name is {{first_name}} and their last name is {{last_name}}.

    user:
    Write me a poem about flowers
    """)

# generate system message from the template, passing in the context as variables
messages = prompt_template.create_messages(first_name="Jane", last_name="Doe")
print(messages)

注意

前置空格元會自動從輸入字串修剪。

此程式代碼會輸出訊息,然後傳遞至聊天完成通話:

[
  {'role': 'system', 'content': "You are a helpful writing assistant.\nThe user's first name is Jane and their last name is Doe."}
  {'role': 'user', 'content': 'Write me a poem about flowers'}
]

您也可以從 Prompty 檔案載入提示,讓您也能從 .prompty 檔案載入模型名稱和參數:

from azure.ai.inference.prompts import PromptTemplate

prompt_template = PromptTemplate.from_prompty("myprompt.prompty")
messages = prompt_template.create_messages(first_name="Jane", last_name="Doe")

response = chat.complete(
    messages=messages,
    model=prompt_template.model_name,
    **prompt_template.parameters,
)

如果您有連線到專案的 Azure AI 搜尋資源,也可以使用專案用戶端,使用專案連線建立 Azure AI 搜尋用戶端。

安裝 Azure AI 搜尋用戶端連結庫:

pip install azure-search-documents

視需要具現化搜尋和/或搜尋索引用戶端:

from azure.core.credentials import AzureKeyCredential
from azure.ai.projects.models import ConnectionType
from azure.search.documents import SearchClient
from azure.search.documents.indexes import SearchIndexClient

# use the project client to get the default search connection
search_connection = project.connections.get_default(
    connection_type=ConnectionType.AZURE_AI_SEARCH,
    with_credentials=True)

# Create a client to create and manage search indexes
index_client = SearchIndexClient(
    endpoint=search_connection.endpoint_url,
    credential=AzureKeyCredential(key=search_connection.key)
)

# Create a client to run search queries
search_client = SearchClient(
    index_name="your_index_name",
    endpoint=search_connection.endpoint_url,
    credential=AzureKeyCredential(key=search_connection.key)
)
dotnet add package Azure.Search.Documents

新增 using 語句:

using Azure.Search.Documents;
using Azure.Search.Documents.Models;

視需要具現化搜尋和/或搜尋索引用戶端:

var connections = projectClient.GetConnectionsClient();
var connection = connections.GetDefaultConnection(ConnectionType.AzureAISearch, withCredential: true).Value;

var properties = connection.Properties as ConnectionPropertiesApiKeyAuth;
if (properties == null) {
    throw new Exception("Invalid auth type, expected API key auth");
}

SearchClient searchClient = new SearchClient(
    new Uri(properties.Target),
    "products",
    new AzureKeyCredential(properties.Credentials.Key));

若要深入瞭解如何使用 Azure AI 搜尋,請參閱 Azure AI 搜尋檔

Azure AI 代理程序服務

Azure AI 代理程式服務是完全受控的服務,可讓開發人員安全地建置、部署及調整高品質且可延伸的 AI 代理程式。 Azure AI 代理程式服務使用來自 OpenAI、Microsoft和第三方提供者的模型、工具和功能的廣泛生態系統,可為各種產生式 AI 使用案例建置代理程式。

評估

您可以使用專案用戶端輕鬆地連線到 Azure AI 評估服務,以及執行評估工具所需的模型。

pip install azure-ai-evaluation

project.scope使用 參數,我們可以具現化 ViolenceEvaluator

from azure.ai.evaluation import ViolenceEvaluator
from azure.identity import DefaultAzureCredential

# Initializing Violence Evaluator with project information
violence_eval = ViolenceEvaluator(
    azure_ai_project=project.scope,
    credential=DefaultAzureCredential())

# Running Violence Evaluator on single input row
violence_score = violence_eval(query="what's the capital of france", response="Paris")
print(violence_score)

注意:若要執行暴力評估工具,您的專案必須位於美國東部 2、瑞典中部、美國中北部、法國中部。

若要深入瞭解,請參閱 使用 SDK 的評估。

C# 尚未提供 Azure AI 評估套件。 如需如何使用 Prompty 和 Semantic Kernel 進行評估的範例,請參閱 contoso-chat-csharp-prompty 範例。

追蹤

若要啟用追蹤,請先確定您的專案具有附加的 Application Insights 資源。 移至專案的 [ 追蹤 ] 頁面,並遵循指示來建立或附加 Application Insights。

安裝 Azure 監視器 OpenTelemetry 套件:

pip install azure-monitor-opentelemetry

使用下列程式代碼來啟用 Azure AI 推斷 SDK 的檢測,並記錄至您的 AI 專案:

from azure.monitor.opentelemetry import configure_azure_monitor

# Enable instrumentation of AI packages (inference, agents, openai, langchain)
project.telemetry.enable()

# Log traces to the project's application insights resource
application_insights_connection_string = project.telemetry.get_connection_string()
if application_insights_connection_string:
    configure_azure_monitor(connection_string=application_insights_connection_string)

追蹤尚未整合到專案套件中。 如需如何從 Azure AI 推斷套件檢測和記錄追蹤的指示,請參閱 azure-sdk-for-dotnet

以下是一些可搭配 Azure AI Foundry SDK 使用之其他服務和架構的實用連結。

Azure AI 服務

用戶端連結庫:

管理連結庫:

架構

Azure Machine Learning

提示流程

語意核心