共用方式為


適用於 JavaScript 的 Azure AI 專案用戶端程式庫 - 1.0.1 版

AI Projects 用戶端庫提供對 Azure AI Foundry 專案中資源的輕鬆訪問。 可用於:

  • 使用用戶端上的屬性.agents
  • 使用該方法.inference.azureOpenAI
  • 使用作列舉部署到 Foundry 專案的 .deployments
  • 使用作枚舉 Foundry 專案中.connections
  • 上傳文檔並創建 Datasets 以使用 .datasets 作引用它們。
  • 使用.indexes
  • 使用該函數enable_telemetry

產品文件 | 樣品 | 包 (npm) | API 參考文件 | SDK 源碼

目錄

入門指南

先決條件

授權

  • 需要 Entra ID 來驗證用戶端。 您的應用程式需要實作 TokenCredential 介面的物件。 這裡的程式代碼範例會使用 DefaultAzureCredential。 若要讓該作業正常運作,您將需要:
    • Contributor 角色。 在 Azure 入口網站中,您可以透過 Azure AI 專案資源的 [存取控制] 索引標籤來完成指派的角色。 在此處了解有關角色分配的更多資訊。
    • 已安裝 Azure CLI
    • 執行 az login,即可登入您的 Azure 帳戶。
    • 請注意,如果您有多個 Azure 訂用帳戶,則包含 Azure AI Project 資源的訂用帳戶必須是您的預設訂用帳戶。 執行 az account list --output table 列出您的所有訂用帳戶,並查看哪一個是預設值。 執行 az account set --subscription "Your Subscription ID or Name" 以變更您的預設訂用帳戶。

安裝套件

npm install @azure/ai-projects @azure/identity

重要概念

建立和驗證用戶端

要構造 AIProjectsClient,可以從 endpoint 獲取 。 下面我們假設定義了環境變數 AZURE_AI_PROJECT_ENDPOINT_STRING 來保存此值:

import { AIProjectClient } from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";

const endpoint = process.env["AZURE_AI_PROJECT_ENDPOINT_STRING"] || "<project endpoint string>";
const client = new AIProjectClient(endpoint, new DefaultAzureCredential());

用戶端使用 API 版本 v1,請參閱 API 文件 以瞭解有關支援功能的更多資訊。

範例

執行 Agent作

.agents屬性 AIProjectClient 允許您存取套件中經過身份驗證AgentsClientazure-ai-agents 。 下面我們將介紹如何創建代理並刪除它。 要查看您可以對創建的 執行agent哪些作,請參閱與該包關聯的azure-ai-agents

const agent = await project.agents.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful agent",
});
console.log(`Created agent, agent ID : ${agent.id}`);

// Do something with your Agent!
// See samples here https://github.com/Azure/azure-sdk-for-js/tree/@azure/ai-projects_1.0.1/sdk/ai/ai-agents/samples
await project.agents.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);

獲取經過身份驗證的 AzureOpenAI 用戶端

您的 Azure AI Foundry 專案可能部署了一個或多個支援聊天完成的 OpenAI 模型。 使用以下代碼從 openai 包中獲取經過身份驗證的 AzureOpenAI,並執行聊天完成調用。

運行下面的代碼。 這裡我們假設 deploymentName (str) 已定義。 它是 Foundry 專案中 AI 模型的部署名稱。 如「模型 + 端點」選項卡的「名稱」列下所示。

api_version使用此的 “Data plane - inference” 行中找到的值更新該值。

您還可以選擇(未顯示)在 AI Foundry 專案中顯式指定 Azure OpenAI 連接名稱,該方法 inference.azureOpenAI 將使用此名稱獲取推理終端節點和身份驗證憑據。 如果不存在,將使用預設的 Azure OpenAI 連接。

const client = await project.inference.azureOpenAI({
  // The API version should match the version of the Azure OpenAI resource.
  apiVersion: "2024-10-21",
});
const response = await client.chat.completions.create({
  model: deploymentName,
  messages: [{ role: "user", content: "How many feet are in a mile?" }],
});
console.log("response = ", JSON.stringify(response, null, 2));

有關其他範例,請參閱 包示例中 的“inference”資料夾。

部署作

下面的代碼顯示了一些 Deployments作,這些作允許您枚舉部署到 AI Foundry 專案的 AI 模型。 這些模型可以在 AI Foundry 專案的 「Models + endpoints」 選項卡中看到。 完整的示例可以在 包示例中的 「deployment」 資料夾下找到。

