코드 인터프리터를 사용하면 Microsoft Foundry 에이전트가 샌드박스 실행 환경에서 Python 코드를 실행할 수 있습니다. 이 도구를 사용하여 코드 실행의 이점을 활용하는 데이터 분석, 차트 생성 및 반복적인 문제 해결 작업을 수행할 수 있습니다.
이 문서에서는 코드 인터프리터를 사용하는 에이전트를 만들고, 분석을 위해 CSV 파일을 업로드하고, 생성된 차트를 다운로드합니다.
사용하도록 설정하면 에이전트가 Python 코드를 반복적으로 작성하고 실행하여 데이터 분석 및 수학 작업을 해결하고 차트를 생성할 수 있습니다.
중요합니다
코드 인터프리터는 Azure OpenAI 사용량에 대한 토큰 기반 요금 외에 추가 요금이 부과 됩니다. 에이전트가 서로 다른 두 대화에서 동시에 코드 인터프리터를 호출하는 경우 두 개의 코드 인터프리터 세션이 만들어집니다. 각 세션은 기본적으로 1시간 동안 활성화되며 유휴 시간 제한은 30분입니다.
사용량 지원
✔️ (GA)는 일반 가용성을 ✔️ 나타내고(미리 보기)는 공개 미리 보기를 나타내고 대시(-)는 기능을 사용할 수 없음을 나타냅니다.
| Microsoft Foundry 지원 | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API | 기본 에이전트 설정 | 표준 에이전트 설정 |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ (미리 보기) | ✔️ (미리 보기) | ✔️ (미리 보기) | - | - | ✔️ | ✔️ |
필수 조건
- 기본 또는 표준 에이전트 환경입니다. 자세한 내용은 에이전트 환경 설정을 참조하세요.
- 최신 시험판 SDK 패키지가 설치되었습니다(
azure-ai-projects>=2.0.0b4Python용). 설치 단계는 빠른 시작을 참조하세요. - 프로젝트에 구성된 Azure AI 모델 배포입니다.
- 파일 작업의 경우: 분석을 위해 업로드할 CSV 또는 기타 지원되는 파일입니다.
비고
코드 인터프리터는 모든 지역에서 사용할 수 없습니다. 지역 및 모델 가용성 확인을 참조하세요.
코드 인터프리터를 사용하여 에이전트 만들기
다음 샘플에서는 코드 인터프리터를 사용하도록 설정된 에이전트를 만들고, 분석을 위해 파일을 업로드하고, 생성된 출력을 다운로드하는 방법을 보여 줍니다.
비고
최신 시험판 패키지가 필요합니다. 자세한 내용은 빠른 시작을 참조하세요.
Python SDK에서 코드 인터프리터 도구와 함께 에이전트 사용 샘플
다음 Python 샘플에서는 코드 인터프리터 도구를 사용하여 에이전트를 만들고, 분석을 위해 CSV 파일을 업로드하고, 데이터를 기반으로 가로 막대형 차트를 요청하는 방법을 보여 줍니다. 파일을 업로드하고, 코드 인터프리터를 사용하도록 설정된 에이전트를 만들고, 데이터 시각화를 요청하고, 생성된 차트를 다운로드하는 전체 워크플로를 보여 줍니다.
다음 환경 변수를 설정합니다.
FOUNDRY_PROJECT_ENDPOINTFOUNDRY_MODEL_DEPLOYMENT_NAME
import os
from dotenv import load_dotenv
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, CodeInterpreterTool, CodeInterpreterContainerAuto
load_dotenv()
# Load the CSV file to be processed
asset_file_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), "../assets/synthetic_500_quarterly_results.csv")
)
endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
with (
DefaultAzureCredential() as credential,
AIProjectClient(endpoint=endpoint, credential=credential) as project_client,
project_client.get_openai_client() as openai_client,
):
# Upload the CSV file for the code interpreter to use
file = openai_client.files.create(purpose="assistants", file=open(asset_file_path, "rb"))
print(f"File uploaded (id: {file.id})")
# Create agent with code interpreter tool
agent = project_client.agents.create_version(
agent_name="MyAgent",
definition=PromptAgentDefinition(
model=os.environ["FOUNDRY_MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful assistant.",
tools=[CodeInterpreterTool(container=CodeInterpreterContainerAuto(file_ids=[file.id]))],
),
description="Code interpreter agent for data analysis and visualization.",
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
# Create a conversation for the agent interaction
conversation = openai_client.conversations.create()
print(f"Created conversation (id: {conversation.id})")
# Send request to create a chart and generate a file
response = openai_client.responses.create(
conversation=conversation.id,
input="Could you please create bar chart in TRANSPORTATION sector for the operating profit from the uploaded csv file and provide file to me?",
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
print(f"Response completed (id: {response.id})")
# Extract file information from response annotations
file_id = ""
filename = ""
container_id = ""
# Get the last message which should contain file citations
last_message = response.output[-1] # ResponseOutputMessage
if (
last_message.type == "message"
and last_message.content
and last_message.content[-1].type == "output_text"
and last_message.content[-1].annotations
):
file_citation = last_message.content[-1].annotations[-1] # AnnotationContainerFileCitation
if file_citation.type == "container_file_citation":
file_id = file_citation.file_id
filename = file_citation.filename
container_id = file_citation.container_id
print(f"Found generated file: {filename} (ID: {file_id})")
print("\nCleaning up...")
project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Agent deleted")
# Download the generated file if available
if file_id and filename:
file_content = openai_client.containers.files.content.retrieve(file_id=file_id, container_id=container_id)
print(f"File ready for download: {filename}")
file_path = os.path.join(os.path.dirname(__file__), filename)
with open(file_path, "wb") as f:
f.write(file_content.read())
print(f"File downloaded successfully: {file_path}")
else:
print("No file generated in response")
예상 출력
샘플 코드는 다음 예제와 유사한 출력을 생성합니다.
File uploaded (id: file-xxxxxxxxxxxxxxxxxxxx)
Agent created (id: agent-xxxxxxxxxxxxxxxxxxxx, name: MyAgent, version: 1)
Created conversation (id: conv-xxxxxxxxxxxxxxxxxxxx)
Response completed (id: resp-xxxxxxxxxxxxxxxxxxxx)
Found generated file: transportation_operating_profit_bar_chart.png (ID: file-xxxxxxxxxxxxxxxxxxxx)
File transportation_operating_profit_bar_chart.png downloaded successfully.
File ready for download: transportation_operating_profit_bar_chart.png
에이전트는 CSV 파일을 Azure Storage에 업로드하고, 샌드박스가 있는 Python 환경을 만들고, 데이터를 분석하여 운송 부문 레코드를 필터링하고, 분기별 영업 이익을 보여 주는 PNG 막대형 차트를 생성하고, 차트를 로컬 디렉터리에 다운로드합니다. 응답의 파일 주석은 생성된 차트를 검색하는 데 필요한 파일 ID 및 컨테이너 정보를 제공합니다.
C# SDK에서 코드 인터프리터 및 파일 첨부 파일과 함께 에이전트 사용 샘플
다음 C# 샘플에서는 코드 인터프리터 도구를 사용하여 에이전트를 만들고 수학 방정식을 해결하도록 요청하는 방법을 보여줍니다. 환경 변수 값(FOUNDRY_PROJECT_ENDPOINT, FOUNDRY_MODEL_DEPLOYMENT_NAME)을 실제 리소스 세부 정보로 바꿉니다. 에이전트는 샌드박스 컨테이너에서 Python 코드를 실행하여 솔루션을 계산합니다. 코드는 단순성을 위해 동기 호출을 사용합니다. 비동기 사용의 경우 GitHub의 .NET용 Azure SDK 리포지토리의 코드 샘플을 참조하세요.
// Create project client and read the environment variables, which will be used in the next steps.
var projectEndpoint = System.Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT");
var modelDeploymentName = System.Environment.GetEnvironmentVariable("FOUNDRY_MODEL_DEPLOYMENT_NAME");
AIProjectClient projectClient = new(endpoint: new Uri(projectEndpoint), tokenProvider: new DefaultAzureCredential());
// Create Agent, capable to use Code Interpreter to answer questions.
PromptAgentDefinition agentDefinition = new(model: modelDeploymentName)
{
Instructions = "You are a helpful agent that can help fetch data from files you know about.",
Tools = {
ResponseTool.CreateCodeInterpreterTool(
new CodeInterpreterToolContainer(
CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration(
fileIds: []
)
)
),
}
};
AgentVersion agentVersion = projectClient.Agents.CreateAgentVersion(
agentName: "myAgent",
options: new(agentDefinition));
// Ask the agent a question, which requires running python code in the container.
AgentReference agentReference = new(name: agentVersion.Name, version: agentVersion.Version);
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentReference);
ResponseResult response = responseClient.CreateResponse("I need to solve the equation sin(x) + x^2 = 42");
// Write out the output of a response, raise the exception if the request was not successful.
Assert.That(response.Status, Is.EqualTo(ResponseStatus.Completed));
Console.WriteLine(response.GetOutputText());
// Clean up resources by deleting conversations and the Agent.
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
예상 출력
샘플 코드는 다음 예제와 유사한 출력을 생성합니다.
Response completed (id: resp-xxxxxxxxxxxxxxxxxxxx)
The solution to the equation sin(x) + x^2 = 42 is approximately x = 6.324555320336759
에이전트는 코드 인터프리터 세션을 만들고, 수식을 숫자로 해결하는 Python 코드를 작성하고, 샌드박스가 지정된 환경에서 코드를 실행하고, 계산된 결과를 반환합니다. 에이전트는 초기 코드가 유효한 솔루션을 생성하지 않는 경우 해당 접근 방식을 반복적으로 구체화합니다.
TypeScript SDK에서 코드 인터프리터 도구와 함께 에이전트 사용 샘플
다음 TypeScript 샘플에서는 코드 인터프리터 도구를 사용하여 에이전트를 만들고, 분석을 위해 CSV 파일을 업로드하고, 데이터를 기반으로 가로 막대형 차트를 요청하는 방법을 보여 줍니다. JavaScript 버전의 경우 GitHub의 JavaScript 리포지토리용 Azure SDK에서 JavaScript 샘플을 참조하세요.
다음 환경 변수를 설정합니다.
FOUNDRY_PROJECT_ENDPOINTFOUNDRY_MODEL_DEPLOYMENT_NAME
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";
import { fileURLToPath } from "url";
import "dotenv/config";
const projectEndpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "<project endpoint>";
const deploymentName =
process.env["FOUNDRY_MODEL_DEPLOYMENT_NAME"] || "<model deployment name>";
// Helper to resolve asset file path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export async function main(): Promise<void> {
// Create AI Project client
const project = new AIProjectClient(projectEndpoint, new DefaultAzureCredential());
const openAIClient = await project.getOpenAIClient();
// Load and upload CSV file
const assetFilePath = path.resolve(
__dirname,
"../assets/synthetic_500_quarterly_results.csv",
);
const fileStream = fs.createReadStream(assetFilePath);
console.log("Uploading CSV file...");
const uploadedFile = await openAIClient.files.create({
file: fileStream,
purpose: "assistants",
});
console.log(`File uploaded (id: ${uploadedFile.id})`);
// Create agent with Code Interpreter tool
console.log("Creating agent with Code Interpreter tool...");
const agent = await project.agents.createVersion("MyAgent", {
kind: "prompt",
model: deploymentName,
instructions: "You are a helpful assistant.",
tools: [
{
type: "code_interpreter",
container: {
type: "auto",
file_ids: [uploadedFile.id],
},
},
],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Create a conversation
const conversation = await openAIClient.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Request chart generation
console.log("\nRequesting chart generation...");
const response = await openAIClient.responses.create(
{
conversation: conversation.id,
input:
"Could you please create bar chart in TRANSPORTATION sector for the operating profit from the uploaded csv file and provide file to me?",
},
{
body: { agent: { name: agent.name, type: "agent_reference" } },
},
);
console.log(`Response completed (id: ${response.id})`);
// Extract file information from response annotations
let fileId = "";
let filename = "";
let containerId = "";
// Get the last message which should contain file citations
const lastMessage = response.output?.[response.output.length - 1];
if (lastMessage && lastMessage.type === "message") {
// Get the last content item
const textContent = lastMessage.content?.[lastMessage.content.length - 1];
if (textContent && textContent.type === "output_text" && textContent.annotations) {
// Get the last annotation (most recent file)
const fileCitation = textContent.annotations[textContent.annotations.length - 1];
if (fileCitation && fileCitation.type === "container_file_citation") {
fileId = fileCitation.file_id;
filename = fileCitation.filename;
containerId = fileCitation.container_id;
console.log(`Found generated file: ${filename} (ID: ${fileId})`);
}
}
}
// Download the generated file if available
if (fileId && filename) {
const safeFilename = path.basename(filename);
const fileContent = await openAIClient.containers.files.content.retrieve({
file_id: fileId,
container_id: containerId,
});
// Read the readable stream into a buffer
const chunks: Buffer[] = [];
for await (const chunk of fileContent.body) {
chunks.push(Buffer.from(chunk));
}
const buffer = Buffer.concat(chunks);
fs.writeFileSync(safeFilename, buffer);
console.log(`File ${safeFilename} downloaded successfully.`);
console.log(`File ready for download: ${safeFilename}`);
} else {
console.log("No file generated in response");
}
// Clean up resources
console.log("\nCleaning up...");
await project.agents.deleteVersion(agent.name, agent.version);
console.log("Agent deleted");
console.log("\nCode Interpreter sample completed!");
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
예상 출력
샘플 코드는 다음 예제와 유사한 출력을 생성합니다.
Uploading CSV file...
File uploaded (id: file-xxxxxxxxxxxxxxxxxxxx)
Creating agent with Code Interpreter tool...
Agent created (id: agent-xxxxxxxxxxxxxxxxxxxx, name: MyAgent, version: 1)
Created conversation (id: conv-xxxxxxxxxxxxxxxxxxxx)
Requesting chart generation...
Response completed (id: resp-xxxxxxxxxxxxxxxxxxxx)
Found generated file: transportation_operating_profit_bar_chart.png (ID: file-xxxxxxxxxxxxxxxxxxxx)
File transportation_operating_profit_bar_chart.png downloaded successfully.
File ready for download: transportation_operating_profit_bar_chart.png
Cleaning up...
Agent deleted
Code Interpreter sample completed!
에이전트는 CSV 파일을 Azure Storage에 업로드하고, 샌드박스가 있는 Python 환경을 만들고, 데이터를 분석하여 운송 부문 레코드를 필터링하고, 분기별 영업 이익을 보여 주는 PNG 막대형 차트를 생성하고, 차트를 로컬 디렉터리에 다운로드합니다. 응답의 파일 주석은 생성된 차트를 검색하는 데 필요한 파일 ID 및 컨테이너 정보를 제공합니다.
지역 및 모델 가용성 확인
도구 가용성은 지역 및 모델에 따라 다릅니다.
코드 인터프리터에 대해 지원되는 지역 및 모델의 현재 목록은 Microsoft Foundry 에이전트 서비스의 도구 사용에 대한 모범 사례를 참조하세요.
지원되는 파일 형식
| 파일 형식 | MIME type |
|---|---|
.c |
text/x-c |
.cpp |
text/x-c++ |
.csv |
application/csv |
.docx |
application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.html |
text/html |
.java |
text/x-java |
.json |
application/json |
.md |
text/markdown |
.pdf |
application/pdf |
.php |
text/x-php |
.pptx |
application/vnd.openxmlformats-officedocument.presentationml.presentation |
.py |
text/x-python |
.py |
text/x-script.python |
.rb |
text/x-ruby |
.tex |
text/x-tex |
.txt |
text/plain |
.css |
text/css |
.jpeg |
image/jpeg |
.jpg |
image/jpeg |
.js |
text/javascript |
.gif |
image/gif |
.png |
image/png |
.tar |
application/x-tar |
.ts |
application/typescript |
.xlsx |
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.xml |
application/xml 또는 text/xml |
.zip |
application/zip |
Java SDK 제한 사항
코드 인터프리터 도구는 현재 Foundry 에이전트용 Java SDK에서 지원되지 않습니다. Java 애플리케이션에서 코드 인터프리터 기능이 필요한 경우 REST API를 직접 사용하거나 지원되는 다른 SDK(Python, C# 또는 TypeScript/JavaScript)를 사용하는 것이 좋습니다.
최신 SDK 지원 상태는 Microsoft Foundry 에이전트 서비스의 도구 사용에 대한 모범 사례를 참조하세요.
문제 해결
| 문제 | 가능한 원인 | 해결 방법 |
|---|---|---|
| 코드 인터프리터가 실행되지 않습니다. | 도구를 사용하도록 설정하지 않았거나 모델이 해당 지역에서 지원하지 않습니다. | 에이전트에서 코드 인터프리터가 사용하도록 설정되어 있는지 확인합니다. 모델 배포가 해당 지역의 도구를 지원하는지 확인합니다. 지역 및 모델 가용성 확인을 참조하세요. |
| 파일이 생성되지 않습니다. | 에이전트는 파일 주석 없이 텍스트 전용 응답을 반환했습니다. |
container_file_citation의 응답 주석을 확인합니다. 존재하지 않는 경우 에이전트가 파일을 생성하지 않았습니다. 파일 출력을 명시적으로 요청하도록 프롬프트를 다시 지정합니다. |
| 파일 업로드가 실패합니다. | 지원되지 않는 파일 형식 또는 잘못된 용도입니다. | 파일 형식이 지원되는 파일 형식 목록에 있는지 확인합니다. 업로드하는 데 purpose="assistants"를 사용합니다. |
| 생성된 파일이 손상되었거나 비어 있습니다. | 코드 실행 오류 또는 불완전한 처리입니다. | 에이전트의 응답에서 오류 메시지를 확인합니다. 입력 데이터가 유효한지 확인합니다. 먼저 더 간단한 요청을 시도합니다. |
| 세션 시간 제한 또는 높은 대기 시간. | 코드 인터프리터 세션에는 시간 제한이 있습니다. | 세션에는 1시간의 활성 시간 제한과 30분 유휴 시간 제한이 있습니다. 작업의 복잡성을 줄이거나 더 작은 작업으로 분할합니다. |
| 예기치 않은 청구 요금입니다. | 여러 개의 동시 세션이 생성되었습니다. | 각 대화는 별도의 세션을 만듭니다. 가능한 경우 세션 사용량을 모니터링하고 작업을 통합합니다. |
| Python 패키지를 사용할 수 없습니다. | 코드 인터프리터에는 고정된 패키지 집합이 있습니다. | 코드 인터프리터는 일반적인 데이터 과학 패키지를 포함합니다. 사용자 지정 패키지의 경우 사용자 지정 코드 인터프리터를 사용합니다. |
| 파일 다운로드가 실패합니다. | 컨테이너 ID 또는 파일 ID가 잘못되었습니다. | 올바른 container_id 및 file_id을(를) 응답 주석에서 사용하고 있는지 확인하십시오. |
자원을 정리하세요
지속적인 비용을 방지하기 위해 더 이상 필요하지 않은 경우 이 샘플에서 만든 리소스를 삭제합니다.
- 에이전트 버전을 삭제합니다.
- 대화를 삭제합니다.
- 업로드된 파일을 삭제합니다.
대화 및 파일 정리 패턴의 예는 에이전트에 대한 웹 검색 도구(미리 보기) 및 파일 검색 도구를 참조하세요.