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

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

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

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

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

重要

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

使用支持

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

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

先决条件

  • 基本或标准代理环境。 有关详细信息,请参阅 代理环境设置
  • 已为您的语言安装最新的 SDK 包。 .NET 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# 示例演示如何使用代码解释器工具创建代理、上传 CSV 文件进行分析和下载生成的图表。 有关异步用法,请参阅 代码示例,在GitHub上的.NET存储库中找到Azure SDK。

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

预期输出

示例代码生成类似于以下示例的输出:

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

代理将 CSV 文件上传到Azure存储,创建沙盒Python环境,分析数据以筛选运输扇区记录,并生成 PNG 条形图。 批注分析从响应中提取容器 ID 和文件 ID,用于将图表下载到本地目录。

在 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</version>
</dependency>

创建代理并生成图表

import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.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());
    }
}

预期输出

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 文件并下载生成的图表的示例,请从本文顶部的语言选择器中选择 PythonTypeScript。 有关更多示例,请参阅 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 代理服务中使用工具的最佳做法

支持的文件类型

文件格式 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/xmltext/xml
.zip application/zip

故障 排除

问题 可能的原因 分辨率
代码解释器未运行。 工具未启用或模型在你的区域中不支持它。 确认代理上已启用代码解释器。 验证模型部署是否支持区域中的工具。 请参阅 “检查区域和模型可用性”。
未生成任何文件。 代理返回了不包含文件注释的仅限文本的响应。 检查container_file_citation的响应批注. 如果不存在,代理未生成文件。 重新表述提示,以明确请求文件输出。
文件上传失败。 不支持的文件类型或错误的用途。 确认文件类型位于 支持的文件类型 列表中。 使用purpose="assistants"进行上传。
生成的文件已损坏或为空。 代码执行错误或处理不完整。 检查智能体响应中的错误消息。 验证输入数据是否有效。 首先尝试更简单的请求。
会话超时或高延迟。 代码解释器会话具有时间限制。 会话具有 1 小时的活动超时和 30 分钟的空闲超时。 减少操作的复杂性或拆分为较小的任务。
意外的计费费用。 创建了多个并发会话。 每个对话都会创建一个单独的会话。 尽可能监视会话使用情况并合并操作。
Python包不可用。 代码解释器有一组固定的包。 代码解释器包括常见的数据科学包。 对于自定义包,请使用 自定义代码解释器
文件下载失败。 容器 ID 或文件 ID 不正确。 请验证您是否在响应批注中使用了正确的 container_idfile_id

清理资源

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

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

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

沙盒执行环境

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

要规划的主要行为:

  • Region:代码解释器沙盒与 Foundry 项目在同一Azure区域中运行。
  • 会话生命周期:代码解释器会话最多活跃一小时,并具有空闲超时(请参阅本文开头的“重要信息”说明)。
  • 隔离:每个会话在隔离的环境中运行。 如果代理在不同的会话中并发调用代码解释器,则创建单独的会话。
  • 网络隔离和 Internet 访问:沙盒不会继承代理子网配置,动态会话无法发出出站网络请求。
  • 沙盒中的文件:沙盒Python运行时有权访问附加的文件进行分析。 代码解释器还可以生成文件(如图表),并将它们作为可下载的输出返回。

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