다음을 통해 공유


JavaScript용 Azure AI 에이전트 클라이언트 라이브러리 - 버전 1.1.0

AI Agents 클라이언트 라이브러리를 사용하여 다음을 수행할 수 있습니다.

  • Azure AI 에이전트 서비스사용하여 에이전트를 개발하여 OpenAI, Microsoft 및 기타 LLM 공급자의 광범위한 모델, 도구 및 기능 에코시스템을 활용합니다. Azure AI 에이전트 서비스를 사용하면 광범위한 생성 AI 사용 사례에 대한 에이전트를 빌드할 수 있습니다.
  • 메모: 이 패키지는 독립적으로 사용할 수 있지만 향상된 환경을 위해 Azure AI Projects 클라이언트 라이브러리를 사용하는 것이 좋습니다. 프로젝트 라이브러리는 에이전트 생성 및 관리, AI 모델 열거, 데이터 세트 작업 및 검색 인덱스 관리, 생성 AI 성능 평가, OpenTelemetry 추적 활성화와 같은 고급 기능에 대한 간소화된 액세스를 제공합니다.

제품 설명서 | 샘플 | 패키지(npm) | API 참조 설명서

목차

시작하기

전제 조건

승인

  • 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-agents @azure/identity

주요 개념

클라이언트 만들기 및 인증

AgentsClient 클라이언트를 구성하는 데 사용됩니다. 현재 를 사용하여 client.agents 통해 AgentsClient를 사용하는 것이 좋습니다.

프로젝트 엔드포인트를 가져오려면 설명서를 참조할 수 있습니다. 아래에서는 환경 변수가 PROJECT_ENDPOINT 이 값을 가지고 있다고 가정합니다.

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

예시

요원

Azure AI Projects 클라이언트 라이브러리의 에이전트는 AI 프로젝트 내에서 다양한 상호 작용 및 작업을 용이하게 하도록 설계되었습니다. 특정 목표를 달성하기 위해 다양한 도구와 리소스를 활용하여 작업을 관리하고 실행하는 핵심 구성 요소 역할을 합니다. 다음 단계에서는 에이전트와 상호 작용하기 위한 일반적인 시퀀스를 간략하게 설명합니다. 추가 에이전트 샘플은 패키지 샘플을 참조하세요.

에이전트 만들기

에이전트를 만드는 방법의 예는 다음과 같습니다.

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

에이전트가 리소스 또는 사용자 지정 함수에 액세스할 수 있도록 하려면 도구가 필요합니다. createAgenttools 인수를 통해 toolResources 도구를 전달할 수 있습니다.

ToolSet 사용하여 다음을 수행할 수 있습니다.

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

여러 에이전트

서로 다른 도구를 사용하여 여러 에이전트를 만든 다음 함께 연결할 수 있습니다.

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

에이전트에서 파일 검색을 수행하려면 먼저 파일을 업로드하고, 벡터 저장소를 만들고, 파일을 벡터 저장소에 연결해야 합니다. 예제는 다음과 같습니다.

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

코드 인터프리터를 사용하여 에이전트 만들기

다음은 파일을 업로드하고 에이전트의 코드 인터프리터에 사용하는 예제입니다.

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

Bing Grounding을 사용하여 에이전트 만들기

에이전트가 Bing Search API를 통해 검색을 수행할 수 있도록 하려면 연결과 함께 ToolUtility.createBingGroundingTool() 사용합니다. Bing Search를 사용한 접지에 대한 자세한 내용은 여기를 참조하세요.

예제는 다음과 같습니다.

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는 고성능 애플리케이션을 위한 엔터프라이즈 검색 시스템입니다. Azure OpenAI Service 및 Azure Machine Learning과 통합되어 벡터 검색 및 전체 텍스트 검색과 같은 고급 검색 기술을 제공합니다. 기술 자료 인사이트, 정보 검색 및 자동화에 적합합니다.

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

함수 호출을 사용하여 에이전트 만들기

콜백 함수를 함수 도구로 정의하여 에이전트를 향상시킬 수 있습니다. createAgenttools조합을 통해 toolResources 제공할 수 있습니다. 함수 정의 및 설명만 구현 없이 createAgent제공됩니다. Run 또는 event handler of stream 함수 정의에 따라 requires_action 상태가 발생합니다. 코드는 이 상태를 처리하고 적절한 함수를 호출해야 합니다.

예제는 다음과 같습니다.

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

OpenAPI를 사용하여 에이전트 만들기

