你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

用于 Microsoft Foundry 代理的代码解释器工具

代码解释器使 Microsoft Foundry 代理能够在沙盒执行环境中运行Python代码。 代理的 Foundry 模型编写和执行用于数据分析、图表生成和迭代解决问题的任务的代码。

提示

请考虑使用 工具箱添加此工具。 通过使用工具箱,可以跨代理和运行时重复使用该工具,并通过托管 MCP 终结点集中凭据管理、版本管理和策略强制实施。 请参阅 工具箱快速入门。

在本文中,你将创建一个代理,该代理使用代码解释器,上传 CSV 文件进行分析,并下载生成的图表。

启用代码解释器时,代理可以迭代编写和运行Python代码,以解决数据分析和数学任务,以及生成图表。

重要

除了与使用 Azure OpenAI 相关的基于令牌的费用之外,代码解释器还有额外的费用。 如果代理在两个不同的会话中同时调用代码解释器,则会创建两个代码解释器会话。 默认情况下,每个会话处于活动状态一小时,空闲超时为 30 分钟。

先决条件

  • 基本或标准代理环境。 有关详细信息,请参阅 代理环境设置 。
  • 已为您的语言安装最新的 SDK 包。 .NET SDK 目前为预览版。 请参阅 快速入门以了解安装步骤。
  • 项目中已配置的 Azure AI 模型部署。

注意

代码解释器在所有区域中都不可用。 请参阅 “检查区域和模型可用性”。

使用支持

下表显示了 SDK 和设置支持。

Microsoft Foundry 支持 Python SDK C# SDK JavaScript SDK Java SDK REST API 基本代理设置 标准代理设置
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

使用代码解释器创建代理

以下示例演示如何创建启用了代码解释器的代理、上传文件进行分析和下载生成的输出。 每个文件上传示例在当前工作目录中生成一个小 CSV,上传它,然后删除本地临时文件。

提示

可以在运行时自定义代码解释器行为,例如,使用 结构化输入指定要包含或调整每个请求的工具参数的文件。

在 Python SDK 中将代理与代码解释器工具配合使用的示例

以下Python示例演示如何将代码解释器工具添加到工具箱、将工具箱附加到代理、上传 CSV 文件进行分析,以及基于数据请求条形图。 选择 Prompt Agents以使用 Azure AI Projects SDK 创建服务器端提示代理,或托管代理使用 Agent Framework FoundryChatClient生成临时进程内代理。

提示智能体

此示例演示了完整的工作流:上传文件、创建启用了代码解释器的代理、请求数据可视化并下载生成的图表。

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 登录。

注意

对于使用 LangGraph、LangChain 或 Deep Agents 构建的 Python 代理,请使用 连接到同一个工具箱终结点。 请参阅 使用工具箱与托管代理配合 和 LangGraph 工具箱示例。

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.
    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 中使用代码解释器创建图表#

以下 C# 示例演示如何将代码解释器工具添加到工具箱、将工具箱附加到代理、上传 CSV 文件进行分析以及下载生成的图表。 选择 Prompt Agents以使用 Azure AI Projects SDK 创建服务器端提示代理,或托管代理使用 Microsoft Agent Framework 生成临时进程内代理。

提示智能体

有关异步用法,请参阅 代码示例,在GitHub上的.NET存储库中找到Azure SDK。

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 Agent Framework 集成,请参阅配合托管代理使用工具箱。


在 TypeScript SDK 中将代理与代码解释器工具配合使用的示例

以下 TypeScript 示例演示如何将代码解释器工具添加到工具箱、将工具箱附加到代理、上传 CSV 文件进行分析,以及基于数据请求条形图。 有关 JavaScript 版本,请参阅 GitHub 上的 javaScript 存储库Azure SDK中的 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 终结点使用代码解释器,使用 matplotlib 编写Python代码来生成图表,并在沙盒环境中执行代码。 有关上传 CSV 文件并下载生成的图表的示例,请从本文顶部的语言选择器中选择 Python 或 TypeScript。 有关更多示例,请参阅 Azure AI 代理Java SDK 示例。

