Azure AI Projects 클라이언트 라이브러리 for JavaScript - 버전 2.11.0

AI Projects 클라이언트 라이브러리는 Microsoft Foundry SDK의 일부로, Microsoft Foundry Project 내 리소스에 쉽게 접근할 수 있도록 합니다. 다음 작업을 수행하는 데 사용합니다.

  • 클라이언트에서 해당 .agents 속성을 사용하여 에이전트를 생성하고 실행하세요.
  • 전문 도구로 에이전트를 강화하세요:
    • 에이전트 메모리 검색 (미리보기)
    • 에이전트 간 (A2A) (미리보기)
    • Azure AI 검색
    • 빙 맞춤 검색 (미리보기)
    • 빙 그라운딩
    • 브라우저 자동화
    • 코드 해석기
    • 컴퓨터 사용
    • 파일 검색
    • 기능 도구
    • 이미지 생성
    • Microsoft Fabric (미리보기)
    • MCP(모델 컨텍스트 프로토콜)
    • OpenAPI
    • Microsoft SharePoint (미리보기)
    • 웹 검색 (미리보기)
    • 도구 검색
  • 이 메서드를 사용해 .getOpenAIClient.에이전트와 함께 응답, 대화, 평가, 미세 조정 작업을 실행하세요.
  • 세션을 지원하는 배포에서 운영을 사용하여 .agents호스팅된 에이전트 세션과 파일을 관리합니다.
  • 작업을 사용하여 .beta.skills 재사용 가능한 에이전트 기능에 대한 스킬 관리(미리보기).
  • 작업을 사용하여 .toolboxes 도구를 재사용 가능한 컬렉션으로 그룹화하기 위한 도구 상자를 관리합니다.
  • Agent 대화의 메모리 저장소(미리보기)를 운영하여 관리합니다..beta.memoryStores
  • 작업을 사용하여 .beta.routines 자동화된 워크플로우를 예약하고 디스패치하기 위한 루틴(미리보기)을 관리하세요.
  • 사용자 지정 모델 버전을 생성, 업데이트 및 관리하는 작업을 위한 모델 버전 관리(미리보기)를 사용하세요..beta.models
  • 생성형 AI 애플리케이션의 성능을 평가하기 위해 , , .beta.evaluationTaxonomies, .beta.evaluators.beta.schedules.beta.insights(미리보기 중 일부)을 포함한 추가 평가 도구를 탐색하세요..evaluationRules
  • 레드 팀 스캔(미리보기)을 실행하여 생성형 AI 애플리케이션과 관련된 위험을 식별하세요..beta.redTeams
  • 미세 조정 데이터 위에 AI 모델을 적용하세요.
  • Foundry Project에 배포된 AI 모델을 연산으로 열거하세요..deployments
  • Foundry 프로젝트에서 연결된 Azure 리소스를 .connections 연산을 사용하여 열거하세요.
  • 문서를 업로드하고 연산을 사용하여 .datasets 이를 참조할 데이터셋을 생성합니다.
  • 다음 작업을 사용하여 .indexes검색 인덱스를 생성하고 열거하세요.

클라이언트 라이브러리는 Microsoft Foundry v1의 버전을 사용합니다.

제품 문서 | 샘플 | 패키지 (npm) | API 참조 문서 | SDK 소스 코드

목차

시작하기

전제 조건

승인

  • 클라이언트를 인증하려면 Entra ID가 필요합니다. 애플리케이션에는 TokenCredential 인터페이스를 구현하는 개체가 필요합니다. 코드 샘플은 여기서 DefaultAzureCredential를 사용합니다. 이 작업을 수행하려면 다음이 필요합니다.
    • 적절한 역할 배정. Foundry 포털의 역할 기반 접근 제어Microsoft 참조. 역할 할당은 Azure 포털의 Azure AI Project 리소스의 "Access Control (IAM)" 탭을 통해 할 수 있습니다.
    • Azure CLI가 설치되었습니다.
    • Azure 계정에 로그인한 것은 az login입니다.
    • 여러 개의 Azure 구독이 있다면, Azure AI Project 리소스가 포함된 구독이 기본 구독이어야 한다는 점을 유의하세요. az account list --output table 실행하여 모든 구독을 나열하고 어떤 구독이 기본값인지 확인합니다. az account set --subscription "Your Subscription ID or Name" 실행하여 기본 구독을 변경합니다.

패키지 설치

npm install @azure/ai-projects dotenv

주요 개념

Entra ID로 클라이언트를 생성하고 인증하세요

현재 클라이언트가 지원하는 인증 방법은 Entra ID뿐입니다.

를 구성AIProjectsClient하려면 projectEndpoint에서 가져올 수 있습니다. 아래에서는 환경 변수가 FOUNDRY_PROJECT_ENDPOINT 이 값을 갖도록 정의되었다고 가정합니다.

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

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

미리보기 운영 그룹 및 옵트인 기능 플래그

일부 미리보기 작업은 명시적인 foundryFeatures 옵트인 플래그를 요구합니다. 다음은 그 예입니다.

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

미리보기 연산 그룹에는 .beta.voiceAgents, .beta.skills, .beta.memoryStores.beta.routines.beta.models.beta.evaluationTaxonomies.beta.evaluators.beta.insights, .beta.schedules그리고 .beta.redTeams포함됩니다. 음성 에이전트는 GA와 미리보기 기능을 모두 갖추고 있습니다; 옵트인 요구 사항은 음성 에이전트 운영 을 참조하세요.

에이전트를 분석하는 모니터를 나열하는 데 사용 .agentInsightMonitors 하세요:

for await (const monitor of project.agentInsightMonitors.list()) {
  console.log(`${monitor.id}: ${monitor.agent_name}`);
}

예제

OpenAI 클라이언트를 사용하여 응답 작업 수행

귀하의 Microsoft Foundry 프로젝트에는 하나 이상의 AI 모델이 배포되어 있을 수 있습니다. 이들은 OpenAI 모델, Microsoft 모델, 또는 다른 제공업체의 모델일 수 있습니다. 아래 코드를 사용하여 openai 패키지에서 인증된 OpenAI를 가져오고 채팅 완료 호출을 실행합니다.

아래 코드를 실행합니다. 여기서는 (str)이 정의되어 있다고 가정합니다 deploymentName . Foundry Project에 AI 모델의 배포 이름입니다. "모델 + 엔드포인트" 탭의 "이름" 열 아래에 표시된 것처럼

스트리밍 응답을 포함한 추가 샘플은 package samples의 "responses" 폴더를 참조하세요.

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

에이전트 작업 수행

.agents 의 AIProjectsClient 속성을 사용하면 모든 에이전트 작업에 액세스할 수 있습니다. 에이전트는 OpenAI 응답 프로토콜의 확장을 사용하므로 아래 예와 같이 클라이언트가 OpenAI 에이전트 작업을 수행하도록 해야 할 수 있습니다.

설정에 대해서는 Quickstart: Set Up Microsoft Foundry 리소스를 참조하세요.

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

음성 에이전트 운영

음성 에이전트를 생성하고 관리하는 데 사용 project.agents 하세요. 에이전트와 일치하는 연결 클라이언트를 선택하세요:

  • project.voiceAgents.realtime 실시간 및 캐스케이드 음성 에이전트를 위한 서비스입니다.
  • project.beta.voiceAgents.live GPT Live(미리보기)용.

이전 project.beta.voiceAgents.realtime 경로는 동일 클라이언트에 대한 더 이상 지원되지 않는 호환성 별칭입니다. 새 코드에서는 루트 경로를 사용하세요. 일반 실시간 연결은 GA이며 기본적으로 VoiceAgents 미리보기 옵트인을 보내지 않습니다.

