次の方法で共有


コード インタープリター ツールの使用方法

Azure AI エージェントでは、コード インタープリター ツールの使用がサポートされています。これにより、エージェントはセキュリティで保護されたサンドボックス実行環境内でコードを記述して実行できます。 これにより、エージェントは、データ分析、数学的計算、ユーザー要求に基づくファイル操作などのタスクを実行できます。 この記事では、Azure AI エージェントでコード インタープリター ツールを有効にして利用するための手順とコード サンプルについて説明します。

エージェントでコード インタープリター ツールを使用する

この記事の上部にあるコード例または Azure AI Foundry ポータルを使用して、コード インタープリター ツールをプログラムでエージェントに追加できます。 ポータルを使用する場合:

  1. エージェントの [エージェント ] 画面で、右側の [セットアップ ] ウィンドウを下にスクロールして 操作します。 その後、追加を選択します。

    Azure AI Foundry ポータルで使用できるツール カテゴリを示すスクリーンショット。

  2. [コード インタープリター] を選択し、画面の表示に従ってツールを追加します。

    Azure AI Foundry ポータルで使用できるアクション ツールを示すスクリーンショット。

  3. 必要に応じて、エージェントにファイルをアップロードして、データセットからの情報の読み取りと解釈、コードの生成、データを使用したグラフやチャートの作成を行うことができます。

    コード インタープリターのアップロード ページを示すスクリーンショット。

初期化

まず、必要なインポートを設定し、AI Project クライアントを初期化します。

import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from azure.ai.agents.models import CodeInterpreterTool


# Create an Azure AI Client from an endpoint, copied from your Azure AI Foundry project.
# You need to login to Azure subscription via Azure CLI and set the environment variables
project_endpoint = os.environ["PROJECT_ENDPOINT"]  # Ensure the PROJECT_ENDPOINT environment variable is set

# Create an AIProjectClient instance
project_client = AIProjectClient(
    endpoint=project_endpoint,
    credential=DefaultAzureCredential(),  # Use Azure Default Credential for authentication
)

ファイルのアップロード

このサンプルでは、分析用のデータ ファイルがアップロードされます。

file = project_client.agents.upload_file_and_poll(
    file_path="nifty_500_quarterly_results.csv", 
    purpose=FilePurpose.AGENTS
)

コード インタープリターのセットアップ

コード インタープリター ツールは、アップロードされたファイルで初期化されます。

code_interpreter = CodeInterpreterTool(file_ids=[file.id])

エージェントの作成

エージェントは、コード インタープリター機能を使用して作成されます。

agent = project_client.agents.create_agent(
    model=os.environ["MODEL_DEPLOYMENT_NAME"],
    name="my-agent",
    instructions="You are helpful agent",
    tools=code_interpreter.definitions,
    tool_resources=code_interpreter.resources,
)

スレッド管理

このコードでは、会話スレッドと初期メッセージが作成されます。

thread = project_client.agents.threads.create()
message = project_client.agents.messages.create(
    thread_id=thread.id,
    role=MessageRole.USER,
    content="Could you please create bar chart in TRANSPORTATION sector for the operating profit from the uploaded csv file and provide file to me?",
)

メッセージ処理

メッセージを処理してコードを実行する実行が作成されます。

run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)

ファイル処理

このコードは、出力ファイルと注釈を処理します。

messages = project_client.agents.messages.list(thread_id=thread.id)

# Save generated image files
for image_content in messages.image_contents:
    file_id = image_content.image_file.file_id
    file_name = f"{file_id}_image_file.png"
    project_client.agents.save_file(file_id=file_id, file_name=file_name)

# Process file path annotations
for file_path_annotation in messages.file_path_annotations:
    print(f"File Paths:")
    print(f"Type: {file_path_annotation.type}")
    print(f"Text: {file_path_annotation.text}")
    print(f"File ID: {file_path_annotation.file_path.file_id}")

クリーンアップ

対話が完了すると、コードによってリソースが適切にクリーンアップされます。

project_client.agents.delete_file(file.id)
project_client.agents.delete_agent(agent.id)

これにより、適切なリソース管理が保証され、不要なリソースの消費が防止されます。

クライアントとエージェントを作成する

まず、 appsettings.jsonを使用して構成を設定し、 PersistentAgentsClientを作成してから、コード インタープリター ツールを有効にして PersistentAgent を作成します。

