Freigeben über


Azure AI Agents-Clientbibliothek für JavaScript – Version 1.1.0

Verwenden Sie die AI Agents-Clientbibliothek für folgende Zwecke:

  • Entwickeln von Agents mit dem Azure AI Agent Service, wobei ein umfangreiches Ökosystem von Modellen, Tools und Funktionen von OpenAI, Microsoft und anderen LLM-Anbietern genutzt wird. Der Azure AI-Agent-Dienst ermöglicht das Erstellen von Agents für eine breite Palette von generativen KI-Anwendungsfällen.
  • Anmerkung: Obwohl dieses Paket unabhängig verwendet werden kann, wird empfohlen, die Azure AI Projects-Clientbibliothek zu verwenden, um eine verbesserte Benutzererfahrung zu erzielen. Die Projektbibliothek bietet einen vereinfachten Zugriff auf erweiterte Funktionen, z. B. das Erstellen und Verwalten von Agents, das Auflisten von KI-Modellen, das Arbeiten mit Datasets und das Verwalten von Suchindizes, das Auswerten der generativen KI-Leistung und das Aktivieren der OpenTelemetry-Ablaufverfolgung.

Produktdokumentation | Proben | Paket (npm) | API-Referenzdokumentation

Inhaltsverzeichnis

Erste Schritte

Voraussetzung

Autorisierung

  • Die Entra ID wird benötigt, um den Client zu authentifizieren. Ihre Anwendung benötigt ein Objekt, das die TokenCredential Schnittstelle implementiert. Codebeispiele verwenden hier DefaultAzureCredential. Um dies zu erreichen, benötigen Sie Folgendes:
    • Die rolle Contributor. Die zugewiesene Rolle kann über die Registerkarte "Access Control (IAM)" Ihrer Azure AI-Projektressource im Azure-Portal erfolgen. Weitere Informationen zu Rollenzuweisungen finden Sie hier.
    • Azure CLI installiert.
    • Sie sind bei Ihrem Azure-Konto angemeldet, indem Sie az loginausführen.
    • Beachten Sie, dass das Abonnement, das Ihre Azure AI Project-Ressource enthält, Ihr Standardabonnement sein muss, wenn Sie über mehrere Azure-Abonnements verfügen. Führen Sie az account list --output table aus, um ihr gesamtes Abonnement auflisten und zu sehen, welche Standardeinstellung ist. Führen Sie az account set --subscription "Your Subscription ID or Name" aus, um Ihr Standardabonnement zu ändern.

Installiere das Paket

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

Wichtige Begriffe

Erstellen und Authentifizieren des Clients

Der AgentsClient wird verwendet, um den Client zu erstellen. Derzeit wird empfohlen, den AgentsClient über die Azure AI Projects-Clientbibliothek mit client.agentszu verwenden.

Um Ihren Projektendpunkt zu erhalten, können Sie in der Dokumentation nachschlagen. Im Folgenden gehen wir davon aus, dass die Umgebungsvariable PROJECT_ENDPOINT diesen Wert enthält.

import { AgentsClient } from "@azure/ai-agents";
import { DefaultAzureCredential } from "@azure/identity";

const projectEndpoint = process.env["PROJECT_ENDPOINT"] || "<project endpoint>";
const modelDeploymentName = process.env["MODEL_DEPLOYMENT_NAME"] || "gpt-4o";
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());

Beispiele

Agenten

Agents in der Azure AI Projects-Clientbibliothek wurden entwickelt, um verschiedene Interaktionen und Vorgänge in Ihren KI-Projekten zu erleichtern. Sie dienen als die Kernkomponenten, die Aufgaben verwalten und ausführen, und nutzen verschiedene Tools und Ressourcen, um bestimmte Ziele zu erreichen. In den folgenden Schritten wird die typische Sequenz für die Interaktion mit Agents beschrieben. Weitere Agentenbeispiele finden Sie in den Paketbeispielen .

Agent erstellen

Hier ist ein Beispiel für das Erstellen eines Agents:

const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful assistant",
});

