Code Interpreter 讓 Microsoft Foundry 代理能在沙盒執行環境中執行 Python 程式碼。 代理的 Foundry 模型負責撰寫並執行資料分析、圖表產生及迭代問題解決任務的程式碼。
在本文中,你要建立一個使用 Code Interpreter 的代理,上傳 CSV 檔案進行分析,並下載產生的圖表。
啟用 Code Interpreter 後,代理可以反覆撰寫並執行 Python 程式碼,以解決資料分析與數學任務,並產生圖表。
重要
對於 Azure OpenAI 使用量,程式碼解譯器除了以權杖為基礎的費用外,還有額外費用。 如果您的 Agent 在兩個不同的交談中同時呼叫程式碼解譯器,將會建立兩個程式碼解譯器工作階段。 每個會話預設為一小時,閒置時間為 30 分鐘。
先決條件
- 基本或標準代理環境。 詳情請參閱 代理環境設定 。
- 安裝了針對你語言的最新 SDK 套件。 .NET SDK 目前處於預覽階段。 請參閱 快速入門 頁面了解安裝步驟。
- 在您的專案中已設定 Azure AI 模型部署。
註
Code Interpreter 並非所有地區都有提供。 請參見 「檢查區域與型號可用性」。
使用支援
下表顯示 SDK 與設定支援。
| Microsoft Foundry 支援 | Python SDK | C# SDK | JavaScript SDK | Java 開發套件 | REST API | 基本代理設定 | 標準代理設定 |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
用 Code Interpreter 建立代理
以下範例示範如何啟用 Code Interpreter 建立代理程式,上傳分析檔案,並下載產生的輸出。 每個檔案上傳範例會在目前的工作目錄中產生一個小型 CSV,上傳後刪除本地暫存檔案。
提示
你可以在執行時自訂 Code Interpreter 的行為,例如指定要包含哪些檔案,或透過結構 化輸入調整每個請求的工具參數。
在 Python SDK 中使用代理程式與程式碼直譯工具的範例
以下的 Python 範例展示了如何將程式碼直譯工具加入工具箱、將工具箱附加到代理程式、上傳 CSV 檔案以供分析,以及根據資料請求長條圖。 選擇 Prompt Agents 以使用 Azure AI Projects SDK 建立伺服器端提示代理,或選擇 Hosted Agents 使用 Agent Framework FoundryChatClient 建立臨時且進行中的代理。
提示詞 Agent
此範例展示了完整的工作流程:上傳檔案、建立啟用 Code Interpreter 的代理程式、請求資料視覺化,並下載產生的圖表。
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, CodeInterpreterTool, AutoCodeInterpreterToolParam
CSV_DATA = """name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
"""
csv_path = os.path.abspath("synthetic-company-financial-results.csv")
with open(csv_path, "w", encoding="utf-8", newline="") as csv_file:
csv_file.write(CSV_DATA)
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Upload the generated CSV file for the code interpreter to use
with open(csv_path, "rb") as csv_file:
file = openai.files.create(purpose="assistants", file=csv_file)
os.remove(csv_path)
# Create agent with code interpreter tool
agent = project.agents.create_version(
agent_name="MyAgent",
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="You are a helpful assistant.",
tools=[CodeInterpreterTool(container=AutoCodeInterpreterToolParam(file_ids=[file.id]))],
),
description="Code interpreter agent for data analysis and visualization.",
)
# Create a conversation for the agent interaction
conversation = openai.conversations.create()
# Send request to create a chart and generate a file
response = openai.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"}},
)
# 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})")
# Clean up resources
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
# Download the generated file if available
if file_id and filename:
file_content = openai.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")
預期產出
範例程式碼輸出類似以下範例:
Found generated file: transportation_operating_profit_bar_chart.png (ID: file-xxxxxxxxxxxxxxxxxxxx)
File ready for download: transportation_operating_profit_bar_chart.png
File downloaded successfully: transportation_operating_profit_bar_chart.png
代理程式會將您的 CSV 檔案上傳到 Azure 儲存,建立沙盒式 Python 環境,篩選運輸業公司,產生顯示各公司營運利潤的 PNG 長條圖,並將圖表下載到您的本地目錄。 回應中的檔案註解提供了取得產生圖表所需的檔案 ID 與容器資訊。
託管代理
此範例會建立程式碼解譯器工具箱,接著使用來自 Microsoft Agent Framework 的 FoundryChatClient,並使用 FoundryToolbox 連線到工具箱的 MCP 端點。 設定 FOUNDRY_PROJECT_ENDPOINT 和 FOUNDRY_MODEL 環境變數,並用 az login登入 。
import asyncio
import os
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient, FoundryToolbox
from azure.identity import AzureCliCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import CodeInterpreterToolboxTool, AutoCodeInterpreterToolParam
PROJECT_ENDPOINT = "https://<account>.services.ai.azure.com/api/projects/<project>"
CSV_DATA = """name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
"""
async def main() -> None:
credential = AzureCliCredential()
csv_path = os.path.abspath("synthetic-company-financial-results.csv")
with open(csv_path, "w", encoding="utf-8", newline="") as csv_file:
csv_file.write(CSV_DATA)
# 1. Add the code interpreter tool to a toolbox. Using a toolbox is the recommended way
# to give agents tools: you curate tools once and reuse the toolbox across agents.
# See /azure/foundry/agents/concepts/toolbox-overview
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=credential)
openai = project.get_openai_client()
with open(csv_path, "rb") as csv_file:
file = openai.files.create(purpose="assistants", file=csv_file)
os.remove(csv_path)
toolbox = project.toolboxes.create_version(
name="code-interpreter-toolbox",
description="Toolbox with the code interpreter tool",
tools=[CodeInterpreterToolboxTool(container=AutoCodeInterpreterToolParam(file_ids=[file.id]))],
)
# 2. The toolbox exposes an MCP-compatible endpoint.
TOOLBOX_MCP_URL = (
f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
f"/versions/{toolbox.version}/mcp?api-version=v1"
)
# 3. Attach the toolbox to the hosted agent as an MCP tool.
, timeout=120.0)
toolbox_tool = FoundryToolbox(credential, url=TOOLBOX_MCP_URL)
agent = Agent(
client=FoundryChatClient(credential=credential),
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
tools=[toolbox_tool],
)
result = await agent.run("Use code to calculate the factorial of 100.")
print(f"Agent: {result.text}")
if __name__ == "__main__":
asyncio.run(main())
預期產出
代理程式產生 Python 程式碼,在沙盒容器中執行,並回傳答案:
Agent: 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
完整範例(包括檔案輸入及產生程式碼的解壓),請參見 foundry_chat_client_with_code_interpreter.py 和 foundry_chat_client_code_interpreter_files.py。
用 C 語言的 Code Interpreter 建立一張圖表#
以下 C# 範例展示了如何將程式碼直譯器工具加入工具箱、將工具箱附加到代理程式、上傳 CSV 檔案進行分析,以及下載產生的圖表。 選擇 Prompt Agents 以使用 Azure AI Projects SDK 建立伺服器端提示代理,或選擇 Hosted Agents 使用 Microsoft 代理框架建立一個短暫且進行中的代理。
提示詞 Agent
關於非同步使用,請參閱 GitHub 上 Azure SDK 的 .NET 資料庫中的 程式碼範例。
using System;
using System.IO;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using OpenAI.Files;
const string CsvData = """
name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
""";
string csvPath = Path.GetFullPath("synthetic-company-financial-results.csv");
File.WriteAllText(csvPath, CsvData);
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Upload a CSV file for Code Interpreter to analyze
OpenAIFileClient fileClient = projectClient.ProjectOpenAIClient.GetOpenAIFileClient();
OpenAIFile uploadedFile = fileClient.UploadFile(
filePath: csvPath,
purpose: FileUploadPurpose.Assistants);
File.Delete(csvPath);
Console.WriteLine($"Uploaded file: {uploadedFile.Id}");
// Create an agent with Code Interpreter enabled
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
Instructions = "You are a helpful assistant.",
Tools = {
ResponseTool.CreateCodeInterpreterTool(
new CodeInterpreterToolContainer(
CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration(
fileIds: [uploadedFile.Id]
)
)
),
}
};
ProjectsAgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myChartAgent",
options: new(agentDefinition));
// Request chart generation from the uploaded CSV data
AgentReference agentReference = new(name: agentVersion.Name, version: agentVersion.Version);
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentReference);
ResponseResult response = responseClient.CreateResponse(
"Could you please create bar chart in TRANSPORTATION sector for the operating profit " +
"from the uploaded csv file and provide file to me?");
Console.WriteLine(response.GetOutputText());
// Extract file information from response annotations
ContainerFileCitationMessageAnnotation containerAnnotation = null;
foreach (ResponseItem item in response.OutputItems)
{
if (item is MessageResponseItem messageItem)
{
foreach (ResponseContentPart content in messageItem.Content)
{
foreach (ResponseMessageAnnotation annotation in content.OutputTextAnnotations)
{
if (annotation is ContainerFileCitationMessageAnnotation cntrAnnotation)
{
containerAnnotation = cntrAnnotation;
}
}
}
}
}
// Download the generated chart if available
if (containerAnnotation is not null)
{
ContainerClient containerClient = projectClient.ProjectOpenAIClient.GetContainerClient();
BinaryData fileData = containerClient.DownloadContainerFile(
containerId: containerAnnotation.ContainerId,
fileId: containerAnnotation.FileId);
File.WriteAllBytes("chart.png", fileData.ToArray());
Console.WriteLine($"Chart downloaded: {Path.GetFullPath("chart.png")}");
}
else
{
Console.WriteLine("No file generated in response");
}
// Clean up resources
projectClient.AgentAdministrationClient.DeleteAgentVersion(
agentName: agentVersion.Name, agentVersion: agentVersion.Version);
預期產出
範例程式碼輸出類似以下範例:
Uploaded file: file-xxxxxxxxxxxxxxxxxxxx
Here is the bar chart showing operating profit by company in the TRANSPORTATION sector...
Chart downloaded: C:\Users\you\chart.png
代理會將你的 CSV 檔案上傳到 Azure 儲存,建立沙盒式的 Python 環境,分析資料以篩選運輸部門紀錄,並產生 PNG 長條圖。 註解解析會從回應中擷取容器 ID 和檔案 ID,這些資料用來將圖表下載到你的本地目錄。
託管代理
此範例建立程式碼直譯器工具箱,並利用 Microsoft Agent Framework AddFoundryToolboxes 整合,使程式碼直譯器可供託管代理使用。 設定 AZURE_AI_PROJECT_ENDPOINT、AZURE_OPENAI_ENDPOINT 和 AZURE_AI_MODEL_DEPLOYMENT_NAME 環境變數,並使用 az login 登入。
using System;
using System.IO;
using Azure.AI.AgentServer.Responses;
using Azure.AI.AgentServer.Responses.Models;
using Azure.AI.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OpenAI.Chat;
using OpenAI.Files;
const string CsvData = """
name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
""";
const string AgentInstructions = "You are a personal math tutor. When asked a math question, write and run code using the python tool to answer the question.";
const string AgentName = "CoderAgent";
string projectEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
?? "https://<account>.services.ai.azure.com/api/projects/<project>";
string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5-mini";
DefaultAzureCredential credential = new();
// 1. Add the code interpreter tool to a toolbox. Using a toolbox is the recommended
// way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
AIProjectClient projectClient = new(endpoint: new Uri(projectEndpoint), tokenProvider: credential);
OpenAIFileClient fileClient = projectClient.ProjectOpenAIClient.GetOpenAIFileClient();
string csvPath = Path.GetFullPath("synthetic-company-financial-results.csv");
File.WriteAllText(csvPath, CsvData);
OpenAIFile uploadedFile = fileClient.UploadFile(
filePath: csvPath,
purpose: FileUploadPurpose.Assistants);
File.Delete(csvPath);
ProjectsAgentTool codeInterpreterTool = ProjectsAgentTool.AsProjectTool(
ResponseTool.CreateCodeInterpreterTool(
new CodeInterpreterToolContainer(
CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration(
fileIds: [uploadedFile.Id]
)
)
));
ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
.GetAgentToolboxes().CreateToolboxVersion(
toolboxName: "code-interpreter-toolbox",
tools: [codeInterpreterTool],
description: "Toolbox with the code interpreter tool");
// Create the hosted agent and register the toolbox integration.
AIAgent agent = projectClient.AsAIAgent(
model: deploymentName,
instructions: "You are a helpful assistant with access to the toolbox tools.",
name: "hosted-toolbox-agent");
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFoundryResponses(agent);
builder.Services.AddFoundryToolboxes(credential, toolboxVersion.Name);
var app = builder.Build();
app.MapFoundryResponses();
app.Run();
預期產出
託管代理使用工具箱 MCP 端點在沙盒中執行 Python,並回傳最終答案:
Response: One solution is x ≈ 6.36, since sin(x) + x^2 is approximately 42 at that value.
關於維護的 .NET 代理框架整合,請參見「使用工具箱搭配託管代理」。
在 TypeScript SDK 中使用代理程式與程式碼直譯工具的範例
以下 TypeScript 範例展示了如何將程式碼直譯工具加入工具箱、將工具箱附加到代理程式、上傳 CSV 檔案進行分析,以及根據資料請求長條圖。 關於 JavaScript 版本,請參閱 GitHub Azure SDK for JavaScript repository 中的 JavaScript 範例。
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const CSV_DATA = `name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
`;
export async function main(): Promise<void> {
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Generate and upload the CSV file
const csvPath = "synthetic-company-financial-results.csv";
fs.writeFileSync(csvPath, CSV_DATA);
const fileStream = fs.createReadStream(csvPath);
// Upload CSV file
const uploadedFile = await openai.files.create({
file: fileStream,
purpose: "assistants",
});
fs.unlinkSync(csvPath);
console.log("Creating a toolbox with the code interpreter tool...");
// 1. Add the code interpreter tool to a toolbox. Using a toolbox is the recommended
// way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
const toolbox = await project.toolboxes.createVersion(
"code-interpreter-toolbox",
[
{
type: "code_interpreter",
container: {
type: "auto",
file_ids: [uploadedFile.id],
},
},
],
{ description: "Toolbox with the code interpreter tool" },
);
// 2. The toolbox exposes an MCP-compatible endpoint.
const toolboxMcpUrl =
`${PROJECT_ENDPOINT}/toolboxes/${toolbox.name}` +
`/versions/${toolbox.version}/mcp?api-version=v1`;
// 3. Create a remote-tool project connection that points at the toolbox endpoint.
// Use a user Entra token so the caller's identity is passed through
// (audience https://ai.azure.com). Create the connection once, for example
// with the Azure Developer CLI:
//
// azd ai connection create code-interpreter-toolbox-conn \
// --kind remote-tool \
// --target "<toolboxMcpUrl>" \
// --auth-type user-entra-token \
// --audience https://ai.azure.com
const toolboxConnectionName = "code-interpreter-toolbox-conn";
// 4. Attach the toolbox to a prompt agent as an MCP tool.
const agent = await project.agents.createVersion("MyAgent", {
kind: "prompt",
model: "gpt-5-mini",
instructions: "You are a helpful assistant.",
tools: [
{
type: "mcp",
server_label: "toolbox",
server_url: toolboxMcpUrl,
require_approval: "never",
project_connection_id: toolboxConnectionName,
},
],
});
// Create a conversation
const conversation = await openai.conversations.create();
// Request chart generation
const response = await openai.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_reference: { name: agent.name, type: "agent_reference" } },
},
);
// 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 openai.containers.files.content.retrieve(
fileId,
{ container_id: containerId },
);
const buffer = Buffer.from(await fileContent.arrayBuffer());
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
await project.agents.deleteVersion(agent.name, agent.version);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
預期產出
範例程式碼輸出類似以下範例:
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 儲存,建立沙盒式 Python 環境,篩選運輸業公司,產生顯示各公司營運利潤的 PNG 長條圖,並將圖表下載到您的本地目錄。 回應中的檔案註解提供了取得產生圖表所需的檔案 ID 與容器資訊。
用 Java 的程式碼直譯器建立圖表
對大多數代理來說,透過 工具箱 加入程式碼直譯器工具,並將工具箱附加到你的代理上作為 MCP 工具。 Java SDK 目前尚未公開工具箱建立 API,因此請使用目前支援的方法之一(Python、REST API、C#、TypeScript 或 Foundry 入口網站)來建立工具箱。 工具箱建立完成後,從你的 Java 代理中引用其 MCP 端點作為 McpTool。 以下範例將程式碼直譯工具箱 MCP 端點附加到代理上。
新增相依性至您的pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.2.0</version>
</dependency>
建立代理人並產生圖表
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.McpTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import java.util.Collections;
public class CodeInterpreterChartExample {
public static void main(String[] args) {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
String toolboxMcpUrl = projectEndpoint
+ "/toolboxes/code-interpreter-toolbox/versions/1/mcp?api-version=v1";
String toolboxConnectionName = "code-interpreter-toolbox-conn";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
AgentsClient agentsClient = builder.buildAgentsClient();
ResponsesClient responsesClient = builder.buildResponsesClient();
// The Java SDK doesn't yet expose a toolbox creation API. Create the
// code-interpreter toolbox with Python, REST, C#, TypeScript, or the
// Foundry portal, then attach its MCP endpoint as an MCP tool.
McpTool toolboxTool = new McpTool("toolbox")
.setServerUrl(toolboxMcpUrl)
.setProjectConnectionId(toolboxConnectionName)
.setRequireApproval("never");
// Create agent with the code-interpreter toolbox MCP tool
PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-5-mini")
.setInstructions("You are a data visualization assistant. When asked to create charts, "
+ "write and run Python code using matplotlib to generate them.")
.setTools(Collections.singletonList(toolboxTool));
AgentVersionDetails agent = agentsClient.createAgentVersion("chart-agent", agentDefinition);
// Request a bar chart with inline data
AgentReference agentReference = new AgentReference(agent.getName())
.setVersion(agent.getVersion());
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("Create a bar chart showing quarterly revenue for 2025: "
+ "Q1=$2.1M, Q2=$2.8M, Q3=$3.2M, Q4=$2.9M. "
+ "Use a blue color scheme, add data labels on each bar, "
+ "and title the chart 'Quarterly Revenue 2025'. "
+ "Save the chart as a PNG file."));
System.out.println("Response: " + response.output());
// Clean up
agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
}
}
預期產出
Response: Here is the bar chart showing quarterly revenue for 2025 with Q1 ($2.1M), Q2 ($2.8M), Q3 ($3.2M), and Q4 ($2.9M) displayed in blue with data labels.
代理程式透過工具箱 MCP 端點使用 Code Interpreter,使用 matplotlib 撰寫 Python 程式碼產生圖表,並在沙盒環境中執行程式碼。 若要上傳 CSV 檔案並下載產生圖表的範例,請從本文頂端的語言選擇器中選擇 Python 或 TypeScript。 更多範例請參考 Azure AI 代理 Java SDK 範例 。
用 REST API 的程式碼直譯器建立圖表
以下範例展示了如何上傳 CSV 檔案、使用 Code Interpreter 建立代理程式、請求圖表,以及下載產生的檔案。
先決條件
設定以下環境變數:
-
FOUNDRY_PROJECT_ENDPOINT: 你的專案端點網址。 -
AGENT_TOKEN:Foundry 的持有人權杖。
取得存取權憑證:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
在工具箱中使用 Code Interpreter
若要透過工具箱上傳檔案供 Code Interpreter 使用,請使用 標頭,將檔案上傳至 POST {account_endpoint}/openai/v1/files Files 端點(x-aml-project-id)。 與提示代理流程不同,透過專案範圍的 Files 端點(/api/projects/{name}/openai/v1/files)上傳的檔案會收到一個 owner_id,而工具箱容器無法驗證它,因此 tools/call 會因所有權驗證錯誤而失敗。
從 Azure Resource Manager 取得專案 GUID。 請使用
properties.amlWorkspace.internalId(帶連字號的 UUID 格式),而不是使用properties.internalId(不含連字號 - 工具箱容器會拒絕):ARM_TOKEN=$(az account get-access-token --query accessToken -o tsv) PROJECT_GUID=$(curl -s -H "Authorization: Bearer $ARM_TOKEN" \ "https://management.azure.com/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.CognitiveServices/accounts/{account}/projects/{project}?api-version=2025-06-01" \ | jq -r '.properties.amlWorkspace.internalId')在帳號(資源)層級上傳檔案,標頭如下
x-aml-project-id:cat > synthetic-company-financial-results.csv <<'CSV' name,sector,operating_profit SkyBridge Logistics,TRANSPORTATION,185.2 Velocity Rail Freight,TRANSPORTATION,310.2 AeroJet Airlines,TRANSPORTATION,510.6 CSV TOKEN=$(az account get-access-token --scope https://ai.azure.com/.default --query accessToken -o tsv) curl -X POST "https://{account}.services.ai.azure.com/openai/v1/files" \ -H "Authorization: Bearer $TOKEN" \ -H "x-aml-project-id: $PROJECT_GUID" \ -F "purpose=assistants" \ -F "file=@synthetic-company-financial-results.csv" rm synthetic-company-financial-results.csv
回傳的檔案 id 就是你在工具設定中提供的 <FILE_ID> 數值。 檔案會掛載在 /mnt/data/{file-id}-{original-filename} 的沙盒中。
重要
當 Code Interpreter 透過託管代理的工具箱使用時, 使用者隔離就不被支援。 同一專案中的所有使用者共享相同的容器上下文。
將程式碼直譯器加入工具箱
透過建立工具箱來新增程式碼直譯器,然後將工具箱附加到你的代理程式中作為 MCP 工具。 欲了解更多資訊,請參閱 「什麼是工具箱?」
建立包含程式碼直譯工具的工具箱:
curl --request POST \ --url "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions?api-version=v1" \ -H "Authorization: Bearer $AGENT_TOKEN" \ -H "Content-Type: application/json" \ --data '{ "description": "Toolbox with the code interpreter tool", "tools": [ { "type": "code_interpreter", "container": { "type": "auto", "file_ids": ["<FILE_ID>"] } } ] }'工具箱在 處暴露一個與 MCP 相容的端點
$FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1,其中<version>是前一次呼叫回傳的版本。建立一個指向工具箱端點的遠端工具專案連線,並使用使用者 Entra 權杖,以便傳遞呼叫者的身分識別 (對象為
https://ai.azure.com)。azd ai connection create code-interpreter-toolbox-conn \ --kind remote-tool \ --target "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1" \ --auth-type user-entra-token \ --audience https://ai.azure.com
用程式碼直譯器工具箱建立代理程式
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"name": "chart-agent",
"definition": {
"kind": "prompt",
"model": "<MODEL_DEPLOYMENT>",
"instructions": "You are a data visualization assistant. When asked to create charts, write and run Python code using matplotlib to generate them.",
"tools": [
{
"type": "mcp",
"server_label": "toolbox",
"server_url": "'$FOUNDRY_PROJECT_ENDPOINT'/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1",
"require_approval": "never",
"project_connection_id": "code-interpreter-toolbox-conn"
}
]
}
}'
產生圖表
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"agent_reference": {"type": "agent_reference", "name": "chart-agent"},
"input": "Create a bar chart of operating profit by company for the TRANSPORTATION sector from the uploaded CSV file. Use a blue color scheme and add data labels."
}'
回覆中包含 container_file_citation 註解,其中包含產生的檔案細節。 從註解中儲存 container_id 和 file_id 值。
下載生成的圖表
curl -X GET "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/containers/<CONTAINER_ID>/files/<FILE_ID>/content" \
-H "Authorization: Bearer $AGENT_TOKEN" \
--output chart.png
清除
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/chart-agent?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
請查閱區域及車型的可用性
工具的可用性會依地區和型號而異。
關於目前支援的 Code Interpreter 區域與模型清單,請參見 Microsoft Foundry Agent Service 工具使用最佳實務。
支援的檔案類型
| 檔案格式 | MIME 類型 |
|---|---|
.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 |
故障排除
| 問題 | 可能的原因 | 解決方法 |
|---|---|---|
| 程式碼解譯器無法執行。 | 該工具未啟用或型號在你所在地區不支援。 | 確認代理程式已啟用程式碼解譯器。 確認你的模型部署是否支援你所在地區的該工具。 請參見 「檢查區域與型號可用性」。 |
| 沒有產生任何檔案。 | 客服回覆僅以文字回覆,未附檔案註解。 | 請檢查 container_file_citation 的回應註解。 如果沒有,代表代理沒有產生檔案。 改寫提示,以明確請求文件輸出。 |
| 檔案上傳失敗。 | 檔案類型不支援或用途錯誤。 | 請確認檔案類型是否在 支援的檔案類型 清單中。 使用 purpose="assistants" 上傳。 |
| 產生的檔案損壞或是空白。 | 程式碼執行錯誤或處理不完整。 | 請檢查客服人員的回覆是否有錯誤訊息。 確認輸入資料的有效性。 先試試簡單的請求。 |
| 會話逾時或高延遲。 | 程式碼解譯器會話有時間限制。 | 工作階段具有 1 小時的作用中逾時時間,以及 30 分鐘的閒置逾時時間。 減少作業複雜度或拆分成較小的任務。 |
| 未預期的收費 | 已建立多個並行會話。 | 每次對話都會建立獨立的工作階段。 監控會話使用情況,並在可能的情況下整合作業。 |
| Python 套件無法使用。 | Code Interpreter 有固定的套件集合。 | Code Interpreter 包含常見的資料科學套件。 自訂套件則使用 自訂程式碼直譯器。 |
| 檔案下載失敗。 | 容器 ID 或檔案 ID 錯誤。 | 確認您使用的是正確的container_id和file_id來自回應註釋。 |
清理資源
當你不再需要這些資源時,請刪除你在此範例中建立的資源,以避免持續的成本:
- 刪除代理版本。
- 刪除對話。
- 刪除已上傳的檔案。
關於對話與檔案清理模式的範例,請參閱 網頁搜尋工具 及 代理人檔案搜尋工具。
沙盒執行環境
Code Interpreter 在 Microsoft 管理的沙盒中執行 Python 程式碼。 沙盒被設計用來執行不受信任的程式碼,並在 Azure 容器應用程式 中使用動態會話(程式碼直譯器會話)。 每個會話都以 Hyper-V 邊界隔離。
需要規劃的關鍵行為:
- Region:Code Interpreter 沙盒運行於與 Foundry 專案相同的 Azure 區域。
- 會話壽命:Code Interpreter 會話最多可持續一小時,並有閒置逾時(詳見本文開頭 的重要 說明)。
- 隔離:每次會話都在隔離環境中進行。 如果你的代理在不同的對話中同時呼叫 Code Interpreter,則會建立獨立的會話。
- 網路隔離與網際網路存取:沙盒不會繼承你的代理子網路設定,動態會話也無法發出外撥網路請求。
- 沙盒中的 Files :沙箱化的 Python 執行時可以使用你附加的檔案進行分析。 Code Interpreter 能夠產生檔案,例如圖表,並以可下載的形式返回。
如果你需要更多對沙盒執行時的控制,或需要不同的隔離模型,請參考代理 自訂程式碼直譯工具。