using Azure;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using System.Diagnostics;

IConfigurationRoot configuration = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

var projectEndpoint = configuration["ProjectEndpoint"];
var modelDeploymentName = configuration["ModelDeploymentName"];

PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());

PersistentAgent agent = client.Administration.CreateAgent(
    model: modelDeploymentName,
    name: "My Friendly Test Agent",
    instructions: "You politely help with math questions. Use the code interpreter tool when asked to visualize numbers.",
    tools: [new CodeInterpreterToolDefinition()]
);

スレッドを作成してメッセージを追加する

次に、会話の PersistentAgentThread を作成し、最初のユーザー メッセージを追加します。

PersistentAgentThread thread = client.Threads.CreateThread();

client.Messages.CreateMessage(
    thread.Id,
    MessageRole.User,
    "Hi, Agent! Draw a graph for a line with a slope of 4 and y-intercept of 9.");

実行の作成と監視

次に、スレッドとエージェントの ThreadRun を作成します。 実行が完了するか、対応が必要になるまで、実行の状態を確認し続けます。

ThreadRun run = client.Runs.CreateRun(
    thread.Id,
    agent.Id,
    additionalInstructions: "Please address the user as Jane Doe. The user has a premium account.");

do
{
    Thread.Sleep(TimeSpan.FromMilliseconds(500));
    run = client.Runs.GetRun(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued
    || run.Status == RunStatus.InProgress
    || run.Status == RunStatus.RequiresAction);

結果を処理してファイルを処理する

実行が完了したら、スレッドからすべてのメッセージを取得します。 メッセージを反復処理してテキスト コンテンツを表示し、生成されたイメージ ファイルをローカルに保存して開くことで処理します。

Pageable<PersistentThreadMessage> messages = client.Messages.GetMessages(
    threadId: thread.Id,
    order: ListSortOrder.Ascending);

foreach (PersistentThreadMessage threadMessage in messages)
{
    foreach (MessageContent content in threadMessage.ContentItems)
    {
        switch (content)
        {
            case MessageTextContent textItem:
                Console.WriteLine($"[{threadMessage.Role}]: {textItem.Text}");
                break;
            case MessageImageFileContent imageFileContent:
                Console.WriteLine($"[{threadMessage.Role}]: Image content file ID = {imageFileContent.FileId}");
                BinaryData imageContent = client.Files.GetFileContent(imageFileContent.FileId);
                string tempFilePath = Path.Combine(AppContext.BaseDirectory, $"{Guid.NewGuid()}.png");
                File.WriteAllBytes(tempFilePath, imageContent.ToArray());
                client.Files.DeleteFile(imageFileContent.FileId);

                ProcessStartInfo psi = new()
                {
                    FileName = tempFilePath,
                    UseShellExecute = true
                };
                Process.Start(psi);
                break;
        }
    }
}

リソースをクリーンアップする

最後に、スレッドとエージェントを削除して、このサンプルで作成されたリソースをクリーンアップします。

    client.Threads.DeleteThread(threadId: thread.Id);
    client.Administration.DeleteAgent(agentId: agent.Id);

プロジェクト クライアントを作成する

コード インタープリターを使用するには、まず、AI プロジェクトへのエンドポイントを含むプロジェクト クライアントを作成し、API 呼び出しの認証に使用する必要があります。

const { AgentsClient, isOutputOfType, ToolUtility } = require("@azure/ai-agents");
const { delay } = require("@azure/core-util");
const { DefaultAzureCredential } = require("@azure/identity");
const fs = require("fs");
const path = require("node:path");
require("dotenv/config");

const projectEndpoint = process.env["PROJECT_ENDPOINT"];

// Create an Azure AI Client
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());

ファイルをアップロードする

ファイルをアップロードし、エージェントまたはメッセージでそれを参照できます。 アップロードすると、参照用のツール ユーティリティに追加できます。

// Upload file and wait for it to be processed
const filePath = "./data/nifty500QuarterlyResults.csv";
const localFileStream = fs.createReadStream(filePath);
const localFile = await client.files.upload(localFileStream, "assistants", {
  fileName: "localFile",
});

console.log(`Uploaded local file, file ID : ${localFile.id}`);

コード インタープリター ツールを使用してエージェントを作成する