Damit Agents auf Ihre Ressourcen oder benutzerdefinierten Funktionen zugreifen können, benötigen Sie Tools. Sie können Tools an createAgent über die Argumente tools und toolResources übergeben.

Dazu können Sie ToolSet verwenden:

import { ToolSet } from "@azure/ai-agents";

// Upload file for code interpreter tool
const filePath1 = "./data/syntheticCompanyQuarterlyResults.csv";
const fileStream1 = fs.createReadStream(filePath1);
const codeInterpreterFile = await client.files.upload(fileStream1, "assistants", {
  fileName: "myLocalFile",
});
console.log(`Uploaded local file, file ID : ${codeInterpreterFile.id}`);
// Upload file for file search tool
const filePath2 = "./data/sampleFileForUpload.txt";
const fileStream2 = fs.createReadStream(filePath2);
const fileSearchFile = await client.files.upload(fileStream2, "assistants", {
  fileName: "sampleFileForUpload.txt",
});
console.log(`Uploaded file, file ID: ${fileSearchFile.id}`);
// Create vector store for file search tool
const vectorStore = await client.vectorStores
  .createAndPoll({
    fileIds: [fileSearchFile.id],
  })
  .pollUntilDone();
// Create tool set
const toolSet = new ToolSet();
toolSet.addFileSearchTool([vectorStore.id]);
toolSet.addCodeInterpreterTool([codeInterpreterFile.id]);

// Create agent with tool set
const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful agent",
  tools: toolSet.toolDefinitions,
  toolResources: toolSet.toolResources,
});
console.log(`Created agent, agent ID: ${agent.id}`);

Mehrere Agenten

Sie können mehrere Agenten mit unterschiedlichen Tools erstellen und diese dann miteinander verbinden.

import { ToolUtility } from "@azure/ai-agents";

const connectedAgentName = "stock_price_bot";
const modelDeploymentName = process.env["MODEL_DEPLOYMENT_NAME"] || "gpt-4o";
const stockAgent = await client.createAgent(modelDeploymentName, {
  name: "stock-price-agent",
  instructions:
    "Your job is to get the stock price of a company. If you don't know the realtime stock price, return the last known stock price.",
});
// Initialize Connected Agent tool with the agent id, name, and description
const connectedAgentTool = ToolUtility.createConnectedAgentTool(
  stockAgent.id,
  connectedAgentName,
  "Gets the stock price of a company",
);
// Create agent with the Connected Agent tool and process assistant run
const agent = await client.createAgent(modelDeploymentName, {
  name: "my-agent",
  instructions: "You are a helpful assistant, and use the connected agent to get stock prices.",
  tools: [connectedAgentTool.definition],
});
console.log(`Created agent, agent ID: ${agent.id}`);

Zum Ausführen der Dateisuche durch einen Agent müssen wir zuerst eine Datei hochladen, einen Vektorspeicher erstellen und die Datei dem Vektorspeicher zuordnen. Hier ist ein Beispiel:

import { ToolUtility } from "@azure/ai-agents";

const filePath = "./data/sampleFileForUpload.txt";
const localFileStream = fs.createReadStream(filePath);
const file = await client.files.upload(localFileStream, "assistants", {
  fileName: "sampleFileForUpload.txt",
});
console.log(`Uploaded file, file ID: ${file.id}`);

const vectorStore = await client.vectorStores.create({
  fileIds: [file.id],
  name: "myVectorStore",
});
console.log(`Created vector store, vector store ID: ${vectorStore.id}`);

const fileSearchTool = ToolUtility.createFileSearchTool([vectorStore.id]);

const agent = await client.createAgent("gpt-4o", {
  name: "File Search Agent",
  instructions: "You are helpful agent that can help fetch data from files you know about.",
  tools: [fileSearchTool.definition],
  toolResources: fileSearchTool.resources,
});
console.log(`Created agent, agent ID : ${agent.id}`);

Agent mit Codedolmetscher erstellen

Nachfolgend sehen Sie ein Beispiel zum Hochladen einer Datei und verwenden sie für Codedolmetscher von einem Agent:

import { ToolUtility } from "@azure/ai-agents";

