> ## Documentation Index
> Fetch the complete documentation index at: https://hobbyist-e43fa225.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Code Interpreter with Microsoft Foundry agents

> Create agents that run Python code in a sandboxed environment using Code Interpreter in Microsoft Foundry. Upload files, analyze data, and download generated charts.

export const ZonePivot = ({group, options = [], defaultValue, label = "Choose an experience"}) => {
  const values = options.map(option => option.id);
  const optionKey = options.map(option => `${option.id}:${option.title}`).join("|");
  const [activePivot, setActivePivot] = useState(defaultValue || values[0]);
  const slugify = value => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
  const resolvePivot = () => {
    if (typeof window === "undefined") return defaultValue || values[0];
    const params = new URLSearchParams(window.location.search);
    const requested = params.get("pivots");
    if (requested) {
      const requestedIds = requested.split(",").map(value => value.trim()).filter(Boolean);
      const match = requestedIds.find(id => values.includes(id));
      if (match) return match;
    }
    const hash = window.location.hash.replace(/^#/, "");
    if (hash) {
      const match = options.find(option => option.id === hash || slugify(option.title) === hash);
      if (match) return match.id;
    }
    try {
      const stored = window.localStorage.getItem(`foundry-zone-pivot:${group}`);
      if (values.includes(stored)) return stored;
    } catch {
      return defaultValue || values[0];
    }
    return defaultValue || values[0];
  };
  const publishPivotChange = value => {
    if (typeof window === "undefined") return;
    window.dispatchEvent(new CustomEvent("foundry-zone-pivot-change", {
      detail: {
        group,
        value
      }
    }));
  };
  const syncTableOfContents = () => {
    if (typeof window === "undefined") return;
    window.requestAnimationFrame(() => {
      const toc = document.getElementById("table-of-contents-content");
      if (!toc) return;
      const links = Array.from(toc.querySelectorAll('a[href^="#"]'));
      for (const link of links) {
        const item = link.closest("li");
        const rawId = link.getAttribute("href")?.slice(1);
        if (!item || !rawId) continue;
        let id = rawId;
        try {
          id = decodeURIComponent(rawId);
        } catch {}
        item.style.display = document.getElementById(id) ? "" : "none";
      }
    });
  };
  useEffect(() => {
    const resolvedPivot = resolvePivot();
    setActivePivot(resolvedPivot);
    publishPivotChange(resolvedPivot);
    window.setTimeout(syncTableOfContents, 0);
  }, [group, defaultValue, values.join("|"), optionKey]);
  const selectPivot = value => {
    setActivePivot(value);
    if (typeof window !== "undefined") {
      try {
        window.localStorage.setItem(`foundry-zone-pivot:${group}`, value);
      } catch {}
      const url = new URL(window.location.href);
      const current = url.searchParams.get("pivots");
      const preserved = current ? current.split(",").map(id => id.trim()).filter(id => id && !values.includes(id)) : [];
      url.searchParams.set("pivots", [...preserved, value].join(","));
      window.history.replaceState(null, "", `${url.pathname}${url.search}${url.hash}`);
    }
    publishPivotChange(value);
    window.setTimeout(syncTableOfContents, 0);
  };
  if (options.length < 2) return null;
  return <div className="not-prose my-6 border-b border-slate-200 pb-3 dark:border-slate-800">
      <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-500 dark:text-slate-400">
        {label}
      </div>
      <div className="flex flex-wrap gap-2" role="tablist" aria-label={label}>
        {options.map(option => {
    const selected = option.id === activePivot;
    return <button key={option.id} type="button" role="tab" aria-selected={selected} onClick={() => selectPivot(option.id)} className={`rounded-md border px-3 py-1.5 text-sm font-medium transition ${selected ? "border-slate-900 bg-slate-900 text-white shadow-sm dark:border-slate-100 dark:bg-slate-100 dark:text-slate-950" : "border-slate-200 bg-white text-slate-700 hover:border-slate-400 hover:text-slate-950 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-200 dark:hover:border-slate-500"}`}>
              {option.title}
            </button>;
  })}
      </div>
    </div>;
};

export const ZoneContent = ({group, value, options = [], values = [], defaultValue, children}) => {
  const optionKey = options.map(option => `${option.id}:${option.title}`).join("|");
  const [activePivot, setActivePivot] = useState(defaultValue || values[0]);
  const slugify = value => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
  const resolvePivot = () => {
    if (typeof window === "undefined") return defaultValue || values[0];
    const params = new URLSearchParams(window.location.search);
    const requested = params.get("pivots");
    if (requested) {
      const requestedIds = requested.split(",").map(value => value.trim()).filter(Boolean);
      const match = requestedIds.find(id => values.includes(id));
      if (match) return match;
    }
    const hash = window.location.hash.replace(/^#/, "");
    if (hash) {
      const match = options.find(option => option.id === hash || slugify(option.title) === hash);
      if (match) return match.id;
    }
    try {
      const stored = window.localStorage.getItem(`foundry-zone-pivot:${group}`);
      if (values.includes(stored)) return stored;
    } catch {
      return defaultValue || values[0];
    }
    return defaultValue || values[0];
  };
  useEffect(() => {
    setActivePivot(resolvePivot());
  }, [group, defaultValue, values.join("|"), optionKey]);
  useEffect(() => {
    const onPivotChange = event => {
      if (event.detail?.group === group && values.includes(event.detail.value)) {
        setActivePivot(event.detail.value);
      }
    };
    window.addEventListener("foundry-zone-pivot-change", onPivotChange);
    return () => window.removeEventListener("foundry-zone-pivot-change", onPivotChange);
  }, [group, values.join("|")]);
  if (activePivot !== value) return null;
  return <>{children}</>;
};

Code Interpreter enables a Microsoft Foundry agent to run Python code in a sandboxed execution environment. The agent's Foundry model writes and executes code for data analysis, chart generation, and iterative problem-solving tasks.

In this article, you create an agent that uses Code Interpreter, upload a CSV file for analysis, and download a generated chart.

When you enable Code Interpreter, your agent can write and run Python code iteratively to solve data analysis and math tasks, and to generate charts.

<Info>
  Code Interpreter has [additional charges](https://azure.microsoft.com/pricing/details/cognitive-services/openai-service/) beyond the token-based fees for Azure OpenAI usage. If your agent calls Code Interpreter simultaneously in two different conversations, it creates two Code Interpreter sessions. Each session is active by default for one hour with an idle timeout of 30 minutes.
</Info>

### Usage support

The following table shows SDK and setup support.

| Microsoft Foundry support | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API | Basic agent setup | Standard agent setup |
| ------------------------- | ---------- | ------ | -------------- | -------- | -------- | ----------------- | -------------------- |
| ✔️                        | ✔️         | ✔️     | ✔️             | ✔️       | ✔️       | ✔️                | ✔️                   |

## Prerequisites

* Basic or standard agent environment. See [agent environment setup](../../../agents/environment-setup) for details.
* Latest SDK package installed for your language. The .NET SDK is currently in preview. See the [quickstart](/get-started/get-started-code) for installation steps.
* Azure AI model deployment configured in your project.
* For file operations: CSV or other supported files to upload for analysis.

<Note>
  Code Interpreter isn't available in all regions. See [Check regional and model availability](#check-regional-and-model-availability).
</Note>

## Create an agent with Code Interpreter

The following samples demonstrate how to create an agent with Code Interpreter enabled, upload a file for analysis, and download the generated output.

<Tip>
  You can customize Code Interpreter behavior at runtime, such as specifying which files to include or adjusting tool parameters per request, by using [structured inputs](../structured-inputs).
</Tip>

<ZonePivot group="csharp__java__python__rest__typescript" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}, {"id": "rest", "title": "REST"}]} defaultValue="python" />

