Azure.AI.Projects (.NET)
Azure AI Foundry 프로젝트 작업을 위한 고급 SDK로서, 에이전트, 연결, 데이터세트, 배포, 평가, 인덱스를 지원합니다.
설치
dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity
dotnet add package Azure.AI.Projects.OpenAI --prerelease
dotnet add package Azure.AI.Agents.Persistent --prerelease
현재 버전: GA v1.1.0, Preview v1.2.0-beta.5
환경 변수
PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>
MODEL_DEPLOYMENT_NAME=gpt-4o-mini
CONNECTION_NAME=<your-connection-name>
AI_SEARCH_CONNECTION_NAME=<ai-search-connection>
AZURE_TOKEN_CREDENTIALS=prod
인증
using Azure.Identity;
using Azure.AI.Projects;
var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
AIProjectClient projectClient = new AIProjectClient(
new Uri(endpoint),
credential);
클라이언트 계층 구조
AIProjectClient
├── Agents → AIProjectAgentsOperations (버전 관리 에이전트)
├── Connections → ConnectionsClient
├── Datasets → DatasetsClient
├── Deployments → DeploymentsClient
├── Evaluations → EvaluationsClient
├── Evaluators → EvaluatorsClient
├── Indexes → IndexesClient
├── Telemetry → AIProjectTelemetry
├── OpenAI → ProjectOpenAIClient (시험판)
└── GetPersistentAgentsClient() → PersistentAgentsClient
핵심 워크플로우
1. 영구 에이전트 클라이언트 가져오기
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
model: "gpt-4o-mini",
name: "Math Tutor",
instructions: "당신은 개인 수학 튜터입니다.");
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "3x + 11 = 14를 푸세요.");
ThreadRun run = await agentsClient.Runs.CreateRunAsync(thread.Id, agent.Id);
do
{
await Task.Delay(500);
run = await agentsClient.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);
await foreach (var msg in agentsClient.Messages.GetMessagesAsync(thread.Id))
{
foreach (var content in msg.ContentItems)
{
if (content is MessageTextContent textContent)
Console.WriteLine(textContent.Text);
}
}
await agentsClient.Threads.DeleteThreadAsync(thread.Id);
await agentsClient.Administration.DeleteAgentAsync(agent.Id);
2. 도구를 사용한 버전 관리 에이전트 (시험판)
using Azure.AI.Projects.OpenAI;
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
Instructions = "당신은 웹을 검색할 수 있는 유용한 도우미입니다.",
Tools = {
ResponseTool.CreateWebSearchTool(
userLocation: WebSearchToolLocation.CreateApproximateLocation(
country: "US",
city: "Seattle",
region: "Washington"
)
),
}
};
AgentVersion agentVersion = await projectClient.Agents.CreateAgentVersionAsync(
agentName: "myAgent",
options: new(agentDefinition));
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);
ResponseResult response = responseClient.CreateResponse("시애틀의 날씨는 어떤가요?");
Console.WriteLine(response.GetOutputText());
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
3. 연결
foreach (AIProjectConnection connection in projectClient.Connections.GetConnections())
{
Console.WriteLine($"{connection.Name}: {connection.ConnectionType}");
}
AIProjectConnection conn = projectClient.Connections.GetConnection(
connectionName,
includeCredentials: true);
AIProjectConnection defaultConn = projectClient.Connections.GetDefaultConnection(
includeCredentials: false);
4. 배포
foreach (AIProjectDeployment deployment in projectClient.Deployments.GetDeployments())
{
Console.WriteLine($"{deployment.Name}: {deployment.ModelName}");
}
foreach (var deployment in projectClient.Deployments.GetDeployments(modelPublisher: "Microsoft"))
{
Console.WriteLine(deployment.Name);
}
ModelDeployment details = (ModelDeployment)projectClient.Deployments.GetDeployment("gpt-4o-mini");
5. 데이터세트
FileDataset fileDataset = projectClient.Datasets.UploadFile(
name: "my-dataset",
version: "1.0",
filePath: "data/training.txt",
connectionName: connectionName);
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
name: "my-dataset",
version: "2.0",
folderPath: "data/training",
connectionName: connectionName,
filePattern: new Regex(".*\\.txt"));
AIProjectDataset dataset = projectClient.Datasets.GetDataset("my-dataset", "1.0");
projectClient.Datasets.Delete("my-dataset", "1.0");
6. 인덱스
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
Description = "샘플 인덱스"
};
searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
name: "my-index",
version: "1.0",
index: searchIndex);
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
Console.WriteLine(index.Name);
}
projectClient.Indexes.Delete(name: "my-index", version: "1.0");
7. 평가
var evaluatorConfig = new EvaluatorConfiguration(id: EvaluatorIDs.Relevance);
evaluatorConfig.InitParams.Add("deployment_name", BinaryData.FromObjectAsJson("gpt-4o"));
Evaluation evaluation = new Evaluation(
data: new InputDataset("<dataset_id>"),
evaluators: new Dictionary<string, EvaluatorConfiguration>
{
{ "relevance", evaluatorConfig }
}
)
{
DisplayName = "샘플 평가"
};
Evaluation result = projectClient.Evaluations.Create(evaluation: evaluation);
Evaluation getResult = projectClient.Evaluations.Get(result.Name);
foreach (var eval in projectClient.Evaluations.GetAll())
{
Console.WriteLine($"{eval.DisplayName}: {eval.Status}");
}
8. Azure OpenAI 채팅 클라이언트 가져오기
using Azure.AI.OpenAI;
using OpenAI.Chat;
ClientConnection connection = projectClient.GetConnection(typeof(AzureOpenAIClient).FullName!);
if (!connection.TryGetLocatorAsUri(out Uri uri) || uri is null)
throw new InvalidOperationException("잘못된 URI입니다.");
uri = new Uri($"https://{uri.Host}");
AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient(uri, new DefaultAzureCredential());
ChatClient chatClient = azureOpenAIClient.GetChatClient("gpt-4o-mini");
ChatCompletion result = chatClient.CompleteChat("무지개 색상을 모두 나열하세요.");
Console.WriteLine(result.Content[0].Text);
사용 가능한 에이전트 도구
| 도구 | 클래스 | 목적 |
|---|
| 코드 인터프리터 | CodeInterpreterToolDefinition | Python 코드 실행 |
| 파일 검색 | FileSearchToolDefinition | 업로드된 파일 검색 |
| 함수 호출 | FunctionToolDefinition | 사용자 정의 함수 호출 |
| Bing 접지 | BingGroundingToolDefinition | Bing을 통한 웹 검색 |
| Azure AI Search | AzureAISearchToolDefinition | Azure AI 인덱스 검색 |
| OpenAPI | OpenApiToolDefinition | 외부 API 호출 |
| Azure Functions | AzureFunctionToolDefinition | Azure Functions 호출 |
| MCP | MCPToolDefinition | 모델 컨텍스트 프로토콜 도구 |
주요 형식 참조
| 형식 | 목적 |
|---|
AIProjectClient | 주 진입점 |
PersistentAgentsClient | 저수준 에이전트 작업 |
PromptAgentDefinition | 버전 관리 에이전트 정의 |
AgentVersion | 버전 관리 에이전트 인스턴스 |
AIProjectConnection | Azure 리소스에 대한 연결 |
AIProjectDeployment | 모델 배포 정보 |
AIProjectDataset | 데이터세트 메타데이터 |
AIProjectIndex | 검색 인덱스 메타데이터 |
Evaluation | 평가 구성 및 결과 |
모범 사례
- 프로덕션 인증에는
DefaultAzureCredential 사용
- 모든 I/O 작업에는 비동기 메서드(
*Async) 사용
- 실행 대기 시 적절한 지연 시간(500ms 권장)으로 폴링
- 리소스 정리 — 작업 완료 후 스레드, 에이전트, 파일 삭제
- 프로덕션 시나리오에서는 (
Azure.AI.Projects.OpenAI를 통한) 버전 관리 에이전트 사용
- 도구 구성 시 이름보다 연결 ID 저장
- **
includeCredentials: true**는 자격 증명이 필요한 경우에만 사용
- 페이징 처리 — 목록 작업에는
AsyncPageable<T> 사용
오류 처리
using Azure;
try
{
var result = await projectClient.Evaluations.CreateAsync(evaluation);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"오류: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
관련 SDK
| SDK | 목적 | 설치 |
|---|
Azure.AI.Projects | 고급 프로젝트 클라이언트 (이 SDK) | dotnet add package Azure.AI.Projects |
Azure.AI.Agents.Persistent | 저수준 에이전트 작업 | dotnet add package Azure.AI.Agents.Persistent |
Azure.AI.Projects.OpenAI | OpenAI를 사용한 버전 관리 에이전트 | dotnet add package Azure.AI.Projects.OpenAI |
참조 링크