Scope API 또는 기능 VoiceAgents=V1Preview
GA 실시간 및 연쇄 정의, 하위 에이전트 위임, 전화 시스템 도구 project.agents 필요하지 않음
GA project.agents.createFromPrompt (agents:generate) 보내지 마세요
GA 모든 14개의 실시간 대화 연산 project.voiceAgents.conversations이 저장되어 있습니다; 실시간 프로토콜 및 OpenAI 실시간 모델 필요하지 않음
GA TPE/Twilio 전화 및 콜 작업 목록/Get 작업 project.voiceAgents.telephony 필요하지 않음
Conditional 인라인 핸드오프, SIP 전송 목적지를 통한 에이전트와의 실시간 연결 post_call 패스 foundryFeaturesconnect()
Conditional 전화 바인딩/전송/통화 쓰기 및 호출 작업 생성/취소/삭제 project.voiceAgents.telephony SIP를 사용할 때만 통과 foundryFeatures
Preview GPT Live 정의, 위임, 세션, 저장된 대화 및 모델 필수; native Live이며 project.beta.voiceAgents.liveConversations 내부적으로 공급됩니다
Preview 인라인 핸드오프 구성/상태/이벤트, SIP 모델 및 post_call 구성/유형 이러한 미리보기 멤버에게 필수; 해당 작업의 옵트인 사용
Preview 일곱 번의 작전 모두 project.beta.voiceAgents.telephony 필수; 내부에서 제공됨

GA 운영은 미리보기 전용 멤버가 있는 유니언을 수용할 수 있습니다. Live, inline handoff 또는 SIP 멤버를 선택할 때나 구성 post_call시 옵트인하세요; 해당 멤버가 있다고 해서 전체 유니언이나 작업 미리보기가 되는 것은 아닙니다.

전화 쓰기 시에는 주소 유형뿐만 아니라 SIP 사용량을 결정하기 위해 연결, 바인딩, 호출 또는 콜-작업 공급자를 사용하세요: SIP 연결은 출발지와 목적지 주소를 사용할 phone_number 수 있습니다. REST 추적 샘플은 선택적 아웃바운드 호출에 기존의 TPE/Twilio 연결만 허용합니다; SIP 호출을 시연하지 않습니다. 별도로, transfer.require_handoff GA 전송-요약 설정이 있으며, 이 설정만으로는 미리보기 인라인 핸드오프를 활성화하지 않습니다.

이전 샘플을 마이그레이션할 때는 , project.beta.voiceAgents.conversationsproject.voiceAgents.conversations로 대체하고, 캠페인 외 용도 project.beta.voiceAgents.telephonyproject.voiceAgents.telephony는 로 대체 project.beta.agents.createFromPromptproject.agents.createFromPrompt하세요. 폐기된 Beta*OptionalParams 응답 유형과 대화 다운로드 응답 유형을 해당 비베타 유형으로 교체하세요. 캠페인과 GPT Live 운영은 아래에 나열된 루트 Realtime 클라이언트를 사용하세요 project.beta.voiceAgents.

이 Node.js 예제는 기존 Realtime 에이전트에 텍스트를 보내고 응답을 출력합니다. 자동 인사말이 없는 에이전트를 사용해서 첫 번째 응답이 메시지에 대한 답이 되도록 하세요.

// Ordinary Realtime sessions are GA and do not require a preview opt-in.
const connection = await project.voiceAgents.realtime.connect("<voice agent name>");
try {
  await connection.sendText("Hello. Please introduce yourself briefly.");
  for await (const event of connection) {
    if (
      event.type === "response.output_text.delta" ||
      event.type === "response.output_audio_transcript.delta"
    ) {
      process.stdout.write(event.delta);
    } else if (event.type === "error") {
      throw new Error(event.error.message);
    } else if (event.type === "response.done") {
      if (event.response.status !== "completed") {
        throw new Error(`Voice response ${event.response.status}.`);
      }
      break;
    }
  }
} finally {
  await connection.close();
}

하나의 for await 루프로 이벤트를 읽으세요. 루프를 벗어나면 연결이 끊깁니다. 알 수 없는 이벤트 유형은 세션을 끊지 않은 상태에서 type: "unknown" 나타나며, 원래 유형은 에 있습니다 eventType. 필드를 사용하기 전에 검증하세요 rawEvent . 기형적인 이벤트 VoiceAgentProtocolError는 . 위 사진과 같이 서비스 error 이벤트를 처리하세요.

대화를 유지하려면 에이전트 또는 를 설정 store: trueconnect()한 후 실시간 대화를 읽으려면 를 사용 project.voiceAgents.conversations 하세요. 비활성화된 에이전트에 연결하는 데 오류가 409 Conflict 발생하고 오류 코드 agent_disabled가 발생합니다.

인라인 핸드오프 샘플은 미리보기 구성을 사용하는 실시간 에이전트에 대한 명시적 옵트인을 보여줍니다:

const connection = await project.voiceAgents.realtime.connect("<inline-handoff agent name>", {
  foundryFeatures: "VoiceAgents=V1Preview",
});
await connection.close();

Node.js이 옵션은 헤더를 foundry-features 보냅니다. 브라우저와 React Native는 동일한 foundry_features WebSocket 쿼리 매개변수를 전송합니다. 예약된 일반 query 매개변수가 아닌 타입 옵션을 사용하세요. 기본 실시간 샘플은 GA 에이전트 구성을 사용합니다; 인라인 핸드오프, SIP 전송 목적지 또는 post_call위와 같이 옵트인을 제공하는 기존 에이전트의 경우

원하는 작업에 대한 전체 샘플을 선택하세요:

작업 Node.js 샘플
에이전트 정의 생성 및 읽기 음성 에이전트 구성
목표에서 에이전트 생성 음성 에이전트 생성
음성 전송 및 음성 응답 저장 실시간 오디오
텍스트 보내기 및 함수 호출 처리 실시간 텍스트와 도구
통화를 하지 않고도 바인딩과 통화 기록을 검사하세요 전화
턴을 인라인 전문가로 라우팅하기(미리보기) 인라인 핸드오프
실시간 (GA) 또는 라이브(미리보기) 녹화 검사 대화 녹음
미리보기 캠페인 및 GA 아웃바운드 콜 작업 검사 읽기 전용 캠페인

미리보기 핸드오프 샘플은 정의를 생성하고 연결할 때 옵트인합니다. 두 개의 인라인 실시간 전문가를 생성하고, 상관된 핸드오프 이벤트와 타겟의 완료된 응답을 관찰한 후 샘플 에이전트를 삭제합니다. 생성이 중단되더라도 중단된 HTTP 요청은 서버 측 생성을 취소하지 않습니다: 로그에 기록된 고유 에이전트 이름을 사용하여 나중에 완료되는 리소스가 있는지 확인합니다. 추적 샘플은 별도의 계측 워크스루입니다; 기본 생성, 실시간 및 GPT Live 예제는 추적 설정이 필요하지 않습니다. 구성 샘플은 기본적으로 GA입니다; 선택적 통화 후 목적지 중 하나를 설정하면 미리보기 전적 전달이 활성화되고 정의 옵트인이 추가됩니다. 통화 후 전달은 선택적 병합 녹음 URL도 지원합니다; 샘플은 발신자 오디오를 요청하지 않습니다.

저장된 대화 및 녹음

대화 녹음 샘플은 읽기 전용이며 두 가지 지속 API 패밀리를 모두 지원합니다. 설정 FOUNDRY_AGENT_NAME 하고 선택 FOUNDRY_VOICE_CONVERSATION_PROTOCOL=realtime 하세요 live. Realtime은 미리보기 헤더 없이 GA project.voiceAgents.conversations 클라이언트를 사용합니다; Live project.beta.voiceAgents.liveConversations 에서는 필수 미리보기 헤더를 사용합니다. 한 페이지를 읽고, sample.env에 문서화된 변수를 사용해 정확한 대화나 항목을 선택할 수 있습니다. REST 컬렉션에서 반환되는 ID를 사용하며, 기본 RealTime WebSocket 항목이나 응답 ID를 사용하지 마십시오. 먼저 녹음을 생성하고 세션에 연결 store: true 해 마무리한 후 오디오를 다운로드하세요. 샘플은 저장된 대화를 삭제하거나 발신자 녹취록을 인쇄하지 않습니다.

