Strumento di interpretazione del codice per gli agenti di Foundry Microsoft

L'interprete del codice consente a un agente foundry di Microsoft di eseguire Python codice in un ambiente di esecuzione in modalità sandbox. Il modello Foundry dell'agente scrive ed esegue il codice per l'analisi dei dati, la generazione di grafici e le attività iterative di risoluzione dei problemi.

Suggerimento

Prendere in considerazione l'aggiunta di questo strumento usando una casella degli strumenti. Usando una casella degli strumenti, è possibile riutilizzare lo strumento tra agenti e runtime, nonché centralizzare la gestione delle credenziali, il controllo delle versioni e l'imposizione dei criteri tramite un endpoint MCP gestito. Consulta la guida rapida di Toolbox.

In questo articolo viene creato un agente che usa l'interprete del codice, si carica un file CSV per l'analisi e si scarica un grafico generato.

Quando si abilita l'interprete del codice, l'agente può scrivere ed eseguire Python codice in modo iterativo per risolvere le attività matematiche e di analisi dei dati e generare grafici.

Importante

L'interprete del codice ha addebiti aggiuntivi oltre alle tariffe basate su token per l'utilizzo di Azure OpenAI. Se l'agente chiama l'interprete del codice contemporaneamente in due conversazioni diverse, crea due sessioni dell'interprete del codice. Ogni sessione è attiva per impostazione predefinita per un'ora con un timeout di inattività di 30 minuti.

Prerequisiti

  • Ambiente dell'agente di base o standard. Per informazioni dettagliate, vedere Configurazione dell'ambiente dell'agente .
  • Pacchetto SDK più recente installato per la tua lingua. L'SDK di .NET è attualmente in anteprima. Vedere la guida introduttiva per la procedura di installazione.
  • Distribuzione del modello di intelligenza artificiale di Azure configurata nel tuo progetto.

Nota

L'interprete del codice non è disponibile in tutte le aree. Consulta Controlla la disponibilità regionale e del modello.

Supporto per l'utilizzo

La tabella seguente illustra il supporto dell'SDK e della configurazione.

Supporto Foundry di Microsoft PYTHON SDK SDK di C# JavaScript SDK JAVA SDK REST API Configurazione dell'agente di base Configurazione dell'agente standard
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

Creare un agente con l'interprete del codice

Gli esempi seguenti illustrano come creare un agente con l'interprete del codice abilitato, caricare un file per l'analisi e scaricare l'output generato. Ogni esempio di caricamento di file genera un file CSV piccolo nella directory di lavoro corrente, lo carica e quindi elimina il file temporaneo locale.

Suggerimento

È possibile personalizzare il comportamento dell'interprete del codice in fase di esecuzione, ad esempio specificando quali file includere o regolare i parametri degli strumenti per ogni richiesta, usando input strutturati.

Esempio di uso dell'agente con lo strumento dell'interprete del codice in Python SDK

L'esempio di Python seguente illustra come aggiungere lo strumento dell'interprete del codice a una casella degli strumenti, allegare la casella degli strumenti a un agente, caricare un file CSV per l'analisi e richiedere un grafico a barre in base ai dati. Selezionare Prompt Agents per usare Azure AI Projects SDK per creare un agente prompt sul lato server o Hosted Agents per usare Agent Framework FoundryChatClient per creare un agente temporaneo in-process.

Agenti rapidi

Questo esempio illustra un flusso di lavoro completo: caricare un file, creare un agente con l'interprete del codice abilitato, richiedere la visualizzazione dei dati e scaricare il grafico generato.

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")

Output previsto

Il codice di esempio genera un output simile all'esempio seguente:

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

L'agente carica il file CSV nella risorsa di archiviazione Azure, crea un ambiente di Python in modalità sandbox, filtra le aziende del settore dei trasporti, genera un grafico a barre PNG che mostra i profitti operativi per società e scarica il grafico nella directory locale. Le annotazioni di file nella risposta forniscono l'ID file e le informazioni sul contenitore necessarie per recuperare il grafico generato.

Agenti ospitati

In questo esempio viene creata la casella degli strumenti dell'interprete del codice, quindi viene usata FoundryChatClient da Microsoft Agent Framework e si connette all'endpoint MCP della casella degli strumenti usando MCPStreamableHTTPTool. Impostare le FOUNDRY_PROJECT_ENDPOINT variabili di ambiente e FOUNDRY_MODEL e accedere con az login.