const filePath = "./data/syntheticCompanyQuarterlyResults.csv";
const localFileStream = fs.createReadStream(filePath);
const localFile = await client.files.upload(localFileStream, "assistants", {
  fileName: "localFile",
});

console.log(`Uploaded local file, file ID : ${localFile.id}`);

const codeInterpreterTool = ToolUtility.createCodeInterpreterTool([localFile.id]);

// Notice that CodeInterpreter must be enabled in the agent creation, otherwise the agent will not be able to see the file attachment
const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful agent",
  tools: [codeInterpreterTool.definition],
  toolResources: codeInterpreterTool.resources,
});
console.log(`Created agent, agent ID: ${agent.id}`);

Agent mit Bing Grounding erstellen

Damit Ihr Agent die Suche über die Bing-Such-API durchführen kann, verwenden Sie ToolUtility.createBingGroundingTool() zusammen mit einer Verbindung. Weitere Informationen zur Erdung mit der Bing-Suche finden Sie hier .

Hier ist ein Beispiel:

import { ToolUtility } from "@azure/ai-agents";

const connectionId = process.env["AZURE_BING_CONNECTION_ID"] || "<connection-name>";

// Initialize agent bing tool with the connection id
const bingTool = ToolUtility.createBingGroundingTool([{ connectionId: connectionId }]);

// Create agent with the bing tool and process assistant run
const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful agent",
  tools: [bingTool.definition],
});
console.log(`Created agent, agent ID : ${agent.id}`);

Azure AI Search ist ein Unternehmenssuchsystem für leistungsstarke Anwendungen. Es ist in Azure OpenAI Service und Azure Machine Learning integriert und bietet erweiterte Suchtechnologien wie Vektorsuche und Volltextsuche. Ideal für Wissensbasiseinblicke, Informationsermittlung und Automatisierung

Hier ist ein Beispiel für die Integration von Azure AI Search:

import { ToolUtility } from "@azure/ai-agents";

const connectionName = process.env["AZURE_AI_SEARCH_CONNECTION_NAME"] || "<connection-name>";

// Initialize Azure AI Search tool
const azureAISearchTool = ToolUtility.createAzureAISearchTool(connectionName, "search-index", {
  queryType: "simple",
  topK: 3,
  filter: "", // Add string here to filter results
  indexConnectionId: connectionName,
  indexName: "search-index",
});

// Create agent with the Azure AI search tool
const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful agent",
  tools: [azureAISearchTool.definition],
  toolResources: azureAISearchTool.resources,
});
console.log(`Created agent, agent ID : ${agent.id}`);

Agent mit Funktionsaufruf erstellen

Sie können Ihre Agents verbessern, indem Sie Rückruffunktionen als Funktionstools definieren. Diese können createAgent über die Kombination aus tools und toolResourcesbereitgestellt werden. Nur die Funktionsdefinitionen und Beschreibungen werden ohne die Implementierungen für createAgentbereitgestellt. Das Run oder event handler of stream löst basierend auf den Funktionsdefinitionen einen requires_action Status aus. Ihr Code muss diesen Status behandeln und die entsprechenden Funktionen aufrufen.

Hier ist ein Beispiel:

import {
  FunctionToolDefinition,
  ToolUtility,
  RequiredToolCall,
  ToolOutput,
} from "@azure/ai-agents";

class FunctionToolExecutor {
  private functionTools: {
    func: Function;
    definition: FunctionToolDefinition;
  }[];

  constructor() {
    this.functionTools = [
      {
        func: this.getUserFavoriteCity,
        ...ToolUtility.createFunctionTool({
          name: "getUserFavoriteCity",
          description: "Gets the user's favorite city.",
          parameters: {},
        }),
      },
      {
        func: this.getCityNickname,
        ...ToolUtility.createFunctionTool({
          name: "getCityNickname",
          description: "Gets the nickname of a city, e.g. 'LA' for 'Los Angeles, CA'.",
          parameters: {
            type: "object",
            properties: {
              location: { type: "string", description: "The city and state, e.g. Seattle, Wa" },
            },
          },
        }),
      },
      {
        func: this.getWeather,
        ...ToolUtility.createFunctionTool({
          name: "getWeather",
          description: "Gets the weather for a location.",
          parameters: {
            type: "object",
            properties: {
              location: { type: "string", description: "The city and state, e.g. Seattle, Wa" },
              unit: { type: "string", enum: ["c", "f"] },
            },
          },
        }),
      },
    ];
  }