WAV 파일 다운로드를 선택하도록 설정 FOUNDRY_VOICE_RECORDING_OUTPUT_FILE 하세요. 이 설정 FOUNDRY_VOICE_AUDIO_ITEM_ID은 해당 항목의 청취된 오디오를 다운로드하며, 그렇지 않으면 병합된 스테레오 녹음을 다운로드합니다. 이 WAV 파일들은 스트리밍 샘플이 작성한 원시 PCM 파일과는 다릅니다. 다운로드된 발신자 미디어는 비공개로 유지하세요. 자체 저장소 가져오기 녹화는 본인의 저장소 자격 증명으로 읽 blob_uri 어야 하며, 이 샘플은 임의 저장소 URL을 가져오지 않습니다.

실시간 기능은 응답 점검과 생성되지만 들리지 않는 항목 오디오도 제공합니다. 생성된 오디오 변수는 서비스가 청각 구간을 넘어 오디오를 생성한 중단되거나 잘린 항목을 필요로 합니다; 단지 취소만으로는 아티팩트가 존재한다는 보장이 없습니다. 누락된 오디오가 돌아옵 404니다. 완료되지 않은 병합된 녹음은 반환 409 recording_not_ready될 수 있으며, 그 응답을 빈 녹음으로 취급하지 말고 그 Retry-After 지침을 따르십시오.

저장된 GPT Live 세션의 경우, .project.beta.voiceAgents.liveConversations 라이브 세션 project.voiceAgents.realtime.connect() 에 project.beta.voiceAgents.live.connect() 연결하고 store: true 지속하려면 실시간 프로토콜을 사용하며 라이브 연결이 아닙니다. 다음 Node.js 예제는 완료된 라이브 대화를 읽고, 기록을 인쇄하지 않고 저장된 항목을 나열하며, Foundry가 관리하는 병합된 WAV 녹음을 저장합니다:

import { AIProjectClient } from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";
import { pipeline } from "node:stream/promises";
import { createWriteStream } from "node:fs";

const project = new AIProjectClient("<project endpoint>", new DefaultAzureCredential());
const agentName = "<GPT Live agent name>";
const conversationId = "<stored Live conversation ID>";
const conversations = project.beta.voiceAgents.liveConversations;
const conversation = await conversations.get(agentName, conversationId);
console.log("Conversation:", conversation.id, conversation.status);
for await (const item of conversations.listItems(agentName, conversationId)) {
  console.log("Stored item:", item.id, item.type);
}
const recording = await conversations.getAudio(agentName, conversationId);
if (recording.blob_uri) {
  throw new Error("Retrieve BYOS audio from blob_uri using your own storage credentials.");
}
const audio = await conversations.downloadAudio(agentName, conversationId);
if (!audio.readableStreamBody) {
  throw new Error("Expected a Node.js audio stream.");
}
await pipeline(audio.readableStreamBody, createWriteStream("live-conversation.wav"));

캠페인 운영은 미리보기 project.beta.voiceAgents.telephony 클라이언트를 사용합니다. 캠페인을 삭제하는 데 사용 deleteCampaign() ; deleteTelephony() 해당 작업의 더 이상 지원되지 않는 호환성 별칭입니다. 콜-작업 목록/가져오기 작업은 미리보기 캠페인으로 생성된 작업을 포함해 GA project.voiceAgents.telephony 클라이언트를 사용합니다. 캠페인 샘플은 캠페인 준비, 검증 오류, 운영 모니터, 호출 작업만 읽습니다. 캠페인 읽기는 해당 미리보기 경로가 활성화된 배포가 필요합니다. 전화를 생성하거나 취소하지 않습니다: 캠페인 생성 시 준비 폴러가 돌아오기 전에 다이얼을 허용할 수 있습니다. 준비 중 검증 오류 페이지가 비어 있어도 캠페인이 유효하거나 준비 완료되었음을 입증하지 않습니다.

사용자 지정 쿼리 매개변수

하나의 연결에 대해 URL 매개변수를 추가하려면 패스 query 합니다. 서비스 또는 게이트웨이에서 지원하는 이름을 사용하세요; 아래의 이름들은 예시입니다:

const connection = await project.voiceAgents.realtime.connect("my-voice-agent", {
  query: {
    custom_key: "custom value",
    custom_flag: true,
    // Explicit URL transport: only use non-sensitive prompt variables.
    structured_inputs: JSON.stringify({ persona: "guide" }),
  },
});
await connection.close();

값은 문자열, 유한수, 또는 불리언일 수 있습니다. SDK URL은 이를 인코딩하고 호출 시 connect() 캡처합니다. 값은 일치하는 엔드포인트 매개변수를 대체합니다; undefined 이 값을 제거합니다. 이 값들은 이후 연결에 재사용되지 않습니다.

SDK 설정에 query넣기보다는 , , agentVersionOverride, 실시간 등 타입된 옵션을 store사용하세요foundryFeatures. SDK/인증 이름, 비정식 구조화 입력 이름, 그리고 이름으로 h- 시작하는 이름은 그대로 예약되어 있습니다. 실시간은 위에서 보듯이 JSON 객체 문자열로 정확한 structured_inputs 키를 명시적으로 허용하며, 이를 결합 structuredInputs하지 마십시오. 다른 사용자 지정 쿼리 값은 프롬프트 변수가 되지 않습니다.

실시간으로 structuredInputs 헤더 기반 전송을 보존Node.js. 브라우저는 임의의 WebSocket 업그레이드 헤더를 보낼 수 없기 때문에 URL 쿼리를 사용합니다. 서비스가 쿼리 폼을 요구하는 경우, 대신 명시적으로 query.structured_inputsstructuredInputs옵트인하여 요청하세요. 쿼리 매개변수에 비밀이나 민감한 프롬프트 변수를 절대 넣지 마세요: 서버 및 프록시 접근 로그는 URL을 유지할 수 있습니다.

GPT Live 음성 에이전트

GPT Live 에이전트에 사용 project.beta.voiceAgents.live 하세요. 에이전트를 생성할 때, , model_type: "self_deployed", 를 설정sub_protocol: "live"하여 model GPT Live 배포 이름으로 설정하세요. 창조는 를 필요로 한다 VoiceAgents=V1Preview. 전달 { foundryFeatures: "VoiceAgents=V1Preview" } 대상 project.agents.create() 또는 createVersion(). 네이티브 라이브 연결은 항상 필요한 미리보기 플래그를 내부적으로 전송합니다; 호출자는 에 플 live.connect()래그가 필요하지 않습니다.

이 짧은 예제는 24 kHz의 모노 PCM16LE 오디오용으로 구성된 기존 에이전트를 필요로 합니다. Live는 텍스트 지시를 추가할 때도 오디오 시계를 앞당겨 진행하므로, 예제는 상관된 확인 응답이 도착할 때까지 무음을 보내고 세션을 종료합니다. 아래 전체 샘플을 사용하여 텍스트나 음성 메시지를 보내고 답글을 읽어보세요.

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