import asyncio
import os
import httpx

from agent_framework import Agent, MCPStreamableHTTPTool
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential, get_bearer_token_provider
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
"""


class _ToolboxAuth(httpx.Auth):
    def __init__(self, token_provider):
        self._token_provider = token_provider

    def auth_flow(self, request):
        request.headers["Authorization"] = "Bearer " + self._token_provider()
        yield request


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.
    token_provider = get_bearer_token_provider(credential, "https://ai.azure.com/.default")
    http_client = httpx.AsyncClient(auth=_ToolboxAuth(token_provider), timeout=120.0)
    mcp_tool = MCPStreamableHTTPTool(
        name="toolbox",
        url=TOOLBOX_MCP_URL,
        http_client=http_client,
        load_prompts=False,
    )

    agent = Agent(
        client=FoundryChatClient(credential=credential),
        instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
        tools=[mcp_tool],
    )

    result = await agent.run("Use code to calculate the factorial of 100.")
    print(f"Agent: {result.text}")


if __name__ == "__main__":
    asyncio.run(main())

Output previsto

L'agente genera Python codice, lo esegue nel contenitore in modalità sandbox e restituisce la risposta:

Agent: 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Per l'esempio completo (inclusi gli input di file ed estrazione del codice generato), vedere foundry_chat_client_with_code_interpreter.py e foundry_chat_client_code_interpreter_files.py.


Creare un grafico con l'interprete del codice in C#

L'esempio C# seguente illustra come aggiungere lo strumento Interprete di codice a una casella degli strumenti, collegare la casella degli strumenti a un agente, caricare un file CSV per l'analisi e scaricare il grafico generato. Selezionare Prompt Agents per usare Azure AI Projects SDK per creare un agente prompt sul lato server o Hosted Agents per usare Microsoft Agent Framework per creare un agente temporaneo e in-process.

Agenti rapidi

Per l'utilizzo asincrono, vedere l'esempio di codice nel repository Azure SDK per .NET su GitHub.

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

Output previsto

Il codice di esempio genera un output simile all'esempio seguente:

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

L'agente carica il file CSV nella risorsa di archiviazione Azure, crea un ambiente di Python in modalità sandbox, analizza i dati per filtrare i record del settore dei trasporti e genera un grafico a barre PNG. L'analisi dell'annotazione estrae l'ID del contenitore e l'ID file dalla risposta, che vengono usati per scaricare il grafico nella directory locale.

Agenti ospitati

Questo esempio crea la toolbox del code interpreter, quindi usa ResponsesServer del Microsoft Agent Framework con un ToolboxMcpClient personalizzato per individuare e invocare il Code Interpreter tramite l'endpoint MCP della toolbox. Impostare le AZURE_AI_PROJECT_ENDPOINTvariabili di ambiente , AZURE_OPENAI_ENDPOINTe AZURE_AI_MODEL_DEPLOYMENT_NAME e accedere con 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.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");

// 2. The toolbox exposes an MCP-compatible endpoint.
string toolboxMcpEndpoint =
    $"{projectEndpoint}/toolboxes/{toolboxVersion.Name}/versions/{toolboxVersion.Version}/mcp?api-version=v1";

// 3. Attach the toolbox to the hosted agent.
AzureOpenAIClient openAIClient = new(new Uri(openAiEndpoint), credential);
ChatClient chatClient = openAIClient.GetChatClient(deploymentName);

// ToolboxMcpClient discovers toolbox tools via MCP tools/list and calls them via tools/call.
ToolboxMcpClient toolboxClient = new(toolboxMcpEndpoint, credential);

ResponsesServer.Run<ToolboxHandler>(configure: builder =>
{
    builder.Services.AddSingleton(new AgentConfig(
        name: AgentName,
        instructions: AgentInstructions,
        chatClient: chatClient,
        toolboxClient: toolboxClient));
});

Output previsto

L'agente ospitato usa l'endpoint MCP della casella degli strumenti per eseguire Python nella sandbox e restituire la risposta finale:

Response: One solution is x ≈ 6.36, since sin(x) + x^2 is approximately 42 at that value.

Per un'integrazione gestita .NET Agent Framework, vedere Usare una casella degli strumenti con un agente ospitato.


Esempio di uso dell'agente con lo strumento di interprete del codice in TypeScript SDK

L'esempio TypeScript seguente illustra come aggiungere lo strumento dell'interprete del codice a una casella degli strumenti, allegare la casella degli strumenti a un agente, caricare un file CSV per l'analisi e richiedere un grafico a barre in base ai dati. Per una versione JavaScript, vedere l'esempio JavaScript nel repository Azure SDK per JavaScript in GitHub.

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);
});

Output previsto

Il codice di esempio genera un output simile all'esempio seguente:

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

L'agente carica il file CSV nella risorsa di archiviazione Azure, crea un ambiente di Python in modalità sandbox, filtra le aziende del settore dei trasporti, genera un grafico a barre PNG che mostra i profitti operativi per società e scarica il grafico nella directory locale. Le annotazioni di file nella risposta forniscono l'ID file e le informazioni sul contenitore necessarie per recuperare il grafico generato.

Creare un grafico con l'interprete del codice in Java

Per la maggior parte degli agenti, aggiungi lo strumento interprete di codice tramite una toolbox e collega la toolbox al tuo agente come strumento MCP. L'SDK di Java non espone ancora un'API di creazione della casella degli strumenti, quindi creare la casella degli strumenti usando uno dei metodi attualmente supportati (Python, API REST, C#, TypeScript o il portale Foundry). Dopo aver creato la casella degli strumenti, fare riferimento al relativo endpoint MCP dall'agente Java come McpTool. Nell'esempio seguente l'endpoint MCP della casella degli strumenti dell'interprete del codice viene associato all'agente.

Aggiungi la dipendenza a pom.xml:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-agents</artifactId>
    <version>2.2.0</version>
</dependency>

Creare un agente e generare un grafico

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

Output previsto

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.

L'agente usa l'interprete del codice tramite l'endpoint MCP della casella degli strumenti, scrive Python codice usando matplotlib per generare il grafico ed esegue il codice in un ambiente in modalità sandbox. Per un esempio che carica un file CSV e scarica il grafico generato, selezionare Python o TypeScript dal selettore di lingua nella parte superiore di questo articolo. Per altri esempi, vedere gli esempi di Azure AI Agents Java SDK.

Creare un grafico con l'interprete del codice usando l'API REST

L'esempio seguente illustra come caricare un file CSV, creare un agente con Interprete codice, richiedere un grafico e scaricare il file generato.

Prerequisiti

Impostare queste variabili di ambiente:

  • FOUNDRY_PROJECT_ENDPOINT: URL dell'endpoint del progetto.
  • AGENT_TOKEN: token di connessione per Foundry.

Ottenere un token di accesso:

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

Usare l'interprete di codice in una casella degli strumenti

Per caricare un file per l'interprete di codice da usare tramite una casella degli strumenti, caricare il file nell'endpoint Files a livello di risorsa (POST {account_endpoint}/openai/v1/files) con l'intestazione x-aml-project-id. A differenza del flusso dell’agente basato su prompt, i file caricati tramite l’endpoint Files con ambito di progetto (/api/projects/{name}/openai/v1/files) ricevono un oggetto owner_id che il contenitore casella degli strumenti non può verificare, quindi tools/call ha esito negativo per errore di verifica della titolarità.

  1. Ottenere il GUID del progetto da Azure Resource Manager. Usare properties.amlWorkspace.internalId (formato UUID con trattini), nonproperties.internalId (senza trattini: il contenitore toolbox lo rifiuta):

    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. Caricare il file a livello di account (risorsa) con l'intestazione 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
    

Il file id restituito è il valore fornito come <FILE_ID> nella configurazione dello strumento. I file vengono montati nella sandbox in /mnt/data/{file-id}-{original-filename}.

Importante

Quando l'interprete del codice viene usato tramite una casella degli strumenti in un agente ospitato, l'isolamento utente non è supportato. Tutti gli utenti nello stesso progetto condividono lo stesso contesto del contenitore.

Aggiungere l'interprete del codice a una casella degli strumenti

Aggiungere l'interprete del codice creando una casella degli strumenti e quindi collegare la casella degli strumenti all'agente come strumento MCP. Per altre informazioni, vedere Che cos'è una casella degli strumenti?

  • Creare una casella degli strumenti contenente lo strumento dell'interprete del codice:

    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>"]
            }
          }
        ]
      }'
    

    La casella degli strumenti espone un endpoint compatibile con MCP in $FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1, dove <version> è la versione restituita dalla chiamata precedente.

  • Creare una connessione al progetto strumento remoto che punti all'endpoint della casella degli strumenti, usando un token Entra dell'utente in modo che l'identità del chiamante venga trasmessa (audience 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
    

Creare un agente con la casella degli strumenti dell'interprete del codice

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"
        }
      ]
    }
  }'

Generare un grafico

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."
  }'

La risposta include container_file_citation annotazioni con i dettagli del file generato. Salvare i valori di container_id e file_id dall'annotazione.

Scaricare il grafico generato

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

Pulizia

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

Verificare la disponibilità a livello di area e modello

La disponibilità degli strumenti varia in base all'area geografica e al modello.

Per l'elenco corrente delle regioni e dei modelli supportati per l'interprete del codice, vedere Migliori pratiche per l'uso di strumenti nel servizio Microsoft Foundry Agent.

Tipi di file supportati

Formato file Tipo 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 O text/xml
.zip application/zip

Risoluzione dei problemi

Problema Probabile causa Risoluzione
L'interprete del codice non viene eseguito. Lo strumento non è abilitato o il modello non lo supporta nell'area. Verificare che l'interprete del codice sia abilitato nell'agente. Verifica che la distribuzione del modello supporti lo strumento nella tua regione. Consulta Controlla la disponibilità regionale e del modello.
Non viene generato alcun file. Agent ha restituito una risposta di sola testo senza annotazione di file. Verificare le annotazioni della risposta per container_file_citation. Se non esiste, l'agente non ha generato un file. Riformula il prompt per richiedere in modo esplicito l'output del file.
Il caricamento del file non riesce. Tipo di file non supportato o scopo errato. Verificare che il tipo di file sia incluso nell'elenco dei tipi di file supportati . Carica con purpose="assistants".
Il file generato è danneggiato o vuoto. Errore di esecuzione del codice o elaborazione incompleta. Controllare la risposta dell'agente per i messaggi di errore. Verificare che i dati di input siano validi. Provare prima una richiesta più semplice.
Scadenza della sessione o latenza elevata. Le sessioni dell'interprete del codice hanno limiti di tempo. Le sessioni hanno un timeout attivo di 1 ora e un timeout di inattività di 30 minuti. Ridurre la complessità delle operazioni o suddividersi in attività più piccole.
Addebiti imprevisti per la fatturazione. Sono state create più sessioni concomitanti. Ogni conversazione crea una sessione separata. Monitorare l'utilizzo della sessione e consolidare le operazioni laddove possibile.
Python pacchetto non disponibile. L'interprete del codice ha un set fisso di pacchetti. L'interprete di codice include i comuni pacchetti di data science. Per i pacchetti personalizzati, usare l'interprete di codice personalizzato.
Il download del file non riesce. ID contenitore o ID file non corretto. Verificare di usare i container_id e file_id corretti dalle annotazioni della risposta.

Pulire le risorse

Eliminare le risorse create in questo esempio quando non sono più necessarie per evitare costi continui:

  • Eliminare la versione dell'agente.
  • Eliminare la conversazione.
  • Eliminare i file caricati.

Per esempi di modelli di pulizia di conversazione e file, vedere Strumento di ricerca Web e Strumento di ricerca file per gli agenti.

Ambiente di esecuzione in modalità sandbox

L'interprete di codice esegue codice Python in una sandbox gestita da Microsoft. La sandbox è progettata per l'esecuzione di codice non attendibile e usa sessioni dynamic sessions (sessioni dell'interprete del codice) in App contenitore di Azure. Ogni sessione è isolata da un limite Hyper-V.

Comportamenti chiave per pianificare:

  • Region: la sandbox dell'interprete del codice viene eseguita nella stessa area Azure del progetto Foundry.
  • Durata della sessione: una sessione dell'interprete del codice è attiva per un massimo di un'ora, con un timeout di inattività (vedere la nota importante all'inizio di questo articolo).
  • Isolamento: ogni sessione viene eseguita in un ambiente isolato. Se l'agente richiama l'interprete del codice contemporaneamente in conversazioni diverse, vengono create sessioni separate.
  • Isolamento della rete e accesso a Internet: la sandbox non eredita la configurazione della subnet dell'agente e le sessioni dinamiche non possono effettuare richieste di rete in uscita.
  • File nella sandbox: il runtime Python in modalità sandbox ha accesso ai file allegati per l'analisi. L'interprete del codice può anche generare file, ad esempio grafici, e restituirli come output scaricabili.

Se è necessario un maggiore controllo sul runtime sandbox o è necessario un modello di isolamento diverso, vedere Strumento interprete di codice personalizzato per gli agenti.