// Create code interpreter tool
const codeInterpreterTool = ToolUtility.createCodeInterpreterTool([localFile.id]);

// Notice that CodeInterpreter must be enabled in the agent creation, otherwise the agent will not be able to see the file attachment
const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful agent",
  tools: [codeInterpreterTool.definition],
  toolResources: codeInterpreterTool.resources,
});
console.log(`Created agent, agent ID: ${agent.id}`);

スレッドとメッセージを作成して、エージェントの応答を取得する

// Create a thread
const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);

// Create a message
const message = await client.messages.create(
  thread.id,
  "user",
  "Could you please create a bar chart in the TRANSPORTATION sector for the operating profit from the uploaded CSV file and provide the file to me?",
  {
    attachments: [
      {
        fileId: localFile.id,
        tools: [codeInterpreterTool.definition],
      },
    ],
  },
);

console.log(`Created message, message ID: ${message.id}`);

// Create and execute a run
let run = await client.runs.create(thread.id, agent.id);
while (run.status === "queued" || run.status === "in_progress") {
  await delay(1000);
  run = await client.runs.get(thread.id, run.id);
}
if (run.status === "failed") {
  // Check if you got "Rate limit is exceeded.", then you want to get more quota
  console.log(`Run failed: ${run.lastError}`);
}
console.log(`Run finished with status: ${run.status}`);

// Delete the original file from the agent to free up space (note: this does not delete your version of the file)
await client.files.delete(localFile.id);
console.log(`Deleted file, file ID: ${localFile.id}`);

// Print the messages from the agent
const messagesIterator = client.messages.list(thread.id);
const allMessages = [];
for await (const m of messagesIterator) {
  allMessages.push(m);
}
console.log("Messages:", allMessages);

// Get most recent message from the assistant
const assistantMessage = allMessages.find((msg) => msg.role === "assistant");
if (assistantMessage) {
  const textContent = assistantMessage.content.find((content) => isOutputOfType(content, "text"));
  if (textContent) {
    console.log(`Last message: ${textContent.text.value}`);
  }
}

// Save the newly created file
console.log(`Saving new files...`);
const imageFile = allMessages[0].content[0].imageFile;
console.log(`Image file ID : ${imageFile.fileId}`);
const imageFileName = path.resolve(
  "./data/" + (await client.files.get(imageFile.fileId)).filename + "ImageFile.png",
);

const fileContent = await (await client.files.getContent(imageFile.fileId).asNodeStream()).body;
if (fileContent) {
  const chunks = [];
  for await (const chunk of fileContent) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  const buffer = Buffer.concat(chunks);
  fs.writeFileSync(imageFileName, buffer);
} else {
  console.error("Failed to retrieve file content: fileContent is undefined");
}
console.log(`Saved image file to: ${imageFileName}`);

// Iterate through messages and print details for each annotation
console.log(`Message Details:`);
allMessages.forEach((m) => {
  console.log(`File Paths:`);
  console.log(`Type: ${m.content[0].type}`);
  if (isOutputOfType(m.content[0], "text")) {
    const textContent = m.content[0];
    console.log(`Text: ${textContent.text.value}`);
  }
  console.log(`File ID: ${m.id}`);
});

// Delete the agent once done
await client.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);

REST API クイック スタートに従って、環境変数のAGENT_TOKENAZURE_AI_FOUNDRY_PROJECT_ENDPOINTAPI_VERSIONに適切な値を設定します。

ファイルをアップロードする

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/files?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -F purpose="assistants" \
  -F file="@c:\\path_to_file\\file.csv"

コード インタープリター ツールを使用してエージェントを作成する

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/assistants?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "instructions": "You are an AI assistant that can write code to help answer math questions.",
    "tools": [
      { "type": "code_interpreter" }
    ],
    "model": "gpt-4o-mini",
    "tool_resources"{
      "code interpreter": {
          "file_ids": ["assistant-1234"]
      }
    }
  }'

スレッドを作成する

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d ''

ユーザーの質問をスレッドに追加する

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/messages?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
      "role": "user",
      "content": "I need to solve the equation `3x + 11 = 14`. Can you help me?"
    }'

スレッドを実行する

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/runs?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "assistant_id": "asst_abc123",
  }'

実行の状態を取得する

curl --request GET \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/runs/run_abc123?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN"

エージェントの応答を取得する

curl --request GET \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/messages?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN"