Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Penerjemah Kode memungkinkan agen Microsoft Foundry menjalankan kode Python di lingkungan eksekusi terisolasi. Model Foundry agen menulis dan menjalankan kode untuk analisis data, pembuatan bagan, dan tugas pemecahan masalah berulang.
Tips
Pertimbangkan untuk menambahkan alat ini menggunakan kotak alat. Dengan menggunakan kotak alat, Anda dapat menggunakan kembali alat di seluruh agen dan runtime, serta memusatkan manajemen kredensial, penerapan versi, dan penegakan kebijakan melalui titik akhir MCP terkelola. Lihat panduan memulai cepat kotak peralatan.
Dalam artikel ini, Anda membuat agen yang menggunakan Penerjemah Kode, mengunggah file CSV untuk analisis, dan mengunduh bagan yang dihasilkan.
Saat Anda mengaktifkan Penerjemah Kode, agen Anda dapat menulis dan menjalankan kode Python secara berulang untuk menyelesaikan analisis data dan tugas matematika, dan untuk menghasilkan bagan.
Penting
Penerjemah Kode memiliki biaya tambahan di luar biaya berbasis token untuk penggunaan OpenAI Azure. Jika agen Anda memanggil Code Interpreter secara bersamaan dalam dua percakapan yang berbeda, itu akan membuat dua sesi Code Interpreter. Setiap sesi aktif secara default selama satu jam dengan batas waktu diam 30 menit.
Prasyarat
- Lingkungan agen dasar atau standar. Lihat penyiapan lingkungan agen untuk detailnya.
- Paket SDK terbaru yang diinstal untuk bahasa Anda. SDK .NET saat ini dalam pratinjau. Lihat panduan cepat untuk langkah-langkah penginstalan.
- Penyebaran model AI Azure dikonfigurasi dalam proyek Anda.
Catatan
Penerjemah Kode tidak tersedia di semua wilayah. Lihat Periksa ketersediaan regional dan model.
Dukungan penggunaan
Tabel berikut ini memperlihatkan SDK dan dukungan penyiapan.
| dukungan Microsoft Foundry | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API | Penyiapan agen dasar | Penyiapan agen standar |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
Membuat agen dengan Penerjemah Kode
Sampel berikut menunjukkan cara membuat agen dengan Penerjemah Kode diaktifkan, mengunggah file untuk analisis, dan mengunduh output yang dihasilkan. Setiap sampel unggahan file menghasilkan CSV kecil di direktori kerja saat ini, mengunggahnya, lalu menghapus file sementara lokal.
Tips
Anda dapat menyesuaikan perilaku Penerjemah Kode saat runtime, seperti menentukan file mana yang akan disertakan atau menyesuaikan parameter alat per permintaan, dengan menggunakan input terstruktur.
Sampel penggunaan agen dengan alat penerjemah kode di SDK Python
Sampel Python berikut menunjukkan cara menambahkan alat penerjemah kode ke kotak alat, melampirkan kotak alat ke agen, mengunggah file CSV untuk analisis, dan meminta bagan batang berdasarkan data. Pilih Prompt Agents untuk menggunakan Azure AI Projects SDK untuk membuat agen prompt sisi server, atau Hosted Agents untuk menggunakan Agent Framework FoundryChatClient untuk membangun agen sementara dan dalam proses.
Agen pemicu
Sampel ini menunjukkan alur kerja lengkap: mengunggah file, membuat agen dengan Penerjemah Kode diaktifkan, meminta visualisasi data, dan mengunduh bagan yang dihasilkan.
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, CodeInterpreterTool, AutoCodeInterpreterToolParam
CSV_DATA = """name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
"""
csv_path = os.path.abspath("synthetic-company-financial-results.csv")
with open(csv_path, "w", encoding="utf-8", newline="") as csv_file:
csv_file.write(CSV_DATA)
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Upload the generated CSV file for the code interpreter to use
with open(csv_path, "rb") as csv_file:
file = openai.files.create(purpose="assistants", file=csv_file)
os.remove(csv_path)
# Create agent with code interpreter tool
agent = project.agents.create_version(
agent_name="MyAgent",
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="You are a helpful assistant.",
tools=[CodeInterpreterTool(container=AutoCodeInterpreterToolParam(file_ids=[file.id]))],
),
description="Code interpreter agent for data analysis and visualization.",
)
# Create a conversation for the agent interaction
conversation = openai.conversations.create()
# Send request to create a chart and generate a file
response = openai.responses.create(
conversation=conversation.id,
input="Could you please create bar chart in TRANSPORTATION sector for the operating profit from the uploaded csv file and provide file to me?",
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
# Extract file information from response annotations
file_id = ""
filename = ""
container_id = ""
# Get the last message which should contain file citations
last_message = response.output[-1] # ResponseOutputMessage
if (
last_message.type == "message"
and last_message.content
and last_message.content[-1].type == "output_text"
and last_message.content[-1].annotations
):
file_citation = last_message.content[-1].annotations[-1] # AnnotationContainerFileCitation
if file_citation.type == "container_file_citation":
file_id = file_citation.file_id
filename = file_citation.filename
container_id = file_citation.container_id
print(f"Found generated file: {filename} (ID: {file_id})")
# Clean up resources
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
# Download the generated file if available
if file_id and filename:
file_content = openai.containers.files.content.retrieve(file_id=file_id, container_id=container_id)
print(f"File ready for download: {filename}")
file_path = os.path.join(os.path.dirname(__file__), filename)
with open(file_path, "wb") as f:
f.write(file_content.read())
print(f"File downloaded successfully: {file_path}")
else:
print("No file generated in response")
Output yang diharapkan
Kode sampel menghasilkan output yang mirip dengan contoh berikut:
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
Agen mengunggah file CSV Anda ke penyimpanan Azure, membuat lingkungan Python terkotakpasir, memfilter perusahaan sektor transportasi, menghasilkan bagan batang PNG yang menunjukkan laba operasi oleh perusahaan, dan mengunduh bagan ke direktori lokal Anda. Anotasi file dalam respons menyediakan ID file dan informasi kontainer yang diperlukan untuk mengambil bagan yang dihasilkan.
Agen yang Dihosting
Contoh ini membuat toolbox code-interpreter, lalu menggunakan FoundryChatClient dari Microsoft Agent Framework dan menghubungkan ke endpoint MCP dari toolbox menggunakan FoundryToolbox. Atur FOUNDRY_PROJECT_ENDPOINT variabel lingkungan dan FOUNDRY_MODEL , dan masuk dengan 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.
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())
Output yang diharapkan
Agen menghasilkan kode Python, menjalankannya di kontainer tersandbox, dan mengembalikan jawabannya:
Agent: 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Untuk sampel lengkap (termasuk input file dan mengekstrak kode yang dihasilkan), lihat foundry_chat_client_with_code_interpreter.py dan foundry_chat_client_code_interpreter_files.py.
Membuat bagan dengan Penerjemah Kode di C#
Sampel C# berikut menunjukkan cara menambahkan alat Penerjemah Kode ke kotak alat, melampirkan kotak alat ke agen, mengunggah file CSV untuk analisis, dan mengunduh bagan yang dihasilkan. Pilih Prompt Agents untuk menggunakan Azure AI Projects SDK untuk membuat agen prompt sisi server, atau Hosted Agents untuk menggunakan Microsoft Agent Framework untuk membangun agen sementara dalam proses.
Agen pemicu
Untuk penggunaan asinkron, lihat sampel code di Azure SDK untuk repositori .NET pada GitHub.
using System;
using System.IO;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using OpenAI.Files;
const string CsvData = """
name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
""";
string csvPath = Path.GetFullPath("synthetic-company-financial-results.csv");
File.WriteAllText(csvPath, CsvData);
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Upload a CSV file for Code Interpreter to analyze
OpenAIFileClient fileClient = projectClient.ProjectOpenAIClient.GetOpenAIFileClient();
OpenAIFile uploadedFile = fileClient.UploadFile(
filePath: csvPath,
purpose: FileUploadPurpose.Assistants);
File.Delete(csvPath);
Console.WriteLine($"Uploaded file: {uploadedFile.Id}");
// Create an agent with Code Interpreter enabled
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
Instructions = "You are a helpful assistant.",
Tools = {
ResponseTool.CreateCodeInterpreterTool(
new CodeInterpreterToolContainer(
CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration(
fileIds: [uploadedFile.Id]
)
)
),
}
};
ProjectsAgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myChartAgent",
options: new(agentDefinition));
// Request chart generation from the uploaded CSV data
AgentReference agentReference = new(name: agentVersion.Name, version: agentVersion.Version);
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentReference);
ResponseResult response = responseClient.CreateResponse(
"Could you please create bar chart in TRANSPORTATION sector for the operating profit " +
"from the uploaded csv file and provide file to me?");
Console.WriteLine(response.GetOutputText());
// Extract file information from response annotations
ContainerFileCitationMessageAnnotation containerAnnotation = null;
foreach (ResponseItem item in response.OutputItems)
{
if (item is MessageResponseItem messageItem)
{
foreach (ResponseContentPart content in messageItem.Content)
{
foreach (ResponseMessageAnnotation annotation in content.OutputTextAnnotations)
{
if (annotation is ContainerFileCitationMessageAnnotation cntrAnnotation)
{
containerAnnotation = cntrAnnotation;
}
}
}
}
}
// Download the generated chart if available
if (containerAnnotation is not null)
{
ContainerClient containerClient = projectClient.ProjectOpenAIClient.GetContainerClient();
BinaryData fileData = containerClient.DownloadContainerFile(
containerId: containerAnnotation.ContainerId,
fileId: containerAnnotation.FileId);
File.WriteAllBytes("chart.png", fileData.ToArray());
Console.WriteLine($"Chart downloaded: {Path.GetFullPath("chart.png")}");
}
else
{
Console.WriteLine("No file generated in response");
}
// Clean up resources
projectClient.AgentAdministrationClient.DeleteAgentVersion(
agentName: agentVersion.Name, agentVersion: agentVersion.Version);
Output yang diharapkan
Kode sampel menghasilkan output yang mirip dengan contoh berikut:
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
Agen mengunggah file CSV Anda ke penyimpanan Azure, menciptakan lingkungan Python terisolasi, menganalisis data untuk memfilter catatan sektor transportasi, dan menghasilkan grafik batang PNG. Penguraian anotasi mengekstrak ID kontainer dan ID file dari respons, yang digunakan untuk mengunduh bagan ke direktori lokal Anda.
Agen yang Dihosting
Sampel ini membuat kotak alat penerjemah kode, lalu menggunakan integrasi Microsoft Agent Framework AddFoundryToolboxes untuk membuat Penerjemah Kode tersedia untuk agen yang dihosting. Atur AZURE_AI_PROJECT_ENDPOINTvariabel lingkungan , AZURE_OPENAI_ENDPOINT, dan AZURE_AI_MODEL_DEPLOYMENT_NAME , dan masuk dengan 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();
Output yang diharapkan
Agen terhosting menggunakan endpoint MCP toolbox untuk menjalankan Python di sandbox dan mengembalikan jawaban akhir:
Response: One solution is x ≈ 6.36, since sin(x) + x^2 is approximately 42 at that value.
Untuk integrasi .NET Agent Framework yang dikelola, lihat Menggunakan kotak alat dengan agen yang dihosting.
Sampel penggunaan agen dengan alat penerjemah kode di TypeScript SDK
Sampel TypeScript berikut menunjukkan cara menambahkan alat penerjemah kode ke kotak alat, melampirkan kotak alat ke agen, mengunggah file CSV untuk analisis, dan meminta bagan batang berdasarkan data. Untuk versi JavaScript, lihat sampel JavaScript di Azure SDK untuk repositori JavaScript di GitHub.
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const CSV_DATA = `name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
`;
export async function main(): Promise<void> {
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Generate and upload the CSV file
const csvPath = "synthetic-company-financial-results.csv";
fs.writeFileSync(csvPath, CSV_DATA);
const fileStream = fs.createReadStream(csvPath);
// Upload CSV file
const uploadedFile = await openai.files.create({
file: fileStream,
purpose: "assistants",
});
fs.unlinkSync(csvPath);
console.log("Creating a toolbox with the code interpreter tool...");
// 1. Add the code interpreter tool to a toolbox. Using a toolbox is the recommended
// way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
const toolbox = await project.toolboxes.createVersion(
"code-interpreter-toolbox",
[
{
type: "code_interpreter",
container: {
type: "auto",
file_ids: [uploadedFile.id],
},
},
],
{ description: "Toolbox with the code interpreter tool" },
);
// 2. The toolbox exposes an MCP-compatible endpoint.
const toolboxMcpUrl =
`${PROJECT_ENDPOINT}/toolboxes/${toolbox.name}` +
`/versions/${toolbox.version}/mcp?api-version=v1`;
// 3. Create a remote-tool project connection that points at the toolbox endpoint.
// Use a user Entra token so the caller's identity is passed through
// (audience https://ai.azure.com). Create the connection once, for example
// with the Azure Developer CLI:
//
// azd ai connection create code-interpreter-toolbox-conn \
// --kind remote-tool \
// --target "<toolboxMcpUrl>" \
// --auth-type user-entra-token \
// --audience https://ai.azure.com
const toolboxConnectionName = "code-interpreter-toolbox-conn";
// 4. Attach the toolbox to a prompt agent as an MCP tool.
const agent = await project.agents.createVersion("MyAgent", {
kind: "prompt",
model: "gpt-5-mini",
instructions: "You are a helpful assistant.",
tools: [
{
type: "mcp",
server_label: "toolbox",
server_url: toolboxMcpUrl,
require_approval: "never",
project_connection_id: toolboxConnectionName,
},
],
});
// Create a conversation
const conversation = await openai.conversations.create();
// Request chart generation
const response = await openai.responses.create(
{
conversation: conversation.id,
input:
"Could you please create bar chart in TRANSPORTATION sector for the operating profit from the uploaded csv file and provide file to me?",
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
// Extract file information from response annotations
let fileId = "";
let filename = "";
let containerId = "";
// Get the last message which should contain file citations
const lastMessage = response.output?.[response.output.length - 1];
if (lastMessage && lastMessage.type === "message") {
// Get the last content item
const textContent = lastMessage.content?.[lastMessage.content.length - 1];
if (textContent && textContent.type === "output_text" && textContent.annotations) {
// Get the last annotation (most recent file)
const fileCitation = textContent.annotations[textContent.annotations.length - 1];
if (fileCitation && fileCitation.type === "container_file_citation") {
fileId = fileCitation.file_id;
filename = fileCitation.filename;
containerId = fileCitation.container_id;
console.log(`Found generated file: ${filename} (ID: ${fileId})`);
}
}
}
// Download the generated file if available
if (fileId && filename) {
const safeFilename = path.basename(filename);
const fileContent = await openai.containers.files.content.retrieve(
fileId,
{ container_id: containerId },
);
const buffer = Buffer.from(await fileContent.arrayBuffer());
fs.writeFileSync(safeFilename, buffer);
console.log(`File ${safeFilename} downloaded successfully.`);
console.log(`File ready for download: ${safeFilename}`);
} else {
console.log("No file generated in response");
}
// Clean up resources
await project.agents.deleteVersion(agent.name, agent.version);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Output yang diharapkan
Kode sampel menghasilkan output yang mirip dengan contoh berikut:
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
Agen mengunggah file CSV Anda ke penyimpanan Azure, membuat lingkungan Python terkotakpasir, memfilter perusahaan sektor transportasi, menghasilkan bagan batang PNG yang menunjukkan laba operasi oleh perusahaan, dan mengunduh bagan ke direktori lokal Anda. Anotasi file dalam respons menyediakan ID file dan informasi kontainer yang diperlukan untuk mengambil bagan yang dihasilkan.
Membuat bagan dengan Penerjemah Kode di Java
Untuk sebagian besar agen, tambahkan alat penerjemah kode melalui kotak alat dan lampirkan kotak alat ke agen Anda sebagai alat MCP. SDK Java belum mengekspos API pembuatan kotak alat, jadi buat kotak alat dengan menggunakan salah satu metode yang saat ini didukung (Python, REST API, C#, TypeScript, atau portal Foundry). Setelah kotak alat dibuat, referensikan titik akhir MCP-nya dari agen Java Anda sebagai McpTool. Contoh berikut melampirkan titik akhir MCP kotak alat penerjemah kode ke agen.
Tambahkan dependensi ke pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.2.0</version>
</dependency>
Membuat agen dan membuat bagan
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.McpTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import java.util.Collections;
public class CodeInterpreterChartExample {
public static void main(String[] args) {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
String toolboxMcpUrl = projectEndpoint
+ "/toolboxes/code-interpreter-toolbox/versions/1/mcp?api-version=v1";
String toolboxConnectionName = "code-interpreter-toolbox-conn";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
AgentsClient agentsClient = builder.buildAgentsClient();
ResponsesClient responsesClient = builder.buildResponsesClient();
// The Java SDK doesn't yet expose a toolbox creation API. Create the
// code-interpreter toolbox with Python, REST, C#, TypeScript, or the
// Foundry portal, then attach its MCP endpoint as an MCP tool.
McpTool toolboxTool = new McpTool("toolbox")
.setServerUrl(toolboxMcpUrl)
.setProjectConnectionId(toolboxConnectionName)
.setRequireApproval("never");
// Create agent with the code-interpreter toolbox MCP tool
PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-5-mini")
.setInstructions("You are a data visualization assistant. When asked to create charts, "
+ "write and run Python code using matplotlib to generate them.")
.setTools(Collections.singletonList(toolboxTool));
AgentVersionDetails agent = agentsClient.createAgentVersion("chart-agent", agentDefinition);
// Request a bar chart with inline data
AgentReference agentReference = new AgentReference(agent.getName())
.setVersion(agent.getVersion());
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("Create a bar chart showing quarterly revenue for 2025: "
+ "Q1=$2.1M, Q2=$2.8M, Q3=$3.2M, Q4=$2.9M. "
+ "Use a blue color scheme, add data labels on each bar, "
+ "and title the chart 'Quarterly Revenue 2025'. "
+ "Save the chart as a PNG file."));
System.out.println("Response: " + response.output());
// Clean up
agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
}
}
Output yang diharapkan
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.
Agen menggunakan Code Interpreter melalui endpoint MCP toolbox, menulis kode Python menggunakan matplotlib untuk membuat bagan, dan menjalankan kode tersebut di lingkungan sandbox. Misalnya yang mengunggah file CSV dan mengunduh bagan yang dihasilkan, pilih Python atau TypeScript dari pemilih bahasa di bagian atas artikel ini. Untuk contoh lebih lanjut, lihat contoh SDK Java untuk Agent AI Azure.
Membuat bagan dengan Penerjemah Kode menggunakan REST API
Contoh berikut menunjukkan cara mengunggah file CSV, membuat agen dengan Penerjemah Kode, meminta bagan, dan mengunduh file yang dihasilkan.
Prasyarat
Atur variabel lingkungan ini:
-
FOUNDRY_PROJECT_ENDPOINT: URL titik akhir proyek Anda. -
AGENT_TOKEN: Token pembawa untuk Foundry.
Dapatkan token akses:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
Menggunakan Penerjemah Kode di kotak alat
Untuk mengunggah file agar dapat digunakan oleh Code Interpreter melalui toolbox, unggah file ke endpoint Files tingkat resource (POST {account_endpoint}/openai/v1/files) dengan header x-aml-project-id. Tidak seperti alur agen prompt, file yang diunggah melalui endpoint Files dengan cakupan proyek (/api/projects/{name}/openai/v1/files) menerima owner_id yang tidak dapat diverifikasi oleh container toolbox, sehingga tools/call gagal dengan kesalahan verifikasi kepemilikan.
Dapatkan GUID proyek dari Azure Resource Manager. Gunakan
properties.amlWorkspace.internalId(format UUID dengan tanda hubung), bukanproperties.internalId(tanpa tanda hubung - kontainer toolbox menolaknya):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')Unggah file pada level akun (sumber daya) dengan tajuk
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
File id yang dikembalikan adalah nilai yang Anda berikan seperti <FILE_ID> dalam konfigurasi alat. File dipasang di kotak pasir di /mnt/data/{file-id}-{original-filename}.
Penting
Saat Penerjemah Kode digunakan melalui kotak alat di agen yang dihosting, isolasi pengguna tidak didukung. Semua pengguna dalam proyek yang sama memiliki konteks kontainer yang sama.
Menambahkan Penerjemah Kode ke kotak alat
Tambahkan Penerjemah Kode dengan membuat kotak alat, lalu lampirkan kotak alat ke agen Anda sebagai alat MCP. Untuk informasi selengkapnya, lihat Apa itu kotak alat?
Buat kotak alat yang berisi alat penerjemah kode:
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>"] } } ] }'Toolbox menyediakan endpoint yang kompatibel dengan MCP di
$FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1, di mana<version>adalah versi yang dikembalikan oleh panggilan sebelumnya.Buat koneksi proyek alat jarak jauh yang menunjuk ke titik akhir kotak alat, menggunakan token Entra pengguna sehingga identitas pemanggil diteruskan (audiens
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
Membuat agen dengan kotak alat penerjemah kode
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"
}
]
}
}'
Membuat diagram
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."
}'
Tanggapan mencakup container_file_citation anotasi dengan detail file yang telah dihasilkan. Simpan nilai container_id dan file_id dari anotasi.
Mengunduh bagan yang dihasilkan
curl -X GET "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/containers/<CONTAINER_ID>/files/<FILE_ID>/content" \
-H "Authorization: Bearer $AGENT_TOKEN" \
--output chart.png
Pembersihan
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/chart-agent?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
Periksa ketersediaan wilayah dan model
Ketersediaan alat bervariasi menurut wilayah dan model.
Untuk daftar wilayah dan model yang didukung saat ini untuk Penerjemah Kode, lihat praktik Praktik terbaik untuk menggunakan alat di Microsoft Foundry Agent Service.
Jenis file yang didukung
| Format berkas | Jenis 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 Atau text/xml |
.zip |
application/zip |
Pemecahan masalah
| Masalah | Kemungkinan penyebabnya | Resolusi |
|---|---|---|
| Penerjemah Kode tidak berjalan. | Alat tidak diaktifkan atau model tidak mendukungnya di area Anda. | Pastikan Penerjemah Kode diaktifkan pada agen. Pastikan penyebaran model Anda mendukung alat tersebut di wilayah Anda. Lihat Periksa ketersediaan regional dan model. |
| Tidak ada file yang dihasilkan. | Agen mengembalikan respons teks saja tanpa anotasi file. | Periksa anotasi respons untuk container_file_citation. Jika tidak ada, agen tidak menghasilkan file. Susun ulang perintah untuk meminta output file secara eksplisit. |
| Pengunggahan file gagal. | Tipe file yang tidak didukung atau tujuan yang salah. | Konfirmasikan bahwa jenis file berada dalam daftar tipe file yang didukung . Unggah dengan purpose="assistants". |
| File yang dihasilkan rusak atau kosong. | Kesalahan eksekusi kode atau pemrosesan yang tidak lengkap. | Periksa respons agen untuk pesan kesalahan. Pastikan bahwa data masukan valid. Coba permintaan yang lebih sederhana terlebih dahulu. |
| Batas waktu sesi atau latensi tinggi. | Sesi Penerjemah Kode memiliki batas waktu. | Sesi memiliki batas waktu aktif 1 jam dan batas waktu diam 30 menit. Kurangi kompleksitas operasi atau pisahkan menjadi tugas yang lebih kecil. |
| Biaya penagihan tak terduga. | Beberapa sesi bersamaan dibuat. | Setiap percakapan membuat sesi terpisah. Pantau penggunaan sesi dan konsolidasikan operasi jika memungkinkan. |
| paket Python tidak tersedia. | Penerjemah Kode memiliki sekumpulan paket tetap. | Penerjemah Kode mencakup paket ilmu data umum. Untuk paket kustom, gunakan Penerjemah kode kustom. |
| Pengunduhan file gagal. | ID kontainer atau ID file salah. | Verifikasi bahwa Anda menggunakan container_id dan file_id yang benar dari anotasi respons. |
Membersihkan sumber daya
Hapus sumber daya yang Anda buat dalam sampel ini saat Anda tidak lagi memerlukannya untuk menghindari biaya yang sedang berlangsung:
- Hapus versi agen.
- Hapus percakapan.
- Hapus file yang diunggah.
Untuk contoh pola percakapan dan pembersihan file, lihat Alat pencarian web dan Alat pencarian file untuk agen.
Lingkungan eksekusi terkotakpasir
Penerjemah Kode menjalankan kode Python dalam kotak pasir yang dikelola Microsoft. Sandbox dirancang untuk menjalankan kode yang tidak tepercaya dan menggunakan sesi dinamis (sesi interpreter kode) di Azure Container Apps. Setiap sesi diisolasi oleh batas Hyper-V.
Perilaku utama yang akan di rencanakan:
- Region: Kotak pasir Penerjemah Kode berjalan di wilayah Azure yang sama dengan proyek Foundry Anda.
- Masa pakai sesi: Sesi Penerjemah Kode aktif hingga satu jam, dengan batas waktu diam (lihat Catatan penting di awal artikel ini).
- Isolasi: Setiap sesi berjalan di lingkungan yang terisolasi. Jika agen Anda memanggil Penerjemah Kode secara bersamaan dalam percakapan yang berbeda, sesi terpisah akan dibuat.
- Isolasi jaringan dan akses internet: Lingkungan sandbox tidak mewarisi konfigurasi subnet agen Anda, dan sesi dinamis tidak dapat melakukan permintaan jaringan keluar.
- File di dalam kotak pasir: Runtime Python dalam sandbox memiliki akses ke file yang Anda lampirkan untuk analisis. Penerjemah Kode juga dapat menghasilkan file, seperti bagan, dan mengembalikannya sebagai output yang dapat diunduh.
Jika Anda memerlukan kontrol yang lebih besar atas runtime sandbox atau memerlukan model isolasi yang berbeda, lihat Alat Pemroses Kode Kustom untuk Agen.