Condividi tramite


Azure AI Projects client library per JavaScript - versione 2.0.1

La libreria client AI Projects (in anteprima) fa parte dell'SDK Microsoft Foundry e offre un facile accesso alle risorse del tuo Microsoft Foundry Project. Usarlo per:

  • Creare ed eseguire agenti utilizzando la .agents proprietà nel client.
  • Migliora gli agenti con strumenti specializzati:
    • Ricerca di memoria dell'agente (Anteprima)
    • Agente-ad-Agente (A2A) (Anteprima)
    • Azure AI Search
    • Ricerca personalizzata Bing (Anteprima)
    • Bing Fondamento
    • Automazione del browser (anteprima)
    • Interprete di codice
    • Uso del computer (anteprima)
    • Ricerca file
    • Strumento funzionale
    • Generazione di immagini
    • Microsoft Fabric (Anteprima)
    • Protocollo di Contesto Modello (MCP)
    • OpenAPI
    • Microsoft SharePoint (Anteprima)
    • Ricerca Web (Anteprima)
  • Crea un client OpenAI che utilizzi il .getOpenAIClient. metodo per eseguire operazioni di Risposte, Conversazioni, Valutazioni e FineTuning con il tuo Agente.
  • Gestire memoria (anteprima) per le conversazioni Agent, utilizzando le .beta.memoryStores operazioni.
  • Esplora ulteriori strumenti di valutazione (alcuni in anteprima) per valorizzare le prestazioni della tua applicazione di IA generativa, utilizzando , .evaluationRules.beta.evaluationTaxonomies, .beta.evaluators, .beta.insights, e .beta.schedules operazioni.
  • Esegui scansioni del Red Team (anteprima) per identificare i rischi associati alla tua applicazione di IA generativa, utilizzando le .beta.redTeams operazioni.
  • Ottimizzare Modelli di IA sui tuoi dati.
  • Enumera i modelli di intelligenza artificiale distribuiti nel tuo progetto di fonderia utilizzando le .deployments operazioni.
  • Enumera risorse Azure connesse nel tuo progetto Foundry usando le operazioni .connections.
  • Carica documenti e crea set di dati per farvi riferimento utilizzando le .datasets operazioni.
  • Creare ed enumerare gli indici di ricerca utilizzando le .indexes operazioni.

La libreria client usa la versione v1 delle API REST del piano dati di Microsoft Foundry.

Documentazione prodotto | Samples | Package (npm) | API reference documentation | SDK

Sommario

Introduzione

Prerequisito

  • Versioni LTS di Node.js
  • Un abbonamento Azure.
  • Un progetto in Microsoft Foundry.
  • L'URL dell'endpoint del progetto del modulo https://your-ai-services-account-name.services.ai.azure.com/api/projects/your-project-name. Lo puoi trovare nella tua pagina panoramica del progetto Microsoft Foundry. Di seguito assumeremo che la variabile AZURE_AI_PROJECT_ENDPOINT ambiente sia stata definita per mantenere questo valore.

Autorizzazione

  • È necessario un ID Entra per autenticare il client. L'applicazione necessita di un oggetto che implementa l'interfaccia token . Qui esempi di codice usa DefaultAzureCredential. Per ottenere questo lavoro, è necessario:
    • Un ruolo appropriato. vedi Controllo degli accessi basato sui ruoli nel portale Microsoft Foundry. Il ruolo assegnato può essere effettuato tramite la scheda "Access Control (IAM)" della risorsa Azure AI Project nel portale Azure.
    • Azure CLI installato.
    • Sei connesso al tuo account Azure eseguendo az login.
    • Nota che se hai più abbonamenti Azure, l'abbonamento che contiene la tua risorsa Azure AI Project deve essere il tuo abbonamento predefinito. Eseguire az account list --output table per elencare tutte le sottoscrizioni e vedere quale è l'impostazione predefinita. Eseguire az account set --subscription "Your Subscription ID or Name" per modificare la sottoscrizione predefinita.

Installare il pacchetto

npm install @azure/ai-projects dotenv

Concetti principali

Crea e autentica il client con Entra ID

Entra ID è l'unico metodo di autenticazione supportato al momento dal client.

Per costruire un AIProjectsClient, può projectEndpoint essere recuperato da projectEndpoint. Di seguito assumeremo che la variabile AZURE_AI_PROJECT_ENDPOINT d'ambiente sia stata definita per mantenere questo valore:

import { AIProjectClient } from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";

const projectEndpoint = process.env["AZURE_AI_PROJECT_ENDPOINT"] || "<project endpoint string>";
project = new AIProjectClient(projectEndpoint, new DefaultAzureCredential());

Gruppi operativi di anteprima e flag di funzionalità opt-in

Alcune operazioni di anteprima richiedono un flag esplicito foundryFeatures di partecipazione automatica. Per esempio:

await project.agents.createVersion(
  "preview-agent",
  {
    kind: "workflow",
  },
  { foundryFeatures: "WorkflowAgents=V1Preview" },
);
for await (const rule of project.evaluationRules.list()) {
  console.log(rule.id);
}

I gruppi di operazioni di anteprima includono .beta.memoryStores, .beta.evaluationTaxonomies, .beta.evaluators, .beta.insights, .beta.schedules, e .beta.redTeams.

Examples

Esecuzione di operazioni di risposte utilizzando il client OpenAI

Il tuo progetto Microsoft Foundry potrebbe avere uno o più modelli di IA distribuiti. Questi possono essere modelli OpenAI, modelli Microsoft o modelli di altri fornitori. Usa il codice qui sotto per ottenere un OpenAI autenticato dal pacchetto openai ed eseguire una chiamata di completamento della chat.

Esegui il codice seguente. Qui assumiamo che deploymentName (str) sia definito. È il nome di distribuzione di un modello di intelligenza artificiale nel progetto di fonderia. Come mostrato nella scheda "Modelli + endpoint", nella colonna "Nome".

Consulta la cartella "responses" nel package samples per ulteriori campioni, inclusi i streaming response.

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

Esecuzione di operazioni dell'agente

La .agents proprietà consente di accedere a tutte le operazioni dell'agente AIProjectsClient . Gli agenti utilizzano un'estensione del protocollo OpenAI Responses, quindi è probabile che sia necessario chiedere a un OpenAI client di eseguire le operazioni dell'agente, come mostrato nell'esempio seguente.

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

Utilizzo degli strumenti Agent

Gli agenti possono essere potenziati con strumenti specializzati per varie capacità. Gli strumenti sono organizzati in base ai requisiti di connessione:

Strumenti integrati

Questi strumenti funzionano immediatamente senza necessità di connessioni esterne.

Interprete di codice

Scrivi ed esegui codice Javascript in un ambiente sandbox, elabora file e lavora con diversi formati dati. Documentazione su 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}`);

Vedi il codice campione completo in agentCodeInterpreter.ts.

Ricerca file

Strumento RAG integrato (Retrieval-Augmented Generation) per elaborare e cercare documenti utilizzando vettoriali store per il recupero della conoscenza. Documentazione su 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})`);

Vedi il codice campione completo in agentFileSearchStream.ts.

Generazione di immagini

Genera immagini basate su prompt di testo con impostazioni personalizzabili di risoluzione, qualità e stile:

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

Dopo aver chiamato responses.create(), puoi scaricare il file usando la risposta restituita:

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

Ricerca Web (Anteprima)

Effettua ricerche generali sul web per recuperare informazioni aggiornate da internet. Documentazione su 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}`);

Vedi il codice campione completo in agentWebSearch.ts.

Uso del computer (anteprima)

Consentire agli agenti di interagire direttamente con i sistemi informatici per l'automazione delle attività e le operazioni di sistema:

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_use_preview",
      display_width: 1026,
      display_height: 769,
      environment: "windows" as const,
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

Dopo aver chiamato responses.create(), elabora la risposta in un ciclo di interazione. Gestisci computer_call gli elementi in uscita e fornisci screenshot come computer_call_output il computer_screenshot tipo per continuare l'interazione.

Vedi il codice campione completo in agentComputerUse.ts.

Protocollo di Contesto Modello (MCP)

Integrare i server MCP per estendere le capacità degli agenti con strumenti e risorse standardizzate. Documentazione su 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" } },
  },
);

Dopo aver chiamato responses.create(), controlla gli mcp_approval_request elementi nell'output della risposta. Invia McpApprovalResponse indietro con la tua approvazione la decisione per permettere all'agente di continuare a lavorare.

Vedi il codice campione completo in agentMcp.ts.

OpenAPI

Chiama API esterne definite dalle specifiche OpenAPI senza codice lato client aggiuntivo. Documentazione su 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})`);