  private getUserFavoriteCity(): {} {
    return { location: "Seattle, WA" };
  }

  private getCityNickname(_location: string): {} {
    return { nickname: "The Emerald City" };
  }

  private getWeather(_location: string, unit: string): {} {
    return { weather: unit === "f" ? "72f" : "22c" };
  }

  public invokeTool(toolCall: RequiredToolCall & FunctionToolDefinition): ToolOutput | undefined {
    console.log(`Function tool call - ${toolCall.function.name}`);
    const args: any[] = [];
    if (toolCall.function.parameters) {
      try {
        const params = JSON.parse(toolCall.function.parameters);
        for (const key in params) {
          if (Object.prototype.hasOwnProperty.call(params, key)) {
            args.push(params[key]);
          }
        }
      } catch (error) {
        console.error(`Failed to parse parameters: ${toolCall.function.parameters}`, error);
        return undefined;
      }
    }
    // Create a mapping of function names to their implementations
    const functionMap = new Map(
      this.functionTools.map((tool) => [tool.definition.function.name, tool.func]),
    );
    const result = functionMap.get(toolCall.function.name)?.(...args);
    return result
      ? {
          toolCallId: toolCall.id,
          output: JSON.stringify(result),
        }
      : {
          toolCallId: toolCall.id,
          output: JSON.stringify({
            error: `No matching tool found for function: ${toolCall.function.name}`,
          }),
        };
  }

  public getFunctionDefinitions(): FunctionToolDefinition[] {
    return this.functionTools.map((tool) => {
      return tool.definition;
    });
  }
}
const functionToolExecutor = new FunctionToolExecutor();
const functionTools = functionToolExecutor.getFunctionDefinitions();
const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions:
    "You are a weather bot. Use the provided functions to help answer questions. Customize your responses to the user's preferences as much as possible and use friendly nicknames for cities whenever possible.",
  tools: functionTools,
});
console.log(`Created agent, agent ID: ${agent.id}`);

Agent mit OpenAPI erstellen

OpenAPI-Spezifikationen beschreiben REST-Vorgänge für einen bestimmten Endpunkt. Agents SDK kann eine OpenAPI-Spezifikation lesen, eine Funktion daraus erstellen und diese Funktion ohne zusätzliche clientseitige Ausführung für den REST-Endpunkt aufrufen. Nachfolgend sehen Sie ein Beispiel zum Erstellen eines OpenAPI-Tools (mit anonymer Authentifizierung):

import { ToolUtility } from "@azure/ai-agents";

// Read in OpenApi spec
const filePath = "./data/weatherOpenApi.json";
const openApiSpec = JSON.parse(fs.readFileSync(filePath, "utf-8"));

// Define OpenApi function
const openApiFunction = {
  name: "getWeather",
  spec: openApiSpec,
  description: "Retrieve weather information for a location",
  auth: {
    type: "anonymous",
  },
  default_params: ["format"], // optional
};

// Create OpenApi tool
const openApiTool = ToolUtility.createOpenApiTool(openApiFunction);

// Create agent with OpenApi tool
const agent = await client.createAgent("gpt-4o", {
  name: "myAgent",
  instructions: "You are a helpful agent",
  tools: [openApiTool.definition],
});
console.log(`Created agent, agent ID: ${agent.id}`);

Thread erstellen

Für jede Sitzung oder Unterhaltung ist ein Thread erforderlich. Hier ist ein Beispiel:

const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);

Thread mit Toolressource erstellen

In einigen Szenarien müssen Sie möglicherweise einzelnen Threads bestimmte Ressourcen zuweisen. Um dies zu erreichen, stellen Sie das toolResources Argument für threads.createbereit. Im folgenden Beispiel erstellen Sie einen Vektorspeicher und laden eine Datei hoch, aktivieren einen Agent für die Dateisuche mithilfe des arguments tools, und ordnen Sie die Datei dann dem Thread mithilfe des Arguments toolResources zu.

