次の方法で共有


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

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

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

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

Important

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

利用サポート

✔️ (GA) は一般提供を示し、✔️(プレビュー) はパブリック プレビューを示し、ダッシュ (-) は機能が使用できないことを示します。

Microsoft Foundry のサポート Python SDK C# SDK JavaScript SDK Java SDK REST API 基本エージェントのセットアップ 標準エージェントのセットアップ
✔️ ✔️ (GA) ✔️ (プレビュー) ✔️ (GA) ✔️ (プレビュー) ✔️ (GA) ✔️ ✔️

[前提条件]

  • 基本または標準のエージェント環境。 詳細については、 エージェント環境のセットアップ を参照してください。
  • お使いの言語用にインストールされた最新の SDK パッケージ。 .NET SDK と Java SDK は現在プレビュー段階です。 インストール手順については、 クイック スタート を参照してください。
  • Azureプロジェクトで構成された AI モデルのデプロイ。
  • ファイル操作の場合: 分析のためにアップロードする CSV またはその他のサポートされているファイル。

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

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

次のサンプルでは、コード インタープリターを有効にしてエージェントを作成し、分析用のファイルをアップロードし、生成された出力をダウンロードする方法を示します。

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

次のPythonサンプルは、コード インタープリター ツールを使用してエージェントを作成し、分析用の CSV ファイルをアップロードし、データに基づいて横棒グラフを要求する方法を示しています。 ファイルのアップロード、コード インタープリターを有効にしたエージェントの作成、データの視覚化の要求、生成されたグラフのダウンロードなどの完全なワークフローを示します。

import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, CodeInterpreterTool, AutoCodeInterpreterToolParam

# Load the CSV file to be processed
asset_file_path = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "../assets/synthetic_500_quarterly_results.csv")
)

# 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 CSV file for the code interpreter to use
file = openai.files.create(purpose="assistants", file=open(asset_file_path, "rb"))

# 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 とコンテナー情報を提供します。

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

次の C# サンプルは、コード インタープリター ツールを使用してエージェントを作成し、それを使用して棒グラフを生成する方法を示しています。 エージェントは、サンドボックス コンテナー Pythonコード (matplotlib を使用) を書き込んで実行します。 非同期の使用については、GitHubの.NETリポジトリのAzure SDKのcode サンプルを参照してください。

using System;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
using Azure.Identity;

// 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());

// Create an agent with Code Interpreter enabled.
PromptAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
    Instructions = "You are a data visualization assistant. When asked to create charts, write and run Python code using matplotlib to generate them.",
    Tools = {
        ResponseTool.CreateCodeInterpreterTool(
            new CodeInterpreterToolContainer(
                CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration(
                    fileIds: []
                )
            )
        ),
    }
};
AgentVersion agentVersion = projectClient.Agents.CreateAgentVersion(
    agentName: "myChartAgent",
    options: new(agentDefinition));

// Ask the agent to create a bar chart from inline data.
AgentReference agentReference = new(name: agentVersion.Name, version: agentVersion.Version);
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentReference);

ResponseResult response = responseClient.CreateResponse(
    "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.");

Console.WriteLine(response.GetOutputText());

// Clean up
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);

想定される出力

サンプル コードでは、次の例のような出力が生成されます。

Here is the bar chart showing quarterly revenue for 2025. The chart displays Q1 ($2.1M), Q2 ($2.8M), Q3 ($3.2M), and Q4 ($2.9M) with a blue color scheme, data labels on each bar, and the title "Quarterly Revenue 2025".

エージェントはコード インタープリター セッションを作成し、matplotlib を使用してコードPython書き込んで横棒グラフを生成し、セキュリティで保護された環境でコードを実行し、生成されたファイルとしてグラフを返します。 CSV ファイルをアップロードして生成されたグラフをダウンロードする例については、この記事の上部にある言語セレクターから Python または TypeScript を選択します。

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";
import { fileURLToPath } from "url";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";

// Helper to resolve asset file path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export async function main(): Promise<void> {
  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Load and upload CSV file
  const assetFilePath = path.resolve(
    __dirname,
    "../assets/synthetic_500_quarterly_results.csv",
  );
  const fileStream = fs.createReadStream(assetFilePath);

  // Upload CSV file
  const uploadedFile = await openai.files.create({
    file: fileStream,
    purpose: "assistants",
  });

  // Create agent with Code Interpreter tool
  const agent = await project.agents.createVersion("MyAgent", {
    kind: "prompt",
    model: "gpt-5-mini",
    instructions: "You are a helpful assistant.",
    tools: [
      {
        type: "code_interpreter",
        container: {
          type: "auto",
          file_ids: [uploadedFile.id],
        },
      },
    ],
  });

  // 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: { 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({
      file_id: fileId,
      container_id: containerId,
    });

    // Read the readable stream into a buffer
    const chunks: Buffer[] = [];
    for await (const chunk of fileContent.body) {
      chunks.push(Buffer.from(chunk));
    }
    const buffer = Buffer.concat(chunks);

    fs.writeFileSync(safeFilename, buffer);
    console.log(`File ${safeFilename} downloaded successfully.`);
    console.log(`File ready for download: ${safeFilename}`);
  } else {
    console.log("No file generated in response");
  }

  // Clean up resources
  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でコード インタープリターを使用してグラフを作成する

依存関係を pom.xmlに追加します。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-agents</artifactId>
    <version>2.0.0-beta.1</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.CodeInterpreterTool;
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";

        AgentsClientBuilder builder = new AgentsClientBuilder()
            .credential(new DefaultAzureCredentialBuilder().build())
            .endpoint(projectEndpoint);

        AgentsClient agentsClient = builder.buildAgentsClient();
        ResponsesClient responsesClient = builder.buildResponsesClient();

        // Create code interpreter tool
        CodeInterpreterTool codeInterpreter = new CodeInterpreterTool();

        // Create agent with code interpreter for data visualization
        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(codeInterpreter));

        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.createWithAgent(
            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.

エージェントはコード インタープリター セッションを作成し、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)

1. CSV ファイルをアップロードする

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/files" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -F "purpose=assistants" \
  -F "file=@quarterly_results.csv"

応答から id を保存します (例: file-abc123)。

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

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": "code_interpreter",
          "container": {
            "type": "auto",
            "file_ids": ["<FILE_ID>"]
          }
        }
      ]
    }
  }'

3. グラフを生成する

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 quarter from the uploaded CSV file. Use a blue color scheme and add data labels."
  }'

応答には、生成されたファイルの詳細を含む container_file_citation 注釈が含まれます。 注釈から container_idfile_id の値を保存します。

4. 生成されたグラフをダウンロードする

curl -X GET "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/containers/<CONTAINER_ID>/files/<FILE_ID>/content" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  --output chart.png

5. クリーンアップ

curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/chart-agent?api-version=v1" \
  -H "Authorization: Bearer $AGENT_TOKEN"

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

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

コード インタープリターでサポートされているリージョンとモデルの現在の一覧については、「 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 パッケージは使用できません。 コード インタープリターには、パッケージの固定セットがあります。 コード インタープリターには、一般的なデータ サイエンス パッケージが含まれています。 カスタム パッケージの場合は、 カスタム コード インタープリターを使用します。
ファイルのダウンロードが失敗します。 コンテナー ID またはファイル ID が正しくありません。 応答注釈から正しい container_idfile_id を使用していることを確認します。

リソースをクリーンアップする

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

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

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