const project = new AIProjectClient("<project endpoint>", new DefaultAzureCredential());
const connection = await project.beta.voiceAgents.live.connect("<GPT Live agent name>", {
  store: false,
});
const eventId = "brief-instructions";
// Requires an agent configured for mono PCM16LE at 24 kHz.
const silence = new Uint8Array(4800); // 100 ms of audio.
let correlatedAck = false;
let serviceError: Error | undefined;
const onAppended = (event: LiveServerEventLiveInstructionsAppended): void => {
  if (event.client_event_id === eventId) correlatedAck = true;
};
const onError = (event: LiveServerEventLiveErrorEvent): void => {
  serviceError = new Error(event.error.message);
};
connection.on("session.instructions.appended", onAppended);
connection.on("error", onError);
try {
  await connection.appendInstructions("Keep your answers brief.", { eventId });
  const deadline = Date.now() + 10000;
  while (!correlatedAck) {
    if (serviceError) throw serviceError;
    if (connection.state !== "connected") {
      throw new Error(`Live connection became ${connection.state} before the instructions ACK.`);
    }
    if (Date.now() >= deadline) {
      throw new Error("Timed out waiting for the correlated instructions ACK.");
    }
    await connection.sendAudio(silence);
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
  if (serviceError) throw serviceError;
} finally {
  connection.off("session.instructions.appended", onAppended);
  connection.off("error", onError);
  await connection.close();
}

GPT Live 샘플 실행

셋 FOUNDRY_PROJECT_ENDPOINT 그리고 FOUNDRY_LIVE_MODEL ..env 모델 카탈로그 ID가 아닌 배포 이름을 사용하세요. 함수 샘플에는 또한 FOUNDRY_LIVE_BACKEND_MODEL필요합니다. 이 설정과 선택적 오디오 파일 경로는 sample.env 를 참조하세요.

작업 Node.js 샘플
인사말을 보내고 음성 답장을 텍스트로 출력하세요 GPT 라이브 텍스트
음성 파일을 보내고 오디오 응답을 저장하세요 GPT 라이브 오디오
로컬 함수를 실행하고 에이전트가 결과를 말하게 하세요 GPT Live 함수 호출

빌드된 SDK 체크아웃에서 22.18 이상Node.js 샘플을 실행하세요:

node samples-dev/agents/agentVoiceLiveText.ts

각 샘플은 자신의 에이전트를 생성하고 삭제합니다. 자막은 출력되지만 스피커를 통해 소리를 재생하지는 않습니다. 오디오 샘플은 마이크가 아닌 녹음된 파일을 사용하며, WAV나 기타 파일 헤더 없이 24 kHz의 원시 모노 PCM16LE을 읽고 저장합니다.

답글 후 Enter 키를 누르거나 Ctrl+C를 눌러 중지하세요. 사용량은 세션이 종료될 때까지 청구 가능합니다. 라이브는 텍스트와 도구조차도 지속적인 오디오 입력이 필요하기 때문에, 샘플은 대기 상태에서도 무음을 보냅니다. Live에는 말로 끝난 이벤트가 없습니다; 백엔드 응답이 완료되었다고 해서 에이전트가 말을 끝냈다는 의미는 아닙니다.

텍스트 샘플은 세션 지시를 덧붙이고, 그들과 연관된 확인을 기다린 후 해설을 덧붙입니다. 그 확인 인사는 이미 말을 완료한 것이 아니라 수락을 확인하는 것입니다; 예상 답변이 올 때까지 세션을 열어 두세요.

세션 컨트롤 및 이벤트

connect() 기다 session.started린다. 해당 시 선택한 관리 에이전트 및 버전을 포함한 현재 설정을 connection.session읽으십시오. 하나의 for await 루프로 이벤트를 읽거나 , , off, once 를 사용하여 on후속 이벤트를 수행한다. 청취자 전용 소비의 경우, onEvent 연결 시 시작 이벤트와 초기 오디오를 수신할 수 있도록 응답을 기다리 connect() 지 않습니다. 서비스가 제공할 때 지속되는 대화 ID를 포함한 원래 시작 이벤트는 connection.sessionStarted. 콜백이 onEvent 구성된 후 시작된 반복자는 과거 이벤트가 아니라 후속 이벤트를 받습니다.

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

const project = new AIProjectClient("<project endpoint>", new DefaultAzureCredential());
const connection = await project.beta.voiceAgents.live.connect("<GPT Live agent name>", {
  store: true,
  onEvent: (event) => {
    if (event.type === "session.started") {
      console.log("Conversation:", event.conversation_id);
    } else if (event.type === "session.output_audio.delta") {
      console.log("Received an audio chunk.");
    }
  },
});
try {
  console.log("Session:", connection.sessionStarted.session.id);
} finally {
  await connection.close();
}
작업 API 또는 이벤트
원본 오디오 전송 sendAudio(); Live는 음성 경계를 감지하므로 오디오 버퍼 커밋이 필요 없습니다
대본 읽기 session.input_transcript.delta, session.output_transcript.delta
오디오 수신 session.output_audio.delta; 저장하거나 재생하기 전에 base64 데이터를 디코딩하세요
사용자 메시지 대신 텍스트 컨텍스트 추가하기 appendInstructions(), appendThinking(), appendCommentary()
오디오 처리 일시 중지 또는 재개 muteInputAudio(), unmuteInputAudio()
백엔드 설정 및 성적 스크립트 트리거 업데이트 configureSession(); 초기 모델, 오디오 형식 및 위임 소유자는 변경할 수 없습니다
세션 닫기 close(); 최종 확정이 확인되지 않으면 대기 session.closed 하다가 거부합니다.

close() dispose() 또한 소켓이 이미 분리된 상태에서 확인되지 않은 종료를 거부합니다. 서비스의 최종 완료 이벤트와 연결 오류가 있는지 검사 connection.closed 합니다.

Responses 위임을 통해 백엔드 이벤트가 내부에 response.event도착합니다. 사용자 메시지를 추가하고 requestResponse() 회신을 요청하는 데 사용 sendResponseItem() 하세요. 함수 호출의 경우, 호출 백엔드 응답이 완료될 때까지 기다린 후 결과를 sendToolOutput() 반환하고 계속을 요청합니다. 이러한 방법들은 응답 위임이 필요합니다. 클라이언트 처리형 위임의 경우, 또는 를 appendCommentary() 사용하고 appendThinking() 위임 ID를 다음과 같이 delegationId전달하세요.

의사결정 컨텍스트 항목은 사용자 메시지, 함수 호출 및 결과, 사용자 지정 도구 호출 및 결과를 지원합니다. decision.item.create전송 시 ; 수신된 decision.item.created 이벤트는 해당 항목 필드와 저장된 ID를 유지합니다. 결정 명령은 서비스 배치의 지원이 필요합니다.

Live는 response.cancelRealtime의 .를 지원하지 않습니다. 중단 신호는 이미 생성 중인 음성 메시지가 아니라 SDK 연결이나 송신 작업을 취소합니다. 라이브 대화를 storeproject.beta.voiceAgents.liveConversations저장하려면 ; 서비스 배포가 지속성을 지원해야 합니다. 연결 변경, 세션 시작 및 종료 타임아웃을 변경하도록 설정 liveOptionsAIProjectClient 하세요. 저장된 대화 샘플FOUNDRY_VOICE_CONVERSATION_PROTOCOL=live 을 사용하여 보존된 항목을 검사하거나 WAV 오디오를 다운로드하세요.

브라우저 인증

.와 같은 InteractiveBrowserCredential브라우저 자격 증명을 사용하세요. SDK는 웹 워커를 포함해 네이티브 WebSocketlive 와 함께 보유자 토큰 서브프로토콜과 단기간 사용 서브프로토콜을 사용합니다. Node.js 대신 베어러 헤더를 사용합니다. 라이브 서브프로토콜로 제공 realtime 하지 말고, URL에 토큰을 넣거나, 브라우저 코드에 API 키, 클라이언트 비밀, 장기 토큰을 삽입하지 마십시오. 직접 브라우저 인증이 불가능한 경우, 를 통해 webSocketFactory인증된 백엔드 릴레이를 제공하십시오.

실시간 연결은 헤더를 x-ms-voice-structured-inputs Node.js에 보관 structuredInputs 하며 브라우저와 워커에서 URL 쿼리를 사용합니다structured_inputs. 명시적 실시간 query.structured_inputs 기능은 어떤 호스트에서든 URL 전송에 동의합니다. GPT Live는 모든 호스트에서 URL 쿼리를 계속 사용하고 있으며, 헤더 기반 대안은 없습니다. 프록시 및 서버 접근 로그는 URL을 유지할 수 있습니다. URL이 전달된 입력에는 자격 증명, 개인 데이터 또는 기타 민감한 정보를 넣지 마십시오.

에이전트 도구 사용

에이전트는 다양한 기능을 위한 특수 도구로 강화될 수 있습니다. 도구는 연결 요구사항에 따라 정리되어 있습니다:

내장 도구

이 도구들은 외부 연결이 필요 없이 즉시 작동합니다.

코드 해석기

샌드박스 환경에서 자바스크립트 코드를 작성하고 실행하며, 파일을 처리하고 다양한 데이터 형식을 다룹니다. 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}`);

전체 샘플 코드는 agentCodeInterpreter.ts에서 확인할 수 있습니다.

파일 검색

벡터 저장소를 사용하여 지식을 검색하기 위해 문서를 처리하고 검색할 수 있는 내장 RAG(Retrieval-Augmented 생성) 도구. 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})`);