import { ToolUtility } from "@azure/ai-agents";

const filePath = "./data/syntheticCompanyQuarterlyResults.csv";
const localFileStream = fs.createReadStream(filePath);
const file = await client.files.upload(localFileStream, "assistants", {
  fileName: "sample_file_for_upload.csv",
});
console.log(`Uploaded file, ID: ${file.id}`);

const vectorStore = await client.agents.vectorStores.create()({
  fileIds: [file.id],
});
console.log(`Created vector store, ID: ${vectorStore.id}`);

const fileSearchTool = ToolUtility.createFileSearchTool([vectorStore.id]);

const agent = await client.agents.createAgent("gpt-4o", {
  name: "myAgent",
  instructions: "You are helpful agent that can help fetch data from files you know about.",
  tools: [fileSearchTool.definition],
});
console.log(`Created agent, agent ID : ${agent.id}`);

// Create thread with file resources.
// If the agent has multiple threads, only this thread can search this file.
const thread = await client.threads.create({ toolResources: fileSearchTool.resources });

Threads auflisten

Um alle Threads aufzulisten, die an einen bestimmten Agent angefügt sind, verwenden Sie threads.list:

const threads = client.threads.list();
console.log(`Threads for agent ${agent.id}:`);
for await (const t of threads) {
  console.log(`Thread ID: ${t.id}`);
  console.log(`Created at: ${t.createdAt}`);
  console.log(`Metadata: ${t.metadata}`);
  console.log(`---- `);
}

Nachricht erstellen

Um eine Nachricht zu erstellen, die der Assistent verarbeiten soll, übergeben Sie user als role und eine Frage als content:

const message = await client.messages.create(thread.id, "user", "hello, world!");
console.log(`Created message, message ID: ${message.id}`);

Nachricht mit Dateisuchanlage erstellen

Wenn Sie eine Datei an eine Nachricht für die Inhaltssuche anfügen möchten, verwenden Sie ToolUtility.createFileSearchTool() und das argument attachments:

import { ToolUtility } from "@azure/ai-agents";

const fileSearchTool = ToolUtility.createFileSearchTool();
const message = await client.messages.create(
  thread.id,
  "user",
  "What feature does Smart Eyewear offer?",
  {
    attachments: [
      {
        fileId: file.id,
        tools: [fileSearchTool.definition],
      },
    ],
  },
);

Nachricht mit Codedolmetscheranlage erstellen

Wenn Sie eine Datei an eine Nachricht für die Datenanalyse anfügen möchten, verwenden Sie ToolUtility.createCodeInterpreterTool() und das argument attachment.

Hier ist ein Beispiel:

import { ToolUtility } from "@azure/ai-agents";

// notice that CodeInterpreter must be enabled in the agent creation,
// otherwise the agent will not be able to see the file attachment for code interpretation
const codeInterpreterTool = ToolUtility.createCodeInterpreterTool();
const agent = await client.agents.createAgent("gpt-4o", {
  name: "my-assistant",
  instructions: "You are helpful assistant",
  tools: [codeInterpreterTool.definition],
});
console.log(`Created agent, agent ID: ${agent.id}`);

const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);

const message = await client.messages.create(
  thread.id,
  "user",
  "Could you please create a bar chart in the TRANSPORTATION sector for the operating profit from the uploaded CSV file and provide the file to me?",
  {
    attachments: [
      {
        fileId: file.id,
        tools: [codeInterpreterTool.definition],
      },
    ],
  },
);
console.log(`Created message, message ID: ${message.id}`);

Nachricht mit Bildeingaben erstellen

Sie können Nachrichten auf folgende Weise an Azure-Agents mit Bildeingaben senden:

  • Verwenden eines Bilds, das als hochgeladene Datei gespeichert ist
  • Verwenden eines öffentlichen Bilds, auf das über die URL zugegriffen werden kann
  • Verwenden einer base64-codierten Bildzeichenfolge

