你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

Azure AI Projects JavaScript客户端库 - 版本 2.11.0

AI Projects 客户端库是 Microsoft Foundry SDK 的一部分,为你提供对 Microsoft Foundry Project 中资源的便捷访问。 使用它可执行以下操作:

  • 在客户端上使用该.agents属性创建并运行代理。
  • 使用专用工具增强代理:
    • 代理记忆搜索(预览)
    • 代理对代理(A2A)(预览)
    • Azure AI 搜索
    • 必应自定义搜索(预览)
    • 必应上下文关联
    • 浏览器自动化
    • 代码解释器
    • 计算机应用
    • 文件搜索
    • 功能工具
    • 图像生成
    • Microsoft Fabric (预览版)
    • 模型上下文协议 (MCP)
    • OpenAPI
    • Microsoft SharePoint(预览)
    • 网页搜索(预览)
    • 工具搜索
  • 使用该.getOpenAIClient.方法创建一个 OpenAI 客户端,与你的代理一起运行响应、对话、评估和微调操作。
  • 在支持会话的部署中,使用.agents操作管理托管代理会话和文件。
  • 使用.beta.skills操作管理可重用代理功能的技能(预览)。
  • 使用 操作 .toolboxes 管理工具箱,用于将工具分组到可重复使用的集合中。
  • 使用操作.beta.memoryStores管理代理会话的内存存储(预览)。
  • 管理用于调度和派遣自动化工作流的例程(预览),并使用操作。.beta.routines
  • 管理模型版本(预览), 用于创建、更新和管理自定义模型版本,使用操作 .beta.models 。
  • 探索其他评估工具(部分处于预览阶段),利用 、 .beta.evaluationTaxonomies、 .beta.evaluators、 .beta.insights和 .beta.schedules 操作来评估您的生成式 AI 应用.evaluationRules的性能。
  • 运行红队扫描(预览), 利用操作 .beta.redTeams 识别与生成式 AI 应用相关的风险。
  • 微调 基于你的数据构建AI模型。
  • 通过操作.deployments枚举部署到您的 Foundry Project 的 AI 模型。
  • 使用操作.connections枚举 Foundry 项目中的已连接 Azure 资源。
  • 上传文档并创建 数据集以使用操作引用这些文档 .datasets 。
  • 使用操作.indexes创建并枚举搜索索引。

客户端库使用Microsoft Foundrydata 平面 REST API 的版本 。

产品文档 | 示例 | 软件包(npm) | API 参考文档 | SDK 源代码

目录

入门

先决条件

授权

  • 验证客户端需要一个 Entra ID。 应用程序需要实现 TokenCredential 接口的对象。 这里的代码示例是 DefaultAzureCredential。 若要使该工作正常,需要:
    • 合适的角色分配。 参见 Microsoft Foundry 门户中的 基于角色的访问控制。 角色分配可以通过Azure门户中Azure AI Project资源中的“访问控制 (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 项目可能部署了一个或多个 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));

执行 Agent作

.agents上的AIProjectsClient属性允许您访问所有代理作。 代理使用 OpenAI Responses 协议的扩展,因此您可能需要让客户端执行 OpenAI 代理作,如以下示例所示。

关于设置,请参见快速入门:设置 Microsoft Foundry 资源。

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 所有14个存储的实时对话操作均用于 project.voiceAgents.conversations;实时协议和OpenAI实时模型 不是必需
GA TPE/Twilio电话及呼叫作业列表/获取操作 project.voiceAgents.telephony 不是必需
Conditional 通过在线切换、SIP 传输目标或 post_call 传给foundryFeaturesconnect()
Conditional 电话绑定/传输/呼叫写入以及呼叫作业创建/取消/删除 project.voiceAgents.telephony 仅在使用 SIP 时通过foundryFeatures
预览版 GPT Live 定义、委派、会话、存储对话和模型 必需;原生 Live 并 project.beta.voiceAgents.liveConversations 内部提供
预览版 在线切换配置/状态/事件、SIP 模型及 post_call 配置/类型 这些预览成员必须使用;使用相关操作的选择加入
预览版 全部七次战役行动均为 project.beta.voiceAgents.telephony 必需;内部供应

GA 操作可以接受仅包含预览成员的联合。 在选择“实时切换”或“SIP成员”,或配置时 post_call选择加入;这些成员的存在不会让整个联合或操作预览生效。

