Microsoft Döküm aracıları için Kod Yorumlayıcı aracı

Kod Yorumlayıcı, bir Microsoft Foundry aracısının korumalı bir yürütme ortamında Python kodu çalıştırmasını sağlar. Foundry modeli, aracının veri analizi, grafik oluşturma ve yinelemeli sorun çözme görevleri için kod yazar ve yürütür.

Ipucu

Bu aracı bir araç kutusu kullanarak eklemeyi göz önünde bulundurun. Araç kutusunu kullanarak aracıları ve çalışma zamanlarını yeniden kullanabilir ve yönetilen bir MCP uç noktası aracılığıyla kimlik bilgisi yönetimi, sürüm oluşturma ve ilke zorlamayı merkezi hale getirebilirsiniz. Araç Kutusu Hızlı Başlangıç Kılavuzu'na bakın.

Bu makalede Kod Yorumlayıcı kullanan bir aracı oluşturacak, analiz için bir CSV dosyası yükleyebilecek ve oluşturulan bir grafiği indirebileceksiniz.

Kod Yorumlayıcı'yı etkinleştirdiğinizde, aracınız veri analizi ve matematik görevlerini çözmek ve grafikler oluşturmak için Python kodu yinelemeli olarak yazabilir ve çalıştırabilir.

Önemli

Kod Yorumlayıcı, Azure OpenAI kullanımı için belirteç tabanlı ücretlerin ötesinde ek ücretler sahiptir. Eğer ajanınız aynı anda iki farklı konuşmada Code Interpreter’ı çağırırsa, iki Code Interpreter oturumu oluşturur. Her oturum, 30 dakikalık boşta kalma zaman aşımıyla bir saat boyunca varsayılan olarak etkindir.

Önkoşullar

  • Temel veya standart etmen ortamı. Ayrıntılar için bkz. aracı ortamı kurulumu .
  • Diliniz için en son SDK paketi yüklendi. .NET SDK şu anda önizleme aşamasındadır. Yükleme adımları için hızlı başlangıç bölümüne bakın.
  • Projenizde yapılandırılmış Azure yapay zeka modeli dağıtımı.

Not

Kod Yorumlayıcı tüm bölgelerde kullanılamaz. Bkz. Bölgesel ve model kullanılabilirliğini denetleme.

Kullanım desteği

Aşağıdaki tabloda SDK ve kurulum desteği gösterilmektedir.

Microsoft Foundry desteği Python SDK'sı C# SDK'sı JavaScript SDK'sı Java SDK'sı REST API Temel aracı kurulumu Standart ajan kurulumu
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

Kod Yorumlayıcı ile aracı oluşturma

Aşağıdaki örneklerde Kod Yorumlayıcı etkin bir aracı oluşturma, analiz için bir dosya yükleme ve oluşturulan çıkışı indirme işlemi gösterilmektedir. Dosya yükleme örneklerinin her biri, mevcut çalışma dizininde küçük bir CSV dosyası oluşturur, bu dosyayı yükler ve ardından yerel geçici dosyayı siler.

Ipucu

Yapılandırılmış girişler kullanarak çalışma zamanında Kod Yorumlayıcı davranışını özelleştirebilirsiniz. Örneğin, istek başına hangi dosyaların ekleneceğini belirtebilir veya araç parametrelerini ayarlayabilirsiniz.

Python SDK'da kod yorumlayıcı aracı ile aracı kullanma örneği

Aşağıdaki Python örnekte kod yorumlayıcı aracının bir araç kutusuna nasıl ekleneceği, araç kutusunu aracıya nasıl ekleneceği, analiz için csv dosyasının nasıl yükleneceği ve verilere dayalı bir çubuk grafik istendiği gösterilmektedir. sunucu tarafı istem aracısı oluşturmak için Azure AI Projeleri SDK'sını kullanmak için Prompt Agents veya kısa ömürlü, işlem içi aracı oluşturmak için Agent Framework kullanmak için FoundryChatClient öğesini seçin.

Yönlendirme ajanları

Bu örnekte eksiksiz bir iş akışı gösterilmektedir: dosya yükleme, Kod Yorumlayıcı etkin bir aracı oluşturma, veri görselleştirme isteğinde bulunma ve oluşturulan grafiği indirme.

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

Beklenen çıkış

Örnek kod, aşağıdaki örneğe benzer bir çıkış oluşturur:

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

Aracı CSV dosyanızı Azure depolama alanına yükler, korumalı bir Python ortamı oluşturur, taşımacılık sektörü şirketlerini filtreler, şirkete göre işletme kârını gösteren bir PNG çubuk grafiği oluşturur ve grafiği yerel dizininize indirir. Yanıttaki dosya ek açıklamaları, oluşturulan grafiği almak için gereken dosya kimliğini ve kapsayıcı bilgilerini sağlar.

