AI Projects 클라이언트 라이브러리를 사용하면 Azure AI Foundry 프로젝트의 리소스에 쉽게 액세스할 수 있습니다. 다음 작업을 수행하는 데 사용합니다.
- 클라이언트에서 속성을 사용하여
.agents. - 이 방법을 사용하여
.inference.azureOpenAI. - 작업을 사용하여 파운드리 프로젝트에 배포된
.deployments. - 작업을 사용하여 Foundry 프로젝트에서 연결된 Azure 리소스를 열거합니다
.connections. -
문서를 업로드하고 작업을 사용하여
.datasets참조할 데이터 세트를 만듭니다. - 작업을 사용하여 검색 인덱스를 만들고 열거합니다
.indexes. - 함수를 사용하여
enable_telemetry.
제품 설명서 | 샘플 | 패키지(npm) | API 참조 설명서 | SDK 소스 코드
목차
시작하기
전제 조건
- Node.js의 LTS 버전
- Azure 구독.
- Azure AI Foundry
프로젝트.
승인
-
Entra ID 는 클라이언트를 인증하는 데 필요합니다. 애플리케이션에는 TokenCredential 인터페이스를 구현하는 개체가 필요합니다. 여기서 코드 샘플은 DefaultAzureCredential사용합니다. 이 작업을 수행하려면 다음이 필요합니다.
-
Contributor역할입니다. 할당된 역할은 Azure Portal에서 Azure AI Project 리소스의 "액세스 제어(IAM)" 탭을 통해 수행할 수 있습니다. 여기에서 역할 할당에 대해 자세히 알아보세요. - Azure CLI 설치되어 있습니다.
-
az login실행하여 Azure 계정에 로그인됩니다. - 여러 Azure 구독이 있는 경우 Azure AI Project 리소스를 포함하는 구독은 기본 구독이어야 합니다.
az account list --output table실행하여 모든 구독을 나열하고 어떤 구독이 기본값인지 확인합니다.az account set --subscription "Your Subscription ID or Name"실행하여 기본 구독을 변경합니다.
-
패키지 설치
npm install @azure/ai-projects @azure/identity
주요 개념
클라이언트 만들기 및 인증
를 구성하려면 AIProjectsClientendpoint엔드포인트에서 가져올 수 있습니다. 아래에서는 환경 변수가 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 설명서를 참조하세요.
예시
에이전트 작업 수행
.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를 가져오고 채팅 완료 호출을 실행합니다.
아래 코드를 실행합니다. 여기서는 (str)이 정의되어 있다고 가정합니다 deploymentName . 파운드리 프로젝트(Foundry Project)에 있는 AI 모델의 배포 이름입니다. "모델 + 엔드포인트" 탭의 "이름" 열 아래에 표시된 것처럼
api_version
이 테이블의 "데이터 평면 - 유추" 행에 있는 값으로 업데이트합니다.
또한 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" 폴더를 참조하세요.
배포 작업
아래 코드는 AI Foundry 프로젝트에 배포된 AI 모델을 열거할 수 있는 몇 가지 디플로이먼트 오퍼레이션을 보여줍니다. 이러한 모델은 AI Foundry Project의 "모델 + 엔드포인트" 탭에서 볼 수 있습니다. 전체 샘플은 패키지 샘플의 "deployment" 폴더에서 찾을 수 있습니다.
import { ModelDeployment } from "@azure/ai-projects";
const modelPublisher = process.env["MODEL_PUBLISHER"] || "<model publisher>";
console.log("List all deployments:");
const deployments: ModelDeployment[] = [];
const properties: Array<Record<string, string>> = [];
for await (const deployment of project.deployments.list()) {
// Check if this is a ModelDeployment (has the required properties)
if (
deployment.type === "ModelDeployment" &&
"modelName" in deployment &&
"modelPublisher" in deployment &&
"modelVersion" in deployment
) {
deployments.push(deployment);
properties.push({
name: deployment.name,
modelPublisher: deployment.modelPublisher,
modelName: deployment.modelName,
});
}
}
console.log(`Retrieved deployments: ${JSON.stringify(properties, null, 2)}`);
// List all deployments by a specific model publisher (assuming we have one from the list)
console.log(`List all deployments by the model publisher '${modelPublisher}':`);
const filteredDeployments: ModelDeployment[] = [];
for await (const deployment of project.deployments.list({
modelPublisher,
})) {
// Check if this is a ModelDeployment
if (
deployment.type === "ModelDeployment" &&
"modelName" in deployment &&
"modelPublisher" in deployment &&
"modelVersion" in deployment
) {
filteredDeployments.push(deployment);
}
}
console.log(
`Retrieved ${filteredDeployments.length} deployments from model publisher '${modelPublisher}'`,
);
// Get a single deployment by name
if (deployments.length > 0) {
const deploymentName = deployments[0].name;
console.log(`Get a single deployment named '${deploymentName}':`);
const singleDeployment = await project.deployments.get(deploymentName);
console.log(`Retrieved deployment: ${JSON.stringify(singleDeployment, null, 2)}`);
}
연결 작업
아래 코드는 AI Foundry 프로젝트에 연결된 Azure 리소스를 열거할 수 있는 몇 가지 연결 작업을 보여 줍니다. 이러한 연결은 AI Foundry Project의 "Connected resources" 탭에 있는 "Management Center"에서 볼 수 있습니다. 전체 샘플은 패키지 샘플의 "연결" 폴더에서 찾을 수 있습니다.
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)}`);
데이터 세트 작업
아래 코드는 몇 가지 데이터 세트 작업을 보여줍니다. 전체 샘플은 패키지 샘플의 "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" 폴더에서 찾을 수 있습니다.
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);
문제 해결
예외
서비스 호출을 만드는 클라이언트 메서드는 서비스에서 성공하지 않은 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'
문제 신고
클라이언트 라이브러리와 관련된 문제를 보고하거나 추가 기능을 요청하려면 여기에서
다음 단계
완전히 실행 가능한 코드를 포함하는 패키지 샘플 폴더를 살펴보세요.
기여하기
이 프로젝트는 기여와 제안을 환영합니다. 대부분의 기여는 귀하가 귀하의 기여를 사용할 권리를 부여할 권리가 있음을 선언하는 CLA(기여자 사용권 계약)에 동의해야 합니다. 자세한 내용은 https://cla.microsoft.com방문하세요.
끌어오기 요청을 제출하면 CLA 봇은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 주석). 봇에서 제공하는 지침을 따르기만 하면 됩니다. CLA를 사용하여 모든 리포지토리에서 한 번만 이 작업을 수행해야 합니다.
이 프로젝트는 Microsoft 오픈 소스 준수 사항을 채택했습니다. 자세한 내용은 행동 강령 FAQ를 참조하거나 추가 질문이나 의견을 opencode@microsoft.com 문의하세요.
Azure SDK for JavaScript