OpenAPI 사양은 특정 엔드포인트에 대한 REST 작업을 설명합니다. 에이전트 SDK는 OpenAPI 사양을 읽고, 함수를 만들고, 추가 클라이언트 쪽 실행 없이 REST 엔드포인트에 대해 해당 함수를 호출할 수 있습니다. 다음은 익명 인증을 사용하여 OpenAPI 도구를 만드는 예제입니다.

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

스레드 만들기

각 세션 또는 대화에 대해 스레드가 필요합니다. 예제는 다음과 같습니다.

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

도구 리소스를 사용하여 스레드 만들기

일부 시나리오에서는 개별 스레드에 특정 리소스를 할당해야 할 수 있습니다. 이를 위해 toolResourcesthreads.create 인수를 제공합니다. 다음 예제에서는 벡터 저장소를 만들고 파일을 업로드하고, tools 인수를 사용하여 에이전트에서 파일 검색을 사용하도록 설정한 다음, toolResources 인수를 사용하여 파일을 스레드와 연결합니다.

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

메시지 만들기

도우미가 처리할 메시지를 만들려면 userrole 전달하고 질문을 content.

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

파일 검색 첨부 파일을 사용하여 메시지 만들기

콘텐츠 검색을 위해 메시지에 파일을 첨부하려면 ToolUtility.createFileSearchTool()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],
      },
    ],
  },
);

코드 인터프리터 첨부 파일을 사용하여 메시지 만들기

데이터 분석을 위해 메시지에 파일을 첨부하려면 ToolUtility.createCodeInterpreterTool()attachment 인수를 사용합니다.

예제는 다음과 같습니다.

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

이미지 입력을 사용하여 메시지 만들기

다음과 같은 방법으로 이미지 입력을 사용하여 Azure 에이전트에 메시지를 보낼 수 있습니다.

  • 업로드된 파일로 저장된 이미지 사용
  • URL을 통해 액세스할 수 있는 공용 이미지 사용
  • base64로 인코딩된 이미지 문자열 사용

다음 예제에서는 base64 메서드를 보여 줍니다.

base64로 인코딩된 이미지 입력을 사용하여 메시지 만들기
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}`);

실행, Run_and_Process 또는 스트림 만들기

다음은 실행이 완료될 때까지 runs.create 폴링의 예입니다.

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

사용자를 대신하여 SDK 폴링하려면 createThreadAndRun 메서드를 사용합니다.

예제는 다음과 같습니다.

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

스트리밍에서는 폴링도 고려할 필요가 없습니다.

예제는 다음과 같습니다.

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

이벤트 처리는 다음과 같이 수행할 수 있습니다.

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

메시지 검색

에이전트에서 메시지를 검색하려면 다음 예제를 사용합니다.

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

파일 검색

에이전트에서 업로드한 파일은 다시 검색할 수 없습니다. 사용 사례가 에이전트에서 업로드한 파일 콘텐츠에 액세스해야 하는 경우 애플리케이션에서 액세스할 수 있는 추가 복사본을 유지하는 것이 좋습니다. 그러나 에이전트에서 생성된 파일은 files.getContent검색할 수 있습니다.

다음은 메시지에서 파일 ID를 검색하는 예제입니다.

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

해체

작업을 완료한 후 리소스를 제거하려면 다음 함수를 사용합니다.

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

문제 해결

예외

서비스 호출을 만드는 클라이언트 메서드는 서비스에서 성공하지 않은 HTTP 상태 코드 응답에 대한 RestError 발생합니다. 예외의 code HTTP 응답 상태 코드를 유지합니다. 예외의 error.message 문제를 진단하는 데 도움이 될 수 있는 자세한 메시지가 포함되어 있습니다.

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

예를 들어 잘못된 자격 증명을 제공하는 경우:

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

문제 신고

클라이언트 라이브러리와 관련된 문제를 보고하거나 추가 기능을 요청하려면 여기에서 GitHub 문제를 여세요.

다음 단계

완전히 실행 가능한 코드를 포함하는 패키지 샘플 폴더를 살펴보세요.

기여하기

이 프로젝트는 기여와 제안을 환영합니다. 대부분의 기여는 귀하가 귀하의 기여를 사용할 권리를 부여할 권리가 있음을 선언하는 CLA(기여자 사용권 계약)에 동의해야 합니다. 자세한 내용은 https://cla.microsoft.com방문하세요.

끌어오기 요청을 제출하면 CLA 봇은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 주석). 봇에서 제공하는 지침을 따르기만 하면 됩니다. CLA를 사용하여 모든 리포지토리에서 한 번만 이 작업을 수행해야 합니다.

이 프로젝트는 Microsoft 오픈 소스 준수 사항을 채택했습니다. 자세한 내용은 행동 강령 FAQ를 참조하거나 추가 질문이나 의견을 opencode@microsoft.com 문의하세요.