Barındırılan aracılar

Bu örnek, kod yorumlayıcı araç kutusunu oluşturur, ardından Microsoft Agent Framework'teki FoundryChatClient öğesini kullanır ve MCPStreamableHTTPTool kullanarak araç kutusunun MCP uç noktasına bağlanır. FOUNDRY_PROJECT_ENDPOINT ve FOUNDRY_MODEL ortam değişkenlerini ayarlayın ve ile az loginoturum açın.

import asyncio
import os
import httpx

from agent_framework import Agent, MCPStreamableHTTPTool
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential, get_bearer_token_provider
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import CodeInterpreterToolboxTool, AutoCodeInterpreterToolParam

PROJECT_ENDPOINT = "https://<account>.services.ai.azure.com/api/projects/<project>"
CSV_DATA = """name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
"""


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

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


async def main() -> None:
    credential = AzureCliCredential()

    csv_path = os.path.abspath("synthetic-company-financial-results.csv")
    with open(csv_path, "w", encoding="utf-8", newline="") as csv_file:
        csv_file.write(CSV_DATA)

    # 1. Add the code interpreter tool to a toolbox. Using a toolbox is the recommended way
    #    to give agents tools: you curate tools once and reuse the toolbox across agents.
    #    See /azure/foundry/agents/concepts/toolbox-overview
    project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=credential)
    openai = project.get_openai_client()
    with open(csv_path, "rb") as csv_file:
        file = openai.files.create(purpose="assistants", file=csv_file)
    os.remove(csv_path)
    toolbox = project.toolboxes.create_version(
        name="code-interpreter-toolbox",
        description="Toolbox with the code interpreter tool",
        tools=[CodeInterpreterToolboxTool(container=AutoCodeInterpreterToolParam(file_ids=[file.id]))],
    )

    # 2. The toolbox exposes an MCP-compatible endpoint.
    TOOLBOX_MCP_URL = (
        f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
        f"/versions/{toolbox.version}/mcp?api-version=v1"
    )

    # 3. Attach the toolbox to the hosted agent as an MCP tool.
    token_provider = get_bearer_token_provider(credential, "https://ai.azure.com/.default")
    http_client = httpx.AsyncClient(auth=_ToolboxAuth(token_provider), timeout=120.0)
    mcp_tool = MCPStreamableHTTPTool(
        name="toolbox",
        url=TOOLBOX_MCP_URL,
        http_client=http_client,
        load_prompts=False,
    )

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

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


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

Beklenen çıkış

Aracı Python kodu oluşturur, bunu yalıtılmış kapsayıcıda çalıştırır ve yanıtı döndürür:

Agent: 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Tam örnek için (dosya girişleri ve oluşturulan kodu ayıklama dahil), bkz. foundry_chat_client_with_code_interpreter.py ve foundry_chat_client_code_interpreter_files.py.


C'de Kod Yorumlayıcı ile grafik oluşturma#

Aşağıdaki C# örneği, Kod Yorumlayıcı aracının bir araç kutusuna nasıl ekleneceğini, araç kutusunu aracıya nasıl ekleyebileceğinizi, analiz için bir CSV dosyasını nasıl yükleyebileceğinizi ve oluşturulan grafiği nasıl indirebileceğinizi gösterir. sunucu tarafı istem aracısı oluşturmak için Azure AI Projeleri SDK'sını kullanmak için Prompt Agents öğesini veya kısa ömürlü, işlem içi aracı oluşturmak için Microsoft Agent Framework' kullanmak için Hosted Agents öğesini seçin.

Yönlendirme ajanları

Zaman uyumsuz kullanım için, GitHub .NET deposu için Azure SDK code örneğine bakın.

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

Beklenen çıkış

Örnek kod, aşağıdaki örneğe benzer bir çıkış oluşturur:

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

Aracı CSV dosyanızı Azure depolama alanına yükler, korumalı bir Python ortamı oluşturur, taşıma sektörü kayıtlarını filtrelemek için verileri analiz eder ve bir PNG çubuk grafiği oluşturur. Ek açıklama ayrıştırma, grafiği yerel dizininize indirmek için kullanılan kapsayıcı kimliğini ve dosya kimliğini yanıttan ayıklar.

Barındırılan aracılar

