Microsoft Foundry エージェント用のコード インタープリター ツール

コード インタープリターを使用すると、Microsoft Foundry エージェントは、サンドボックス実行環境でPythonコードを実行できます。 エージェントの Foundry モデルは、データ分析、グラフ生成、反復的な問題解決タスクのコードを記述して実行します。

ヒント

ツールボックスを使用してこのツールを追加することを検討 してください。 ツールボックスを使用すると、エージェントとランタイム間でツールを再利用できるほか、マネージド MCP エンドポイントを介して資格情報の管理、バージョン管理、ポリシーの適用を一元化できます。 ツールボックスの クイック スタートを参照してください。

この記事では、コード インタープリターを使用するエージェントを作成し、分析用の CSV ファイルをアップロードし、生成されたグラフをダウンロードします。

コード インタープリターを有効にすると、エージェントはPythonコードを繰り返し記述して実行し、データ分析と数学タスクを解決したり、グラフを生成したりできます。

重要

コード インタープリターには、Azure OpenAI の使用に対するトークン ベースの料金を超える追加料金があります。 エージェントが 2 つの異なる会話でコード インタープリターを同時に呼び出すと、2 つのコード インタープリター セッションが作成されます。 各セッションは既定で 1 時間アクティブであり、アイドル タイムアウトは 30 分です。

前提 条件

  • 基本または標準のエージェント環境。 詳細については、 エージェント環境のセットアップ を参照してください。
  • お使いの言語用にインストールされた最新の SDK パッケージ。 .NET SDK は現在プレビュー段階です。 インストール手順については、 クイック スタート を参照してください。
  • Azureプロジェクトで構成された AI モデルのデプロイ。

メモ

コード インタープリターは、すべてのリージョンで使用できるわけではありません。 リージョンとモデルの可用性の確認を参照してください。

使用サポート

次の表に、SDK とセットアップのサポートを示します。

Microsoft Foundry のサポート Python SDK C# SDK JavaScript SDK Java SDK REST API 基本的なエージェントのセットアップ 標準エージェントのセットアップ
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

コード インタープリターを使用してエージェントを作成する

次のサンプルでは、コード インタープリターを有効にしてエージェントを作成し、分析用のファイルをアップロードし、生成された出力をダウンロードする方法を示します。 各ファイル アップロード サンプルでは、現在の作業ディレクトリに小さな CSV が生成され、アップロードされた後、ローカルの一時ファイルが削除されます。

ヒント

構造化された入力を使用して、コード インタープリターの動作 (含めるファイルの指定、要求ごとのツール パラメーターの調整など) を実行時にカスタマイズできます。

Python SDK でコード インタープリター ツールでエージェントを使用するサンプル

次のPythonサンプルは、コード インタープリター ツールをツールボックスに追加し、そのツールボックスをエージェントにアタッチし、分析用の CSV ファイルをアップロードし、データに基づいて横棒グラフを要求する方法を示しています。 Azure AI Projects SDK を使用してサーバー側プロンプト エージェントを作成する場合は Prompt Agents を選択します。エージェント フレームワーク を使用してエフェメラルなインプロセス エージェントを作成するには、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_ENDPOINTFOUNDRY_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.pyfoundry_chat_client_code_interpreter_files.pyを参照してください。


C でコード インタープリターを使用してグラフを作成する#

次の C# サンプルは、コード インタープリター ツールをツールボックスに追加し、そのツールボックスをエージェントにアタッチし、分析用の CSV ファイルをアップロードして、生成されたグラフをダウンロードする方法を示しています。 Prompt Agents を選択して、Azure AI Projects SDK を使用してサーバー側プロンプト エージェントを作成するか、Hosted Agents を使用して、Microsoft Agent Framework を使用してエフェメラルなインプロセス エージェントを構築します。

エージェントに指示を促す

非同期の使用については、GitHubの.NETリポジトリのAzure SDKのcode サンプルを参照してください。

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_ENDPOINTAZURE_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 のベアラー トークン。

アクセス トークンを取得します。

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

ツールボックスでコード インタープリターを使用する

ツールボックスを介して使用するコード インタープリター用のファイルをアップロードするには、 リソース レベル の Files エンドポイント (POST {account_endpoint}/openai/v1/files) で x-aml-project-id ヘッダーを使用してファイルをアップロードします。 プロンプト エージェント フローとは異なり、プロジェクト スコープの Files エンドポイント (/api/projects/{name}/openai/v1/files) を介してアップロードされたファイルは、ツールボックス コンテナーで検証できない owner_id を受け取るので、 tools/call は所有権検証エラーで失敗します。

  1. 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')
    
  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> は前の呼び出しによって返されたバージョンです。

  • 呼び出し元の ID が渡されるようにユーザー 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_idfile_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"

リージョンとモデルの可用性を確認する

ツールの可用性は、リージョンとモデルによって異なります。

コード インタープリターでサポートされているリージョンとモデルの現在の一覧については、「 Foundry Agent Service でツールを使用するためのベスト プラクティスMicrosoftを参照してください。

サポートされているファイルの種類

ファイル形式 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_idfile_id を使用していることを確認します。

リソースのクリーンアップ

リソースが不要になった場合は、継続的なコストを回避するために、このサンプルで作成したリソースを削除してください。

  • エージェントのバージョンを削除します。
  • 会話を削除します。
  • アップロードしたファイルを削除します。

会話パターンとファイル クリーンアップ パターンの例については、エージェントの Web 検索ツールファイル検索ツールを参照してください。

サンドボックス実行環境

コード インタープリターは、Microsoftマネージド サンドボックス内Pythonコードを実行します。 サンドボックスは、信頼されていないコードを実行するために設計されており、Azure Container Apps で dynamic セッション (コード インタープリター セッション) を使用します。 各セッションは、Hyper-V 境界によって分離されます。

計画する主な動作:

  • Region: Code Interpreter サンドボックスは、Foundry プロジェクトと同じAzure リージョンで実行されます。
  • セッションの有効期間: コード インタープリター セッションは、アイドル タイムアウトで最大 1 時間アクティブです (この記事の冒頭の 重要な 注意事項を参照してください)。
  • 分離: 各セッションは、分離された環境で実行されます。 エージェントが異なる会話でコード インタープリターを同時に呼び出すと、個別のセッションが作成されます。
  • ネットワークの分離とインターネット アクセス: サンドボックスはエージェント のサブネット構成を継承せず、動的セッションでは送信ネットワーク要求を行うことができません。
  • サンドボックス内のファイル: サンドボックス化されたPythonランタイムは、分析のためにアタッチするファイルにアクセスできます。 コード インタープリターでは、グラフなどのファイルを生成し、ダウンロード可能な出力として返すこともできます。

サンドボックス ランタイムをより詳細に制御する必要がある場合、または別の分離モデルが必要な場合は、 エージェント用のカスタム コード インタープリター ツールを参照してください。