전체 샘플 코드는 agentFileSearchStream.ts에서 확인할 수 있습니다.

이미지 생성

텍스트 프롬프트를 기반으로 해상도, 품질, 스타일 설정을 맞춤 설정할 수 있는 이미지를 생성하세요:

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

전화를 responses.create()걸면 답변을 통해 파일을 다운로드할 수 있습니다:

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

웹 검색 (미리보기)

인터넷에서 최신 정보를 얻기 위해 일반적인 웹 검색을 수행하세요. 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}`);

전체 샘플 코드는 agentWebSearch.ts에서 확인할 수 있습니다.

컴퓨터 사용

에이전트가 작업 자동화 및 시스템 운영을 위해 컴퓨터 시스템과 직접 상호작용할 수 있도록 허용합니다(도구를 지원하는 computer 모델 배포가 필요합니다. 예를 들어 gpt-5.4, 배포 시 computer-use-preview 사용 computer_use_preview하세요):

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",
    },
  ],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

를 호출 responses.create()한 후 상호작용 루프에서 응답을 처리합니다. 출력 항목을 처리 computer_call 하고 상호작용을 계속할 수 있도록 타입에 따라 computer_call_outputcomputer_screenshot 스크린샷을 제공하세요.

전체 샘플 코드는 agentComputerUse.ts에서 확인할 수 있습니다.

모델 컨텍스트 프로토콜(MCP)

MCP 서버를 통합하여 표준화된 도구와 자원으로 에이전트 기능을 확장하세요. 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" } },
  },
);

를 호출 responses.create()한 후 응답 출력에 항목이 있는지 mcp_approval_request 확인하세요. 승인 결정을 내린 후 에이전트 McpApprovalResponse 가 계속 작업할 수 있도록 다시 보내세요.

전체 샘플 코드는 agentMcp.ts에서 확인할 수 있습니다.

OpenAPI

추가 클라이언트 사이드 코드 없이 OpenAPI 명세에 정의된 외부 API를 호출할 수 있습니다. 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})`);

전체 샘플 코드는 agentOpenApi.ts에서 확인할 수 있습니다.

기능 도구

에이전트가 외부 API, 데이터베이스 또는 애플리케이션 로직과 상호작용할 수 있도록 하는 맞춤형 함수를 정의하세요. 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})`);

응답 출력에서 항목을 호출 responses.create()function_call 한 후 제공된 인수로 함수 로직을 실행한 후 결과를 다시 FunctionCallOutput 전송합니다.

전체 샘플 코드는 agentFunctionTool.ts에서 확인하세요.

  • 메모리 검색 도구 (미리보기)

메모리 스토어 도구는 에이전트에게 메모리를 추가하여 에이전트의 AI 모델이 현재 사용자 프롬프트와 관련된 과거 정보를 검색할 수 있게 합니다.

이 embeddingModelDeployment 모델은 기억을 저장하고 탐색하기 위해 벡터 임베딩을 생성하는 데 사용되는 모델의 이름입니다.

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

전체 샘플 코드는 agentMemorySearch.ts에서 확인할 수 있습니다.

Connection-Based 도구

이 도구들은 AI 파운드리 프로젝트에서 연결을 구성하고 projectConnectionId사용하는 것이 필요합니다.

Azure AI 검색

강력한 지식 검색 및 의미 검색 기능을 위해 Azure AI 검색 인덱스와 통합하세요:

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

전체 샘플 코드는 agentAiSearch.ts에서 확인할 수 있습니다.

빙 접지

빙의 실시간 웹 검색 결과 제공된 지상 요원의 답변 up-to날짜 정보:

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

전체 샘플 코드는 agentBingGrounding.ts에서 확인할 수 있습니다.

Bing 사용자 지정 검색(미리보기)

도메인 특화 또는 필터링된 웹 검색 결과에는 맞춤 설정된 Bing 검색 인스턴스를 사용하세요:

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

전체 샘플 코드는 agentBingCustomSearch.ts에서 확인할 수 있습니다.

Microsoft Fabric (미리보기)

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

전체 샘플 코드는 agentFabric.ts에서 확인할 수 있습니다.

Microsoft SharePoint (미리보기)

기업 지식 통합을 위해 SharePoint 문서, 목록, 사이트를 접근하고 검색하세요:

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

전체 샘플 코드는 agentSharepoint.ts에서 확인할 수 있습니다.

브라우저 자동화

웹 스크래핑, 테스트 및 웹 애플리케이션과의 상호작용을 위한 브라우저 상호작용 자동화:

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

전체 샘플 코드는 agentBrowserAutomation.ts에서 확인하세요.

샘플을 실행하기 전에 , , FOUNDRY_MODEL_NAME, (BROWSER_AUTOMATION_PROJECT_CONNECTION_IDAzure Playwright 리소스의 프로젝트 연결 리소스 ID)를 설정FOUNDRY_PROJECT_ENDPOINT하세요. GA 도구를 사용 browser_automation 해 브라우저 결과를 바탕으로 페이지 제목과 가시적 설명을 방문 https://example.com 하고 보고합니다. 선택적으로 에이전트 이름을 선택하도록 설정 FOUNDRY_AGENT_NAME 하며; 기본값은 MyAgent.

스트리밍 샘플은 브라우저 라이브 뷰 URL을 포함해 각 완성된 텍스트 메시지를 한 번씩 출력하고, 원격 함수 행동 이름, 호출 ID, 인자를 기록합니다 browserSessionId. 라이브 뷰 URL은 민감한 URL로 간주하세요: 공유하거나 소스 컨트롤에 커밋하지 마세요. 실패하거나 불완전한 응답은 성공 보고가 아닌 상태로 종료됩니다. 샘플은 응답 처리가 성공하든 실패하든 블록 내에서 finally 생성한 에이전트 버전을 삭제합니다.

Project Connection이 포함된 MCP

연결된 MCP 서버에 접근하기 위한 프로젝트별 연결을 이용한 MCP 통합:

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

전체 샘플 코드는 agentMcpConnectionAuth.ts에서 확인할 수 있습니다.

에이전트 간 (A2A) (미리보기)

에이전트가 다른 전문 에이전트에게 소통하고 작업을 위임할 수 있는 다중 에이전트 협업을 가능하게 합니다:

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

전체 샘플 코드는 agentAgentToAgent.ts에서 확인할 수 있습니다.

Project Connection을 이용한 OpenAPI

프로젝트 연결 인증을 사용하여 OpenAPI 명세에서 정의된 외부 API를 호출합니다:

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

전체 샘플 코드는 agentOpenApiConnectionAuth.ts에서 확인할 수 있습니다.

모든 도구의 완전한 작동 예제는 samples-dev 디렉토리를 참조하세요.

Evaluation

Azure AI Project 클라이언트 라이브러리의 평가는 정량적이고 AI 지원 품질 및 안전 지표를 제공하여 LLM 모델, 생성형 AI 애플리케이션 및 에이전트의 성능을 평가하고 평가합니다. 지표는 평가자로 정의됩니다. 내장된 또는 맞춤형 평가자는 포괄적인 평가 인사이트를 제공할 수 있습니다.

아래 코드는 일부 평가 연산을 보여줍니다. 샘플의 전체 목록은 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})`);

