Azure AI Projects クライアントライブラリ for JavaScript - バージョン 2.11.0

AI Projects クライアントライブラリは Microsoft Foundry SDK の一部であり、Microsoft Foundry Project 内のリソースに簡単にアクセスできるようサポートします。 これは次の目的で使用されます。

  • クライアントの.agentsプロパティを使用してエージェントを作成および実行します。
  • 専門ツールでエージェントを強化する:
    • エージェントメモリーサーチ(プレビュー)
    • エージェント間通信(A2A)(プレビュー)
    • Azure AI 検索
    • Bingカスタム検索(プレビュー)
    • Bingグラウンドング
    • ブラウザーの自動化
    • コード インタープリター
    • コンピューターの使用
    • ファイル検索
    • ファンクションツール
    • 画像生成
    • Microsoft Fabric(プレビュー版)
    • モデル コンテキスト プロトコル (MCP)
    • OpenAPI
    • Microsoft SharePoint(プレビュー)
    • ウェブ検索(プレビュー)
    • ツール検索
  • .getOpenAIClient.メソッドを使って、エージェントと一緒にレスポンス、会話、評価、ファインチューニング操作を実行するOpenAIクライアントを用意しましょう。
  • セッションをサポートする展開上で、.agents操作を使用してホストされたエージェントセッションとファイルを管理します。
  • .beta.skills操作を使用して再利用可能なエージェント機能のスキル管理(プレビュー)。
  • .toolboxes操作を使用してツールを再利用可能なコレクションにグループ化するためのツールボックスを管理します。
  • .beta.memoryStores操作を使用してエージェント会話のメモリストア(プレビュー)を管理します。
  • .beta.routines操作を使用して、自動ワークフローのスケジューリングおよびディスパッチのためのルーティン(プレビュー)を管理します。
  • .beta.models操作を使用してカスタムモデルバージョンの作成、更新、管理を行うモデルバージョン(プレビュー)を管理します。
  • .evaluationRules、.beta.evaluationTaxonomies、.beta.evaluators、.beta.insights、.beta.schedules操作を用いて、生成AIアプリケーションのパフォーマンスを評価するための追加の評価ツール(プレビュー中のものもあります)を探索してください。
  • Red Teamスキャン(プレビュー)を実行し 、 .beta.redTeams 操作を使って生成AIアプリケーションに関連するリスクを特定します。
  • 微調整 あなたのデータにAIモデルを活用。
  • .deployments操作を使用してファウンドリー Projectに展開したAIモデルを列挙します。
  • .connections操作を使用して、Foundry プロジェクト内の接続されたAzureリソースを列挙します。
  • ドキュメントをアップロードし、.datasets操作を使ってそれらを参照するためのデータセットを作成します。
  • .indexes操作を使用して検索インデックスを作成および列挙します。

クライアントライブラリはMicrosoft Foundry v1のバージョンを使用しています。

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

目次

作業の開始

前提条件

認可

  • クライアントを認証するにはEntra IDが必要です。 アプリケーションには、TokenCredential インターフェイスを実装するオブジェクトが必要です。 ここでのコードサンプルはDefaultAzureCredentialを使用しています。 この作業を行うには、次のものが必要です。
    • 適切な役割割り当て。 Foundryポータルの役割ベースのアクセス制御Microsoftを参照してください。 役割の割り当ては、Azureポータル内のAzure AI Projectリソースの「Access Control (IAM)」タブから行えます。
    • Azure CLI がインストール済み。
    • Azureアカウントにaz loginを実行してログインします。
    • 複数のAzureサブスクリプションがある場合、Azure AI Projectリソースを含むサブスクリプションがデフォルトのサブスクリプションである必要があります。 az account list --output table 実行して、すべてのサブスクリプションを一覧表示し、既定のサブスクリプションを確認します。 az account set --subscription "Your Subscription ID or Name" を実行して、既定のサブスクリプションを変更します。

パッケージ をインストールする

npm install @azure/ai-projects dotenv

主な概念

Entra IDでクライアントを作成・認証する

Entra IDは現在クライアントがサポートしている唯一の認証方法です。

AIProjectsClientを構築するには、projectEndpoint からを取得できます。 以下では、環境変数 FOUNDRY_PROJECT_ENDPOINT がこの値を保持するように定義されていると仮定します。

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

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

プレビュー運用グループとオプトイン機能フラグ

一部のプレビュー操作では、明示的な foundryFeatures オプトインフラグが必要です。 例えば次が挙げられます。

await project.agents.createVersion(
  "preview-agent",
  {
    kind: "workflow",
  },
  { foundryFeatures: "WorkflowAgents=V1Preview" },
);
for await (const rule of project.evaluationRules.list()) {
  console.log(rule.id);
}

プレビュー運用グループには、 .beta.voiceAgents、 .beta.skills、 .beta.memoryStores、 .beta.routines、 .beta.models、 .beta.evaluationTaxonomies、 .beta.evaluators、、 .beta.insights、 .beta.schedules、 .beta.redTeamsが含まれます。 ボイスエージェントにはGA機能とプレビュー機能の両方があります。オプトイン要件については 、ボイスエージェントの運用 を参照してください。

.agentInsightMonitorsを使って、エージェントを分析するモニターを一覧にしてください:

for await (const monitor of project.agentInsightMonitors.list()) {
  console.log(`${monitor.id}: ${monitor.agent_name}`);
}

例

OpenAIクライアントを使用したレスポンス操作の実行

あなたのMicrosoft Foundryプロジェクトには、1つ以上のAIモデルが展開されている場合があります。 これらはOpenAIモデル、Microsoftモデル、または他のプロバイダーのモデルかもしれません。 以下のコードを使用して、openai パッケージから認証された OpenAI を取得し、チャット完了呼び出しを実行します。

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

ストリーミング回答を含む追加のサンプルについては、package samplesの「responses」フォルダをご覧ください。

const openAIClient = project.getOpenAIClient();
const response = await openAIClient.responses.create({
  model: deploymentName,
  input: "What is the size of France in square miles?",
});
console.log("response = ", JSON.stringify(response, null, 2));
const detailResponse = await openAIClient.responses.create({
  model: deploymentName,
  input: "And what is the capital city?",
  previous_response_id: response.id,
});
console.log("detailed response = ", JSON.stringify(detailResponse, null, 2));

エージェント操作の実行

.agentsのAIProjectsClientプロパティを使用すると、すべてのエージェント操作にアクセスできます。 エージェントは OpenAI Responses プロトコルの拡張機能を使用するため、以下の例に示すように、エージェント操作を実行するには OpenAI クライアントを取得する必要がある可能性があります。

セットアップについては「Quickstart: Set Up Microsoft Foundry resources」をご覧ください。