Das folgende Beispiel veranschaulicht die base64-Methode:

Erstellen einer Nachricht mit base64-codierter Bildeingabe
function imageToBase64DataUrl(imagePath: string, mimeType: string): string {
  try {
    // Read the image file as binary
    const imageBuffer = fs.readFileSync(imagePath);
    // Convert to base64
    const base64Data = imageBuffer.toString("base64");
    // Format as a data URL
    return `data:${mimeType};base64,${base64Data}`;
  } catch (error) {
    console.error(`Error reading image file at ${imagePath}:`, error);
    throw error;
  }
}

// Convert your image file to base64 format
const filePath = "./data/image_file.png";
const imageDataUrl = imageToBase64DataUrl(filePath, "image/png");

// Create a message with both text and image content
console.log("Creating message with image content...");
const inputMessage = "Hello, what is in the image?";
const content = [
  {
    type: "text",
    text: inputMessage,
  },
  {
    type: "image_url",
    imageUrl: {
      url: imageDataUrl,
      detail: "high",
    },
  },
];

const message = await client.messages.create(thread.id, "user", content);
console.log(`Created message, message ID: ${message.id}`);

Erstellen von "Ausführen", "Run_and_Process" oder "Stream"

Nachfolgend sehen Sie ein Beispiel für runs.create und Abfragen, bis die Ausführung abgeschlossen ist:

// Create and poll a run
console.log("Creating run...");
const run = await client.runs.createAndPoll(thread.id, agent.id, {
  pollingOptions: {
    intervalInMs: 2000,
  },
  onResponse: (response): void => {
    console.log(`Received response with status: ${response.parsedBody.status}`);
  },
});
console.log(`Run finished with status: ${run.status}`);

Verwenden Sie die createThreadAndRun-Methode, um die SDK-Umfrage in Ihrem Auftrag zu erhalten.

Hier ist ein Beispiel:

const run = await client.runs.createThreadAndRun(agent.id, {
  thread: {
    messages: [
      {
        role: "user",
        content: "hello, world!",
      },
    ],
  },
});

Bei Streaming müssen Umfragen auch nicht berücksichtigt werden.

Hier ist ein Beispiel:

const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();

Die Ereignisbehandlung kann wie folgt erfolgen:

import { RunStreamEvent, MessageStreamEvent, ErrorEvent, DoneEvent } from "@azure/ai-agents";

const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();

for await (const eventMessage of streamEventMessages) {
  switch (eventMessage.event) {
    case RunStreamEvent.ThreadRunCreated:
      console.log(`ThreadRun status: ${eventMessage.data.status}`);
      break;
    case MessageStreamEvent.ThreadMessageDelta:
      {
        const messageDelta = eventMessage.data;
        messageDelta.delta.content.forEach((contentPart) => {
          if (contentPart.type === "text") {
            const textContent = contentPart;
            const textValue = textContent.text?.value || "No text";
            console.log(`Text delta received:: ${textValue}`);
          }
        });
      }
      break;
    case RunStreamEvent.ThreadRunCompleted:
      console.log("Thread Run Completed");
      break;
    case ErrorEvent.Error:
      console.log(`An error occurred. Data ${eventMessage.data}`);
      break;
    case DoneEvent.Done:
      console.log("Stream completed.");
      break;
  }
}

Nachricht abrufen

Verwenden Sie das folgende Beispiel, um Nachrichten von Agents abzurufen:

const messagesIterator = client.messages.list(thread.id);
const allMessages = [];
for await (const m of messagesIterator) {
  allMessages.push(m);
}
console.log("Messages:", allMessages);

// The messages are following in the reverse order,
// we will iterate them and output only text contents.
const messages = await client.messages.list(thread.id, {
  order: "asc",
});

for await (const dataPoint of messages) {
  const textContent = dataPoint.content.find((item) => item.type === "text");
  if (textContent && "text" in textContent) {
    console.log(`${dataPoint.role}: ${textContent.text.value}`);
  }
}

Datei abrufen