<ZoneContent group="csharp__java__python__rest__typescript" value="python" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}, {"id": "rest", "title": "REST"}]} values={["python", "csharp", "typescript", "java", "rest"]} defaultValue="python">
  ## Sample of using agent with code interpreter tool in Python SDK

  The following Python sample shows how to create an agent with the code interpreter tool, upload a CSV file for analysis, and request a bar chart based on the data. Select **Prompt Agents** to use the Azure AI Projects SDK to create a server-side prompt agent, or **Hosted Agents** to use the Agent Framework [`FoundryChatClient`](../../quickstarts/responses-api) to build an ephemeral, in-process agent.

  <Tabs>
    <Tab title="Prompt Agents">
      This sample demonstrates a complete workflow: upload a file, create an agent with Code Interpreter enabled, request data visualization, and download the generated chart.

      ```python theme={null}
      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")
      ```

      ### Expected output

      The sample code produces output similar to the following example:

      ```console theme={null}
      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
      ```

      The agent uploads your CSV file to Azure storage, creates a sandboxed Python environment, analyzes the data to filter transportation sector records, generates a PNG bar chart showing operating profit by quarter, and downloads the chart to your local directory. The file annotations in the response provide the file ID and container information needed to retrieve the generated chart.
    </Tab>

    <Tab title="Hosted Agents">
      This sample uses [`FoundryChatClient`](../../quickstarts/responses-api) from the Microsoft Agent Framework and calls `get_code_interpreter_tool()` to give the agent a sandboxed Python execution environment. Install the package with `pip install agent-framework-foundry aiohttp`, set the `FOUNDRY_PROJECT_ENDPOINT` and `FOUNDRY_MODEL` environment variables, and sign in with `az login`.

      ```python theme={null}
      import asyncio

      from agent_framework import Agent
      from agent_framework.foundry import FoundryChatClient
      from azure.identity import AzureCliCredential

      async def main() -> None:
          # Reads FOUNDRY_PROJECT_ENDPOINT and FOUNDRY_MODEL from the environment.
          agent = Agent(
              client=FoundryChatClient(credential=AzureCliCredential()),
              instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
              tools=[FoundryChatClient.get_code_interpreter_tool()],
          )

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

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

      ### Expected output

      The agent generates Python code, runs it in the sandboxed container, and returns the answer:

      ```console theme={null}
      Agent: 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
      ```

      For the full sample (including file inputs and extracting the generated code), see [foundry\_chat\_client\_with\_code\_interpreter.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/providers/foundry/foundry_chat_client_with_code_interpreter.py) and [foundry\_chat\_client\_code\_interpreter\_files.py](https://github.com/microsoft/agent-framework/blob/main/python/samples/02-agents/providers/foundry/foundry_chat_client_code_interpreter_files.py).
    </Tab>
  </Tabs>
</ZoneContent>

<ZoneContent group="csharp__java__python__rest__typescript" value="csharp" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}, {"id": "rest", "title": "REST"}]} values={["python", "csharp", "typescript", "java", "rest"]} defaultValue="python">
  ## Create a chart with Code Interpreter in C\#

  The following C# sample shows how to create an agent with the Code Interpreter tool, upload a CSV file for analysis, and download the generated chart. Select **Prompt Agents** to use the Azure AI Projects SDK to create a server-side prompt agent, or **Hosted Agents** to use the Microsoft Agent Framework to build an ephemeral, in-process agent.

  <Tabs>
    <Tab title="Prompt Agents">
      For asynchronous usage, see the [code sample](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/ai/Azure.AI.Extensions.OpenAI/samples/Sample32_CodeInterpreterFileGeneration.md) in the Azure SDK for .NET repository on GitHub.

      ```csharp theme={null}
      using System;
      using System.IO;
      using Azure.AI.Projects;
      using Azure.AI.Extensions.OpenAI;
      using Azure.Identity;
      using OpenAI.Files;

      // 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: "synthetic_500_quarterly_results.csv",
          purpose: FileUploadPurpose.Assistants);
      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);
      ```

      ### Expected output

      The sample code produces output similar to the following example:

      ```console theme={null}
      Uploaded file: file-xxxxxxxxxxxxxxxxxxxx
      Here is the bar chart showing operating profit by quarter in the TRANSPORTATION sector...
      Chart downloaded: C:\Users\you\chart.png
      ```

      The agent uploads your CSV file to Azure storage, creates a sandboxed Python environment, analyzes the data to filter transportation sector records, and generates a PNG bar chart. The annotation parsing extracts the container ID and file ID from the response, which are used to download the chart to your local directory.
    </Tab>

    <Tab title="Hosted Agents">
      This sample uses the Microsoft Agent Framework and calls `AsAIAgent(...)` on `AIProjectClient` together with `HostedCodeInterpreterTool` to give the agent a sandboxed Python environment. Install the `Microsoft.Agents.AI.Foundry` and `Azure.AI.Projects` packages, set the `AZURE_AI_PROJECT_ENDPOINT` and `AZURE_AI_MODEL_DEPLOYMENT_NAME` environment variables, and sign in with `az login`.

      ```csharp theme={null}
      using System.Text;
      using Azure.AI.Projects;
      using Azure.Identity;
      using Microsoft.Agents.AI;
      using Microsoft.Extensions.AI;
      using OpenAI.Assistants;

      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 endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
          ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set.");
      string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5-mini";

      AIProjectClient aiProjectClient = new(new Uri(endpoint), new DefaultAzureCredential());

      AIAgent agent = aiProjectClient.AsAIAgent(
          deploymentName,
          instructions: AgentInstructions,
          name: AgentName,
          tools: [new HostedCodeInterpreterTool() { Inputs = [] }]);

      AgentResponse response = await agent.RunAsync("I need to solve the equation sin(x) + x^2 = 42");

      // Print the code that the agent generated.
      CodeInterpreterToolCallContent? toolCallContent = response.Messages
          .SelectMany(m => m.Contents)
          .OfType<CodeInterpreterToolCallContent>()
          .FirstOrDefault();
      if (toolCallContent?.Inputs is not null)
      {
          DataContent? codeInput = toolCallContent.Inputs.OfType<DataContent>().FirstOrDefault();
          if (codeInput?.HasTopLevelMediaType("text") ?? false)
          {
              Console.WriteLine($"Code Input: {Encoding.UTF8.GetString(codeInput.Data.ToArray())}");
          }
      }

      // Print the code execution result.
      CodeInterpreterToolResultContent? toolResultContent = response.Messages
          .SelectMany(m => m.Contents)
          .OfType<CodeInterpreterToolResultContent>()
          .FirstOrDefault();
      if (toolResultContent?.Outputs is not null &&
          toolResultContent.Outputs.OfType<TextContent>().FirstOrDefault() is { } resultOutput)
      {
          Console.WriteLine($"Code Tool Result: {resultOutput.Text}");
      }

      Console.WriteLine($"Agent: {response.Text}");
      ```

      ### Expected output

      The agent writes Python in the sandbox, runs it, and prints both the generated code and the final answer:

      ```console theme={null}
      Code Input: import math
      result = math.sin(0.5) + 0.5**2
      print(result)
      Code Tool Result: 0.7294255386042029
      Agent: One solution is x ≈ 0.5, since sin(0.5) + 0.5^2 ≈ 0.73 ...
      ```

      To download container files generated by the agent, see [Agent\_Step24\_CodeInterpreterFileDownload](https://github.com/microsoft/agent-framework/tree/main/dotnet/samples/02-agents/AgentProviders/foundry/Agent_Step24_CodeInterpreterFileDownload).
    </Tab>
  </Tabs>
</ZoneContent>

<ZoneContent group="csharp__java__python__rest__typescript" value="typescript" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}, {"id": "rest", "title": "REST"}]} values={["python", "csharp", "typescript", "java", "rest"]} defaultValue="python">
  ## Sample of using agent with code interpreter tool in TypeScript SDK

  The following TypeScript sample shows how to create an agent with the code interpreter tool, upload a CSV file for analysis, and request a bar chart based on the data. For a JavaScript version, see the [JavaScript sample](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/ai/ai-projects/samples/v2-beta/javascript/agents/agentCodeInterpreter.js) in the Azure SDK for JavaScript repository on GitHub.

  ```typescript theme={null}
  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);
  });
  ```

  ### Expected output

  The sample code produces output similar to the following example:

  ```console theme={null}
  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
  ```

  The agent uploads your CSV file to Azure storage, creates a sandboxed Python environment, analyzes the data to filter transportation sector records, generates a PNG bar chart showing operating profit by quarter, and downloads the chart to your local directory. The file annotations in the response provide the file ID and container information needed to retrieve the generated chart.
</ZoneContent>

<ZoneContent group="csharp__java__python__rest__typescript" value="java" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}, {"id": "rest", "title": "REST"}]} values={["python", "csharp", "typescript", "java", "rest"]} defaultValue="python">
  ## Create a chart with Code Interpreter in Java

  Add the dependency to your `pom.xml`:

  ```xml theme={null}
  <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-ai-agents</artifactId>
      <version>2.0.0</version>
  </dependency>
  ```

  ### Create an agent and generate a chart

  ```java theme={null}
  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.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.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());
      }
  }
  ```

  ### Expected output

  ```console theme={null}
  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.
  ```

  The agent creates a Code Interpreter session, writes Python code by using matplotlib to generate the chart, and executes the code in a sandboxed environment. For an example that uploads a CSV file and downloads the generated chart, select **Python** or **TypeScript** from the language selector at the top of this article. For more examples, see the [Azure AI Agents Java SDK samples](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/).
</ZoneContent>

<ZoneContent group="csharp__java__python__rest__typescript" value="rest" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}, {"id": "rest", "title": "REST"}]} values={["python", "csharp", "typescript", "java", "rest"]} defaultValue="python">
  ## Create a chart with Code Interpreter using the REST API

  The following example shows how to upload a CSV file, create an agent with Code Interpreter, request a chart, and download the generated file.

  ### Prerequisites

  Set these environment variables:

  * `FOUNDRY_PROJECT_ENDPOINT`: Your project endpoint URL.
  * `AGENT_TOKEN`: A bearer token for Foundry.

  Get an access token:

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

  ### 1. Upload a CSV file

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

  Save the `id` from the response (for example, `file-abc123`).

  ### 2. Create an agent with code interpreter

  ```bash theme={null}
  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. Generate a chart

  ```bash theme={null}
  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."
    }'
  ```

  The response includes `container_file_citation` annotations with the generated file details. Save the `container_id` and `file_id` values from the annotation.

  ### 4. Download the generated chart

  ```bash theme={null}
  curl -X GET "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/containers/<CONTAINER_ID>/files/<FILE_ID>/content" \
    -H "Authorization: Bearer $AGENT_TOKEN" \
    --output chart.png
  ```

  ### 5. Clean up

  ```bash theme={null}
  curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/chart-agent?api-version=v1" \
    -H "Authorization: Bearer $AGENT_TOKEN"
  ```