const openAIClient = project.getOpenAIClient();
const agent = await project.agents.createVersion("my-agent-basic", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant that answers general questions",
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
const conversation = await openAIClient.conversations.create({
  items: [
    { type: "message", role: "user", content: "What is the size of France in square miles?" },
  ],
});
console.log(`Created conversation with initial user message (id: ${conversation.id})`);
// Generate response using the agent
console.log("\nGenerating response...");
const response = await openAIClient.responses.create(
  {
    conversation: conversation.id,
  },
  {
    body: { agent: { name: agent.name, type: "agent_reference" } },
  },
);
console.log(`Response output: ${response.output_text}`);
// Add a second user message to the conversation
console.log("\nAdding a second user message to the conversation...");
await openAIClient.conversations.items.create(conversation.id, {
  items: [{ type: "message", role: "user", content: "And what is the capital city?" }],
});
console.log("Added a second user message to the conversation");
// Generate second response
console.log("\nGenerating second response...");
const response2 = await openAIClient.responses.create(
  {
    conversation: conversation.id,
  },
  {
    body: { agent: { name: agent.name, type: "agent_reference" } },
  },
);
console.log(`Response output: ${response2.output_text}`);
// Clean up
console.log("\nCleaning up resources...");
await openAIClient.conversations.delete(conversation.id);
console.log("Conversation deleted");
await project.agents.deleteVersion(agent.name, agent.version);
console.log("Agent deleted");

ボイスエージェントの運用

project.agentsを使ってボイスエージェントを作成・管理します。 エージェントに合う接続クライアントを選択してください:

  • project.voiceAgents.realtime リアルタイムおよびカスケード音声エージェント向けに。
  • project.beta.voiceAgents.live GPT Live(プレビュー)用。

古い project.beta.voiceAgents.realtime パスは、同じクライアント用の非推奨の互換性エイリアスです。 新しいコードではルートパスを使用してください。 通常のリアルタイム接続はGAであり、 デフォルトではVoiceAgentsのプレビューオプトインを送信しません。

Scope APIまたは機能 VoiceAgents=V1Preview
GA リアルタイム/カスケード定義、代理サブエージェント、電話システムツール project.agents 必須ではない
GA project.agents.createFromPrompt (agents:generate) 送信しないでください
GA project.voiceAgents.conversations 上で保存された14種類のリアルタイム会話操作すべて;リアルタイムプロトコルおよびOpenAIリアルタイムモデル 必須ではない
GA TPE/Twilio電話およびコールジョブリスト/取得操作 project.voiceAgents.telephony 必須ではない
Conditional インラインハンドオフ、SIP転送宛先、または post_call foundryFeaturesをパスするconnect()
Conditional テレフォニーバインディング/転送/コール書き込みおよびコールジョブの作成/キャンセル/削除 project.voiceAgents.telephony SIPを使用した時のみ foundryFeatures パス
Preview GPT Liveの定義、委任、セッション、保存された会話、およびモデル 必須;ネイティブライブ project.beta.voiceAgents.liveConversations 社内で供給
Preview インラインハンドオフ構成/状態/イベント、SIPモデル、および post_call 構成/タイプ これらのプレビューメンバーには必須;該当オペレーションのオプトインを使用してください
Preview 7つの作戦すべて project.beta.voiceAgents.telephony 必須;社内供給

GAオペレーションはプレビューメンバーのみのユニオンを受け入れることができます。 Live、inline-handoff、SIPメンバーを選択する際、または post_call設定時にオプトインしてください。これらのメンバーが存在しても、ユニオンやオペレーション全体がプレビューされることはありません。

電話書き込みでは、接続、バインディング、コール、またはコールジョブプロバイダを使ってSIPの使用状況を決定し、アドレスタイプだけでなく、SIP接続 phone_number 送信元アドレスと宛先アドレスを使用できます。 RESTトレースのサンプルは、オプションの送信コールに対して既存のTPE/Twilio接続のみを受け付けています。SIPコールのデモは含まれていません。 別個に、 transfer.require_handoff は GA 転送・概要設定であり、それ自体ではプレビューインラインハンドオフは有効にしません。

古いサンプルを移行する際は、 project.beta.agents.createFromPrompt を project.agents.createFromPromptに、 project.beta.voiceAgents.conversations を project.voiceAgents.conversationsに、キャンペーン以外の project.beta.voiceAgents.telephony を project.voiceAgents.telephonyに置き換えます。 廃止された Beta*OptionalParams および会話ダウンロード型の応答タイプを、対応する非ベータ型タイプに置き換えてください。 キャンペーンおよびGPT Liveの運用は project.beta.voiceAgentsに管理し、上記のルートリアルタイムクライアントを使用してください。

この Node.js 例では、既存のリアルタイムエージェントにテキストを送信し、返信を印刷します。 自動的なあいさびを使わないエージェントを使い、最初の返信がメッセージへの答えとなるようにしましょう。

// Ordinary Realtime sessions are GA and do not require a preview opt-in.
const connection = await project.voiceAgents.realtime.connect("<voice agent name>");
try {
  await connection.sendText("Hello. Please introduce yourself briefly.");
  for await (const event of connection) {
    if (
      event.type === "response.output_text.delta" ||
      event.type === "response.output_audio_transcript.delta"
    ) {
      process.stdout.write(event.delta);
    } else if (event.type === "error") {
      throw new Error(event.error.message);
    } else if (event.type === "response.done") {
      if (event.response.status !== "completed") {
        throw new Error(`Voice response ${event.response.status}.`);
      }
      break;
    }
  }
} finally {
  await connection.close();
}

1 for await ループでイベントを読み取る。 ループを離れると接続が閉じます。 未知のイベントタイプはセッションを切断せずに type: "unknown" として到着し、元のタイプは eventTypeに存在します。 フィールドを使用する前に rawEvent を検証してください。 不適切な出来事は VoiceAgentProtocolErrorを混乱させます。 上記のようにサービス error イベントを処理します。

会話を保持するには、エージェントまたはconnect()でstore: trueを設定し、project.voiceAgents.conversationsでリアルタイム会話を読みます。 無効化されたエージェントへの接続が失敗し、 409 Conflict およびエラーコード agent_disabled。

インラインハンドオフのサンプルは、プレビュー構成を使用するリアルタイムエージェントの明示的なオプトインを示しています:

const connection = await project.voiceAgents.realtime.connect("<inline-handoff agent name>", {
  foundryFeatures: "VoiceAgents=V1Preview",
});
await connection.close();

Node.jsでは、このオプションは foundry-features ヘッダーを送信します。 ブラウザーと React Native は、WebSocket クエリパラメータ foundry_features 同等のものを送信します。 保留された汎用 query パラメーターではなく、型付きオプションを使用してください。 デフォルトのリアルタイムサンプルはGAエージェント構成を使用します。インラインハンドオフ、SIP転送宛先、または post_callを持つ既存エージェントの場合は、上記の通りオプトインしてください。

ご希望のタスクの完全なサンプルを選択してください:

Task Node.js のサンプル
エージェント定義を作成して読み取る 音声エージェントを構成する
目標からエージェントを生成する ボイスエージェントを生成する
音声を送信し、音声返信を保存する リアルタイムオーディオ
テキストを送信し関数呼び出しを処理する リアルタイムテキストとツール
通話をかけずにバインディングや通話履歴を確認 電話
ターンをインラインスペシャリストにルーティングする(プレビュー) インラインハンドオフ
リアルタイム(GA)またはライブ(プレビュー)録画を検査する 会話録音
プレビューキャンペーンとGAアウトバウンドコールジョブを検査する 読み取り専用キャンペーン

プレビューのハンドオフサンプルは、定義の作成と接続時にオプトインします。 2つのインラインリアルタイムスペシャリストを作成し、相関したハンドオフイベントとターゲットの完了した応答を観察し、サンプルエージェントを削除します。 作成が中断された場合、中止された HTTP リクエストはサーバー側の作成をキャンセルしません。ログに登録された一意のエージェント名を使って、後で完了するリソースをチェックします。 トレースサンプルは別々の計測ツールのウォークスルーです。基本生成、リアルタイム、GPT Liveの例はトレース設定を必要としません。 構成サンプルはデフォルトでGAです。任意のポストコール送信先を設定すると、プレビュー文字起こし配信が有効になり、定義のオプトインが追加されます。 通話後の配信は、オプションでマージ録音URLもサポートしています。サンプルは発信者の音声を要求しません。

保存された会話と録音

会話録音サンプルは読み取り専用で、両方の永続APIファミリーをサポートしています。 FOUNDRY_AGENT_NAME設定し、FOUNDRY_VOICE_CONVERSATION_PROTOCOL=realtimeまたはliveを選択します。 RealtimeはプレビューヘッダーなしでGA project.voiceAgents.conversations クライアントを使用します。Liveは必要なプレビューヘッダーを持つ project.beta.voiceAgents.liveConversations を使用します。 1ページを読み取り、 sample.envに記載された変数を使って、正確な会話や項目を選択できます。 REST コレクションから返される ID を使用しており、ネイティブの RealTime WebSocket アイテムやレスポンス ID は使いません。 まず store: true に接続して録音を作成し、音声をダウンロードする前にセッションを完了してください。 サンプルは保存された会話を削除したり、発信者の書き起こしを印刷したりしません。

WAVファイルのダウンロードに FOUNDRY_VOICE_RECORDING_OUTPUT_FILE 設定します。 FOUNDRY_VOICE_AUDIO_ITEM_IDの場合、その項目の音声をダウンロードします。そうでなければ、結合されたステレオ録音をダウンロードします。 これらのWAVファイルは、ストリーミングサンプルによって書かれた生のPCMファイルとは異なります。 ダウンロードした発信者メディアは非公開に保つ。 「自分で持つストレージの記録」は、 blob_uri から自分のストレージ認証情報で読み取る必要があります。このサンプルでは任意のストレージ URL を取得しません。

リアルタイムでは、応答検査や生成されたが未聴の音声も提供されます。 生成されたオーディオ変数は、サービスが聞いたセグメントを超えて音声を生成した中断または切り詰められた項目を必要とします。キャンセルだけではアーティファクトの存在を保証するものではありません。 音声が欠落すると 404返します。 未完成のマージ録音は 409 recording_not_readyを戻すことができます。その回答を空の録音として扱うのではなく、 Retry-After のガイダンスに従ってください。

保存されたGPT Liveセッションの場合は project.beta.voiceAgents.liveConversationsを使用します。 project.beta.voiceAgents.live.connect()と接続し、ライブセッションを永続化するstore: true。project.voiceAgents.realtime.connect()リアルタイムプロトコルを使用し、ライブ接続ではありません。 以下の Node.js 例は、完了したライブ会話を読み取り、記録を印刷せずに保存した項目を一覧表示し、Foundry管理の統合WAV録音を保存しています。

import { AIProjectClient } from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";
import { pipeline } from "node:stream/promises";
import { createWriteStream } from "node:fs";

const project = new AIProjectClient("<project endpoint>", new DefaultAzureCredential());
const agentName = "<GPT Live agent name>";
const conversationId = "<stored Live conversation ID>";
const conversations = project.beta.voiceAgents.liveConversations;
const conversation = await conversations.get(agentName, conversationId);
console.log("Conversation:", conversation.id, conversation.status);
for await (const item of conversations.listItems(agentName, conversationId)) {
  console.log("Stored item:", item.id, item.type);
}
const recording = await conversations.getAudio(agentName, conversationId);
if (recording.blob_uri) {
  throw new Error("Retrieve BYOS audio from blob_uri using your own storage credentials.");
}
const audio = await conversations.downloadAudio(agentName, conversationId);
if (!audio.readableStreamBody) {
  throw new Error("Expected a Node.js audio stream.");
}
await pipeline(audio.readableStreamBody, createWriteStream("live-conversation.wav"));

キャンペーン操作ではプレビュー project.beta.voiceAgents.telephony クライアントを使用します。 deleteCampaign() を使用してキャンペーンを削除します。deleteTelephony() はその操作の非推奨互換性エイリアスです。 コールジョブリスト/取得操作は、プレビューキャンペーンで作成されたジョブを含め、GA project.voiceAgents.telephony クライアントを使用します。 キャンペーンサンプルは、キャンペーン準備、検証エラー、操作モニター、およびコールジョブのみを読み取ります。 キャンペーン読み取りには、これらのプレビュールートを有効にしたデプロイが必要です。 通話を作成またはキャンセルすることは決してありません。キャンペーン作成時は、準備ポーラーが戻る前にダイヤルを許可できます。 準備中の空の検証エラーページは、キャンペーンが有効または準備完了であることを証明しません。

カスタムクエリパラメータ

1つの接続にURLパラメータを追加するには query を渡します。 サービスまたはゲートウェイでサポートされている名前を使用してください。以下の名前は例です:

const connection = await project.voiceAgents.realtime.connect("my-voice-agent", {
  query: {
    custom_key: "custom value",
    custom_flag: true,
    // Explicit URL transport: only use non-sensitive prompt variables.
    structured_inputs: JSON.stringify({ persona: "guide" }),
  },
});
await connection.close();

値は文字列、有限数、またはブール値のいずれかです。 SDK はそれらを URL でエンコードし、 connect() が呼び出されたときにキャプチャします。 値はマッチするエンドポイントパラメータに置き換えられます。 undefined はそれを削除します。 これらの値は後の接続では再利用されません。

queryにSDK設定を入れる代わりに、store、agentVersionOverride、リアルタイムのfoundryFeaturesなどのタイプ付きオプションを使いましょう。 SDK/認証名、非標準的な構造化入力名、および h- で始まる名前は保留されたままです。 リアルタイムでは、上記のようにJSONオブジェクト文字列による正確な structured_inputs キーが明示的に許可されていますが、 structuredInputsと組み合わせないでください。 その他のカスタムクエリ値はプロンプト変数にはなりません。

リアルタイム structuredInputs は Node.jsにおけるヘッダーベースのトランスポートを保持します。 ブラウザは任意のWebSocketアップグレードヘッダーを送信できないためURLクエリを使用します。 サービスでクエリフォームが必要な場合は、structuredInputsではなくquery.structured_inputsを通じて明示的にオプトインしてください。 クエリパラメータにシークレットやセンシティブなプロンプト変数を絶対に入れないでください。 サーバーおよびプロキシのアクセスログはURLを保持することがあります。

GPT Live ボイスエージェント

GPT Liveエージェントには project.beta.voiceAgents.live を使いましょう。 エージェントを作成する際は、 sub_protocol: "live"、 model_type: "self_deployed"、 model を GPT Live のデプロイメント名に設定してください。 創造には VoiceAgents=V1Previewが必要です。 project.agents.create() または createVersion() に{ foundryFeatures: "VoiceAgents=V1Preview" }を渡します。 ネイティブライブ接続は常に必要なプレビューフラグを内部で送信します。発信者は live.connect()にフラグを付ける必要はありません。

この短い例では、24 kHz のモノラルPCM16LEオーディオ用に設定された既存のエージェントが必要です。 ライブはテキスト指示を追加しても音声時計を進めるため、例は相関応答が届くまで無音を送り、その後セッションを閉じます。 以下の完全なサンプルを使ってテキストまたは音声を送信し、返信を読んでください。

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

const project = new AIProjectClient("<project endpoint>", new DefaultAzureCredential());
const connection = await project.beta.voiceAgents.live.connect("<GPT Live agent name>", {
  store: false,
});
const eventId = "brief-instructions";
// Requires an agent configured for mono PCM16LE at 24 kHz.
const silence = new Uint8Array(4800); // 100 ms of audio.
let correlatedAck = false;
let serviceError: Error | undefined;
const onAppended = (event: LiveServerEventLiveInstructionsAppended): void => {
  if (event.client_event_id === eventId) correlatedAck = true;
};
const onError = (event: LiveServerEventLiveErrorEvent): void => {
  serviceError = new Error(event.error.message);
};
connection.on("session.instructions.appended", onAppended);
connection.on("error", onError);
try {
  await connection.appendInstructions("Keep your answers brief.", { eventId });
  const deadline = Date.now() + 10000;
  while (!correlatedAck) {
    if (serviceError) throw serviceError;
    if (connection.state !== "connected") {
      throw new Error(`Live connection became ${connection.state} before the instructions ACK.`);
    }
    if (Date.now() >= deadline) {
      throw new Error("Timed out waiting for the correlated instructions ACK.");
    }
    await connection.sendAudio(silence);
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
  if (serviceError) throw serviceError;
} finally {
  connection.off("session.instructions.appended", onAppended);
  connection.off("error", onError);
  await connection.close();
}

GPT Live サンプルを実行する

FOUNDRY_PROJECT_ENDPOINT設定して.envでFOUNDRY_LIVE_MODEL。 モデルカタログIDではなく 、展開名を使用してください。 関数サンプルも FOUNDRY_LIVE_BACKEND_MODELが必要です。 これらの設定およびオプションのオーディオファイルパスについては sample.env を参照してください。

Task Node.js のサンプル
挨拶を送り、音声返信をテキストとして印刷してください GPT ライブテキスト
音声ファイルを送信し、音声返信を保存する GPT Live オーディオ
ローカル関数を実行し、エージェントに結果を伝えさせます GPT Live 関数呼び出し

ビルド済み SDK チェックアウトから、Node.js 22.18 以降のサンプルを実行します。

node samples-dev/agents/agentVoiceLiveText.ts

各サンプルは独自のエージェントを作成・削除します。 字幕は出力しますが、スピーカーから音声を再生することはできません。 この音声サンプルはマイクではなく録音ファイルを使用し、WAVやその他のファイルヘッダーなしで 24 kHzの生モノラルPCM16LEを読み取り保存します。

返信の後に Enter キーを押すか、Ctrl+C キーを押して停止します。 使用量はセッション終了まで請求可能です。 ライブはテキストやツールの音声入力も連続しているため、サンプルはアイドル状態でも無音を送ります。 ライブにはスピーチ終了イベントはありません。バックエンドの応答が完了したからといって、エージェントが話し終えたとは限りません。

テキストサンプルはセッションの指示を付加し、それらに対応する確認を待ってからコメントを追加します。 その確認は、受諾の確認であり、話し終わったことを示すものではありません。期待される返答が届くまでセッションを開いたままにしてください。

セッションコントロールとイベント

connect() session.startedを待つ。 connection.sessionの現在の設定を読み取り、該当する場合は選択した管理対象エージェントとバージョンを読み取ってください。 1つの for await ループでイベントを読み取るか、 on、 off、 once リスナーを後続のイベントに使用します。 リスナーのみの利用の場合、接続時に onEvent を供給し、 connect() の戻りを待たずに起動イベントや初期音声を受信できます。 サービスが提供した際の永続会話IDを含む元の起動イベントは、 connection.sessionStartedを通じて引き続き利用可能です。 onEventコールバックの設定後に起動したイテレーターは、過去のイベントではなくその後のイベントを受け取る。

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

const project = new AIProjectClient("<project endpoint>", new DefaultAzureCredential());
const connection = await project.beta.voiceAgents.live.connect("<GPT Live agent name>", {
  store: true,
  onEvent: (event) => {
    if (event.type === "session.started") {
      console.log("Conversation:", event.conversation_id);
    } else if (event.type === "session.output_audio.delta") {
      console.log("Received an audio chunk.");
    }
  },
});
try {
  console.log("Session:", connection.sessionStarted.session.id);
} finally {
  await connection.close();
}
Task API またはイベント
生の音声を送信する sendAudio();Live は音声の境界を検出するため、オーディオバッファのコミットは不要です
トランスクリプトの読み取り session.input_transcript.delta、session.output_transcript.delta
音声を受信する session.output_audio.delta;保存または再生する前に base64 データをデコードする
ユーザーメッセージではなくテキストコンテキストを追加する appendInstructions()、appendThinking()、appendCommentary()
音声処理を一時停止または再開する muteInputAudio()、unmuteInputAudio()
バックエンド設定と文字起こしトリガーを更新する configureSession();初期モデル、オーディオフォーマット、および委任所有者は変更できません
セッションを閉じる close(); session.closed を待ち、最終決定が確認されない場合は拒否します

close() また、ソケットがすでに切断されている場合の未確認シャットダウンも dispose() 拒否します。 サービスの最終化イベントや接続エラーがないか connection.closed 検査してください。

Responses 委任により、バックエンドイベントは response.event 内に届きます。 sendResponseItem() を使ってユーザーメッセージを追加し、返信を求めるrequestResponse()を使います。 関数呼び出しの場合は、呼び出し先のバックエンド応答が終了するのを待ってから、 sendToolOutput() を使って結果を返し、続行を要求します。 これらの手法にはレスポンス委任が必要です。 クライアントが扱う委任の場合は、 appendThinking() または appendCommentary() を使用し、委任 ID を delegationId として渡してください。

意思決定コンテキストアイテムは、ユーザーメッセージ、関数呼び出しおよび結果、カスタムツール呼び出しおよび結果をサポートします。 decision.item.createを添えて送信し、受信したdecision.item.createdイベントは対応するアイテムフィールドと保存されたIDを保持します。 意思決定コマンドは、サービス展開側の支援を必要とします。

LiveはRealtimeの response.cancelをサポートしていません。 中止シグナルはSDK接続または送信操作をキャンセルするものであり、すでに生成されている音声をキャンセルするものではありません。 ライブ会話を保存するには、 store を有効にして project.beta.voiceAgents.liveConversationsを使用します。サービス展開は永続化をサポートしている必要があります。 AIProjectClientのliveOptionsを設定して、接続、セッション開始、終了タイムアウトを変更します。 保存済みの会話サンプルをFOUNDRY_VOICE_CONVERSATION_PROTOCOL=liveで使用して、永続的な項目を確認したり、WAV音声をダウンロードしたりできます。

ブラウザ認証

InteractiveBrowserCredentialなどのブラウザ認証情報を使用してください。 SDKは、Web Workersを含むliveおよび短命のベアラートークンサブプロトコルを用いたネイティブWebSocketを使用しています。 Node.js 代わりにベアラーヘッダーを使用します。 realtimeをライブサブプロトコルとして提供せず、URLにトークンを配置せず、APIキーやクライアントシークレット、またはブラウザコードに長期トークンを埋め込むこともしないでください。 ダイレクトブラウザ認証が利用できない場合は、 webSocketFactoryを通じて認証済みバックエンドリレーを提供します。

リアルタイム接続は Node.js のx-ms-voice-structured-inputsヘッダーにstructuredInputsを保持し、ブラウザやワーカーではstructured_inputs URLクエリを使用します。 明示的リアルタイム query.structured_inputs は、任意のホストでのURL転送を選択できます。 GPT LiveはすべてのホストでURLクエリを使用し続けており、ヘッダーベースの代替手段はありません。 プロキシおよびサーバーアクセスログはURLを保持できます。URL由来の入力には認証情報、個人データ、その他の機密情報を記載しないでください。

エージェントツールの利用

エージェントは様々な機能に対応する専門ツールで強化可能です。 ツールは接続要件ごとに整理されています:

組み込みツール

これらのツールは外部接続を必要とせず、即座に動作します。

コード インタープリター

サンドボックス環境でJavaScriptコードを書き、実行し、ファイルを処理し、多様なデータフォーマットに取り組むことができます。 OpenAIドキュメント

const openAIClient = project.getOpenAIClient();
const response = await openAIClient.responses.create({
  model: deploymentName,
  input: "I need to solve the equation 3x + 11 = 14. Can you help me?",
  tools: [{ type: "code_interpreter", container: { type: "auto" } }],
});
console.log(`Response output: ${response.output_text}`);

完全なサンプルコードはagentCodeInterpreter.tsでご覧ください。

ファイル検索

ベクターストアを用いて文書を処理・検索する組み込みのRAG(Retrieval-Augmented 生成)ツール。 OpenAIドキュメント

const openAIClient = project.getOpenAIClient();
const assetFilePath = path.join(
  __dirname,
  "..",
  "samples-dev",
  "agents",
  "assets",
  "product_info.txt",
);
const vectorStore = await openAIClient.vectorStores.create({
  name: "ProductInfoStreamStore",
});
console.log(`Vector store created (id: ${vectorStore.id})`);
// Upload file to vector store
const fileStream = fs.createReadStream(assetFilePath);
const uploadedFile = await openAIClient.vectorStores.files.uploadAndPoll(
  vectorStore.id,
  fileStream,
);
console.log(`File uploaded to vector store (id: ${uploadedFile.id})`);
// Create agent with file search tool
const agent = await project.agents.createVersion("StreamingFileSearchAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful assistant that can search through product information and provide detailed responses. Use the file search tool to find relevant information before answering.",
  tools: [
    {
      type: "file_search",
      vector_store_ids: [vectorStore.id],
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentFileSearchStream.tsをご覧ください。

画像生成

テキストプロンプトに基づいて画像を生成し、解像度、画質、スタイルをカスタマイズ可能です:

const agent = await project.agents.createVersion("agent-image-generation", {
  kind: "prompt",
  model: deploymentName,
  instructions: "Generate images based on user prompts",
  tools: [
    {
      type: "image_generation",
      quality: "low",
      size: "1024x1024",
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

responses.create()に電話した後、返答したファイルをダウンロードできます:

import { fileURLToPath } from "url";

const openAIClient = project.getOpenAIClient();
const agent = await project.agents.createVersion("agent-image-generation", {
  kind: "prompt",
  model: deploymentName,
  instructions: "Generate images based on user prompts",
  tools: [
    {
      type: "image_generation",
      quality: "low",
      size: "1024x1024",
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
const response = await openAIClient.responses.create(
  {
    input: "Generate an image of Microsoft logo.",
  },
  {
    body: { agent: { name: agent.name, type: "agent_reference" } },
  },
);
console.log(`Response created: ${response.id}`);
const imageData = response.output?.filter((output) => output.type === "image_generation_call");
if (imageData && imageData.length > 0 && imageData[0].result) {
  console.log("Downloading generated image...");
  const __filename = fileURLToPath(import.meta.url);
  const __dirname = path.dirname(__filename);
  const filename = "microsoft.png";
  const filePath = path.join(__dirname, filename);
  // Decode base64 and save to file
  const imageBuffer = Buffer.from(imageData[0].result, "base64");
  fs.writeFileSync(filePath, imageBuffer);
  console.log(`Image downloaded and saved to: ${path.resolve(filePath)}`);
} else {
  console.log("No image data found in the response.");
}

ウェブ検索(プレビュー)

インターネットから最新の情報を取得するために一般的なウェブ検索を行いましょう。 OpenAIドキュメント

const openAIClient = project.getOpenAIClient();
// Create Agent with web search tool
const agent = await project.agents.createVersion("agent-web-search", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant that can search the web",
  tools: [
    {
      type: "web_search_preview",
      user_location: {
        type: "approximate",
        country: "GB",
        city: "London",
        region: "London",
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Create a conversation for the agent interaction
const conversation = await openAIClient.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Send a query to search the web
console.log("\nSending web search query...");
const response = await openAIClient.responses.create(
  {
    conversation: conversation.id,
    input: "Show me the latest London Underground service updates",
  },
  {
    body: { agent: { name: agent.name, type: "agent_reference" } },
  },
);
console.log(`Response: ${response.output_text}`);

完全なサンプルコードはagentWebSearch.tsをご覧ください。

コンピュータ利用

エージェントがタスク自動化やシステム操作のためにコンピュータシステムと直接やり取りできるようにします(gpt-5.4などのcomputerツールをサポートするモデル展開が必要です。computer-use-preview展開の場合はcomputer_use_previewを使用します):

const agent = await project.agents.createVersion("ComputerUseAgent", {
  kind: "prompt" as const,
  model: deploymentName,
  instructions: `
You are a computer automation assistant.

Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.
    `.trim(),
  tools: [
    {
      type: "computer",
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

responses.create()を呼び出した後、応答をインタラクションループで処理します。 出力項目computer_call処理し、computer_call_outputタイプcomputer_screenshotスクリーンショットを提供してやり取りを続けましょう。

完全なサンプルコードはagentComputerUse.tsをご覧ください。

モデル コンテキスト プロトコル (MCP)

MCPサーバーを統合し、標準化されたツールやリソースでエージェントの機能を拡張します。 OpenAIドキュメント

const openAIClient = project.getOpenAIClient();
const agent = await project.agents.createVersion("agent-mcp", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful agent that can use MCP tools to assist users. Use the available MCP tools to answer questions and perform tasks.",
  tools: [
    {
      type: "mcp",
      server_label: "api-specs",
      server_url: "https://gitmcp.io/Azure/azure-rest-api-specs",
      require_approval: "always",
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Create a conversation thread to maintain context across multiple interactions
console.log("\nCreating conversation...");
const conversation = await openAIClient.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Send initial request that will trigger the MCP tool to access Azure REST API specs
// This will generate an approval request since requireApproval="always"
console.log("\nSending request that will trigger MCP approval...");
const response = await openAIClient.responses.create(
  {
    conversation: conversation.id,
    input: "Please summarize the Azure REST API specifications Readme",
  },
  {
    body: { agent: { name: agent.name, type: "agent_reference" } },
  },
);

responses.create()を呼び出した後、レスポンス出力に項目がmcp_approval_requestがないか確認してください。 承認の決定を伝えて、エージェントの作業継続を許可する McpApprovalResponse を返送してください。

完全なサンプルコードはagentMcp.tsをご覧ください。

OpenAPI

追加のクライアントサイドコードなしでOpenAPI仕様で定義された外部APIを呼び出します。 OpenAIドキュメント

const weatherSpecPath = path.resolve(__dirname, "../assets", "weather_openapi.json");
const agent = await project.agents.createVersion("MyOpenApiAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful assistant that can call external APIs defined by OpenAPI specs to answer user questions. When calling the weather tool, always include the query parameter format=j1.",
  tools: [
    {
      type: "openapi",
      openapi: {
        name: "get_weather",
        description: "Retrieve weather information for a location using wttr.in",
        spec: weatherSpecPath,
        auth: { type: "anonymous" },
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentOpenApi.tsでご覧ください。

機能ツール

エージェントが外部API、データベース、アプリケーションロジックとやり取りできるカスタム関数を定義します。 OpenAIドキュメント

/**
 * Define a function tool for the model to use
 */
const funcTool = {
  type: "function" as const,
  function: {
    name: "get_horoscope",
    description: "Get today's horoscope for an astrological sign.",
    strict: true,
    parameters: {
      type: "object",
      properties: {
        sign: {
          type: "string",
          description: "An astrological sign like Taurus or Aquarius",
        },
      },
      required: ["sign"],
      additional_properties: false,
    },
  },
};
const agent = await project.agents.createVersion("function-tool-agent", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant that can use function tools.",
  tools: [funcTool],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

responses.create()を呼び出した後、応答出力からfunction_call項目を処理し、指定された引数で関数ロジックを実行し、結果をFunctionCallOutputに返します。

完全なサンプルコードはagentFunctionTool.tsをご覧ください。

  • メモリ検索ツール(プレビュー)

メモリストアツールはエージェントにメモリを追加し、エージェントのAIモデルが現在のユーザープロンプトに関連する過去情報を検索できるようにします。

embeddingModelDeploymentは記憶の保存や探索のためにベクトル埋め込みを作成するために使われるモデルの名前です。

const memoryStoreName = "AgentMemoryStore";
const embeddingModelDeployment =
  process.env["MEMORY_STORE_EMBEDDING_MODEL_DEPLOYMENT_NAME"] || "<embedding model>";
const scope = "user_123";
const memoryStore = await project.beta.memoryStores.create(
  memoryStoreName,
  {
    kind: "default",
    chat_model: deploymentName,
    embedding_model: embeddingModelDeployment,
    options: {
      user_profile_enabled: true,
      chat_summary_enabled: true,
    },
  },
  {
    description: "Memory store for agent conversations",
  },
);
console.log(
  `Created memory store: ${memoryStore.name} (${memoryStore.id}) using chat model '${deploymentName}'`,
);
// Create an agent that will use the Memory Search tool
const agent = await project.agents.createVersion("MemorySearchAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful assistant that remembers user preferences using the memory search tool.",
  tools: [
    {
      type: "memory_search_preview",
      memory_store_name: memoryStore.name,
      scope,
      update_delay: 1, // wait briefly after conversation inactivity before updating memories
    },
  ],
});

完全なサンプルコードはagentMemorySearch.tsをご覧ください。

Connection-Based ツール

これらのツールは、AI Foundryプロジェクト内で接続を設定し、その projectConnectionIdを活用する必要があります。

Azure AI 検索

Azure AI 検索インデックスと連携して、強力な知識検索およびセマンティック検索機能を実現しましょう:

const aiSearchConnectionId = process.env["AI_SEARCH_CONNECTION_ID"] || "";
const aiSearchIndexName = process.env["AI_SEARCH_INDEX_NAME"] || "";
const agent = await project.agents.createVersion("MyAISearchAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful assistant. You must always provide citations for answers using the tool and render them as: `[message_idx:search_idx†source]`.",
  tools: [
    {
      type: "azure_ai_search",
      azure_ai_search: {
        indexes: [
          {
            project_connection_id: aiSearchConnectionId,
            index_name: aiSearchIndexName,
            query_type: "simple",
          },
        ],
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentAiSearch.tsをご覧ください。

Bing グラウンディング

Bingからのリアルタイムウェブ検索結果による地上エージェントの応答による、up-to日付情報提供:

const bingProjectConnectionId = process.env["BING_GROUNDING_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("MyBingGroundingAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant.",
  tools: [
    {
      type: "bing_grounding",
      bing_grounding: {
        search_configurations: [
          {
            project_connection_id: bingProjectConnectionId,
          },
        ],
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentBingGrounding.tsをご覧ください。

Bing カスタム検索(プレビュー)

ドメイン固有の検索結果やフィルター付きのウェブ検索結果には、カスタム設定のBing検索インスタンスを使用してください:

const bingCustomSearchProjectConnectionId = process.env["BING_CUSTOM_SEARCH_CONNECTION_ID"] || "";
const bingCustomSearchInstanceName = process.env["BING_CUSTOM_SEARCH_INSTANCE_NAME"] || "";
const agent = await project.agents.createVersion("MyAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful agent that can use Bing Custom Search tools to assist users. Use the available Bing Custom Search tools to answer questions and perform tasks.",
  tools: [
    {
      type: "bing_custom_search_preview",
      bing_custom_search_preview: {
        search_configurations: [
          {
            project_connection_id: bingCustomSearchProjectConnectionId,
            instance_name: bingCustomSearchInstanceName,
          },
        ],
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentBingCustomSearch.tsをご覧ください。

Microsoft Fabric(プレビュー)

Microsoft Fabricに接続しクエリを問い合わせること:

const fabricProjectConnectionId = process.env["FABRIC_PROJECT_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("MyFabricAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant.",
  tools: [
    {
      type: "fabric_dataagent_preview",
      fabric_dataagent_preview: {
        project_connections: [
          {
            project_connection_id: fabricProjectConnectionId,
          },
        ],
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentFabric.tsをご覧ください。

Microsoft SharePoint(プレビュー)

エンタープライズナレッジ統合のためにSharePointのドキュメント、リスト、サイトにアクセスし検索する:

const sharepointProjectConnectionId = process.env["SHAREPOINT_PROJECT_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("MyAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a helpful agent that can use SharePoint tools to assist users. Use the available SharePoint tools to answer questions and perform tasks.",
  // Define SharePoint tool that searches SharePoint content
  tools: [
    {
      type: "sharepoint_grounding_preview",
      sharepoint_grounding_preview: {
        project_connections: [
          {
            project_connection_id: sharepointProjectConnectionId,
          },
        ],
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentSharepoint.tsをご覧ください。

ブラウザーの自動化

ウェブスクレイピング、テスト、ウェブアプリケーションとのやり取りのためのブラウザ操作の自動化:

const browserAutomationProjectConnectionId =
  process.env["BROWSER_AUTOMATION_PROJECT_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("MyAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions: `You are an Agent helping with browser automation tasks.
              You can answer questions, provide information, and assist with various tasks
              related to web browsing using the Browser Automation tool available to you.`,
  // Define Browser Automation tool
  tools: [
    {
      type: "browser_automation",
      browser_automation: {
        connection: {
          project_connection_id: browserAutomationProjectConnectionId,
        },
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentBrowserAutomation.tsをご覧ください。

サンプルを実行する前にFOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODEL_NAME、BROWSER_AUTOMATION_PROJECT_CONNECTION_ID(Azure Playwrightリソースのプロジェクト接続リソースID)を設定してください。 GA browser_automation ツールを使って https://example.com にアクセスし、ブラウザの結果に基づいてページタイトルや表示された説明を報告します。 オプションで FOUNDRY_AGENT_NAME をエージェント名を選択するように設定してください。デフォルトは MyAgentです。

ストリーミングサンプルは、完成した各テキストメッセージを一度だけ印刷し、ブラウザのライブビューURLも含め、リモート関数のアクション名、コールID、引数を browserSessionIdせずに記録します。 ライブビューURLは機密扱いとして扱い、共有やソース管理へのコミットは避けてください。 失敗または不完全な回答は、成功を報告せずに非ゼロの状態で終了します。 サンプルは、レスポンス処理が成功するか失敗するかにかかわらず、 finally ブロック内で作成したエージェントバージョンを削除します。

Project Connection を使用した MCP

プロジェクト固有の接続を使ったMCP統合で、接続されたMCPサーバーへのアクセス:

const mcpProjectConnectionId = process.env["MCP_PROJECT_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("agent-mcp-connection-auth", {
  kind: "prompt",
  model: deploymentName,
  instructions: "Use MCP tools as needed",
  tools: [
    {
      type: "mcp",
      server_label: "api-specs",
      server_url: "https://api.githubcopilot.com/mcp",
      require_approval: "always",
      project_connection_id: mcpProjectConnectionId,
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentMcpConnectionAuth.tsでご覧ください。

エージェント間通信(A2A)(プレビュー)

エージェント同士がコミュニケーションを取り、タスクを他の専門エージェントに委任できるマルチエージェント協働を可能にする:

const a2aProjectConnectionId = process.env["A2A_PROJECT_CONNECTION_ID"] || "";
const agent = await project.agents.createVersion("MyA2AAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions: "You are a helpful assistant.",
  // Define A2A tool for agent-to-agent communication
  tools: [
    {
      type: "a2a_preview",
      project_connection_id: a2aProjectConnectionId,
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentAgentToAgent.tsをご覧ください。

Project Connection を利用した OpenAPI

プロジェクト接続認証を用いてOpenAPI仕様で定義された外部APIを呼び出します:

const tripAdvisorProjectConnectionId = process.env["TRIPADVISOR_PROJECT_CONNECTION_ID"] || "";
function loadOpenApiSpec(specPath: string): unknown {
  if (!fs.existsSync(specPath)) {
    throw new Error(`OpenAPI specification not found at: ${specPath}`);
  }
  try {
    const data = fs.readFileSync(specPath, "utf-8");
    return JSON.parse(data);
  } catch (error) {
    throw new Error(`Failed to read or parse OpenAPI specification at ${specPath}: ${error}`);
  }
}
const tripAdvisorSpecPath = path.resolve(__dirname, "../assets", "tripadvisor_openapi.json");
const tripAdvisorSpec = loadOpenApiSpec(tripAdvisorSpecPath);
const agent = await project.agents.createVersion("MyOpenApiConnectionAgent", {
  kind: "prompt",
  model: deploymentName,
  instructions:
    "You are a travel assistant that consults the TripAdvisor Content API via project connection to answer user questions about locations.",
  tools: [
    {
      type: "openapi",
      openapi: {
        name: "get_tripadvisor_location_details",
        description:
          "Fetch TripAdvisor location details, reviews, or photos using the Content API via project connection auth.",
        spec: tripAdvisorSpec,
        auth: {
          type: "project_connection",
          security_scheme: {
            project_connection_id: tripAdvisorProjectConnectionId,
          },
        },
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

完全なサンプルコードはagentOpenApiConnectionAuth.tsでご覧ください。

すべてのツールの完全な動作例については、samples-devディレクトリをご覧ください。

Evaluation

Azure AI Projectの評価クライアントライブラリは、定量的かつAI支援による品質・安全性指標を提供し、LLMモデル、生成AIアプリケーション、エージェントのパフォーマンス評価と評価を行います。 指標は評価者として定義されます。 組み込みまたはカスタム評価ツールは包括的な評価洞察を提供します。

以下のコードは評価操作のいくつかを示しています。 サンプルの全リストは、package samples

const openAIClient = project.getOpenAIClient();
const dataSourceConfig = {
  type: "custom" as const,
  item_schema: {
    type: "object",
    properties: { query: { type: "string" } },
    required: ["query"],
  },
  include_sample_schema: true,
};
const evalObject = await openAIClient.evals.create({
  name: "Agent Evaluation",
  data_source_config: dataSourceConfig,
  testing_criteria: [
    {
      type: "azure_ai_evaluator",
      name: "violence_detection",
      evaluator_name: "builtin.violence",
      data_mapping: { query: "{{item.query}}", response: "{{item.response}}" },
    } as any,
  ],
});
console.log(`Evaluation created (id: ${evalObject.id}, name: ${evalObject.name})`);

完全なサンプルコードはagentEvaluation.tsをご覧ください。

デプロイ操作

以下のコードは、Microsoft Foundryプロジェクトに展開したAIモデルを列挙できるデプロイメント操作を示しています。 これらのモデルは、Microsoft Foundry Projectの「Models + endpoints」タブで確認できます。 完全なサンプルはpackage samplesの「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)}`);
}

接続操作

以下のコードは、Microsoft Foundry Projectsに接続されたAzureリソースを列挙できるConnection操作を示しています。 これらの接続は、Microsoft Foundry Projectの「Connected resources」タブの「Management Center」で確認できます。 完全なサンプルはpackage samplesの「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", {
  includeCredentials: true,
});
console.log(`Retrieved default connection ${JSON.stringify(defaultConnection, null, 2)}`);

データセットの操作

次のコードは、一部のデータセット操作を示しています。 完全なサンプルはpackage samplesの「datasets」フォルダで見つけることができます。

ローカルファイルシステムのアップロード(project.datasets.uploadFile、 project.datasets.uploadFolder、 project.beta.models.create)は Node.jsでのみサポートされています。 ブラウザアプリケーションは@azure/ai-projectsからAIProjectClientやVoiceAgentRealtimeClientを取り込み、データセットやモデルのREST操作を Node.js ファイルシステムのポリフィルなしで利用できます。

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 = 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.");

ファイル操作

以下のコードは、OpenAI クライアントを使用したいくつかのファイル操作を示しており、ファイルのアップロード、取得、一覧表示、削除が可能です。 これらの操作は、微調整やその他の AI モデル操作に使用できるファイルを操作する場合に役立ちます。 フルサンプルはpackage samplesの「files」フォルダ内で見つけることができます。

const openAIClient = project.getOpenAIClient();
console.log("Uploading file");
const created = await openAIClient.files.create({
  file: fs.createReadStream(filePath),
  purpose: "fine-tune",
});
console.log(`Uploaded file with ID: ${created.id}`);
const uploadedFile = await openAIClient.files.retrieve(created.id);
console.log("Processed file metadata:\n", JSON.stringify(uploadedFile, null, 2));
console.log(`Retrieving file content with ID: ${uploadedFile.id}`);
const contentResponse = await openAIClient.files.content(uploadedFile.id);
const buf = Buffer.from(await contentResponse.arrayBuffer());
console.log(buf.toString("utf-8"));
// 4) List all files
console.log("Listing all files:");
const filesList = await openAIClient.files.list();
for (const f of filesList.data ?? []) {
  console.log(JSON.stringify(f));
}
// 5) Delete the file
console.log(`Deleting file with ID: ${uploadedFile.id}`);
const deleted = await openAIClient.files.delete(uploadedFile.id);
console.log(
  `Successfully deleted file: ${deleted?.id || uploadedFile.id}, deleted=${String(deleted?.deleted ?? true)}`,
);

インデックス操作

次のコードは、一部の Indexes 操作を示しています。 完全なサンプルはpackage samplesの「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);

微調整操作

以下のコードはOpenAIクライアントを使ってファインチューニングジョブを作成する方法を示しています。 これらの運用は、監督付き Fine-Tuning(SFT)、強化 Fine-Tuning(RFT)、直接パフォーマンス最適化(DPO)などの様々なファインチューニング技術をサポートしています。 フルサンプルはpackage samplesの「finetuning」フォルダで見つけることができます。

import { JobCreateParams } from "openai/resources/fine-tuning/jobs";

const trainingFilePath = "training_data_path.jsonl";
const validationFilePath = "validation_data_path.jsonl";
const openAIClient = project.getOpenAIClient();
// 1) Create the training and validation files
const trainingFile = await openAIClient.files.create({
  file: fs.createReadStream(trainingFilePath),
  purpose: "fine-tune",
});
console.log(`Uploaded file with ID: ${trainingFile.id}`);
const validationFile = await openAIClient.files.create({
  file: fs.createReadStream(validationFilePath),
  purpose: "fine-tune",
});
console.log(`Uploaded file with ID: ${validationFile.id}`);
// 2) Wait for the files to be processed
await openAIClient.files.waitForProcessing(trainingFile.id);
await openAIClient.files.waitForProcessing(validationFile.id);
console.log("Files processed.");
// 3) Create a supervised fine-tuning job
const fineTuningJob = await openAIClient.fineTuning.jobs.create({} as JobCreateParams, {
  body: {
    trainingType: "Standard",
    training_file: trainingFile.id,
    validation_file: validationFile.id,
    model: deploymentName,
    method: {
      type: "supervised",
      supervised: {
        hyperparameters: {
          n_epochs: 3,
          batch_size: 1,
          learning_rate_multiplier: 1.0,
        },
      },
    },
  },
});
console.log("Created fine-tuning job:\n", JSON.stringify(fineTuningJob));

エージェントセッション操作

ホストされたエージェントのセッションおよびセッションファイルを管理するには project.agents を使用します。 セッションはエージェント間の相互作用のための孤立したサンドボックス環境を提供します。 この例では、セッション操作をサポートするホスト型エージェントの展開が必要です。

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

const agentName = "MySessionAgent";
// Create a session for the agent
const versionIndicator: VersionRefIndicator = {
  type: "version_ref",
  agent_version: "1.0",
};
const session = await project.agents.createSession(agentName, versionIndicator);
console.log(`Session created: ${session.agent_session_id}`);
// Upload a file to the session sandbox
const filePath = "/sandbox/hello.txt";
const fileContent = new TextEncoder().encode("Hello from the agent sessions sample!");
const uploadResult = await project.agents.uploadSessionFile(
  agentName,
  session.agent_session_id,
  filePath,
  fileContent,
);
console.log(`Uploaded file: ${uploadResult.path} (${uploadResult.bytes_written} bytes)`);

agentSessions.tsのサンプルコードと対応するノートブックをご覧ください。

スキルオペレーション(プレビュー)

.beta.skillsオペレーションでは、エージェントの能力を定義する再利用可能なスキルを作成・管理できます。

const skillName = "sample-skill";
// Create a new skill
const created = await project.beta.skills.create(skillName, {
  inlineContent: {
    description: "Example skill created by the @azure/ai-projects sample.",
    instructions: "You are a helpful assistant that answers questions concisely.",
    metadata: { owner: "sample" },
  },
});
console.log(`Skill created: ${created.name} (id: ${created.skill_id})`);
// Retrieve the skill
const fetched = await project.beta.skills.get(skillName);
console.log(`Retrieved skill: ${fetched.name} (id: ${fetched.id})`);

完全なサンプルコードはskillBasic.tsをご覧ください。

ツールボックス操作(プレビュー)

.toolboxes操作では、ツールボックスを作成・管理できます。ツールボックスはエージェント間で共有可能な再利用可能なツールのコレクションです。

import { ToolUnion, MCPTool } from "@azure/ai-projects";

const toolboxName = "mcp";
// Define tools for the toolbox
const tools: ToolUnion[] = [
  {
    type: "mcp",
    server_label: "api_specs",
    server_url: "https://github.com/Azure/azure-rest-api-specs",
    require_approval: "never",
  } satisfies MCPTool,
];
// Create a new toolbox version
const created = await project.toolboxes.createVersion(toolboxName, tools, {
  description: "Example toolbox created by the @azure/ai-projects sample.",
  metadata: { status: "created" },
});
console.log(`Toolbox: ${created.name} (tools: ${created.tools.length})`);
// Retrieve the toolbox
const fetched = await project.toolboxes.get(toolboxName);
console.log(`Retrieved toolbox: ${fetched.name} (${fetched.id})`);

完全なサンプルコードはtoolboxesCrud.tsをご覧ください。

追跡

実験的特徴ゲート

重要: GenAIトレース計測は実験的なプレビュー機能です。 スパン、属性、およびイベントは、将来のバージョンで変更される可能性があります。 使用するには、tracingOptionsを構築する際にexperimental: trueAIProjectClientで明示的にオプトインするか、環境変数を設定することでオプトインする必要があります。

AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING=true

この機能は、要件を確認し、トレーシングの動作が今後のバージョンで変わる可能性があることを理解した後にのみ有効にしてください。

トレースの始め方

Microsoft FoundryプロジェクトにApplication Insights Azureリソースを追加できます。 もし有効にしていれば、Application Insightsの接続文字列を取得し、AI Projectsクライアントを設定し、Azure Monitorでトレースを観察できます。 通常、クライアントまたはエージェントを作成する前にトレースを開始することをお勧めします。

Installation

Azure Monitorにtracesを送信するには:

npm install @azure/monitor-opentelemetry @opentelemetry/api

コンソールへのトレースを印刷するには(ローカル開発に有用):

npm install @opentelemetry/sdk-trace-node @opentelemetry/api

トレースを有効にする方法

トレーシングはtracingOptions構造体に渡すことで実現AIProjectClientします。 tracingOptionsが提供されない場合、GenAIトレーシングは完全に無効化され、GenAIのスパンや指標は一切出力されません。 この設定はGenAI固有のトレーシングのみを制御します(モデル呼び出し、エージェント操作、トークン使用などの意味慣習の範囲)。 トレース設定は、その特定のクライアントインスタンスを通じて行われるすべての操作に適用されます。エージェント操作や project.getOpenAIClient()を通じて取得したOpenAIクライアントも含まれます。 異なるクライアントインスタンスは独立したトレーシング構成を持つことができます。

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

const endpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint>";
const credential = new DefaultAzureCredential();

// Tracing enabled
const project = new AIProjectClient(endpoint, credential, {
  tracingOptions: { experimental: true },
});

// Tracing disabled (default — no tracingOptions passed)
const projectNoTrace = new AIProjectClient(endpoint, credential);

console.log(project, projectNoTrace);

tracingOptions: {}(空のオブジェクト)を渡すことでトレースも可能になり、その場合、すべての個別設定は対応する環境変数から解決されます。

tracingOptionsオブジェクトは以下の性質を受け入れます:

Option 環境変数 Default Description
experimental AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING false この機能の実験的な性質(スパンを発信するために必要)を認めてください。
contentRecording OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT false トレースにプロンプトや完了のコンテンツをキャプチャする
traceContextPropagation AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION true 要求にW3Cのトレースコンテキストヘッダーを注入する

各選択肢は以下の優先順位で解決されます:

  1. tracingOptionsにおける明示的値(最高優先度)
  2. 環境変数 (オプションが省略または未定義の場合にチェック)
  3. デフォルト値 (どちらも設定されていない場合、または環境変数を読み取れない場合に使用)

注意: 現在、すべてのトレース機能は実験的であるため、 experimental: true スパンを出力する際には(明示的または環境変数を介して)設定する必要があります。

ボイスエージェントのトレーシング

OpenTelemetry プロバイダーとエクスポーターを登録し、AIProjectClient で tracingOptions: { experimental: true } を設定します。 これはボイスエージェント生成、電話の変更、会話削除、リアルタイムセッションと応答を追跡します。 Voice Agentsの追跡フラグは別途必要ありません。

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

const project = new AIProjectClient("<project endpoint>", new DefaultAzureCredential(), {
  tracingOptions: {
    experimental: true,
    contentRecording: false,
  },
});
const connection = await project.voiceAgents.realtime.connect("<voice agent name>");
try {
  await connection.sendText("Hello.");
  for await (const event of connection) {
    if (event.type === "error") {
      throw new Error(event.error.message);
    }
    if (event.type === "response.done") {
      if (event.response.status !== "completed") {
        throw new Error(`Voice response ${event.response.status}.`);
      }
      break;
    }
  }
} finally {
  await connection.close();
}

リアルタイムは、音声チャンクごとのものではなく、レスポンスごとにセッションスパン、接続スパン、 invoke_agent スパンを記録します。 これにはステータス、トークン使用量、音声バイト数が含まれます。 最初の音声遅延は、ユーザーの音声やスピーカーの再生からではなく、応答作成から受信までの遅延で測定されます。 サービスIDはトレースに現れ、メトリック次元には表示されません。

REST と project.voiceAgents.realtime はプロジェクトのトレース設定を共有します。 別に構築された VoiceAgentRealtimeClient はそれらを継承しません。 入力要約は最新の入力を記述しており、会話履歴全体を記述するわけではありません。

コンテンツ録画はデフォルトでオフになっています。 テキスト、文字起こし、ツールの引数/結果を記録したい場合のみ contentRecording: true を有効にしてください。これらには機密データが含まれている場合があります。 生のメディア、認証情報、クエリ値、電話番号、SDP、生のエラー/クローズメッセージは記録されません。 読み取り/リスト操作は既存のHTTPパイプライントレースを使用します。

リアルタイム トレーシングサンプル および REST トレースサンプルを参照してください。

Azure Monitor tracing

こちらはAzure Monitorトレーシングを有効にする方法を示すコードサンプルです:

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

const projectEndpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint>";
// Configure Azure Monitor tracing (must be done before creating the client)
const connectionString =
  process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<connection string>";
useAzureMonitor({
  azureMonitorExporterOptions: { connectionString },
  samplingRatio: 1,
  tracesPerSecond: 0,
});
// Create client with tracing enabled (experimental)
const project = new AIProjectClient(projectEndpoint, new DefaultAzureCredential(), {
  tracingOptions: {
    experimental: true,
    contentRecording: false,
    traceContextPropagation: true,
  },
});

また、あなたのシナリオに合ったスパンを作成することも検討してください:

import { trace, context } from "@opentelemetry/api";

const tracer = trace.getTracer("MyScenario");
const span = tracer.startSpan("myOperation");
const ctx = trace.setSpan(context.active(), span);
await context.with(ctx, async () => {
  // Your agent operations here
});
span.end();

完全なサンプルコードは agentBasicWithAzureMonitorTracing.tsをご覧ください。

コンソールトレーシング

ローカル開発の場合は、コンソールへのトレースを印刷できます:

import {
  NodeTracerProvider,
  SimpleSpanProcessor,
  ConsoleSpanExporter,
} from "@opentelemetry/sdk-trace-node";
import { AIProjectClient } from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";

// Set up OpenTelemetry with a console exporter (must be done before creating the client)
const provider = new NodeTracerProvider({
  spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())],
});
provider.register();
// Create client with tracing enabled (experimental)
const projectEndpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint>";
const project = new AIProjectClient(projectEndpoint, new DefaultAzureCredential(), {
  tracingOptions: {
    experimental: true,
    contentRecording: false,
    traceContextPropagation: true,
  },
});

完全なサンプルコードは agentBasicWithConsoleTracing.tsをご覧ください。

コンテンツ録画の実現

コンテンツ記録は、メッセージの内容やツール呼び出しの詳細(パラメータや返り値など)がトレースに記録されるかどうかを制御します。 このデータには機密性の高いユーザー情報が含まれている場合があります。

コンテンツ録画を有効にするには、クライアント構築時に contentRecording: true を tracingOptions に渡すか、環境変数 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT を trueに設定してください。 コンテンツ録画はデフォルトで falseです。

トレースコンテキスト伝播の実現

トレースコンテキスト伝播により、クライアント側のスパンをAzure、OpenAIや他のAzureサービスのサーバー側スパンと相関させることが可能になります。 有効化されると、SDKはtraceparentを通じて取得したOpenAIクライアントからのHTTPリクエストにW3C Trace Contextヘッダー(tracestateおよびproject.getOpenAIClient())を自動的に注入します。

これにより、分散トレース内のすべての操作が同じトレースIDを共有し、アプリケーションおよびAzureサービス全体でエンドツーエンドの可視性が提供されます。

トレースコンテキスト伝播はデフォルトで有効です。 無効にするには、クライアント構築時に traceContextPropagation: false にtracingOptionsを渡すか、環境変数 AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION を false に設定してください。

重要なセキュリティおよびプライバシーの考慮事項:

  • トレース ID:トレースコンテキスト伝播が有効になると、トレース ID は Azure OpenAI やその他の外部サービスに送信されます。
  • リクエスト相関:トレースIDは、Azureサービスが同一セッションまたはユーザーからのリクエストを複数のAPIコールにまたがって相関させることを可能にします。これはユースケースによってプライバシーに影響する可能性があります。

トレースコンテキスト伝播は、観察可能性、プライバシー、セキュリティ要件を慎重に検討した後にのみ有効にしてください。

トラブルシューティング

例外

サービス呼び出しを行うクライアント メソッドは、サービスからの成功しない 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号hereを開いてください。

次のステップ

完全に実行可能なコードが入っているpackage samplesフォルダを見てみてください。

TypeSpecからの再生成(メンテナ)

このパッケージはAzure/azure-rest-api-specsのTypeSpec仕様から再生成されています。 6つの再生段階と課題割り当てされたオーケストレーターは.github/skills/のスキルとしてエンコードされ、GitHub Copilotのコーディングエージェントタスクによってエンドツーエンドで駆動可能です。

リポジトリレベルのカスタムエージェントai-projects-regen、あくまでGitHubディスカバリーのエントリーポイントに過ぎません。 課題割り当てワークフローはパッケージローカル run-issue-regeneration スキルが所有します。

問題からワークフローを開始するには、問題説明に各必要なラベルに対して正確に1つの値を含めてください:

TypeSpec commit: <40-character-lowercase-SHA>
Base branch: <branch>

問題をCopilotに割り当て、ai-projects-regenカスタムエージェントを選択し、説明に記載されている同じ開始ブランチを選択します。 エージェントは、いずれかの値が欠落または無効な場合に変更を加える前に停止します。

クラウドエージェントタスクとして再生をディスパッチするには、以下のディレクトリから実行します:

pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1                     # latest commit on feature/foundry-release
pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1 -TspCommit <sha>    # pin a specific commit
pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1 -DryRun             # render the prompt locally, do not dispatch
pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1 -Repo myuser/azure-sdk-for-js -Follow   # smoke-test on a fork

Windowsでは、スクリプトを直接呼び出す(例:./scripts/start-cloud-regen.ps1)はデフォルトのRestricted実行ポリシーによってブロックされることがあります。 上の pwsh -NoProfile -File ... 形態はそれを回避しています。 あるいは、ローカルスクリプトを許可するために一度だけ Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned 実行する方法もあります。

前提条件:

  • gh CLI がターゲットリポジトリに対してインストールされ、認証(gh auth login)されました。 agent-taskサブコマンドはプレビュー中で、最近のghが必要です。
  • ターゲットリポジトリでGitHub Copilotコーディングエージェントが有効になっている組織のメンバーシップ。
  • ターゲットリポジトリへのアクセスをプッシュします(クラウドエージェントは自身のGitHubアプリIDを使ってドラフトPRをプッシュ・オープンします)。

注意点として、送信されたプロンプトはタスク開始時にインラインで pnpm install --filter "@azure/ai-projects..." と pnpm turbo build --filter="@azure/ai-projects..." --token 1 実行されます。 クラウドエージェントのサンドボックスがこれらのネットワーク通話をブロックすると、セットアップ時にタスクが失敗します。その場合はスキルをローカルで実行するか、SDKビルドチームと連携してリポジトリルートに中央管理 copilot-setup-steps.yml ワークフローを追加してください。

貢献

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの投稿では、お客様が投稿を使用する権利を当社に付与する権利を有し、実際に行うことを宣言する共同作成者ライセンス契約 (CLA) に同意する必要があります。 詳細については、https://cla.microsoft.comを参照してください。

プル要求を送信すると、CLA ボットは、CLA を提供し、PR を適切に装飾する必要があるかどうかを自動的に判断します (ラベル、コメントなど)。 ボットによって提供される手順にそのまま従ってください。 これは、CLA を使用するすべてのリポジトリで 1 回だけ行う必要があります。

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