你当前正在访问 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
。 -
获取 Azure AI 推理客户端 ,以使用作
.inference
进行聊天完成、文本或图像嵌入。 -
读取 Prompty 文件或字符串 ,并使用该
PromptTemplate
类为推理客户端呈现消息。 -
Run Evaluations (
evaluations
运行评估) 以使用作评估生成式 AI 应用程序的性能。 - 使用该函数
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
:
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());
例子
执行 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.0-beta.8/sdk/ai/ai-agents/samples
await project.agents.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);
获取经过身份验证的 AzureOpenAI 客户端
您的 Azure AI Foundry 项目可能部署了一个或多个支持聊天完成的 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”文件夹。
获取经过身份验证的 ChatCompletionsClient
您的 Azure AI Foundry 项目可能部署了一个或多个支持聊天完成的 AI 模型。 这些模型可以是 OpenAI 模型、Microsoft 模型或来自其他提供商的模型。 使用以下代码从 azure-ai-inference 包获取经过身份验证的客户端,并执行聊天完成调用。
这里我们假设 deploymentName
(str) 已定义。 它是 Foundry 项目中 AI 模型的部署名称。 如“模型 + 端点”选项卡的“名称”列下所示。
const client = project.inference.chatCompletions();
const response = await client.post({
body: {
model: deploymentName,
messages: [{ role: "user", content: "How many feet are in a mile?" }],
},
});
console.log(response.body.choices[0].message.content);
有关其他示例,请参阅 包示例中 的“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);
评估
Azure AI Project 客户端库中的评估旨在评估云中生成式 AI 应用程序的性能。 生成式 AI 应用程序的输出使用基于数学的指标、AI 辅助的质量和安全指标进行定量测量。 指标定义为评估器。 内置或自定义评估器可以提供对应用程序功能和限制的全面见解。
计算器
评估器是自定义或预构建的类或函数,旨在衡量语言模型或生成式 AI 应用程序的输出质量。
评估器可通过 azure-ai-evaluation SDK 获得本地体验,也可在 Azure AI Foundry 的 评估器库中 使用,以便在云中使用它们。
有关内置和自定义计算器的更多详细信息, 请参阅此处。
在云中运行评估
要在云中运行评估,需要满足以下条件:
- 计算器
- 要评估的数据
- [可选]Azure Open AI 模型。
计算器
要在云中运行 evaluator,需要 evaluator ID
。 若要通过代码获取它,请使用 azure-ai-evaluation
import { DatasetVersion } from "@azure/ai-projects";
const dataset: DatasetVersion = await project.datasets.uploadFile(
"jss-eval-sample-dataset",
"1",
"./samples_folder/sample_data_evaluation.jsonl",
);
要评估的数据
云中的评估支持文件形式的 jsonl
数据。 可以通过项目客户端上的 helper 方法 upload_file
上传数据。
import { DatasetVersion } from "@azure/ai-projects";
const dataset: DatasetVersion = await project.datasets.uploadFile(
"jss-eval-sample-dataset",
"1",
"./samples_folder/sample_data_evaluation.jsonl",
);
[可选]Azure OpenAI 模型
Azure AI Foundry 项目附带一个默认的 Azure Open AI 终结点,可以使用以下代码轻松访问该终结点。 这将提供 Azure OpenAI 终结点的终结点详细信息。 一些评估器需要支持聊天完成的模型。
const defaultConnection = await project.connections.getDefault("AzureOpenAI");
远程评估示例
import { EvaluationWithOptionalName, EvaluatorIds, Evaluation } from "@azure/ai-projects";
const newEvaluation: EvaluationWithOptionalName = {
displayName: "Evaluation 1",
description: "This is a test evaluation",
data: {
type: "dataset",
id: "data-id", // dataset.name
},
evaluators: {
relevance: {
id: EvaluatorIds.RELEVANCE,
initParams: {
deploymentName: "gpt-4o-mini",
},
dataMapping: {
query: "${data.query}",
response: "${data.response}",
},
},
},
};
const evalResp = await project.evaluations.createRun(newEvaluation);
console.log("Create a new evaluation:", JSON.stringify(evalResp, null, 2));
// get the evaluation by ID
const eval2 = await project.evaluations.get(evalResp.name);
console.log("Get the evaluation by ID:", eval2);
const evaluations: Evaluation[] = [];
const evaluationNames: string[] = [];
for await (const evaluation of project.evaluations.list()) {
evaluations.push(evaluation);
evaluationNames.push(evaluation.displayName ?? "");
}
console.log("List of evaluation display names:", evaluationNames);
// This is temporary, as interface recommend the name of the evaluation
const name = evaluations[0].name;
const evaluation = await project.evaluations.get(name);
console.log("Get an evaluation by ID:", JSON.stringify(evaluation, null, 2));
注意:有关在本地运行评估器的信息,请参阅 使用 Azure AI 评估 SDK 进行评估。
故障 排除
异常
发出服务调用的客户端方法会引发 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,了解任何其他问题或意见。