Vedi il codice campione completo in agentOpenApi.ts.

Strumento funzionale

Definire funzioni personalizzate che permettano agli agenti di interagire con API esterne, database o logica applicativa. Documentazione su 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})`);

Dopo aver chiamato responses.create(), processa function_call gli elementi dall'output della risposta, esegui la logica della funzione con gli argomenti forniti e invia indietro FunctionCallOutput con i risultati.

Consulta il codice campione completo in agentFunctionTool.ts.

  • Strumento di ricerca di memoria (Anteprima)

Lo strumento di memorizzazione aggiunge memoria a un Agente, permettendo al modello AI dell'Agente di cercare informazioni passate relative al prompt utente corrente.

Il embeddingModelDeployment è il nome del modello utilizzato per creare embedding vettoriali per memorizzare e cercare memorie.

const memoryStoreName = "AgentMemoryStore";
const embeddingModelDeployment =
  process.env["AZURE_AI_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
    },
  ],
});

Vedi il codice campione completo in agentMemorySearch.ts.

Connection-Based Strumenti

Questi strumenti richiedono di configurare le connessioni nel tuo progetto AI Foundry e di utilizzare projectConnectionId.

Ricerca di intelligenza artificiale di Azure

Integra con gli indici di Azure AI Search per potenti capacità di recupero della conoscenza e ricerca semantica:

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

Vedi il codice campione completo in agentAiSearch.ts.

Fondamenti di Bing

Risposte degli agenti di terra con risultati di ricerca web in tempo reale da Bing per fornire informazioni up-todata:

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

Vedi il codice campione completo in agentBingGrounding.ts.

Ricerca personalizzata Bing (Anteprima)

Usa istanze di ricerca Bing configurate su misura per risultati di ricerca web specifici per dominio o filtrati:

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

Consulta il codice campione completo in agentBingCustomSearch.ts.

Microsoft Fabric (Anteprima)

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

Vedi il codice campione completo in agentFabric.ts.

Microsoft SharePoint (Anteprima)

Accedi e cerca documenti, liste e siti SharePoint per l'integrazione della conoscenza aziendale:

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

Vedi il codice campione completo in agentSharepoint.ts.

Automazione del browser (anteprima)

Automatizza le interazioni con i browser per web scraping, test e interazione con applicazioni web:

const browserAutomationProjectConnectionId = process.env["BROWSER_AUTOMATION_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_preview",
      browser_automation_preview: {
        connection: {
          project_connection_id: browserAutomationProjectConnectionId,
        },
      },
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

Vedi il codice campione completo in agentBrowserAutomation.ts.

MCP con Project Connection

Integrazione MCP utilizzando connessioni specifiche per progetto per accedere ai server MCP connessi:

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

Vedi il codice campione completo in agentMcpConnectionAuth.ts.

Agente-ad-Agente (A2A) (Anteprima)

Consentire la collaborazione multi-agente in cui gli agenti possono comunicare e delegare compiti ad altri agenti specializzati:

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

Consulta il codice campione completo in agentAgentToAgent.ts.

OpenAPI con Project Connection

Chiama API esterne definite dalle specifiche OpenAPI utilizzando l'autenticazione della connessione di progetto:

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

Vedi il codice campione completo in agentOpenApiConnectionAuth.ts.

Per esempi completi di tutti gli strumenti, consulta la directory samples-dev.

Evaluation

La valutazione nella libreria client Azure AI Project fornisce metriche quantitative di qualità e sicurezza assistite dall'IA per valutare le prestazioni e valutare modelli LLM, applicazioni GenAI e agenti. Le metriche sono definite come valutatori. Valutatori integrati o personalizzati possono fornire approfondimenti completi sulle valutazioni.

Il codice qui sotto mostra alcune operazioni di valutazione. L'elenco completo dei campioni si trova nella cartella "valutazioni" nella sezione 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})`);

Vedi il codice campione completo in agentEvaluation.ts.

Operazioni di distribuzione

Il codice seguente mostra alcune operazioni di distribuzione, che consentono di enumerare i modelli di intelligenza artificiale distribuiti nei progetti Microsoft Foundry. Questi modelli possono essere visualizzati nella scheda "Modelli + endpoint" nel progetto Microsoft Foundry. Campioni completi si trovano nella cartella "deployment" nel package samples.

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

Operazioni di connessione