对于电话写入,请使用连接、绑定、呼叫或呼叫作业提供者来确定 SIP 使用情况,而不仅仅是地址类型:SIP 连接可以使用 phone_number 源地址和目的地址。 REST 跟踪示例仅接受现有的 TPE/Twilio 连接作为可选的出站调用;它不演示 SIP 调用。 单独 transfer.require_handoff ,是一个 GA 传输-摘要设置;单独它并不启用预览内联交接。

在迁移较旧样本时,将 替换为 project.agents.createFromPrompt,project.voiceAgents.conversationsproject.beta.voiceAgents.conversations并将非活动用途project.beta.voiceAgents.telephony替换project.beta.agents.createFromPrompt为 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();
}

用一个 for await 循环读取事件。 离开环路会关闭连接。 未知事件类型在未断开会话时出现 type: "unknown" ;其原始类型位于 eventType。 在使用其字段之前先进行验证 rawEvent 。 畸形事件抛出 VoiceAgentProtocolError。 按照上述方式处理服务 error 事件。

要保持对话,请将 agent 或 设置为 store: trueconnect(),然后使用 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 会发送等效 foundry_features 的 WebSocket 查询参数。 使用带类型选项,而非保留的通用 query 参数。 默认的实时示例使用 GA 代理配置;对于已有具有内联切换、SIP 传输目的地或 post_call的代理,请按上述方式选择加入。

为你想要的任务选择一个完整的示例:

Task Node.js 示例
创建并读取代理定义 配置语音代理
从目标生成代理 生成语音代理
发送语音并保存音频回复 实时音频
发送文本并处理函数调用 实时文本和工具
无需拨打电话即可检查绑定和通话历史 电话
将回合路由至内线专家(预览) 内联切换
检查实时(GA)或实时(预览)录制 对话录音
检查预览活动和 GA 外站呼叫作业 只读活动

预览切换示例在创建定义并连接时会主动加入。 它创建两个在线实时专家,观察相关交接事件和目标的完成响应,然后删除其样本代理。 如果创建被中断,中止的 HTTP 请求不会取消服务器端的创建:使用日志中唯一代理名称检查资源是否会稍后完成。 这些描摹样本是独立的仪表操作演示;基础生成、实时和 GPT Live 示例不需要进行跟踪设置。 配置示例默认为 GA;设置可选的通话后目标可启用预览转录副本投递,并添加定义选择加入。 通话后交付还支持可选的合并录音 URL;该示例不请求来电音频。

存储的对话和录音

会话录音示例为只读,支持两种持久化的 API 家族。 设置 FOUNDRY_AGENT_NAME 并选择 FOUNDRY_VOICE_CONVERSATION_PROTOCOL=realtime 或 live。 实时使用不含预览头的 GA project.voiceAgents.conversations 客户端;Live 则使用 project.beta.voiceAgents.liveConversations 所需的预览头。 它读取一页,并可使用 sample.env中描述的变量选择一个精确的对话或项目。 使用 REST 集合返回的 ID,而不是本地 RealTent 项目或响应 ID。 先通过连接 store: true 录音并完成会话,然后再下载音频。 该样本从不删除存储的对话,也不会打印其来电者文字记录。

设置为 FOUNDRY_VOICE_RECORDING_OUTPUT_FILE 选择是否下载WAV文件。 使用 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 示例读取已完成的 Live 会话,列出其存储项目而不打印转录,并保存其由 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 客户端,包括由预览活动创建的作业。 活动示例仅读取活动准备、验证错误、操作监控和调用作业。 活动阅读需要部署时启用了这些预览路径。 它从不创建或取消通话:活动创建可以在其准备轮询器返回之前授权拨号。 在准备过程中出现空白的验证错误页面并不能证明活动已有效或已就绪。

自定义查询参数

通过以 query 添加一个连接的 URL 参数。 使用您的服务或网关支持的名称;以下名称为示例:

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 将其移除。 这些值不会在后续连接中重复使用。

使用foundryFeatures诸如 store、 agentVersionOverride和 实时等类型选项,而不是在 中输入 SDK 设置。query SDK/认证名称、非规范结构化输入名称以及以 ID h- 开头的名称保持保留。 实时明确允许与 JSON 对象字符串相同的精确 structured_inputs 键,如上所示;不要将其 structuredInputs与 组合。 其他自定义查询值不会成为提示变量。

实时 structuredInputs 保存基于头部的传输 Node.js。 浏览器使用 URL 查询,因为它们无法发送任意的 WebSocket 升级头。 如果您的服务需要查询表单,请通过 明确 query.structured_inputs 选择加入,而不是 structuredInputs。 切勿在查询参数中放置秘密或敏感提示变量: 服务器和代理访问日志可以保留 URL。

