次の方法で共有


JavaScript 用 Azure AI プロジェクト クライアント ライブラリ - バージョン 1.0.0-beta.8

AI Projects クライアント ライブラリを使用すると、Azure AI Foundry プロジェクトのリソースに簡単にアクセスできます。 これは次の目的で使用されます。

  • クライアントで Agent の プロパティを使用して.agents
  • メソッドを使用して .inference.azureOpenAI
  • 操作を使用して、Foundry プロジェクトにデプロイされた .deploymentsします。
  • 操作を使用して、Foundry プロジェクト.connectionsします。
  • ドキュメントをアップロードし、.datasets操作を使用して参照するデータセットを作成します。
  • 操作を使用して.indexesします。
  • Azure AI Inference クライアントを取得して.inference 操作を使用してチャットの完了、テキストまたは画像の埋め込みを行います。
  • Prompty ファイルまたは文字列を読み取りPromptTemplate クラスを使用して推論クライアント用のメッセージをレンダリングします。
  • 操作を使用して、生成 AI アプリケーションのパフォーマンスを評価します。
  • 関数を使用して enable_telemetry

製品ドキュメント | サンプル | パッケージ(npm) | API リファレンス ドキュメント | SDK ソースコード

目次

はじめ

前提

認証

  • Entra ID は、クライアントを認証するために必要です。 アプリケーションには、TokenCredential インターフェイスを実装するオブジェクトが必要です。 ここでのコード サンプルでは、DefaultAzureCredential使用します。 この作業を行うには、次のものが必要です。
    • Contributor ロール。 割り当てられたロールは、Azure portal の Azure AI プロジェクト リソースの [アクセス制御 (IAM)]タブを使用して実行できます。 ロールの割り当ての詳細については 、こちらをご覧ください
    • 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を作成するには:

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

エージェント操作の実行

.agentsAIProjectClient プロパティを使用すると、AgentsClient パッケージから認証されたazure-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.0-beta.8/sdk/ai/ai-agents/samples
await project.agents.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);

認証された AzureOpenAI クライアントを取得する

Azure AI Foundry プロジェクトには、チャットの完了をサポートする 1 つ以上の OpenAI モデルがデプロイされている場合があります。 次のコードを使用して、openai パッケージから認証された AzureOpenAI を取得し、チャット完了呼び出しを実行します。

以下のコードを実行します。 ここでは、 deploymentName (str) が定義されていると仮定します。 これは、Foundry プロジェクトの AI モデルのデプロイ名です。 [モデル + エンドポイント] タブの [名前] 列に示されているように。

api_versionの [データ プレーン - 推論] 行にある 1 つで 値を更新します。

また、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));

その他のサンプルについては、 パッケージ samples の "inference" フォルダーを参照してください。

認証された ChatCompletionsClient を取得する

Azure AI Foundry プロジェクトには、チャットの完了をサポートする 1 つ以上の AI モデルがデプロイされている場合があります。 これらは、OpenAI モデル、Microsoft モデル、または他のプロバイダーのモデルである可能性があります。 次のコードを使用して、 azure-ai-inference パッケージから認証されたクライアントを取得し、チャット完了呼び出しを実行します。

ここでは、 deploymentName (str) が定義されていると仮定します。 これは、Foundry プロジェクトの AI モデルのデプロイ名です。 [モデル + エンドポイント] タブの [名前] 列に示されているように。

const client = project.inference.chatCompletions();
const response = await client.post({
  body: {
    model: deploymentName,
    messages: [{ role: "user", content: "How many feet are in a mile?" }],
  },
});
console.log(response.body.choices[0].message.content);

その他のサンプルについては、 パッケージ samples の "inference" フォルダーを参照してください。

デプロイ操作

次のコードは、AI Foundry プロジェクトにデプロイされた AI モデルを列挙できる一部の Deployments 操作を示しています。 これらのモデルは、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)}`);
}

接続操作

次のコードは、AI Foundry プロジェクトに接続されている Azure リソースを列挙できる一部の接続操作を示しています。 これらの接続は、AI Foundry プロジェクトの [Management Center] の [Connected resources] タブで確認できます。 完全なサンプルは、パッケージ サンプルの "connections" フォルダーにあります。

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)}`);

データセットの操作

次のコードは、一部のデータセット操作を示しています。 完全なサンプルは、 パッケージ samples の "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);

評価