Il codice qui sotto mostra alcune operazioni di Connessione, che ti permettono di enumerare le Risorse Azure collegate ai tuoi progetti Microsoft Foundry. Queste connessioni possono essere visualizzate nel "Centro di gestione", nella scheda "Risorse connesse" del progetto Microsoft Foundry. I campioni completi si trovano nella cartella "connection" nel package samples.

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

Operazioni sui set di dati

Il codice seguente mostra alcune operazioni del set di dati. I campioni completi si trovano nella cartella "datasets" nel package samples.

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

Operazioni sui file

Il codice seguente mostra alcune operazioni sui file utilizzando il client OpenAI, che consentono di caricare, recuperare, elencare ed eliminare file. Queste operazioni sono utili per l'uso di file che possono essere utilizzati per l'ottimizzazione e altre operazioni del modello di intelligenza artificiale. Campioni completi si trovano nella cartella "files" nella sezione package samples.

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

Operazioni sugli indici

Il codice seguente mostra alcune operazioni sugli indici. I campioni completi si trovano nella cartella "indexes" nella sezione package samples.

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

Operazioni di ottimizzazione

Il codice qui sotto mostra come creare lavori di fine-tuning utilizzando il client OpenAI. Queste operazioni supportano varie tecniche di fine-tuning come il Supervised Fine-Tuning (SFT), il Reinforcement Fine-Tuning (RFT) e l'Ottimizzazione Diretta delle Prestazioni (DPO). I campioni completi si trovano nella cartella "finetuning" nel package samples.

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

tracciamento

Nota: La funzionalità di analisi è in anteprima preliminare ed è soggetta a modifiche. Gli intervalli, gli attributi e gli eventi possono essere modificati nelle versioni future.

Puoi aggiungere una risorsa Azure di Application Insights al tuo progetto Microsoft Foundry. Vedere la scheda Traccia nel progetto Microsoft Foundry. Se una era abilitata, puoi ottenere la connection string Application Insights, configurare il client AI Projects e osservare l'intero percorso di esecuzione tramite Azure Monitor. In genere, potrebbe essere necessario iniziare la traccia prima di creare un client o un agente.

Installazione

npm install @azure/monitor-opentelemetry@^1.14.2 @opentelemetry/api@^1.9.0

Come abilitare il tracciamento

Ecco un esempio di codice che mostra come abilitare il tracciamento Azure Monitor:

import { AzureMonitorOpenTelemetryOptions, useAzureMonitor } from "@azure/monitor-opentelemetry";

const TELEMETRY_CONNECTION_STRING = process.env["TELEMETRY_CONNECTION_STRING"];
const options: AzureMonitorOpenTelemetryOptions = {
  azureMonitorExporterOptions: {
    connectionString: TELEMETRY_CONNECTION_STRING,
  },
};
useAzureMonitor(options);

Vedi il codice campione completo in remoteTelemetry.ts.

Risoluzione dei problemi

Eccezioni

I metodi client che effettuano chiamate al servizio generano un RestError per una risposta di codice di stato HTTP non riuscita dal servizio. Il code dell'eccezione conterrà il codice di stato della risposta HTTP. L'error.message dell'eccezione contiene un messaggio dettagliato che può essere utile per diagnosticare il problema:

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

Ad esempio, quando si specificano credenziali errate:

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

La segnalazione dei problemi

Per segnalare problemi con la libreria client o richiedere funzionalità aggiuntive, si prega di aprire un GitHub issue qui

Passaggi successivi

Dai un'occhiata alla cartella package samples, che contiene codice completamente eseguibile.

contributi

Questo progetto accoglie contributi e suggerimenti. La maggior parte dei contributi richiede l'accettazione di un Contratto di licenza collaboratore (CLA) che dichiara di avere il diritto e, in realtà, concedere a Microsoft i diritti per l'uso del contributo. Per informazioni dettagliate, visitare https://cla.microsoft.com.

Quando si invia una richiesta pull, un bot CLA determinerà automaticamente se è necessario fornire un cla e decorare la richiesta pull in modo appropriato (ad esempio, etichetta, commento). Seguire semplicemente le istruzioni fornite dal bot. Dovrai eseguire questa operazione una sola volta in tutti i repository usando la nostra cla.

Questo progetto ha adottato il codice di comportamento open source Microsoft. Per altre informazioni, vedere domande frequenti sul codice di condotta o contattare opencode@microsoft.com con eventuali domande o commenti aggiuntivi.