GPT Live 语音代理

用于 project.beta.voiceAgents.live GPT Live 代理。 创建代理时,将 、 sub_protocol: "live"model_type: "self_deployed"、 model 设置为您的 GPT Live 部署名称。 创造需要 VoiceAgents=V1Preview。 传递 { foundryFeatures: "VoiceAgents=V1Preview" } 到 project.agents.create() 或 createVersion(). 原生 Live 连接始终会在内部发送所需的预览标志;调用者不需要在 上 live.connect()设置标志。

此简短示例需要一个已配置为单声道PCM16LE音频且频率为 24 kHz 的代理。 即使添加文本指令,实时也会在音频时钟上提前,因此示例会发送静默,直到相关确认到达,然后关闭会话。 请使用以下完整示例发送文本或语音并阅读回复。

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 并 FOUNDRY_LIVE_MODEL 进入 .env。 请使用 部署名称,而非模型目录 ID。 函数样本还需要 FOUNDRY_LIVE_BACKEND_MODEL。 有关这些设置和可选音频文件路径,请参见 sample.env 。

Task Node.js 示例
发送问候语,并将口头回复打印成文本 GPT Live 文本
发送语音文件并保存音频回复 GPT Live 音频
运行本地函数,让代理说出结果 GPT Live 函数调用

从已构建的 SDK 签出中,运行包含 22.18 或更高版本 Node.js 示例:

node samples-dev/agents/agentVoiceLiveText.ts

每个样本都会创建和删除自己的代理。 它会打印字幕,但不会通过扬声器播放声音。 音频采样使用录制的文件,而非麦克风,读取并保存 原始单声道PCM16LE,频率为24 kHz,无需WAV或其他文件头。

回复后按 Enter 键,或按 Ctrl+C 停止。 使用量在会话结束前可计费。 现场需要持续的音频输入,即使是文本和工具,因此采样在闲置时会发送静音。 Live 没有语音完成的事件;完成后端响应并不意味着代理已经说完。

文本示例会附加会话指令,并在对应的确认后再添加评论。 这种确认表示接受,而非完成演讲;保持会话开放,直到预期回复到来。

会话控制和事件

connect() 等待 session.started。 读取当前设置, connection.session包括所选受管代理和版本(如适用)。 读取一个循环的 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 服务的最终事件及任何连接错误。

通过响应委派,后端事件会传入 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;服务部署必须支持持久性。 设置为liveOptionsAIProjectClient更改连接、会话启动和关闭超时。 使用存储对话示例FOUNDRY_VOICE_CONVERSATION_PROTOCOL=live检查持久化项目或下载其 WAV 音频。

浏览器身份验证

使用浏览器凭据,例如 InteractiveBrowserCredential。 SDK 使用原生 WebSocket 的承 live 载令牌子协议,包括 Web Workers 中。 Node.js 则使用承载头。 不要作为 Live 子协议提供 realtime ,不要在 URL 中放置令牌,也不要在浏览器代码中嵌入 API 密钥、客户端密钥或长效令牌。 如果无法进行直接浏览器认证,请通过 提供经过认证的后端中继 webSocketFactory。

实时连接会保留structuredInputsx-ms-voice-structured-inputs在 Node.js 的头部,并在浏览器和工作程序中使用 structured_inputs URL 查询。 Explicit Realtime query.structured_inputs 会在任何主机上选择 URL 传输。 GPT Live 在所有主机上仍然使用 URL 查询,没有基于头部的替代方案。 代理和服务器访问日志可以保留 URL:不要在 URL 携带的输入中放入凭据、个人数据或其他敏感信息。

使用 Agent 工具

代理可以通过各种能力的专用工具进行增强。 工具按连接需求进行组织:

内置工具

这些工具无需外部连接即可立即使用。

代码解释器

在沙箱环境中编写和运行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.");
}

Web 搜索(预览)

进行一般的网络搜索,获取互联网的最新信息。 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。

计算机使用