Bu örnek, Kod Yorumlayıcı araç kutusunu oluşturur; ardından Microsoft Agent Framework'ten ResponsesServer ile özel bir ToolboxMcpClient kullanarak, araç kutusu MCP uç noktası üzerinden Kod Yorumlayıcı'yı bulup çağırır. AZURE_AI_PROJECT_ENDPOINT, , AZURE_OPENAI_ENDPOINTve AZURE_AI_MODEL_DEPLOYMENT_NAME ortam değişkenlerini ayarlayın ve ile az loginoturum açın.

using System;
using System.IO;
using Azure.AI.AgentServer.Responses;
using Azure.AI.AgentServer.Responses.Models;
using Azure.AI.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using OpenAI.Chat;
using OpenAI.Files;

const string CsvData = """
name,sector,operating_profit
SkyBridge Logistics,TRANSPORTATION,185.2
Velocity Rail Freight,TRANSPORTATION,310.2
AeroJet Airlines,TRANSPORTATION,510.6
""";
const string AgentInstructions = "You are a personal math tutor. When asked a math question, write and run code using the python tool to answer the question.";
const string AgentName = "CoderAgent";

string projectEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
    ?? "https://<account>.services.ai.azure.com/api/projects/<project>";
string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5-mini";

DefaultAzureCredential credential = new();

// 1. Add the code interpreter tool to a toolbox. Using a toolbox is the recommended
//    way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
AIProjectClient projectClient = new(endpoint: new Uri(projectEndpoint), tokenProvider: credential);
OpenAIFileClient fileClient = projectClient.ProjectOpenAIClient.GetOpenAIFileClient();
string csvPath = Path.GetFullPath("synthetic-company-financial-results.csv");
File.WriteAllText(csvPath, CsvData);
OpenAIFile uploadedFile = fileClient.UploadFile(
  filePath: csvPath,
    purpose: FileUploadPurpose.Assistants);
File.Delete(csvPath);

ProjectsAgentTool codeInterpreterTool = ProjectsAgentTool.AsProjectTool(
    ResponseTool.CreateCodeInterpreterTool(
        new CodeInterpreterToolContainer(
            CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration(
                fileIds: [uploadedFile.Id]
            )
        )
    ));

ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
    .GetAgentToolboxes().CreateToolboxVersion(
        toolboxName: "code-interpreter-toolbox",
        tools: [codeInterpreterTool],
        description: "Toolbox with the code interpreter tool");

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

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

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

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

Beklenen çıkış

Barındırılan ajan, Python’u korumalı alanda çalıştırmak ve son yanıtı döndürmek için toolbox MCP uç noktasını kullanır:

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

Bakımı yapılan bir .NET Agent Framework tümleştirmesi için Barındırılan bir aracıyla araç kutusu kullanma bölümüne bakın.


TypeScript SDK'sında kod yorumlayıcı aracı ile aracı kullanma örneği

Aşağıdaki TypeScript örneğinde kod yorumlayıcı aracının bir araç kutusuna nasıl ekleneceği, araç kutusunu aracıya nasıl ekleneceği, analiz için bir CSV dosyasının nasıl yükleneceği ve verilere dayalı bir çubuk grafik istendiği gösterilmektedir. JavaScript sürümü için GitHub javascript için Azure SDK deposundaki JavaScript örneğine bakın.

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

Beklenen çıkış

Örnek kod, aşağıdaki örneğe benzer bir çıkış oluşturur:

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

Aracı CSV dosyanızı Azure depolama alanına yükler, korumalı bir Python ortamı oluşturur, taşımacılık sektörü şirketlerini filtreler, şirkete göre işletme kârını gösteren bir PNG çubuk grafiği oluşturur ve grafiği yerel dizininize indirir. Yanıttaki dosya ek açıklamaları, oluşturulan grafiği almak için gereken dosya kimliğini ve kapsayıcı bilgilerini sağlar.

Java'de Kod Yorumlayıcı ile grafik oluşturma