使用 REST API 通过代码解释器创建图表

以下示例演示如何上传 CSV 文件、使用代码解释器创建代理、请求图表以及下载生成的文件。

先决条件

设置以下环境变量:

  • FOUNDRY_PROJECT_ENDPOINT:项目终结点 URL。
  • AGENT_TOKEN:用于 Foundry 的 Bearer 令牌。

获取访问令牌:

export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)

在工具箱中使用代码解释器

要通过工具箱上传供代码解释器使用的文件,请在资源级别文件终结点 (POST {account_endpoint}/openai/v1/files) 上使用 x-aml-project-id 标头上传文件。 与提示智能体流不同,通过项目范围的文件终结点 (/api/projects/{name}/openai/v1/files) 上传的文件会收到一个工具箱容器无法验证的 owner_id,因此 tools/call 会因所有权验证错误而失败。

  1. 从Azure 资源管理器获取项目 GUID。 使用 properties.amlWorkspace.internalId(带连字符的 UUID 格式),不要使用properties.internalId(无连字符——toolbox 容器不接受这种格式):

    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')
    
  2. 使用 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}。

重要

当代码解释器通过托管代理中的工具箱使用时, 不支持用户隔离。 同一项目中的所有用户共享相同的容器上下文。

将代码解释器添加到工具箱

通过创建工具箱添加代码解释器,然后将工具箱作为 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>"]
            }
          }
        ]
      }'
    

    该工具箱在 $FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1 处提供了一个与 MCP 兼容的端点,其中 <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"

检查区域和模型可用性

工具可用性因区域和模型而异。

有关代码解释器的受支持区域和模型的当前列表,请参阅 有关在 Microsoft Foundry 代理服务中使用工具的最佳做法。

支持的文件类型

文件格式 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包不可用。 代码解释器有一组固定的包。 代码解释器包括常见的数据科学包。 对于自定义包,请使用 自定义代码解释器。
文件下载失败。 容器 ID 或文件 ID 不正确。 请验证您是否在响应批注中使用了正确的 container_id 和 file_id。

清理资源

不再需要资源来避免持续成本时,请删除此示例中创建的资源:

  • 删除代理版本。
  • 删除对话。
  • 删除上传的文件。

有关聊天和文件清理模式的示例,请参阅代理的 Web 搜索工具和文件搜索工具。

沙盒执行环境

代码解释器在Microsoft管理的沙盒中运行Python代码。 沙盒旨在运行不受信任的代码,并在 Azure 容器应用中使用动态会话(代码解释器会话)。 每个会话都由 Hyper-V 边界隔离。

要规划的主要行为:

  • 区域:代码解释器沙盒运行在与您的 Foundry 项目相同的 Azure 区域中。
  • 会话持续时间:代码解释器会话最长可保持活动状态一小时,并设有空闲超时机制(请参阅本文开头的 重要 说明)。
  • 隔离:每个会话在隔离的环境中运行。 如果代理在不同的会话中并发调用代码解释器,则创建单独的会话。 此隔离分隔代码执行。 它不会限制哪些调用方可以使用活动容器。 在项目中,代码解释器容器不会按代理或按用户分别隔离。 可以在项目中使用代码解释器的调用方,引用活动容器可以访问其文件和状态。 将容器 ID 以及包含它们的响应项视为敏感项。 不要跨用户或信任边界重复使用容器。
  • 网络隔离和 Internet 访问:沙盒不会继承代理子网配置,动态会话无法发出出站网络请求。
  • 沙盒中的文件:沙盒 Python 运行时可访问你附加以供分析的文件。 代码解释器还可以生成文件(如图表),并将它们作为可下载的输出返回。

如果需要对沙盒运行时进行更多控制,或者需要其他隔离模型,请参阅 代理的自定义代码解释器工具。