import { ModelDeployment } from "@azure/ai-projects";

const modelPublisher = process.env["MODEL_PUBLISHER"] || "<model publisher>";
console.log("List all deployments:");
const deployments: ModelDeployment[] = [];
const properties: Array<Record<string, string>> = [];

for await (const deployment of project.deployments.list()) {
  // Check if this is a ModelDeployment (has the required properties)
  if (
    deployment.type === "ModelDeployment" &&
    "modelName" in deployment &&
    "modelPublisher" in deployment &&
    "modelVersion" in deployment
  ) {
    deployments.push(deployment);
    properties.push({
      name: deployment.name,
      modelPublisher: deployment.modelPublisher,
      modelName: deployment.modelName,
    });
  }
}
console.log(`Retrieved deployments: ${JSON.stringify(properties, null, 2)}`);

// List all deployments by a specific model publisher (assuming we have one from the list)
console.log(`List all deployments by the model publisher '${modelPublisher}':`);
const filteredDeployments: ModelDeployment[] = [];
for await (const deployment of project.deployments.list({
  modelPublisher,
})) {
  // Check if this is a ModelDeployment
  if (
    deployment.type === "ModelDeployment" &&
    "modelName" in deployment &&
    "modelPublisher" in deployment &&
    "modelVersion" in deployment
  ) {
    filteredDeployments.push(deployment);
  }
}
console.log(
  `Retrieved ${filteredDeployments.length} deployments from model publisher '${modelPublisher}'`,
);

// Get a single deployment by name
if (deployments.length > 0) {
  const deploymentName = deployments[0].name;
  console.log(`Get a single deployment named '${deploymentName}':`);
  const singleDeployment = await project.deployments.get(deploymentName);
  console.log(`Retrieved deployment: ${JSON.stringify(singleDeployment, null, 2)}`);
}

連接作

下面的代碼顯示了一些 Connection作,這些作允許您枚舉連接到 AI Foundry 專案的 Azure 資源。 這些連接可以在 AI Foundry 專案的「管理中心」 的「Connected resources」選項卡中看到。 您可以在 套件範例的 [連線] 資料夾下找到完整範例,

import { Connection } from "@azure/ai-projects";

// List the details of all the connections
const connections: Connection[] = [];
const connectionNames: string[] = [];
for await (const connection of project.connections.list()) {
  connections.push(connection);
  connectionNames.push(connection.name);
}
console.log(`Retrieved connections: ${connectionNames}`);

// Get the details of a connection, without credentials
const connectionName = connections[0].name;
const connection = await project.connections.get(connectionName);
console.log(`Retrieved connection ${JSON.stringify(connection, null, 2)}`);

const connectionWithCredentials = await project.connections.getWithCredentials(connectionName);
console.log(
  `Retrieved connection with credentials ${JSON.stringify(connectionWithCredentials, null, 2)}`,
);

// List all connections of a specific type
const azureAIConnections: Connection[] = [];
for await (const azureOpenAIConnection of project.connections.list({
  connectionType: "AzureOpenAI",
  defaultConnection: true,
})) {
  azureAIConnections.push(azureOpenAIConnection);
}
console.log(`Retrieved ${azureAIConnections.length} Azure OpenAI connections`);

// Get the details of a default connection
const defaultConnection = await project.connections.getDefault("AzureOpenAI", true);
console.log(`Retrieved default connection ${JSON.stringify(defaultConnection, null, 2)}`);

數據集作

下面的代碼展示了一些 Dataset作。 完整示例可以在 包示例的“datasets”資料夾下找到。

import { DatasetVersionUnion } from "@azure/ai-projects";

const VERSION1 = "1.0";
const VERSION2 = "2.0";
const VERSION3 = "3.0";

// sample files to use in the demonstration
const sampleFolder = "sample_folder";
// Create a unique dataset name for this sample run
const datasetName = `sample-dataset-basic`;
console.log("Upload a single file and create a new Dataset to reference the file.");
console.log("Here we explicitly specify the dataset version.");

const dataset1 = await project.datasets.uploadFile(
  datasetName,
  VERSION1,
  path.join(__dirname, sampleFolder, "sample_file1.txt"),
);
console.log("Dataset1 created:", JSON.stringify(dataset1, null, 2));