Çoğu aracı için kod yorumlayıcı aracını bir araç kutusu aracılığıyla ekleyin ve araç kutusunu aracınıza MCP aracı olarak ekleyin. Java SDK'sı henüz bir araç kutusu oluşturma API'sini kullanıma sunmadığından, şu anda desteklenen yöntemlerden birini (Python, REST API, C#, TypeScript veya Foundry portalı) kullanarak araç kutusunu oluşturun. Araç kutusu oluşturulduktan sonra, MCP uç noktasını Java ajanınızda McpTool olarak belirtin. Aşağıdaki örnek, kod yorumlayıcı araç kutusu MCP uç noktasını aracıya ekler.

bağımlılığını öğesinin pom.xmliçine ekleyin:

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

Bir araç oluşturun ve bir grafik oluşturun

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

Beklenen çıkış

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.

Ajan, araç kutusu MCP uç noktası üzerinden Kod Yorumlayıcısı’nı kullanır, grafiği oluşturmak için matplotlib kullanarak Python kodu yazar ve kodu yalıtılmış bir ortamda yürütür. Csv dosyasını karşıya yükleyen ve oluşturulan grafiği indiren bir örnek için, bu makalenin üst kısmındaki dil seçiciden Python veya TypeScript seçin. Daha fazla örnek için bkz. Azure AI Agents Java SDK örnekleri.

REST API kullanarak Kod Yorumlayıcı ile grafik oluşturma

Aşağıdaki örnekte CSV dosyasını karşıya yükleme, Kod Yorumlayıcı ile aracı oluşturma, grafik isteme ve oluşturulan dosyayı indirme işlemi gösterilmektedir.

Önkoşullar

Şu ortam değişkenlerini ayarlayın:

  • FOUNDRY_PROJECT_ENDPOINT: Proje uç noktası URL'niz.
  • AGENT_TOKEN: Foundry için taşıyıcı kimlik doğrulama belirteci.

Erişim belirteci alma:

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

Araç kutusunda Kod Yorumlayıcı kullanma

Kod Yürütücü'nün bir araç kutusu aracılığıyla kullanacağı bir dosyayı yüklemek için, dosyayı üst bilgisiyle birlikte POST {account_endpoint}/openai/v1/files Dosyalar uç noktasına (x-aml-project-id) yükleyin. İstem aracı akışından farklı olarak, proje kapsamındaki Files uç noktası (/api/projects/{name}/openai/v1/files) aracılığıyla yüklenen dosyalar, araç kutusu kapsayıcısının doğrulayamadığı bir owner_id alır; bu nedenle tools/call, sahiplik doğrulama hatasıyla başarısız olur.

  1. Projenin GUID’sini Azure Resource Manager’dan alın. Kullan properties.amlWorkspace.internalId (kesikli UUID biçimi), değilproperties.internalId (tire yok - araç kutusu kapsayıcısı bunu reddeder):

    ARM_TOKEN=$(az account get-access-token --query accessToken -o tsv)
    PROJECT_GUID=$(curl -s -H "Authorization: Bearer $ARM_TOKEN" \
      "https://management.azure.com/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.CognitiveServices/accounts/{account}/projects/{project}?api-version=2025-06-01" \
      | jq -r '.properties.amlWorkspace.internalId')
    
  2. x-aml-project-id üst bilgisiyle dosyayı hesap (kaynak) düzeyinde karşıya yükleyin:

    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
    

Döndürülen dosya id, araç yapılandırmasında <FILE_ID> olarak sağladığınız değerdir. Dosyalar, korumalı alanda /mnt/data/{file-id}-{original-filename} konumuna bağlanır.

Önemli

Kod Yorumlayıcı barındırılan aracıdaki bir araç kutusu aracılığıyla kullanıldığında , kullanıcı yalıtımı desteklenmez. Aynı projedeki tüm kullanıcılar aynı kapsayıcı bağlamını paylaşır.

Araç kutusuna Kod Yorumlayıcı ekleme

Bir araç kutusu oluşturarak Kod Yorumlayıcı ekleyin ve ardından araç kutusunu aracınıza MCP aracı olarak ekleyin. Daha fazla bilgi için bkz. Araç kutusu nedir?

  • Kod yorumlayıcı aracını içeren bir araç kutusu oluşturun:

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

    Araç kutusu, $FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1 adresinde MCP ile uyumlu bir uç nokta sunar; burada <version>, önceki çağrının döndürdüğü sürümdür.

  • Çağıranın kimliğinin aktarılması için (hedef kitle https://ai.azure.com), bir kullanıcı Entra belirteci kullanarak araç kutusu uç noktasını işaret eden bir uzak araç projesi bağlantısı oluşturun.

    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
    

Kod yürütücü araç kutusuyla bir ajan oluşturun

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

Grafik oluşturma

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

Yanıt, oluşturulan dosya ayrıntılarını içeren ek açıklamalar içerir container_file_citation . Ek açıklamadaki container_id ve file_id değerlerini kaydedin.

Oluşturulan grafiği indirme

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

Temizleme

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

Bölgesel ve model kullanılabilirliğini denetleme

Araç kullanılabilirliği bölgeye ve modele göre değişir.

Kod Yorumlayıcı için desteklenen bölgeler ve modellerin geçerli listesini görmek için Microsoft Foundry Aracı Hizmeti'nde araçları kullanmaya yönelik en iyi uygulamalar bölümüne bakın.

Desteklenen dosya türleri

Dosya biçimi MIME türü
.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 Veya text/xml
.zip application/zip

Sorun giderme

Sorunu Olası neden Çözünürlük
Kod Yorumlayıcı çalışmıyor. Araç etkinleştirilmedi veya model bölgenizde bunu desteklemiyor. Aracıda Kod Yorumlayıcı'nın etkinleştirildiğini onaylayın. Model dağıtımınızın bölgenizdeki aracı desteklediğini doğrulayın. Bkz. Bölgesel ve model kullanılabilirliğini denetleme.
Hiçbir dosya oluşturulmaz. Aracı, dosya notlandırması olmadan salt metin yanıtı döndürdü. container_file_citation için yanıt ek açıklamalarını denetleyin. Hiçbiri yoksa, aracı bir dosya oluşturmadı. Dosya çıkışını açıkça istemek için istemi yeniden ifade edin.
Dosya karşıya yükleme başarısız oluyor. Desteklenmeyen dosya türü veya yanlış amaç. Dosya türünün desteklenen dosya türleri listesinde olduğunu onaylayın. purpose="assistants" ile yükleyin.
Oluşturulan dosya bozuk veya boş. Kod yürütme hatası veya tamamlanmamış işleme. Hata mesajları için temsilcinin yanıtını kontrol edin. Giriş verilerinin geçerli olduğunu doğrulayın. Önce daha basit bir istek deneyin.
Oturum zaman aşımı veya yüksek gecikme süresi. Kod Yorumlayıcı oturumlarının zaman sınırları vardır. Oturumlar 1 saatlik etkin zaman aşımına ve 30 dakikalık boşta kalma zaman aşımına sahiptir. İşlemlerin karmaşıklığını azaltın veya daha küçük görevlere bölün.
Beklenmeyen faturalama ücretleri. Birden çok eşzamanlı oturum oluşturuldu. Her konuşma ayrı bir oturum oluşturur. Oturum kullanımını izleyin ve mümkün olduğunca işlemleri birleştirin.
Python paketi kullanılamıyor. Kod Yorumlayıcı'nın sabit bir paket kümesi vardır. Kod Yorumlayıcı ortak veri bilimi paketlerini içerir. Özel paketler için Özel kod yorumlayıcısını kullanın.
Dosya indirme başarısız oluyor. Kapsayıcı kimliği veya dosya kimliği yanlış. "Yanıt ek açıklamalarında doğru container_id ve file_id kullandığınızdan emin olun."

Kaynakları temizleme

Devam eden maliyetlerden kaçınmak için artık ihtiyacınız kalmadığında bu örnekte oluşturduğunuz kaynakları silin:

  • Ajan sürümünü silin.
  • Konuşmayı silin.
  • Karşıya yüklenen dosyaları silin.

Konuşma ve dosya temizleme desenleri örnekleri için bkz. Web arama aracı ve Aracılar için dosya arama aracı.

Korumalı yürütme ortamı

Kod Yorumlayıcı, Microsoft yönetilen bir korumalı alanda Python kod çalıştırır. Korumalı alan, güvenilmeyen kodu çalıştırmak için tasarlanmıştır ve Azure Container Apps içinde dinamik oturumlar (kod yorumlayıcı oturumları) kullanır. Her oturum bir Hyper-V sınırıyla yalıtılır.

Plan yapmak için temel davranışlar:

  • Region: Kod Yorumlayıcı korumalı alanı, Foundry projenizle aynı Azure bölgesinde çalışır.
  • Oturum ömrü: Boşta kalma zaman aşımıyla kod yorumlayıcı oturumu bir saate kadar etkindir (bu makalenin başındaki Önemli nota bakın).
  • Yalıtım: Her oturum yalıtılmış bir ortamda çalışır. Aracınız, Kod Yorumlayıcı'yı farklı konuşmalarda eşzamanlı olarak çağırırsa, ayrı oturumlar oluşturulur.
  • Ağ yalıtımı ve İnternet erişimi: Korumalı alan aracı alt ağ yapılandırmanızı devralmıyor ve dinamik oturumlar giden ağ istekleri gerçekleştiremiyor.
  • korumalı alandaki Dosyalar: Korumalı Python çalışma zamanı, analiz için eklediğiniz dosyalara erişebilir. Kod Yorumlayıcı ayrıca grafikler gibi dosyalar oluşturabilir ve bunları indirilebilir çıkışlar olarak döndürebilir.

Korumalı alan çalışma zamanı üzerinde daha fazla denetime veya farklı bir yalıtım modeline ihtiyacınız varsa bkz. Aracılar için özel kod yorumlayıcı aracı.