使代理能够直接与计算机系统交互,实现任务自动化和系统操作(需要支持该 computer 工具的模型部署,例如 gpt-5.4;对于 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_outputcomputer_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。

必应基础设置

地面工作人员的回复,附带必应的实时网络搜索结果,提供 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 自定义搜索(预览)

使用自定义配置的必应搜索实例,针对特定领域或筛选的网页搜索结果:

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 连接的 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 连接的 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 辅助质量与安全指标,用于评估性能并评估大型语言模型模型、生成式人工智能应用和代理。 指标被定义为评估者。 内置或定制评估器可以提供全面的评估洞察。

下面的代码展示了一些评估作。 完整的样本列表可在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 项目相连的 Azure 资源。 这些连接可以在你的 Microsoft Foundry Project 中的“已连接资源”标签页的“管理中心”中看到。 完整样本可在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)}`);

数据集作

下面的代码展示了一些 Dataset作。 完整样本可在package samples的“datasets”文件夹中找到。

本地文件系统上传(、project.datasets.uploadFileproject.datasets.uploadFolder 和 project.beta.models.create)仅支持 Node.js。 浏览器应用程序可以导入 AIProjectClient 和 VoiceAgentRealtimeClient 从数据集和模型 @azure/ai-projects 操作,而无需 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。

跟踪

实验特征门

重要提示: 生成式AI追踪仪器是一项实验性预览功能。 跨度、属性和事件可能会在将来的版本中进行修改。 使用该变量时,必须通过在tracingOptions构experimental: true造 时通过 明确AIProjectClient选择,或设置环境变量:

AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING=true

只有在审核需求并了解追踪行为未来版本可能会变化后,才启用此功能。

开始描摹

你可以为你的 Microsoft Foundry 项目添加 Application Insights Azure 资源。 如果启用了,你可以获取 Application Insights 连接字符串,配置你的 AI Projects 客户端,并在 Azure Monitor 中观察跟踪。 通常,您可能希望在创建客户端或代理之前开始跟踪。

安装

发送traces to Azure Monitor:

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

打印到控制台的痕迹(对本地开发很有用):

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

如何启用追踪

追踪通过传递 tracingOptions 给 AIProjectClient 构造子实现。 如果 tracingOptions 没有提供,生成式AI追踪将完全关闭,生成式AI的跨度或指标不会被输出。 该设置仅控制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 环境变量 默认 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 提供程序和导出器,然后设置 tracingOptions: { experimental: true } 。AIProjectClient 这追踪语音代理生成、电话变更、对话删除以及实时会话和响应。 不需要单独的语音代理追踪标记。

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_CONTENTtrue设置为 。 内容录制默认为 false。

支持迹线上下文传播

追踪上下文传播允许客户端的跨度与 Azure、OpenAI 及其他 Azure 服务的服务器端跨度关联。 启用后,SDK会自动向OpenAI客户端通过 获得traceparent的HTTP请求注入W3C追踪上下文头部(tracestate和project.getOpenAIClient())。

这确保分布式跟踪内的所有操作共享相同的跟踪ID,从而在你的应用和Azure可观察性后端服务之间实现端到端的可视化。

默认启用了跟踪上下文传播。 要禁用它,可以在traceContextPropagation: false构建客户端时传递,tracingOptions或将环境变量AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATIONfalse设置为 。

重要的安全与隐私注意事项:

  • 跟踪 ID:启用跟踪上下文传播时,跟踪 ID 会发送到 Azure OpenAI 及其他外部服务。
  • 请求关联:跟踪 ID 允许 Azure 服务在多个 API 调用中关联来自同一会话或用户的请求,这可能会根据您的使用场景带来隐私影响。

只有在仔细审查你的可观察性、隐私和安全要求后,才启用跟踪上下文传播。

故障排除

异常

发出服务调用的客户端方法会引发 RestError,以响应来自该服务的非成功 HTTP 状态代码响应。 异常 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 规范重新生成的。 六个重生阶段及其分配给问题的编排器被编码为技能,代码为.github/skills/,并可由GitHub Copilot编码代理任务端到端驱动。

仓库级ai-projects-regen自定义代理只是 GitHub 发现的入口。 问题分配的工作流程由 package-local run-issue-regeneration 技能负责。

要从某个问题开始工作流程,请在问题描述中为每个必需标签恰好包含一个值:

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 一次以允许本地脚本。

Prerequisites:

  • gh CLI 已gh auth login针对目标仓库安装并认证()。 该 agent-task 子命令目前处于预览阶段,需要最近的 gh.
  • 在目标仓库中启用了 GitHub Copilot 编码代理的组织成员身份。
  • 推送访问目标仓库(云代理使用自己的 GitHub 应用身份推送并打开草稿 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 在所有存储库中执行此操作一次。

该项目已采用Microsoft开源行为准则。 有关详细信息,请参阅《行为准则常见问题解答》或联系 opencode@microsoft.com,了解任何其他问题或意见。