</ZoneContent>

## Check regional and model availability

Tool availability varies by region and model.

For the current list of supported regions and models for Code Interpreter, see [Best practices for using tools in Microsoft Foundry Agent Service](/tools-and-knowledge/tool-best-practice).

### Supported file types

| File format | MIME type                                                                   |
| ----------- | --------------------------------------------------------------------------- |
| `.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` or `text/xml`                                             |
| `.zip`      | `application/zip`                                                           |

## Troubleshooting

| Issue                               | Likely cause                                                 | Resolution                                                                                                                                                                                            |
| ----------------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Code Interpreter doesn't run.       | Tool not enabled or model doesn't support it in your region. | Confirm Code Interpreter is enabled on the agent. Verify your model deployment supports the tool in your region. See [Check regional and model availability](#check-regional-and-model-availability). |
| No file is generated.               | Agent returned text-only response without file annotation.   | Check response annotations for `container_file_citation`. If none exist, the agent didn't generate a file. Rephrase the prompt to explicitly request file output.                                     |
| File upload fails.                  | Unsupported file type or wrong purpose.                      | Confirm the file type is in the [supported file types](#supported-file-types) list. Upload with `purpose="assistants"`.                                                                               |
| Generated file is corrupt or empty. | Code execution error or incomplete processing.               | Check the agent's response for error messages. Verify the input data is valid. Try a simpler request first.                                                                                           |
| Session timeout or high latency.    | Code Interpreter sessions have time limits.                  | Sessions have a 1-hour active timeout and 30-minute idle timeout. Reduce the complexity of operations or split into smaller tasks.                                                                    |
| Unexpected billing charges.         | Multiple concurrent sessions created.                        | Each conversation creates a separate session. Monitor session usage and consolidate operations where possible.                                                                                        |
| Python package not available.       | Code Interpreter has a fixed set of packages.                | Code Interpreter includes common data science packages. For custom packages, use [Custom code interpreter](/tools-and-knowledge/custom-code-interpreter).                                             |
| File download fails.                | Container ID or file ID incorrect.                           | Verify you're using the correct `container_id` and `file_id` from the response annotations.                                                                                                           |

## Clean up resources

Delete resources you created in this sample when you no longer need them to avoid ongoing costs:

* Delete the agent version.
* Delete the conversation.
* Delete uploaded files.

For examples of conversation and file cleanup patterns, see [Web search tool](/tools-and-knowledge/web-search) and [File search tool for agents](/tools-and-knowledge/file-search).

## Sandboxed execution environment

Code Interpreter runs Python code in a Microsoft-managed sandbox. The sandbox is designed for running untrusted code and uses [dynamic sessions (code interpreter sessions) in Azure Container Apps](https://learn.microsoft.com/azure/container-apps/sessions-code-interpreter). Each session is isolated by a Hyper-V boundary.

Key behaviors to plan for:

* **Region**: The Code Interpreter sandbox runs in the same Azure region as your Foundry project.
* **Session lifetime**: A Code Interpreter session is active for up to one hour, with an idle timeout (see the *Important* note at the beginning of this article).
* **Isolation**: Each session runs in an isolated environment. If your agent invokes Code Interpreter concurrently in different conversations, separate sessions are created.
* **Network isolation and internet access**: The sandbox doesn't inherit your agent subnet configuration, and dynamic sessions can't make outbound network requests.
* **Files in the sandbox**: The sandboxed Python runtime has access to files you attach for analysis. Code Interpreter can also generate files, such as charts, and return them as downloadable outputs.

If you need more control over the sandbox runtime or you need a different isolation model, see [Custom code interpreter tool for agents](/tools-and-knowledge/custom-code-interpreter).

## Related content

* [Best practices for using tools in Microsoft Foundry Agent Service](/tools-and-knowledge/tool-best-practice)
* [Custom code interpreter tool for agents (preview)](/tools-and-knowledge/custom-code-interpreter)