전체 샘플 코드는 agentEvaluation.ts에서 확인할 수 있습니다.

배포 작업

아래 코드는 Microsoft Foundry 프로젝트에 배포된 AI 모델을 열거할 수 있는 배포 작업을 보여줍니다. 이 모델들은 Microsoft Foundry Project의 "Models + 엔드포인트" 탭에서 확인할 수 있습니다. 전체 샘플은 package samples의 "deployment" 폴더에서 찾을 수 있습니다.

import { ModelDeployment } from "@azure/ai-projects";

const modelPublisher = process.env["MODEL_PUBLISHER"] || "<model publisher>";
console.log("List all deployments:");
const deployments: ModelDeployment[] = [];
const properties: Array<Record<string, string>> = [];

for await (const deployment of project.deployments.list()) {
  // Check if this is a ModelDeployment (has the required properties)
  if (
    deployment.type === "ModelDeployment" &&
    "modelName" in deployment &&
    "modelPublisher" in deployment &&
    "modelVersion" in deployment
  ) {
    deployments.push(deployment);
    properties.push({
      name: deployment.name,
      modelPublisher: deployment.modelPublisher,
      modelName: deployment.modelName,
    });
  }
}
console.log(`Retrieved deployments: ${JSON.stringify(properties, null, 2)}`);

// List all deployments by a specific model publisher (assuming we have one from the list)
console.log(`List all deployments by the model publisher '${modelPublisher}':`);
const filteredDeployments: ModelDeployment[] = [];
for await (const deployment of project.deployments.list({
  modelPublisher,
})) {
  // Check if this is a ModelDeployment
  if (
    deployment.type === "ModelDeployment" &&
    "modelName" in deployment &&
    "modelPublisher" in deployment &&
    "modelVersion" in deployment
  ) {
    filteredDeployments.push(deployment);
  }
}
console.log(
  `Retrieved ${filteredDeployments.length} deployments from model publisher '${modelPublisher}'`,
);

// Get a single deployment by name
if (deployments.length > 0) {
  const deploymentName = deployments[0].name;
  console.log(`Get a single deployment named '${deploymentName}':`);
  const singleDeployment = await project.deployments.get(deploymentName);
  console.log(`Retrieved deployment: ${JSON.stringify(singleDeployment, null, 2)}`);
}

연결 작업

아래 코드는 Microsoft Foundry 프로젝트에 연결된 Azure 리소스를 열거할 수 있는 Connection 작업을 보여줍니다. 이 연결은 Microsoft Foundry Project의 "Connected resources" 탭의 "Management Center"에서 확인할 수 있습니다. 전체 샘플은 package samples의 "connections" 폴더에서 찾을 수 있습니다.

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

데이터 세트 작업

아래 코드는 몇 가지 데이터 세트 작업을 보여줍니다. 전체 샘플은 package samples의 "datasets" 폴더에서 찾을 수 있습니다.

로컬 파일 시스템 업로드(project.datasets.uploadFile, project.datasets.uploadFolder, , ) project.beta.models.create는 Node.js에서만 지원됩니다. 브라우저 애플리케이션은 파일 시스템 폴리필 없이 데이터셋과 모델 @azure/ai-projects REST 작업을 가져오 AIProjectClientVoiceAgentRealtimeClient 고 사용할 수 Node.js 있습니다.

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

파일 작업

아래 코드는 파일을 업로드, 검색, 나열 및 삭제할 수 있는 OpenAI 클라이언트를 사용하는 일부 파일 작업을 보여줍니다. 이러한 작업은 미세 조정 및 기타 AI 모델 작업에 사용할 수 있는 파일 작업에 유용합니다. 전체 샘플은 package samples의 "files" 폴더에서 찾을 수 있습니다.

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

인덱스 연산

아래 코드는 몇 가지 인덱스 작업을 보여줍니다. 전체 샘플은 package samples의 "indexes" 폴더에서 찾을 수 있습니다.

import { AzureAISearchIndex } from "@azure/ai-projects";

const indexName = "sample-index";
const version = "1";
const azureAIConnectionConfig: AzureAISearchIndex = {
  name: indexName,
  type: "AzureSearch",
  version,
  indexName,
  connectionName: "sample-connection",
};

// Create a new Index
const newIndex = await project.indexes.createOrUpdate(indexName, version, azureAIConnectionConfig);
console.log("Created a new Index:", newIndex);
console.log(`Get an existing Index version '${version}':`);
const index = await project.indexes.get(indexName, version);
console.log(index);
console.log(`Listing all versions of the Index named '${indexName}':`);
const indexVersions = project.indexes.listVersions(indexName);
for await (const indexVersion of indexVersions) {
  console.log(indexVersion);
}
console.log("List all Indexes:");
const allIndexes = project.indexes.list();
for await (const i of allIndexes) {
  console.log("Index:", i);
}
console.log("Delete the Index versions created above:");
await project.indexes.delete(indexName, version);

미세 조정 작업

아래 코드는 OpenAI 클라이언트를 사용해 미세 조정 작업을 만드는 방법을 보여줍니다. 이 작업들은 감독 Fine-Tuning(SFT), 강화 Fine-Tuning(RFT), 직접 성능 최적화(DPO)와 같은 다양한 미세 조정 기법을 지원합니다. 전체 샘플은 package samples의 "finetunening" 폴더에서 찾을 수 있습니다.

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

에이전트 세션 운영

호스팅된 에이전트의 세션 및 세션 파일을 관리하는 데 사용됩니다 project.agents . 세션은 에이전트 간 상호작용을 위한 고립된 샌드박스 환경을 제공합니다. 이 예제는 세션 작업을 지원하는 호스팅 에이전트 배포를 필요로 합니다.

import { VersionRefIndicator } from "@azure/ai-projects";

const agentName = "MySessionAgent";
// Create a session for the agent
const versionIndicator: VersionRefIndicator = {
  type: "version_ref",
  agent_version: "1.0",
};
const session = await project.agents.createSession(agentName, versionIndicator);
console.log(`Session created: ${session.agent_session_id}`);
// Upload a file to the session sandbox
const filePath = "/sandbox/hello.txt";
const fileContent = new TextEncoder().encode("Hello from the agent sessions sample!");
const uploadResult = await project.agents.uploadSessionFile(
  agentName,
  session.agent_session_id,
  filePath,
  fileContent,
);
console.log(`Uploaded file: ${uploadResult.path} (${uploadResult.bytes_written} bytes)`);

전체 샘플 코드는 agentSessions.ts 과 해당 노트북에서 확인하세요.

기술 운영 (미리보기)

운영은 .beta.skills 에이전트 역량을 정의하는 재사용 가능한 기술을 생성하고 관리할 수 있게 해줍니다.