Azure AI Project クライアント ライブラリの評価は、クラウド内のジェネレーティブ AI アプリケーションのパフォーマンスを評価するように設計されています。 ジェネレーティブAIアプリケーションの出力は、数学的ベースのメトリクス、AI支援の品質および安全性メトリクスで定量的に測定されます。 メトリックはエバリュエーターとして定義されます。 組み込みエバリュエーターまたはカスタムエバリュエーターは、アプリケーションの機能と制限に関する包括的な分析情報を提供できます。

エバリュエータ

エバリュエーターは、言語モデルまたは生成 AI アプリケーションからの出力の品質を測定するように設計された、カスタムまたは事前構築済みのクラスまたは関数です。

エバリュエーターは、ローカル エクスペリエンスの場合は azure-ai-evaluation SDK を介して、クラウドで使用する場合は Azure AI Foundry の Evaluator Library で利用できます。

組み込みエバリュエーターとカスタムエバリュエーターの詳細については、 こちらをご覧ください

クラウドでの評価の実行

クラウドで評価を実行するには、次のものが必要です。

  • エバリュエーター
  • 評価するデータ
  • [オプション]Azure Open AI モデル。
エバリュエーター

エバリュエーターをクラウドで実行するには、エバリュエーター ID が必要です。 コードで取得するには、azure-ai-evaluation を使用します

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

const dataset: DatasetVersion = await project.datasets.uploadFile(
  "jss-eval-sample-dataset",
  "1",
  "./samples_folder/sample_data_evaluation.jsonl",
);
評価するデータ

クラウドでの評価は、 jsonl ファイル形式のデータをサポートします。 データは、プロジェクトクライアントで upload_file ヘルパーメソッドを介してアップロードできます。

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

const dataset: DatasetVersion = await project.datasets.uploadFile(
  "jss-eval-sample-dataset",
  "1",
  "./samples_folder/sample_data_evaluation.jsonl",
);
[オプション]Azure OpenAI モデル

Azure AI Foundry プロジェクトには、次のコードを使用して簡単にアクセスできる既定の Azure Open AI エンドポイントが付属しています。 これにより、Azure OpenAI エンドポイントのエンドポイントの詳細が表示されます。 一部の評価者は、チャットの完了をサポートするモデルを必要としています。

const defaultConnection = await project.connections.getDefault("AzureOpenAI");
リモート評価の例
import { EvaluationWithOptionalName, EvaluatorIds, Evaluation } from "@azure/ai-projects";

const newEvaluation: EvaluationWithOptionalName = {
  displayName: "Evaluation 1",
  description: "This is a test evaluation",
  data: {
    type: "dataset",
    id: "data-id", // dataset.name
  },
  evaluators: {
    relevance: {
      id: EvaluatorIds.RELEVANCE,
      initParams: {
        deploymentName: "gpt-4o-mini",
      },
      dataMapping: {
        query: "${data.query}",
        response: "${data.response}",
      },
    },
  },
};
const evalResp = await project.evaluations.createRun(newEvaluation);
console.log("Create a new evaluation:", JSON.stringify(evalResp, null, 2));
// get the evaluation by ID
const eval2 = await project.evaluations.get(evalResp.name);
console.log("Get the evaluation by ID:", eval2);

const evaluations: Evaluation[] = [];
const evaluationNames: string[] = [];
for await (const evaluation of project.evaluations.list()) {
  evaluations.push(evaluation);
  evaluationNames.push(evaluation.displayName ?? "");
}
console.log("List of evaluation display names:", evaluationNames);

// This is temporary, as interface recommend the name of the evaluation
const name = evaluations[0].name;
const evaluation = await project.evaluations.get(name);
console.log("Get an evaluation by ID:", JSON.stringify(evaluation, null, 2));

注: エバリュエーターをローカルで実行する方法については、「 Azure AI Evaluation SDK を使用した評価」を参照してください。

トラブルシューティング

例外

サービス呼び出しを行うクライアント メソッドは、サービスからの成功しない 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 ボットは、CLA を提供し、PR を適切に装飾する必要があるかどうかを自動的に判断します (ラベル、コメントなど)。 ボットによって提供される指示に従うだけです。 これは、CLA を使用するすべてのリポジトリで 1 回だけ行う必要があります。

このプロジェクトでは、Microsoft オープン ソースの行動規範を採用しています。 詳細については、行動規範に関する FAQ を参照するか、その他の質問やコメントを opencode@microsoft.com にお問い合わせください。