Aracılığıyla paylaş


JavaScript için Azure AI Projeleri istemci kitaplığı - sürüm 1.0.1

AI Projeleri istemci kitaplığı, Azure AI Foundry projenizdeki kaynaklara kolay erişim sağlar. Bunu şunlar için kullanın:

  • İstemcideki özelliği kullanarak .agents.
  • Yöntemini kullanarak .inference.azureOpenAI.
  • İşlemleri kullanarak Foundry Projenize dağıtılan Yapay Zeka Modellerini numaralandırın.deployments.
  • İşlemleri kullanarak Foundry projenizdeki bağlı Azure kaynaklarını numaralandırın.connections.
  • İşlemleri kullanarak bunlara başvurmak için .datasets.
  • İşlemleri kullanarak Arama Dizinleri oluşturun ve numaralandırın.indexes.
  • İşlevi kullanarak enable_telemetry.

Ürün belgeleri | Örnekleri | Paket (npm) | API başvuru belgeleri | SDK kaynak kodu

İçindekiler tablosu

Başlangıç Yapmak

Önkoşul

İzin

  • İstemcinin kimliğini doğrulamak için Entra Kimliği gereklidir. Uygulamanızın TokenCredential arabirimini uygulayan bir nesnesine ihtiyacı var. Buradaki kod örnekleri DefaultAzureCredentialkullanır. Bunun çalışması için şunları yapmanız gerekir:
    • Contributor rolü. Atanan rol, Azure portalındaki Azure AI Projesi kaynağınızın "Erişim Denetimi (IAM)" sekmesi aracılığıyla gerçekleştirilebilir. Rol atamaları hakkında daha fazla bilgiyi burada bulabilirsiniz.
    • Azure CLI yüklendi.
    • az loginçalıştırarak Azure hesabınızda oturum açtınız.
    • Birden çok Azure aboneliğiniz varsa, Azure AI Project kaynağınızı içeren aboneliğin varsayılan aboneliğiniz olması gerektiğini unutmayın. Tüm aboneliğinizi listelemek ve hangisinin varsayılan olduğunu görmek için az account list --output table çalıştırın. Varsayılan aboneliğinizi değiştirmek için az account set --subscription "Your Subscription ID or Name" çalıştırın.

Paketi yükle

npm install @azure/ai-projects @azure/identity

Temel kavramlar

İstemci oluşturma ve kimlik doğrulaması

Bir oluşturmak AIProjectsClientiçin, uç endpointnoktadan getirilebilir. Aşağıda, ortam değişkeninin AZURE_AI_PROJECT_ENDPOINT_STRING bu değeri tutacak şekilde tanımlandığını varsayacağız:

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());

İstemci API sürümünü v1kullanır, desteklenen özellikler hakkında daha fazla bilgi edinmek için API belgelerine bakın.

Örnekler

Agent işlemlerini gerçekleştirme