const credential = project.datasets.getCredentials(dataset1.name, dataset1.version, {});
console.log("Credential for the dataset:", credential);
console.log(
  "Upload all files in a folder (including subfolders) to the existing Dataset to reference the folder.",
);
console.log("Here again we explicitly specify a new dataset version");
const dataset2 = await project.datasets.uploadFolder(
  datasetName,
  VERSION2,
  path.join(__dirname, sampleFolder),
);
console.log("Dataset2 created:", JSON.stringify(dataset2, null, 2));
console.log(
  "Upload a single file to the existing dataset, while letting the service increment the version",
);
const dataset3 = await project.datasets.uploadFile(
  datasetName,
  VERSION3,
  path.join(__dirname, sampleFolder, "sample_file2.txt"),
);
console.log("Dataset3 created:", JSON.stringify(dataset3, null, 2));

console.log("Get an existing Dataset version `1`:");
const datasetVersion1 = await project.datasets.get(datasetName, VERSION1);
console.log("Dataset version 1:", JSON.stringify(datasetVersion1, null, 2));
console.log(`Listing all versions of the Dataset named '${datasetName}':`);
const datasetVersions = await project.datasets.listVersions(datasetName);
for await (const version of datasetVersions) {
  console.log("List versions:", version);
}
console.log("List latest versions of all Datasets:");
const latestDatasets = project.datasets.list();
for await (const dataset of latestDatasets) {
  console.log("List datasets:", dataset);
}
// List the details of all the datasets
const datasets = project.datasets.listVersions(datasetName);
const allDatasets: DatasetVersionUnion[] = [];
for await (const dataset of datasets) {
  allDatasets.push(dataset);
}
console.log(`Retrieved ${allDatasets.length} datasets`);
console.log("Delete all Datasets created above:");
await project.datasets.delete(datasetName, VERSION1);
await project.datasets.delete(datasetName, VERSION2);
await project.datasets.delete(datasetName, dataset3.version);
console.log("All specified Datasets have been deleted.");

索引作

下面的代碼顯示了一些 Indexes作。 完整的示例可以在 包示例的 「indexes」 資料夾下找到。

import { AzureAISearchIndex } from "@azure/ai-projects";

const indexName = "sample-index";
const version = "1";
const azureAIConnectionConfig: AzureAISearchIndex = {
  name: indexName,
  type: "AzureSearch",
  version,
  indexName,
  connectionName: "sample-connection",
};

// Create a new Index
const newIndex = await project.indexes.createOrUpdate(indexName, version, azureAIConnectionConfig);
console.log("Created a new Index:", newIndex);
console.log(`Get an existing Index version '${version}':`);
const index = await project.indexes.get(indexName, version);
console.log(index);
console.log(`Listing all versions of the Index named '${indexName}':`);
const indexVersions = project.indexes.listVersions(indexName);
for await (const indexVersion of indexVersions) {
  console.log(indexVersion);
}
console.log("List all Indexes:");
const allIndexes = project.indexes.list();
for await (const i of allIndexes) {
  console.log("Index:", i);
}
console.log("Delete the Index versions created above:");
await project.indexes.delete(indexName, version);

故障排除

例外狀況

進行服務呼叫的用戶端方法會針對來自服務的非成功 HTTP 狀態代碼回應,引發 RestError。 例外狀況的 code 會保存 HTTP 回應狀態代碼。 例外狀況的 error.message 包含詳細的訊息,可能有助於診斷問題:

import { isRestError } from "@azure/core-rest-pipeline";

try {
  const result = await project.connections.list();
} catch (e) {
  if (isRestError(e)) {
    console.log(`Status code: ${e.code}`);
    console.log(e.message);
  } else {
    console.error(e);
  }
}

例如,當您提供錯誤的認證時:

Status code: 401 (Unauthorized)
Operation returned an invalid status 'Unauthorized'

報告問題

若要回報客戶端連結庫的問題,或要求其他功能,請在這裡開啟 GitHub 問題

後續步驟

請查看 套件範例 資料夾,其中包含完全可執行的程式代碼。

貢獻

此項目歡迎參與和建議。 大部分的捐款都要求您同意「參與者許可協定」(CLA),宣告您有權,而且實際上確實會授與我們使用您貢獻的許可權。 如需詳細資訊,請瀏覽 https://cla.microsoft.com

當您提交提取要求時,CLA-Bot 會自動判斷您是否需要提供 CLA 並適當裝飾 PR(例如標籤、批註)。 只要遵循 Bot 所提供的指示即可。 您只需要使用我們的 CLA 在所有存放庫上執行此動作一次。

此專案採用了 Microsoft 開放原始碼管理辦法。 如需詳細資訊,請參閱《管理辦法》常見問題或連絡 opencode@microsoft.com,以取得任何其他問題或意見。