你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
AI Projects 客户端库提供对 Azure AI Foundry 项目中资源的轻松访问。 使用它可执行以下操作:
- 使用客户端上的属性
.agents。 - 使用该方法
.inference.azureOpenAI。 - 使用作列举部署到 Foundry 项目的
.deployments。 - 使用作枚举 Foundry 项目中
.connections。 -
上传文档并创建 Datasets 以使用
.datasets作引用它们。 - 使用作
.indexes。 - 使用该函数
enable_telemetry。
产品文档 | 样品 | 包 (npm) | API 参考文档 | SDK 源码
目录
入门指南
先决条件
- LTS 版本的 Node.js
- 一个 Azure 订阅。
- Azure AI Foundry中的
项目。
授权
- 需要 Entra ID 来验证客户端。 应用程序需要实现 TokenCredential 接口的对象。 此处的代码示例使用 DefaultAzureCredential。 若要使该工作正常,需要:
-
Contributor角色。 可以通过 Azure 门户中 Azure AI 项目资源的“访问控制(IAM)”选项卡完成分配的角色。 在此处了解有关角色分配的更多信息。 - 已安装 Azure CLI。
- 通过运行
az login登录到 Azure 帐户。 - 请注意,如果有多个 Azure 订阅,则包含 Azure AI 项目资源的订阅必须是默认订阅。 运行
az account list --output table列出所有订阅,并查看默认订阅。 运行az account set --subscription "Your Subscription ID or Name"以更改默认订阅。
-
安装软件包
npm install @azure/ai-projects @azure/identity
重要概念
创建客户端并对其进行身份验证
要构造 AIProjectsClient,可以从 endpoint 获取 。 下面我们假设定义了环境变量 AZURE_AI_PROJECT_ENDPOINT_STRING 来保存此值:
import { AIProjectClient } from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";
const endpoint = process.env["AZURE_AI_PROJECT_ENDPOINT_STRING"] || "<project endpoint string>";
const client = new AIProjectClient(endpoint, new DefaultAzureCredential());
客户端使用 API 版本 v1,请参阅 API 文档 以了解有关支持功能的更多信息。
例子
执行 Agent作
.agents上的 AIProjectClient 属性允许您访问包中经过身份验证AgentsClient的 azure-ai-agents 。 下面我们将介绍如何创建代理并删除它。 要查看您可以对创建的 执行agent哪些作,请参阅与该包关联的azure-ai-agents。
const agent = await project.agents.createAgent("gpt-4o", {
name: "my-agent",
instructions: "You are a helpful agent",
});
console.log(`Created agent, agent ID : ${agent.id}`);
// Do something with your Agent!
// See samples here https://github.com/Azure/azure-sdk-for-js/tree/@azure/ai-projects_1.0.1/sdk/ai/ai-agents/samples
await project.agents.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);
获取经过身份验证的 AzureOpenAI 客户端
您的 Azure AI Foundry 项目可能部署了一个或多个支持聊天完成的 OpenAI 模型。 使用以下代码从 openai 包中获取经过身份验证的 AzureOpenAI,并执行聊天完成调用。
运行下面的代码。 这里我们假设 deploymentName (str) 已定义。 它是 Foundry 项目中 AI 模型的部署名称。 如“模型 + 端点”选项卡的“名称”列下所示。
api_version使用此表的 “Data plane - inference” 行中找到的值更新该值。
您还可以选择(未显示)在 AI Foundry 项目中显式指定 Azure OpenAI 连接名称,该方法 inference.azureOpenAI 将使用此名称获取推理终端节点和身份验证凭据。 如果不存在,将使用默认的 Azure OpenAI 连接。
const client = await project.inference.azureOpenAI({
// The API version should match the version of the Azure OpenAI resource.
apiVersion: "2024-10-21",
});
const response = await client.chat.completions.create({
model: deploymentName,
messages: [{ role: "user", content: "How many feet are in a mile?" }],
});
console.log("response = ", JSON.stringify(response, null, 2));
有关其他示例,请参阅 包示例中 的“inference”文件夹。
部署作
下面的代码显示了一些 Deployments作,这些作允许您枚举部署到 AI Foundry 项目的 AI 模型。 这些模型可以在 AI Foundry 项目的 “Models + endpoints” 选项卡中看到。 完整的示例可以在 包示例中的 “deployment” 文件夹下找到。
import { ModelDeployment } from "@azure/ai-projects";
const modelPublisher = process.env["MODEL_PUBLISHER"] || "<model publisher>";
console.log("List all deployments:");
const deployments: ModelDeployment[] = [];
const properties: Array<Record<string, string>> = [];
for await (const deployment of project.deployments.list()) {
// Check if this is a ModelDeployment (has the required properties)
if (
deployment.type === "ModelDeployment" &&
"modelName" in deployment &&
"modelPublisher" in deployment &&
"modelVersion" in deployment
) {
deployments.push(deployment);
properties.push({
name: deployment.name,
modelPublisher: deployment.modelPublisher,
modelName: deployment.modelName,
});
}
}
console.log(`Retrieved deployments: ${JSON.stringify(properties, null, 2)}`);
// List all deployments by a specific model publisher (assuming we have one from the list)
console.log(`List all deployments by the model publisher '${modelPublisher}':`);
const filteredDeployments: ModelDeployment[] = [];
for await (const deployment of project.deployments.list({
modelPublisher,
})) {
// Check if this is a ModelDeployment
if (
deployment.type === "ModelDeployment" &&
"modelName" in deployment &&
"modelPublisher" in deployment &&
"modelVersion" in deployment
) {
filteredDeployments.push(deployment);
}
}
console.log(
`Retrieved ${filteredDeployments.length} deployments from model publisher '${modelPublisher}'`,
);
// Get a single deployment by name
if (deployments.length > 0) {
const deploymentName = deployments[0].name;
console.log(`Get a single deployment named '${deploymentName}':`);
const singleDeployment = await project.deployments.get(deploymentName);
console.log(`Retrieved deployment: ${JSON.stringify(singleDeployment, null, 2)}`);
}
连接作
下面的代码显示了一些 Connection作,这些作允许您枚举连接到 AI Foundry 项目的 Azure 资源。 这些连接可以在 AI Foundry 项目的“管理中心”的“Connected resources”选项卡中看到。 可以在 包示例的“connections”文件夹下找到完整示例。
import { Connection } from "@azure/ai-projects";
// List the details of all the connections
const connections: Connection[] = [];
const connectionNames: string[] = [];
for await (const connection of project.connections.list()) {
connections.push(connection);
connectionNames.push(connection.name);
}
console.log(`Retrieved connections: ${connectionNames}`);
// Get the details of a connection, without credentials
const connectionName = connections[0].name;
const connection = await project.connections.get(connectionName);
console.log(`Retrieved connection ${JSON.stringify(connection, null, 2)}`);
const connectionWithCredentials = await project.connections.getWithCredentials(connectionName);
console.log(
`Retrieved connection with credentials ${JSON.stringify(connectionWithCredentials, null, 2)}`,
);
// List all connections of a specific type
const azureAIConnections: Connection[] = [];
for await (const azureOpenAIConnection of project.connections.list({
connectionType: "AzureOpenAI",
defaultConnection: true,
})) {
azureAIConnections.push(azureOpenAIConnection);
}
console.log(`Retrieved ${azureAIConnections.length} Azure OpenAI connections`);
// Get the details of a default connection
const defaultConnection = await project.connections.getDefault("AzureOpenAI", true);
console.log(`Retrieved default connection ${JSON.stringify(defaultConnection, null, 2)}`);
数据集作
下面的代码展示了一些 Dataset作。 完整示例可以在 包示例的“datasets”文件夹下找到。
import { DatasetVersionUnion } from "@azure/ai-projects";
const VERSION1 = "1.0";
const VERSION2 = "2.0";
const VERSION3 = "3.0";
// sample files to use in the demonstration
const sampleFolder = "sample_folder";
// Create a unique dataset name for this sample run
const datasetName = `sample-dataset-basic`;
console.log("Upload a single file and create a new Dataset to reference the file.");
console.log("Here we explicitly specify the dataset version.");
const dataset1 = await project.datasets.uploadFile(
datasetName,
VERSION1,
path.join(__dirname, sampleFolder, "sample_file1.txt"),
);
console.log("Dataset1 created:", JSON.stringify(dataset1, null, 2));
const credential = project.datasets.getCredentials(dataset1.name, dataset1.version, {});
console.log("Credential for the dataset:", credential);
console.log(
"Upload all files in a folder (including subfolders) to the existing Dataset to reference the folder.",
);
console.log("Here again we explicitly specify a new dataset version");
const dataset2 = await project.datasets.uploadFolder(
datasetName,
VERSION2,
path.join(__dirname, sampleFolder),
);
console.log("Dataset2 created:", JSON.stringify(dataset2, null, 2));
console.log(
"Upload a single file to the existing dataset, while letting the service increment the version",
);
const dataset3 = await project.datasets.uploadFile(
datasetName,
VERSION3,
path.join(__dirname, sampleFolder, "sample_file2.txt"),
);
console.log("Dataset3 created:", JSON.stringify(dataset3, null, 2));
console.log("Get an existing Dataset version `1`:");
const datasetVersion1 = await project.datasets.get(datasetName, VERSION1);
console.log("Dataset version 1:", JSON.stringify(datasetVersion1, null, 2));
console.log(`Listing all versions of the Dataset named '${datasetName}':`);
const datasetVersions = await project.datasets.listVersions(datasetName);
for await (const version of datasetVersions) {
console.log("List versions:", version);
}
console.log("List latest versions of all Datasets:");
const latestDatasets = project.datasets.list();
for await (const dataset of latestDatasets) {
console.log("List datasets:", dataset);
}
// List the details of all the datasets
const datasets = project.datasets.listVersions(datasetName);
const allDatasets: DatasetVersionUnion[] = [];
for await (const dataset of datasets) {
allDatasets.push(dataset);
}
console.log(`Retrieved ${allDatasets.length} datasets`);
console.log("Delete all Datasets created above:");
await project.datasets.delete(datasetName, VERSION1);
await project.datasets.delete(datasetName, VERSION2);
await project.datasets.delete(datasetName, dataset3.version);
console.log("All specified Datasets have been deleted.");
索引作
下面的代码显示了一些 Indexes作。 完整的示例可以在 包示例的 “indexes” 文件夹下找到。
import { AzureAISearchIndex } from "@azure/ai-projects";
const indexName = "sample-index";
const version = "1";
const azureAIConnectionConfig: AzureAISearchIndex = {
name: indexName,
type: "AzureSearch",
version,
indexName,
connectionName: "sample-connection",
};
// Create a new Index
const newIndex = await project.indexes.createOrUpdate(indexName, version, azureAIConnectionConfig);
console.log("Created a new Index:", newIndex);
console.log(`Get an existing Index version '${version}':`);
const index = await project.indexes.get(indexName, version);
console.log(index);
console.log(`Listing all versions of the Index named '${indexName}':`);
const indexVersions = project.indexes.listVersions(indexName);
for await (const indexVersion of indexVersions) {
console.log(indexVersion);
}
console.log("List all Indexes:");
const allIndexes = project.indexes.list();
for await (const i of allIndexes) {
console.log("Index:", i);
}
console.log("Delete the Index versions created above:");
await project.indexes.delete(indexName, version);
故障排除
例外
发出服务调用的客户端方法会引发 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'
报告问题
若要报告客户端库问题或请求其他功能,请在此处
后续步骤
查看 包示例 文件夹,其中包含完全可运行的代码。
贡献
此项目欢迎贡献和建议。 大多数贡献要求你同意参与者许可协议(CLA),声明你有权(实际这样做)授予我们使用你的贡献的权利。 有关详细信息,请访问 https://cla.microsoft.com。
提交拉取请求时,CLA 机器人会自动确定是否需要提供 CLA 并适当修饰 PR(例如标签、注释)。 只需按照机器人提供的说明进行操作。 只需使用 CLA 在所有存储库中执行此操作一次。
该项目已采用 Microsoft开源行为准则。 有关详细信息,请参阅《行为准则常见问题解答》或联系 opencode@microsoft.com,了解任何其他问题或意见。