Üzerindeki .agents özellik, AIProjectClient paketten kimliği doğrulanmış AgentsClient bir pakete azure-ai-agents erişmenizi sağlar. Aşağıda bir aracının nasıl oluşturulacağını ve silineceğini gösteriyoruz. Oluşturduğunuz öğelerle agent neler yapabileceğinizi görmek için, paketle ilişkili birçok örneğeazure-ai-agents bakın.

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}`);

Kimliği doğrulanmış bir AzureOpenAI istemcisi edinin

Azure AI Foundry projeniz, sohbet tamamlamalarını destekleyen bir veya daha fazla OpenAI modeline dağıtılmış olabilir. Openai paketinden kimliği doğrulanmış bir AzureOpenAI almak için aşağıdaki kodu kullanın ve bir sohbet tamamlama çağrısı yürütün.

Aşağıdaki kodu çalıştırın. Burada (str)'nin tanımlandığını varsayıyoruz deploymentName . Bu, Foundry Projenizdeki bir yapay zeka modelinin dağıtım adıdır. "Modeller + uç noktalar" sekmesinde, "Ad" sütununun altında gösterildiği gibi.

Değeri, api_versionbu tablodaki "Veri düzlemi - çıkarım" satırında bulunan bir değerle güncelleştirin.

Ayrıca, yöntemin çıkarım uç noktasını ve kimlik doğrulama kimlik bilgilerini almak için kullanacağı inference.azureOpenAI AI Foundry Projenizde Azure OpenAI bağlantı adını açıkça belirtme seçeneğiniz de vardır (gösterilmez). Aksi takdirde, varsayılan Azure OpenAI bağlantısı kullanılır.

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));

Ek örnekler için paket örneklerindeki "çıkarım" klasörüne bakın.

Dağıtım işlemleri

Aşağıdaki kod, AI Foundry Projelerinize dağıtılan AI modellerini numaralandırmanıza olanak tanıyan bazı Dağıtımlar işlemlerini gösterir. Bu modeller, AI Foundry Projenizdeki "Modeller + uç noktalar" sekmesinde görülebilir. Tam örnekler, paket örneklerindeki "dağıtım" klasörü altında bulunabilir.

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)}`);
}

Bağlantı işlemleri

Aşağıdaki kod, AI Foundry Projelerinize bağlı Azure Kaynaklarını listelemenize olanak tanıyan bazı Bağlantı işlemlerini gösterir. Bu bağlantılar, AI Foundry Projenizdeki "Bağlı kaynaklar" sekmesindeki "Yönetim Merkezi"nde görülebilir. Tam örnekler, paket örneklerinin "bağlantılar" klasöründe bulunabilir.

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)}`);

Veri kümesi işlemleri

Aşağıdaki kodda bazı Veri Kümesi işlemleri gösterilmektedir. Tam örnekler, paket örneklerindeki "veri setleri" klasörü altında bulunabilir.

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

Dizin işlemleri

Aşağıdaki kod bazı Dizin işlemlerini gösterir. Tam örnekler, paket örneklerindeki "indexes" klasörü altında bulunabilir.

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);

Sorun giderme

Özel durumlar

Hizmet çağrıları oluşturan istemci yöntemleri, hizmetten başarılı olmayan bir HTTP durum kodu yanıtı için RestError oluşturur. Özel durumun code HTTP yanıt durum kodunu barındıracaktır. Özel durumun error.message, sorunun tanılanmasında yardımcı olabilecek ayrıntılı bir ileti içerir:

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);
  }
}

Örneğin, yanlış kimlik bilgileri sağladığınızda:

Status code: 401 (Unauthorized)
Operation returned an invalid status 'Unauthorized'

Raporlama sorunları

İstemci kitaplığıyla ilgili sorunları bildirmek veya ek özellikler istemek için lütfen burada bir GitHub sorunu açın

Sonraki Adımlar

Tam olarak çalıştırılabilir kod içeren paket örnekleri klasörüne göz atın.

Katkıda Bulunmak

Bu proje katkıları ve önerileri memnuniyetle karşılar. Çoğu katkı, Katkıda Bulunan Lisans Sözleşmesi'ni (CLA) kabul ederek bize katkınızı kullanma hakları verme hakkına sahip olduğunuzu bildirmenizi gerektirir. Ayrıntılar için https://cla.microsoft.comadresini ziyaret edin.

Çekme isteği gönderdiğinizde, CLA botu otomatik olarak CLA sağlamanız gerekip gerekmediğini belirler ve çekme isteğini uygun şekilde süsler (örneğin, etiket, açıklama). Bot tarafından sağlanan yönergeleri izlemeniz yeterlidir. Cla'mızı kullanarak bunu tüm depolarda yalnızca bir kez yapmanız gerekir.

Bu projede Microsoft Açık Kaynak Kullanım Şartları kabul edilmiştir. Daha fazla bilgi için Kullanım Kuralları SSS bölümüne bakın veya ek sorularınız veya yorumlarınızla opencode@microsoft.com iletişime geçin.