Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
O Interpretador de Código permite que um agente do Microsoft Foundry execute Python código em um ambiente de execução em área restrita. O modelo foundry do agente grava e executa código para análise de dados, geração de gráfico e tarefas iterativas de solução de problemas.
Dica
Considere adicionar essa ferramenta usando uma caixa de ferramentas. Usando uma caixa de ferramentas, você pode reutilizar a ferramenta entre agentes e runtimes, bem como centralizar o gerenciamento de credenciais, controle de versão e imposição de política por meio de um ponto de extremidade MCP gerenciado. Consulte o início rápido da caixa de ferramentas.
Neste artigo, você cria um agente que usa o Interpretador de Código, carrega um arquivo CSV para análise e baixa um gráfico gerado.
Quando você habilita o Interpretador de Código, seu agente pode escrever e executar Python código iterativamente para resolver tarefas de análise e matemática de dados e gerar gráficos.
Importante
O Interpretador de Código tem encargos adicionais além das taxas baseadas em token para uso do Azure OpenAI. Se o agente chamar o Interpretador de Código simultaneamente em duas conversas diferentes, ele criará duas sessões de Interpretador de Código. Cada sessão está ativa por padrão por uma hora com um tempo limite ocioso de 30 minutos.
Pré-requisitos
- Ambiente de agente básico ou padrão. Consulte a configuração do ambiente do agente para obter detalhes.
- Pacote do SDK mais recente instalado para seu idioma. O SDK do .NET está atualmente em versão prévia. Consulte o início rápido para ver as etapas de instalação.
- Implantação de modelo de IA do Azure configurada no seu projeto.
Nota
O Interpretador de Código não está disponível em todas as regiões. Consulte Verifique a disponibilidade regional e de modelo.
Suporte ao uso
A tabela a seguir mostra o SDK e o suporte à instalação.
| Suporte ao Microsoft Foundry | SDK do Python | C# SDK | SDK para JavaScript | SDK do Java | API REST | Configuração básica do agente | Configuração do agente padrão |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
Criar um agente com o Interpretador de Código
Os exemplos a seguir demonstram como criar um agente com o Interpretador de Código habilitado, carregar um arquivo para análise e baixar a saída gerada. Cada exemplo de upload de arquivo gera um CSV pequeno no diretório de trabalho atual, carrega-o e exclui o arquivo temporário local.
Dica
Você pode personalizar o comportamento do Interpretador de Código em runtime, como especificar quais arquivos incluir ou ajustar parâmetros de ferramenta por solicitação usando entradas estruturadas.
Exemplo de como usar o agente com a ferramenta de interpretador de código no SDK do Python
O exemplo de Python a seguir mostra como adicionar a ferramenta de interpretador de código a uma caixa de ferramentas, anexar a caixa de ferramentas a um agente, carregar um arquivo CSV para análise e solicitar um gráfico de barras com base nos dados. Selecione Prompt Agents para usar o SDK de Projetos de IA Azure para criar um agente de prompt do lado do servidor ou Hosted Agents para usar o Agent Framework FoundryChatClient para criar um agente efêmero em processo.
Agentes de prompt
Este exemplo demonstra um fluxo de trabalho completo: carregar um arquivo, criar um agente com o Interpretador de Código habilitado, solicitar visualização de dados e baixar o gráfico gerado.
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")
Saída esperada
O código de exemplo produz uma saída semelhante ao seguinte exemplo:
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
O agente carrega seu arquivo CSV para Azure armazenamento, cria um ambiente de Python em área restrita, filtra empresas do setor de transporte, gera um gráfico de barras PNG mostrando o lucro operacional por empresa e baixa o gráfico para seu diretório local. As anotações de arquivo na resposta fornecem a ID do arquivo e as informações de contêiner necessárias para recuperar o gráfico gerado.
Agentes hospedados
Este exemplo cria o toolbox de interpretador de código, depois usa FoundryChatClient do Microsoft Agent Framework e se conecta ao endpoint MCP do toolbox usando FoundryToolbox. Defina as variáveis de ambiente FOUNDRY_PROJECT_ENDPOINT e FOUNDRY_MODEL e faça login com az login.
import asyncio
import os
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient, FoundryToolbox
from azure.identity import AzureCliCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import CodeInterpreterToolboxTool, AutoCodeInterpreterToolParam
PROJECT_ENDPOINT = "https://<account>.services.ai.azure.com/api/projects/<project>"
CSV_DATA = """name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
"""
async def main() -> None:
credential = AzureCliCredential()
csv_path = os.path.abspath("synthetic-company-financial-results.csv")
with open(csv_path, "w", encoding="utf-8", newline="") as csv_file:
csv_file.write(CSV_DATA)
# 1. Add the code interpreter tool to a toolbox. Using a toolbox is the recommended way
# to give agents tools: you curate tools once and reuse the toolbox across agents.
# See /azure/foundry/agents/concepts/toolbox-overview
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=credential)
openai = project.get_openai_client()
with open(csv_path, "rb") as csv_file:
file = openai.files.create(purpose="assistants", file=csv_file)
os.remove(csv_path)
toolbox = project.toolboxes.create_version(
name="code-interpreter-toolbox",
description="Toolbox with the code interpreter tool",
tools=[CodeInterpreterToolboxTool(container=AutoCodeInterpreterToolParam(file_ids=[file.id]))],
)
# 2. The toolbox exposes an MCP-compatible endpoint.
TOOLBOX_MCP_URL = (
f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
f"/versions/{toolbox.version}/mcp?api-version=v1"
)
# 3. Attach the toolbox to the hosted agent as an MCP tool.
, timeout=120.0)
toolbox_tool = FoundryToolbox(credential, url=TOOLBOX_MCP_URL)
agent = Agent(
client=FoundryChatClient(credential=credential),
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
tools=[toolbox_tool],
)
result = await agent.run("Use code to calculate the factorial of 100.")
print(f"Agent: {result.text}")
if __name__ == "__main__":
asyncio.run(main())
Saída esperada
O agente gera código Python, executa-o no contêiner isolado e retorna a resposta:
Agent: 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Para obter o exemplo completo (incluindo entradas de arquivo e extração do código gerado), consulte foundry_chat_client_with_code_interpreter.py e foundry_chat_client_code_interpreter_files.py.
Criar um gráfico com o Interpretador de Código em C#
O exemplo de C# a seguir mostra como adicionar a ferramenta Interpretador de Código a uma caixa de ferramentas, anexar a caixa de ferramentas a um agente, carregar um arquivo CSV para análise e baixar o gráfico gerado. Selecione Prompt Agents para usar o SDK de Projetos de IA Azure para criar um agente de prompt do lado do servidor ou Hosted Agents para usar o Microsoft Agent Framework para criar um agente efêmero em processo.
Agentes de prompt
Para uso assíncrono, consulte o exemplo de código no repositório do SDK do Azure para .NET no 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);
Saída esperada
O código de exemplo produz uma saída semelhante ao seguinte exemplo:
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
O agente carrega seu arquivo CSV para Azure armazenamento, cria um ambiente de Python em área restrita, analisa os dados para filtrar registros do setor de transporte e gera um gráfico de barras PNG. A análise de anotação extrai a ID do contêiner e a ID do arquivo da resposta, que são usadas para baixar o gráfico para o diretório local.
Agentes hospedados
Este exemplo cria a caixa de ferramentas do interpretador de código e, em seguida, usa a integração do Microsoft Agent Framework AddFoundryToolboxes para disponibilizar o Interpretador de Código para o agente hospedado. Defina as variáveis de ambiente AZURE_AI_PROJECT_ENDPOINT, AZURE_OPENAI_ENDPOINT e AZURE_AI_MODEL_DEPLOYMENT_NAME e faça login com az login.
using System;
using System.IO;
using Azure.AI.AgentServer.Responses;
using Azure.AI.AgentServer.Responses.Models;
using Azure.AI.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OpenAI.Chat;
using OpenAI.Files;
const string CsvData = """
name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
""";
const string AgentInstructions = "You are a personal math tutor. When asked a math question, write and run code using the python tool to answer the question.";
const string AgentName = "CoderAgent";
string projectEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
?? "https://<account>.services.ai.azure.com/api/projects/<project>";
string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5-mini";
DefaultAzureCredential credential = new();
// 1. Add the code interpreter tool to a toolbox. Using a toolbox is the recommended
// way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
AIProjectClient projectClient = new(endpoint: new Uri(projectEndpoint), tokenProvider: credential);
OpenAIFileClient fileClient = projectClient.ProjectOpenAIClient.GetOpenAIFileClient();
string csvPath = Path.GetFullPath("synthetic-company-financial-results.csv");
File.WriteAllText(csvPath, CsvData);
OpenAIFile uploadedFile = fileClient.UploadFile(
filePath: csvPath,
purpose: FileUploadPurpose.Assistants);
File.Delete(csvPath);
ProjectsAgentTool codeInterpreterTool = ProjectsAgentTool.AsProjectTool(
ResponseTool.CreateCodeInterpreterTool(
new CodeInterpreterToolContainer(
CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration(
fileIds: [uploadedFile.Id]
)
)
));
ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
.GetAgentToolboxes().CreateToolboxVersion(
toolboxName: "code-interpreter-toolbox",
tools: [codeInterpreterTool],
description: "Toolbox with the code interpreter tool");
// Create the hosted agent and register the toolbox integration.
AIAgent agent = projectClient.AsAIAgent(
model: deploymentName,
instructions: "You are a helpful assistant with access to the toolbox tools.",
name: "hosted-toolbox-agent");
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFoundryResponses(agent);
builder.Services.AddFoundryToolboxes(credential, toolboxVersion.Name);
var app = builder.Build();
app.MapFoundryResponses();
app.Run();
Saída esperada
O agente hospedado usa o endpoint MCP do Toolbox para executar Python no sandbox e retornar a resposta final:
Response: One solution is x ≈ 6.36, since sin(x) + x^2 is approximately 42 at that value.
Para obter uma integração mantida do .NET Agent Framework, consulte Usar uma caixa de ferramentas com um agente hospedado.
Exemplo de como usar o agente com a ferramenta de interpretador de código no SDK do TypeScript
O exemplo de TypeScript a seguir mostra como adicionar a ferramenta de interpretador de código a uma caixa de ferramentas, anexar a caixa de ferramentas a um agente, carregar um arquivo CSV para análise e solicitar um gráfico de barras com base nos dados. Para obter uma versão do JavaScript, consulte o exemplo JavaScript no repositório SDK do Azure para JavaScript no 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);
});
Saída esperada
O código de exemplo produz uma saída semelhante ao seguinte exemplo:
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
O agente carrega seu arquivo CSV para Azure armazenamento, cria um ambiente de Python em área restrita, filtra empresas do setor de transporte, gera um gráfico de barras PNG mostrando o lucro operacional por empresa e baixa o gráfico para seu diretório local. As anotações de arquivo na resposta fornecem a ID do arquivo e as informações de contêiner necessárias para recuperar o gráfico gerado.
Criar um gráfico com o Interpretador de Código no Java
Para a maioria dos agentes, adicione a ferramenta de interpretador de código por meio de uma caixa de ferramentas e anexe a caixa de ferramentas ao seu agente como uma ferramenta MCP. O SDK do Java ainda não expõe uma API de criação de caixa de ferramentas, portanto, crie a caixa de ferramentas usando um dos métodos atualmente compatíveis (Python, API REST, C#, TypeScript ou o portal da Foundry). Depois que a caixa de ferramentas for criada, referencie o seu ponto de extremidade MCP a partir do seu agente Java como um McpTool. O exemplo a seguir anexa o ponto de extremidade do MCP da caixa de ferramenta do interpretador de código ao agente.
Adicione a dependência ao seu pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.2.0</version>
</dependency>
Criar um agente e gerar um gráfico
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());
}
}
Saída esperada
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.
O agente usa o Interpretador de Código por meio do endpoint MCP da caixa de ferramentas, escreve código Python usando o matplotlib para gerar o gráfico e executa o código em um ambiente isolado. Para obter um exemplo que carrega um arquivo CSV e baixa o gráfico gerado, selecione Python ou TypeScript no seletor de idioma na parte superior deste artigo. Para obter mais exemplos, consulte os exemplos do SDK do Azure AI Agents para Java.
Criar um gráfico com o Interpretador de Código usando a API REST
O exemplo a seguir mostra como carregar um arquivo CSV, criar um agente com o Interpretador de Código, solicitar um gráfico e baixar o arquivo gerado.
Pré-requisitos
Defina estas variáveis de ambiente:
-
FOUNDRY_PROJECT_ENDPOINT: URL do endpoint do projeto. -
AGENT_TOKEN: um token de portador para o Foundry.
Obtenha um token de acesso:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
Usar o Interpretador de Código em uma caixa de ferramentas
Para carregar um arquivo para ser usado pelo Interpretador de Código por meio de uma caixa de ferramentas, carregue o arquivo no ponto de extremidade de Arquivos no nível de recurso (POST {account_endpoint}/openai/v1/files) com o cabeçalho x-aml-project-id. Ao contrário do fluxo do agente de prompt, os arquivos carregados por meio do ponto de extremidade de Arquivos com escopo de projeto (/api/projects/{name}/openai/v1/files) recebem um owner_id que o contêiner da caixa de ferramentas não consegue verificar, portanto tools/call falha com um erro de verificação de propriedade.
Obtenha o GUID do projeto do Azure Resource Manager. Use
properties.amlWorkspace.internalId(formato UUID com traços), notproperties.internalId(sem traços - o contêiner da caixa de ferramentas não o aceita):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')Carregue o arquivo no nível da conta (recurso) com o cabeçalho
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
O arquivo id retornado é o valor fornecido como <FILE_ID> na configuração da ferramenta. Os arquivos são montados no sandbox em /mnt/data/{file-id}-{original-filename}.
Importante
Quando o Interpretador de Código é usado por meio de uma caixa de ferramentas em um agente hospedado, não há suporte para o isolamento do usuário. Todos os usuários no mesmo projeto compartilham o mesmo contexto de contêiner.
Adicionar interpretador de código a uma caixa de ferramentas
Adicione o Interpretador de Código criando uma caixa de ferramentas e anexe a caixa de ferramentas ao agente como uma ferramenta MCP. Para obter mais informações, consulte o que é uma caixa de ferramentas?
Crie uma caixa de ferramentas que contenha a ferramenta de interpretador de código:
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>"] } } ] }'O kit de ferramentas expõe um endpoint compatível com MCP em
$FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1, em que<version>é a versão retornada pela chamada anterior.Crie uma conexão de projeto de ferramenta remota que aponte para o ponto de extremidade da caixa de ferramentas, usando um token Entra do usuário para que a identidade do chamador seja passada (audiência
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
Criar um agente com a caixa de ferramentas do interpretador de código
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"
}
]
}
}'
Gerar um gráfico
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."
}'
A resposta inclui container_file_citation anotações com os detalhes do arquivo gerado. Salve os valores container_id e file_id da anotação.
Baixar o gráfico gerado
curl -X GET "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/containers/<CONTAINER_ID>/files/<FILE_ID>/content" \
-H "Authorization: Bearer $AGENT_TOKEN" \
--output chart.png
Limpeza
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/chart-agent?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
Verificar a disponibilidade regional e de modelo
A disponibilidade da ferramenta varia de acordo com a região e o modelo.
Para obter a lista atual de regiões e modelos com suporte para o Interpretador de Código, consulte as Práticas recomendadas para usar ferramentas no Microsoft Foundry Agent Service.
Tipos de arquivo com suporte
| Formato de arquivo | tipo de 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 Ou text/xml |
.zip |
application/zip |
Solucionando problemas
| Questão | Causa provável | Resolução |
|---|---|---|
| O Interpretador de Código não é executado. | A ferramenta não está habilitada ou o modelo não dá suporte a ela em sua região. | Confirme se o Interpretador de Código está habilitado no agente. Verifique se a implantação do modelo dá suporte à ferramenta em sua região. Consulte Verifique a disponibilidade regional e de modelo. |
| Nenhum arquivo é gerado. | A resposta do agente foi apenas em texto, sem anotação de arquivo. | Verifique as anotações de resposta para container_file_citation. Caso não exista nenhum, o agente não gerou um arquivo. Reformular o prompt para solicitar explicitamente a saída do arquivo. |
| Falha no upload do arquivo. | Tipo de arquivo sem suporte ou finalidade incorreta. | Confirme se o tipo de arquivo está na lista de tipos de arquivo com suporte . Carregar com purpose="assistants". |
| O arquivo gerado está corrompido ou vazio. | Erro de execução de código ou processamento incompleto. | Verifique a resposta do agente em busca de mensagens de erro. Verifique se os dados de entrada são válidos. Tente uma solicitação mais simples primeiro. |
| Tempo limite de sessão ou alta latência. | As sessões do Interpretador de Código têm limites de tempo. | As sessões têm um tempo limite ativo de 1 hora e tempo limite ocioso de 30 minutos. Reduza a complexidade das operações ou divida em tarefas menores. |
| Cobranças inesperadas. | Várias sessões simultâneas criadas. | Cada conversa cria uma sessão separada. Monitore o uso da sessão e consolide as operações sempre que possível. |
| Python pacote não disponível. | O Interpretador de Código tem um conjunto fixo de pacotes. | O Interpretador de Código inclui pacotes comuns de ciência de dados. Para pacotes personalizados, use o interpretador de código personalizado. |
| Falha no download do arquivo. | ID do contêiner ou ID de arquivo incorreto. | Verifique se você está usando container_id e file_id corretos das anotações de resposta. |
Limpar recursos
Exclua os recursos criados neste exemplo quando não precisar mais deles para evitar custos contínuos:
- Exclua a versão do agente.
- Exclua a conversa.
- Excluir arquivos carregados.
Para obter exemplos de padrões de conversa e limpeza de arquivos, consulte a ferramenta de pesquisa na Web e a ferramenta de pesquisa de arquivos para agentes.
Ambiente de execução em área restrita
O Interpretador de Código executa código Python em uma área restrita gerenciada pela Microsoft. A área restrita foi projetada para executar código não confiável e usa sessões dinâmicas (sessões de interpretador de código) em Aplicativos de Contêiner do Azure. Cada sessão é isolada por um limite Hyper-V.
Comportamentos principais para planejar
- Region: A sandbox do Interpretador de Código é executada na mesma região do Azure que o projeto Foundry.
- Tempo de vida da sessão: uma sessão de Interpretador de Código está ativa por até uma hora, com um tempo limite ocioso (consulte a nota Importante no início deste artigo).
- Isolamento: cada sessão é executada em um ambiente isolado. Se o agente invocar o Interpretador de Código simultaneamente em conversas diferentes, sessões separadas serão criadas.
- Isolamento de rede e acesso à Internet: a sandbox não herda a configuração da sub-rede do agente e as sessões dinâmicas não podem fazer requisições de rede externa.
- Arquivos no sandbox: o ambiente de execução Python em sandbox tem acesso aos arquivos que você anexa para análise. O Interpretador de Código também pode gerar arquivos, como gráficos, e devolvê-los como saídas para download.
Se você precisar de mais controle sobre o runtime de área restrita ou precisar de um modelo de isolamento diferente, consulte a ferramenta de interpretador de código personalizado para agentes.