const skillName = "sample-skill";
// Create a new skill
const created = await project.beta.skills.create(skillName, {
  inlineContent: {
    description: "Example skill created by the @azure/ai-projects sample.",
    instructions: "You are a helpful assistant that answers questions concisely.",
    metadata: { owner: "sample" },
  },
});
console.log(`Skill created: ${created.name} (id: ${created.skill_id})`);
// Retrieve the skill
const fetched = await project.beta.skills.get(skillName);
console.log(`Retrieved skill: ${fetched.name} (id: ${fetched.id})`);

전체 샘플 코드는 skillBasic.ts에서 확인할 수 있습니다.

툴박스 작업 (미리보기)

운영을 통해 .toolboxes 툴박스를 생성하고 관리할 수 있습니다 — 에이전트 간 공유 가능한 재사용 가능한 도구 모음입니다.

import { ToolUnion, MCPTool } from "@azure/ai-projects";

const toolboxName = "mcp";
// Define tools for the toolbox
const tools: ToolUnion[] = [
  {
    type: "mcp",
    server_label: "api_specs",
    server_url: "https://github.com/Azure/azure-rest-api-specs",
    require_approval: "never",
  } satisfies MCPTool,
];
// Create a new toolbox version
const created = await project.toolboxes.createVersion(toolboxName, tools, {
  description: "Example toolbox created by the @azure/ai-projects sample.",
  metadata: { status: "created" },
});
console.log(`Toolbox: ${created.name} (tools: ${created.tools.length})`);
// Retrieve the toolbox
const fetched = await project.toolboxes.get(toolboxName);
console.log(`Retrieved toolbox: ${fetched.name} (${fetched.id})`);

전체 샘플 코드는 toolboxesCrud.ts에서 확인할 수 있습니다.

추적

실험적 특징 게이트

중요: GenAI 추적 계측은 실험적인 미리보기 기능입니다. 범위, 특성 및 이벤트는 향후 버전에서 수정될 수 있습니다. 사용하려면 를 구성할 tracingOptions때 명시적으로 옵트인 experimental: true 을 해야 하며, 또는 환경 변수를 설정하여 다음과 AIProjectClient 같이 해야 합니다:

AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING=true

이 기능은 요구사항을 검토하고 추적 동작이 향후 버전에서 변경될 수 있음을 이해한 후에만 활성화하세요.

추적 시작

Microsoft Foundry 프로젝트에 Application Insights Azure 리소스를 추가할 수 있습니다. 활성화되어 있다면 Application Insights 연결 문자열을 받고, AI 프로젝트 클라이언트를 설정하며, Azure Monitor에서 트레이스를 관찰할 수 있습니다. 일반적으로 클라이언트 또는 에이전트를 생성하기 전에 추적을 시작할 수 있습니다.

설치

Azure Monitor 發送 traces:

npm install @azure/monitor-opentelemetry @opentelemetry/api

콘솔로 가는 트레이스를 출력하려면(로컬 개발에 유용함):

npm install @opentelemetry/sdk-trace-node @opentelemetry/api

추적 활성화 방법

추적은 생성자에게 전달 tracingOptionsAIProjectClient 함으로써 가능해집니다. 제공되지 않으면 tracingOptions GenAI 추적이 완전히 비활성화되어 생성 AI 스팬이나 메트릭이 전혀 출력되지 않습니다. 이 설정은 오직 GenAI 전용 추적(모델 호출, 에이전트 연산, 토큰 사용 등에 대한 의미 규칙 범위)만 제어합니다. 추적 구성은 해당 클라이언트 인스턴스를 통해 수행되는 모든 작업에 적용됩니다. 여기에는 에이전트 작업과 를 통해 project.getOpenAIClient()얻은 모든 OpenAI 클라이언트가 포함됩니다. 서로 다른 클라이언트 인스턴스는 독립적인 추적 구성을 가질 수 있습니다.

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

const endpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint>";
const credential = new DefaultAzureCredential();

// Tracing enabled
const project = new AIProjectClient(endpoint, credential, {
  tracingOptions: { experimental: true },
});

// Tracing disabled (default — no tracingOptions passed)
const projectNoTrace = new AIProjectClient(endpoint, credential);

console.log(project, projectNoTrace);

빈 객체를 전달하면 tracingOptions: {} 추적도 가능하며, 이 경우 모든 개별 설정은 해당 환경 변수로부터 해결됩니다.

객체는 tracingOptions 다음과 같은 성질을 받아들입니다:

Option 환경 변수 기본값 Description
experimental AZURE_EXPERIMENTAL_ENABLE_GENAI_TRACING false 이 기능의 실험적 성격을 인정하세요(스팬을 방출하는 데 필요함)
contentRecording OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT false 프롬프트 및 완료 콘텐츠를 트레이스에 캡처하기
traceContextPropagation AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATION true 요청에 W3C 트레이스 컨텍스트 헤더를 주입하세요

각 옵션은 다음과 같은 우선순위로 해결됩니다:

  1. 명시적 값 (tracingOptions최고 우선순위)
  2. 환경 변수 (옵션이 생략되거나 정의되지 않았을 때 체크됨)
  3. 기본값( 둘 다 설정되지 않았거나 환경 변수를 읽을 수 없는 경우 사용)

참고: 현재 모든 추적 기능은 실험 단계이므로, experimental: true 방출될 구간을 명시적으로 또는 환경 변수를 통해 설정해야 합니다.

음성 에이전트 추적

OpenTelemetry 공급자와 익스포터를 등록한 다음 를 설정합니다tracingOptions: { experimental: true }.AIProjectClient 이는 음성 에이전트 생성, 전화 통화 변경, 대화 삭제, 실시간 세션 및 응답 등을 추적합니다. 별도의 음성 에이전트 추적 플래그가 필요하지 않습니다.

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

const project = new AIProjectClient("<project endpoint>", new DefaultAzureCredential(), {
  tracingOptions: {
    experimental: true,
    contentRecording: false,
  },
});
const connection = await project.voiceAgents.realtime.connect("<voice agent name>");
try {
  await connection.sendText("Hello.");
  for await (const event of connection) {
    if (event.type === "error") {
      throw new Error(event.error.message);
    }
    if (event.type === "response.done") {
      if (event.response.status !== "completed") {
        throw new Error(`Voice response ${event.response.status}.`);
      }
      break;
    }
  }
} finally {
  await connection.close();
}

실시간으로 세션 구간, 연결 구간, invoke_agent 그리고 응답별로 세션 구간, 그리고 오디오 청크별로 기록하는 것이 아닙니다. 여기에는 상태, 토큰 사용량, 오디오 바이트 수가 포함됩니다. 첫 번째 오디오 지연은 응답 생성부터 수신까지의 지연 시간을 측정하며, 사용자의 음성이나 스피커 재생에서 측정하는 것이 아닙니다. 서비스 ID는 메트릭 차원이 아닌 추적 단위로 나타납니다.

REST를 하고 project.voiceAgents.realtime 프로젝트의 추적 설정을 공유하세요. 별도로 구성된 경우 VoiceAgentRealtimeClient 는 이를 상속하지 않습니다. 입력 요약은 최신 입력을 설명하는 것이지, 전체 대화 기록을 설명하는 것은 아닙니다.

콘텐츠 녹화는 기본적으로 꺼져 있습니다. 민감한 데이터가 포함될 수 있는 텍스트, 대본, 도구 인수/결과를 기록하려는 경우에만 활성화하세요 contentRecording: true . 원본 미디어, 자격 증명, 쿼리 값, 전화번호, SDP, 그리고 원본 오류/닫기 메시지는 기록되지 않습니다. 읽기/목록 작업은 기존 HTTP 파이프라인 추적을 사용합니다.

실시간 추적 샘플과 REST 추적 샘플을 참조하세요.

Azure Monitor tracing