Von Agents hochgeladene Dateien können nicht zurückgefragt werden. Wenn Ihr Anwendungsfall auf den von den Agents hochgeladenen Dateiinhalt zugreifen muss, wird empfohlen, eine zusätzliche Kopie von Ihrer Anwendung zugänglich zu halten. Von Agents generierte Dateien können jedoch von files.getContentabgerufen werden.

Hier ist ein Beispiel zum Abrufen von Datei-IDs aus Nachrichten:

import { isOutputOfType, MessageTextContent, MessageImageFileContent } from "@azure/ai-agents";

const messagesIterator = client.messages.list(thread.id);
const allMessages = [];
for await (const m of messagesIterator) {
  allMessages.push(m);
}
console.log("Messages:", allMessages);

// Get most recent message from the assistant
const assistantMessage = allMessages.find((msg) => msg.role === "assistant");
if (assistantMessage) {
  const textContent = assistantMessage.content.find((content) =>
    isOutputOfType<MessageTextContent>(content, "text"),
  ) as MessageTextContent;
  if (textContent) {
    console.log(`Last message: ${textContent.text.value}`);
  }
}

const imageFile = (allMessages[0].content[0] as MessageImageFileContent).imageFile;
const imageFileName = (await client.agents.files.get(imageFile.fileId)).filename;

const fileContent = await (await client.files.getContent(imageFile.fileId).asNodeStream()).body;
if (fileContent) {
  const chunks: Buffer[] = [];
  for await (const chunk of fileContent) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  const buffer = Buffer.concat(chunks);
  fs.writeFileSync(imageFileName, buffer);
} else {
  console.error("Failed to retrieve file content: fileContent is undefined");
}
console.log(`Saved image file to: ${imageFileName}`);

Teardown

Verwenden Sie die folgenden Funktionen, um Ressourcen nach Abschluss von Vorgängen zu entfernen:

await client.vectorStores.delete(vectorStore.id);
console.log(`Deleted vector store, vector store ID: ${vectorStore.id}`);

await client.files.delete(file.id);
console.log(`Deleted file, file ID : ${file.id}`);

await client.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);

Problembehandlung

Ausnahmen

Clientmethoden, die Dienstaufrufe ausführen, lösen eine RestError- für eine nicht erfolgreiche HTTP-Statuscodeantwort des Diensts aus. Die code der Ausnahme enthält den HTTP-Antwortstatuscode. Die error.message der Ausnahme enthält eine detaillierte Meldung, die bei der Diagnose des Problems hilfreich sein kann:

import { RestError } from "@azure/core-rest-pipeline";

try {
  const thread = await client.threads.create();
} catch (e) {
  if (e instanceof RestError) {
    console.log(`Status code: ${e.code}`);
    console.log(e.message);
  } else {
    console.error(e);
  }
}

Wenn Sie beispielsweise falsche Anmeldeinformationen angeben:

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

Melden von Problemen

Um Probleme mit der Clientbibliothek zu melden oder zusätzliche Features anzufordern, öffnen Sie bitte ein GitHub-Problem hier

Nächste Schritte

Sehen Sie sich die Paketbeispiele Ordners an, die vollständig ausgeführten Code enthalten.

Mitarbeit

Dieses Projekt begrüßt Beiträge und Vorschläge. Die meisten Beiträge erfordern, dass Sie einem Mitwirkenden-Lizenzvertrag (CLA) zustimmen, der erklärt, dass Sie das Recht haben, uns tatsächlich die Rechte zur Nutzung Ihres Beitrags zu gewähren. Weitere Informationen finden Sie unter https://cla.microsoft.com.

Wenn Sie eine Pullanfrage einreichen, bestimmt ein CLA-Bot automatisch, ob Sie eine CLA bereitstellen und die PR entsprechend dekorieren müssen (z. B. Bezeichnung, Kommentar). Folgen Sie einfach den Anweisungen des Bots. Sie müssen dies nur einmal über alle Reposs hinweg tun, indem Sie unsereN CLA verwenden.

Dieses Projekt hat den Microsoft Open Source Code of Conductübernommen. Weitere Informationen finden Sie im Code of Conduct FAQ oder wenden Sie sich an opencode@microsoft.com mit weiteren Fragen oder Kommentaren.