다음은 Azure Monitor 추적을 활성화하는 방법을 보여주는 코드 샘플입니다:

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

const projectEndpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint>";
// Configure Azure Monitor tracing (must be done before creating the client)
const connectionString =
  process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<connection string>";
useAzureMonitor({
  azureMonitorExporterOptions: { connectionString },
  samplingRatio: 1,
  tracesPerSecond: 0,
});
// Create client with tracing enabled (experimental)
const project = new AIProjectClient(projectEndpoint, new DefaultAzureCredential(), {
  tracingOptions: {
    experimental: true,
    contentRecording: false,
    traceContextPropagation: true,
  },
});

또한 시나리오에 맞는 스팬(span)을 만드는 것도 좋습니다:

import { trace, context } from "@opentelemetry/api";

const tracer = trace.getTracer("MyScenario");
const span = tracer.startSpan("myOperation");
const ctx = trace.setSpan(context.active(), span);
await context.with(ctx, async () => {
  // Your agent operations here
});
span.end();

전체 샘플 코드를 agentBasicWithAzureMonitorTracing.ts에서 확인하세요.

콘솔 추적

로컬 개발을 위해서는 콘솔로 트레이스를 출력할 수 있습니다:

import {
  NodeTracerProvider,
  SimpleSpanProcessor,
  ConsoleSpanExporter,
} from "@opentelemetry/sdk-trace-node";
import { AIProjectClient } from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";

// Set up OpenTelemetry with a console exporter (must be done before creating the client)
const provider = new NodeTracerProvider({
  spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())],
});
provider.register();
// Create client with tracing enabled (experimental)
const projectEndpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint>";
const project = new AIProjectClient(projectEndpoint, new DefaultAzureCredential(), {
  tracingOptions: {
    experimental: true,
    contentRecording: false,
    traceContextPropagation: true,
  },
});

전체 샘플 코드를 agentBasicWithConsoleTracing.ts에서 확인하세요.

콘텐츠 녹화 기능

콘텐츠 기록은 메시지 내용과 도구 호출 세부사항(매개변수 및 반환 값 등)이 트레이스에 캡처되는지 여부를 제어합니다. 이 데이터에는 민감한 사용자 정보가 포함될 수 있습니다.

콘텐츠 녹화를 활성화하려면 클라이언트를 구성할 때 패스 contentRecording: true 인 tracingOptions 을 하거나 환경 변수 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT 를 로 true설정하세요. 콘텐츠 녹화는 false기본적으로 .

트레이스 컨텍스트 전파 가능

트레이스 컨텍스트 전파는 클라이언트 측 스팬을 Azure OpenAI 및 기타 Azure 서비스의 서버 측 스팬과 상관관계 설정할 수 있게 합니다. 활성화되면 SDK는 OpenAI 클라이언트가 HTTP 요청을 통해 얻traceparent은 W3C Trace Context 헤더(tracestate와 project.getOpenAIClient())를 자동으로 주입합니다.

이로 인해 분산 트레이스 내 모든 작업이 동일한 트레이스 ID를 공유하여, 애플리케이션과 Azure 서비스 전반에 걸쳐 관측성 백엔드에서 종단 간 가시성을 제공합니다.

트레이스 컨텍스트 전파는 기본적으로 활성화되어 있습니다. 이를 비활성화하려면 클라이언트를 구성할 때 패스 traceContextPropagation: false 인 tracingOptions 을 하거나, 환경 변수 AZURE_TRACING_GEN_AI_ENABLE_TRACE_CONTEXT_PROPAGATIONfalse를 로 설정하세요.

중요한 보안 및 개인정보 보호 고려사항:

  • 트레이스 ID: 트레이스 컨텍스트 전파가 활성화되면 트레이스 ID가 Azure OpenAI 및 기타 외부 서비스로 전송됩니다.
  • 요청 상관관계: 추적 ID는 Azure 서비스가 동일한 세션 또는 사용자의 요청을 여러 API 호출에 걸쳐 상관관계로 연결할 수 있게 해주며, 사용 사례에 따라 개인정보 보호에 영향을 미칠 수 있습니다.

추적 컨텍스트 전파는 관찰 가능성, 개인정보 보호, 보안 요구사항을 신중히 검토한 후에만 활성화하세요.

문제 해결

예외

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

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

try {
  const result = await project.connections.list();
} catch (e) {
  if (isRestError(e)) {
    console.log(`Status code: ${e.code}`);
    console.log(e.message);
  } else {
    console.error(e);
  }
}

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

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

보고 문제

클라이언트 라이브러리 문제를 신고하거나 추가 기능을 요청하려면 GitHub호를 열어 here

다음 단계

package samples 폴더를 살펴보세요. 이 폴더에는 완전히 실행 가능한 코드가 들어 있습니다.

TypeSpec에서 재생성하기 (유지보수)

이 패키지는 Azure/azure-rest-api-specs의 TypeSpec 사양에서 재생성되었습니다. 여섯 개의 재생성 단계와 이슈에 할당된 오케스트레이터는 .github/skills/ 아래에 스킬로 인코딩되어 있으며, GitHub Copilot 코딩 에이전트 작업에 의해 종단 간 실행이 가능합니다.

저장소 수준의 ai-projects-regen 커스텀 에이전트는 단지 GitHub 검색 진입점일 뿐입니다. 이슈 할당 워크플로우는 패키지-로컬 run-issue-regeneration 스킬이 소유합니다.

이슈에서 워크플로우를 시작하려면 이슈 설명에 각 필요한 라벨에 대해 정확히 하나의 값을 포함하세요:

TypeSpec commit: <40-character-lowercase-SHA>
Base branch: <branch>

문제를 Copilot에 할당하고, 커스텀 에이전트를 ai-projects-regen 선택한 뒤, 설명에 명시된 동일한 시작 브랜치를 선택하세요. 에이전트는 값이 누락되었거나 유효하지 않을 때 변경을 하기 전에 중단합니다.

클라우드 에이전트 태스크로 리젠을 디스패치하려면 다음 디렉터리에서 실행하세요:

pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1                     # latest commit on feature/foundry-release
pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1 -TspCommit <sha>    # pin a specific commit
pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1 -DryRun             # render the prompt locally, do not dispatch
pwsh -NoProfile -File ./scripts/start-cloud-regen.ps1 -Repo myuser/azure-sdk-for-js -Follow   # smoke-test on a fork

Windows에서는 스크립트를 직접 호출하는 것(예: ./scripts/start-cloud-regen.ps1)이 기본 Restricted 실행 정책에 의해 차단될 수 있습니다. 위의 양식은 pwsh -NoProfile -File ... 그 부분을 우회합니다. 또는 한 번 실행 Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned 해서 로컬 스크립트를 허용하는 방법도 있습니다.

필수 조건:

  • gh CLI 가 대상 저장소에 대해 설치하고 인증()했습니다gh auth login. 서브명령어는 agent-task 미리보기 중이며 최근 gh.
  • 대상 저장소에 GitHub Copilot 코딩 에이전트가 활성화된 조직 회원 자격 요건.
  • 목표 저장소에 접근 권한을 푸시하세요(클라우드 에이전트는 자체 GitHub 앱 아이덴티티를 사용해 초안 PR을 푸시하고 엽니다).

단서: 디스패치된 프롬프트는 작업 시작 시 인라인으로 실행 pnpm install --filter "@azure/ai-projects..."pnpm turbo build --filter="@azure/ai-projects..." --token 1 됩니다. 클라우드 에이전트의 샌드박스가 네트워크 호출을 차단하면 설정 시 작업이 실패합니다; 그럴 경우 스킬을 로컬에서 실행하거나 SDK 빌드 팀과 협력해 저장소 루트에 중앙 관리 copilot-setup-steps.yml 워크플로우를 추가하세요.

기여

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

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

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