次の方法で共有


クイック スタート: 新しいエージェントを作成する

Azure AI Foundry Agent Service を使用すると、カスタム命令を使用してニーズに合わせて調整された AI エージェントを作成し、コード インタープリターやカスタム関数などの高度なツールによって拡張できます。

Prerequisites

  • Azure サブスクリプション。無料で作成できます
  • アカウントとプロジェクトを作成する個人が、サブスクリプション スコープで Azure AI アカウント所有者 ロールを持っていることを確認します。これにより、プロジェクトを作成するために必要なアクセス許可が付与されます
    • または、サブスクリプション レベルで 共同作成者 ロールまたは Cognitive Services 共同作成者 ロールを持つことで、プロジェクトの作成が可能になります。
  • プロジェクトが作成されたら、プロジェクト内でエージェントを作成する個人がプロジェクト レベルで Azure AI ユーザー ロールを持っていることを確認します

Important

Azure AI Foundry ポータルでは、現時点では基本的なエージェントのセットアップのみがサポートされています。 標準エージェントのセットアップを実行する場合は、 環境のセットアップ に関する記事を参照して詳細を確認してください。

Azure AI Foundry ポータルで Foundry アカウントとプロジェクトを作成する

Azure AI Foundry でアカウントとプロジェクトを作成するには、次の手順に従います。

  1. Azure AI Foundry に移動します。 プロジェクト内にいる場合は、ページの左上にある Azure AI Foundry を選択して、ホーム ページに移動します。

  2. 動作を最速にするために、エージェントの概要作成フローを使用します。 [ エージェントの作成] をクリックします。

    Azure AI Foundry ポータルのスクリーンショット。

  3. プロジェクトの名前を入力します。 既定値をカスタマイズする場合は、[ 詳細オプション] を選択します。

    プロジェクトを作成するための詳細オプションのスクリーンショット。

  4. を選択してを作成します。

  5. リソースがプロビジョニングされるまで待ちます。

    1. アカウントとプロジェクト (アカウントの子リソース) が作成されます。
    2. gpt-4o モデルが自動的にデプロイされます
    3. 既定のエージェントが作成されます
  6. 完了すると、エージェントのプレイグラウンドに直接着陸し、エージェントの作成を開始できます。 エージェントに対して、実行する操作とその方法について説明できます。 たとえば、「 地理に関する質問に答えることができる役に立つエージェントです。」 などです。その後、エージェントとのチャットを開始できます。

    エージェントのプレイグラウンドのスクリーンショット。

    Note

    エージェントを構成または作成しようとしたときにアクセス許可エラーが発生する場合は、プロジェクトに Azure AI ユーザー があることを確認します。

| リファレンス ドキュメント | サンプル | ライブラリ ソース コード | パッケージ (NuGet) |

Prerequisites

  • エージェント環境のセットアップ
  • SDK または Agent Playground を使用してエージェントを作成または編集する必要がある各チーム メンバーに Azure AI ユーザーRBAC ロール を割り当てる
    • このロールはプロジェクト スコープで割り当てる必要があります
    • 最低限必要なアクセス許可: agents/*/readagents/*/actionagents/*/delete

エージェントを構成して実行する

.NET コンソール プロジェクトを作成します。

dotnet new console

.NET パッケージをプロジェクトにインストールします。 たとえば、.NET CLI を使用する場合は、次のコマンドを実行します。

dotnet add package Azure.AI.Agents.Persistent
dotnet add package Azure.Identity

次に、API 要求を認証してプログラムを実行するために、az login コマンドを使用して Azure サブスクリプションにサインインします。

az login

次のコードを使用して、エージェントを作成し実行します。 このコードを実行するには、プロジェクトのエンドポイントを取得する必要があります。 この文字列の形式は次のとおりです。

https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>

Important

2025 年 5 月以降、Azure AI エージェント サービスでは、ハブベースのプロジェクトで以前に使用されていた接続文字列ではなく 、Foundry プロジェクト のエンドポイントが使用されます。 ハブベースのプロジェクトを使用している場合、SDK と REST API の現在のバージョンを使用することはできません。 詳細については、 ハブベースのプロジェクトでの SDK の使用に関する説明を参照してください。

エンドポイントは、プロジェクトの 概要 にある Azure AI Foundry ポータルの [ ライブラリ>Azure AI Foundry] にあります。

Azure AI Foundry ポータルのエンドポイントを示すスクリーンショット。

このエンドポイントは、 ProjectEndpoint という名前の環境変数に設定します。

また、モデルのデプロイ名も必要です。 左側のナビゲーション メニューの [モデルとエンドポイント ] で見つけることができます。

AI Foundry ポータルのモデルデプロイ画面を示すスクリーンショット。

モデル デプロイ名の名前を、 ModelDeploymentNameという名前の環境変数として保存します。

using Azure;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using System.Diagnostics;

var projectEndpoint = System.Environment.GetEnvironmentVariable("ProjectEndpoint");
var modelDeploymentName = System.Environment.GetEnvironmentVariable("ModelDeploymentName");



//Create a PersistentAgentsClient and PersistentAgent.
PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());

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

//Create a thread to establish a session between Agent and a User.
PersistentAgentThread thread = client.Threads.CreateThread();

//Ask a question of the Agent.
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.");

//Have Agent begin processing user's question with some additional instructions associated with the ThreadRun.
ThreadRun run = client.Runs.CreateRun(
    thread.Id,
    agent.Id,
    additionalInstructions: "Please address the user as Jane Doe. The user has a premium account.");

//Poll for completion.
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);

//Get the messages in the PersistentAgentThread. Includes Agent (Assistant Role) and User (User Role) messages.
Pageable<PersistentThreadMessage> messages = client.Messages.GetMessages(
    threadId: thread.Id,
    order: ListSortOrder.Ascending);

//Display each message and open the image generated using CodeInterpreterToolDefinition.
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;
        }
    }
}

//If you want to delete your agent, uncomment the following lines:
//client.Threads.DeleteThread(threadId: thread.Id);
//client.Administration.DeleteAgent(agentId: agent.Id);

| リファレンス ドキュメント | サンプル | ライブラリ ソース コード | パッケージ (PyPi) |

Prerequisites

  • エージェント環境のセットアップ
  • SDK または Agent Playground を使用してエージェントを作成または編集する必要がある各チーム メンバーに Azure AI ユーザーRBAC ロール を割り当てる
    • このロールはプロジェクト スコープで割り当てる必要があります
    • 最低限必要なアクセス許可: agents/*/readagents/*/actionagents/*/delete

エージェントを構成して実行する

次のコマンドを実行して、Python パッケージをインストールします。

pip install azure-ai-projects
pip install azure-identity

次に、API 要求を認証してプログラムを実行するために、az login コマンドを使用して Azure サブスクリプションにサインインします。

az login

次のコードを使用して、エージェントを作成し実行します。 このコードを実行するには、プロジェクトのエンドポイントを取得する必要があります。 この文字列の形式は次のとおりです。

https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>

Important

2025 年 5 月以降、Azure AI エージェント サービスでは、ハブベースのプロジェクトで以前に使用されていた接続文字列ではなく 、Foundry プロジェクト のエンドポイントが使用されます。 ハブベースのプロジェクトを使用している場合、SDK と REST API の現在のバージョンを使用することはできません。 詳細については、 ハブベースのプロジェクトでの SDK の使用に関する説明を参照してください。

エンドポイントは、プロジェクトの 概要 にある Azure AI Foundry ポータルの [ ライブラリ>Azure AI Foundry] にあります。

Azure AI Foundry ポータルのエンドポイントを示すスクリーンショット。

このエンドポイントを PROJECT_ENDPOINT という名前の環境変数として設定します。

また、モデルのデプロイ名も必要です。 左側のナビゲーション メニューの [モデルとエンドポイント ] で見つけることができます。

AI Foundry ポータルのモデルデプロイ画面を示すスクリーンショット。

モデル デプロイ名の名前を、 MODEL_DEPLOYMENT_NAMEという名前の環境変数として保存します。

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

# Create an AIProjectClient 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
)

code_interpreter = CodeInterpreterTool()
with project_client:
    # Create an agent with the Code Interpreter tool
    agent = project_client.agents.create_agent(
        model=os.environ["MODEL_DEPLOYMENT_NAME"],  # Model deployment name
        name="my-agent",  # Name of the agent
        instructions="You politely help with math questions. Use the Code Interpreter tool when asked to visualize numbers.",  # Instructions for the agent
        tools=code_interpreter.definitions,  # Attach the tool
    )
    print(f"Created agent, ID: {agent.id}")

    # Create a thread for communication
    thread = project_client.agents.threads.create()
    print(f"Created thread, ID: {thread.id}")

    # Add a message to the thread
    message = project_client.agents.messages.create(
        thread_id=thread.id,
        role="user",  # Role of the message sender
        content="Hi, Agent! Draw a graph for a line with a slope of 4 and y-intercept of 9.",  # Message content
    )
    print(f"Created message, ID: {message['id']}")

    # Create and process an agent run
    run = project_client.agents.runs.create_and_process(
        thread_id=thread.id,
        agent_id=agent.id,
        additional_instructions="Please address the user as Jane Doe. The user has a premium account",
    )
    print(f"Run finished with status: {run.status}")

    # Check if the run failed
    if run.status == "failed":
        print(f"Run failed: {run.last_error}")

    # Fetch and log all messages
    messages = project_client.agents.messages.list(thread_id=thread.id)
    for message in messages:
        print(f"Role: {message.role}, Content: {message.content}")

        # Save every image file in the message
        for img in message.image_contents:
            file_id = img.image_file.file_id
            file_name = f"{file_id}_image_file.png"
            project_client.agents.files.save(file_id=file_id, file_name=file_name)
            print(f"Saved image file to: {Path.cwd() / file_name}")

    # Uncomment these lines to delete the agent when done
    # project_client.agents.delete_agent(agent.id)
    # print("Deleted agent")

| リファレンス ドキュメント | サンプル | ライブラリ ソース コード | パッケージ (npm) |

Prerequisites

  • エージェント環境のセットアップ
  • SDK または Agent Playground を使用してエージェントを作成または編集する必要がある各チーム メンバーに Azure AI ユーザーRBAC ロール を割り当てる
    • このロールはプロジェクト スコープで割り当てる必要があります
    • 最低限必要なアクセス許可: agents/*/readagents/*/actionagents/*/delete

エージェントを構成して実行する

このコードの主なオブジェクトは次のとおりです。

まず、次を実行して新しい TypeScript プロジェクトを初期化します。

npm init -y
npm pkg set type="module"

次のコマンドを実行して、必要な npm パッケージをインストールします。

npm install @azure/ai-agents @azure/identity
npm install @types/node typescript --save-dev

次に、API 要求を認証してプログラムを実行するために、az login コマンドを使用して Azure サブスクリプションにサインインします。

az login

次のコードを使用して、数学の質問 I need to solve the equation '3x + 11 = 14'. Can you help me?に回答します。 このコードを実行するには、プロジェクトのエンドポイントを取得する必要があります。 この文字列の形式は次のとおりです。

https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>

エンドポイントは、プロジェクトの 概要 にある Azure AI Foundry ポータルの [ ライブラリ>Azure AI Foundry] にあります。

Azure AI Foundry ポータルのエンドポイントを示すスクリーンショット。

このエンドポイントを、PROJECT_ENDPOINT ファイル内の .env という名前の環境変数として設定します。

また、モデルのデプロイ名も必要です。 左側のナビゲーション メニューの [モデルとエンドポイント ] で見つけることができます。

AI Foundry ポータルのモデルデプロイ画面を示すスクリーンショット。

モデル デプロイ名の名前を、 MODEL_DEPLOYMENT_NAMEという名前の環境変数として保存します。

Important

  • このクイック スタート コードでは、機密性の高い構成に環境変数を使用します。 バージョン管理に .env ファイルをコミットしないように、.env.gitignore ファイルに追加していることを確認してください。
  • 注意: 機密情報を誤ってコミットした場合は、その資格情報が侵害されたと考えてください。そして、すぐに資格情報を変更してください。

次の内容を含む tsconfig.json ファイルを作成します。

{
  "compilerOptions": {
    "module": "nodenext",
    "target": "esnext",
    "types": ["node"],
    "lib": ["esnext"],
    "sourceMap": true,
    "declaration": true,
    "declarationMap": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "strict": true,
    "verbatimModuleSyntax": true,
    "isolatedModules": true,
    "noUncheckedSideEffectImports": true,
    "moduleDetection": "force",
    "skipLibCheck": true,
  }
}

次に、 index.ts ファイルを作成し、次のコードを貼り付けます。

import { AgentsClient } from "@azure/ai-agents";
import { DefaultAzureCredential } from "@azure/identity";

const projectEndpoint = process.env["PROJECT_ENDPOINT"] || "<project endpoint>";
const modelDeploymentName = process.env["MODEL_DEPLOYMENT_NAME"] || "gpt-4o";

export async function main(): Promise<void> {
  // Create an Azure AI Client
  const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());

  // Create an agent
  const agent = await client.createAgent(modelDeploymentName, {
    name: "my-agent",
    instructions: "You are a helpful agent specialized in math. When providing mathematical explanations, use plain text formatting with simple characters like +, -, *, / for operations. Do not use LaTeX formatting with backslashes or special notation. Make your explanations clear and easy to read in a terminal.",
  });
  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}`);

  // List all threads for the agent
  const threads = client.threads.list();
  console.log(`Threads for agent ${agent.id}:`);
  for await (const t of threads) {
    console.log(`Thread ID: ${t.id} created at: ${t.createdAt}`);
  }

  // Create a message
  const message = await client.messages.create(thread.id, "user", "I need to solve the equation `3x + 11 = 14`. Can you help me?");
  console.log(`Created message, message ID : ${message.id}`);

  // Create and poll a run
  console.log("Creating run...");
  const run = await client.runs.createAndPoll(thread.id, agent.id, {
    pollingOptions: {
      intervalInMs: 2000,
    },
    onResponse: (response): void => {
      const parsedBody =
        typeof response.parsedBody === "object" && response.parsedBody !== null
          ? response.parsedBody
          : null;
      const status = parsedBody && "status" in parsedBody ? parsedBody.status : "unknown";
      console.log(`Received response with status: ${status}`);
    },
  });
  console.log(`Run finished with status: ${run.status}`);

  const messagesIterator = client.messages.list(thread.id);
  console.log("\n\n========================================================");
  console.log("=================== CONVERSATION RESULTS ===================");
  console.log("========================================================\n");
  
  // Collect all messages first
  const messages = [];
  for await (const m of messagesIterator) {
    messages.push(m);
  }
  
  // Reverse the order of messages (or sort by timestamp if available)
  messages.reverse();
  
  // Display messages in the new order
  for (const m of messages) {
    if (m.role === "user") {
      console.log(`\n❓ USER QUESTION: ${
        Array.isArray(m.content) && m.content[0]?.type === "text" && 'text' in m.content[0]
          ? m.content[0].text.value
          : JSON.stringify(m.content)
      }`);
    } else if (m.role === "assistant") {
      console.log("\n🤖 ASSISTANT'S ANSWER:");
      console.log("--------------------------------------------------");
      
      // Extract and print the text content in a more readable format
      if (m.content && Array.isArray(m.content)) {
        for (const content of m.content) {
          if (content.type === "text" && 'text' in content) {
            console.log(content.text?.value);
          } else {
            console.log(content);
          }
        }
      } else {
        console.log(JSON.stringify(m.content, null, 2));
      }
      console.log("--------------------------------------------------\n");
    }
  }
  
  console.log("\n========================================================");
  console.log("====================== END OF RESULTS ======================");
  console.log("========================================================\n");

  // Clean up
  await client.threads.delete(thread.id);
  await client.deleteAgent(agent.id);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

npx tsx -r dotenv/config index.tsを使用してコードを実行します。 このコードは、質問の I need to solve the equation '3x + 11 = 14'. Can you help me?に回答します。 応答は決定論的ではありません。出力は次の出力のようになります。

Created agent, agent ID : asst_X4yDNWrdWKb8LN0SQ6xlzhWk
Created thread, thread ID : thread_TxqZcHL2BqkNWl9dFzBYMIU6
Threads for agent asst_X4yDNWrdWKb8LN0SQ6xlzhWk:
...
Created message, message ID : msg_R0zDsXdc2UbfsNXvS1zeS6hk
Creating run...
Received response with status: queued
Received response with status: in_progress
Received response with status: completed
Run finished with status: completed


========================================================
=================== CONVERSATION RESULTS ===================
========================================================


❓ USER QUESTION: I need to solve the equation `3x + 11 = 14`. Can you help me?

🤖 ASSISTANT'S ANSWER:
--------------------------------------------------
Certainly! Let's solve the equation step by step:

We have:
3x + 11 = 14

### Step 1: Eliminate the constant (+11) on the left-hand side.
Subtract 11 from both sides:
3x + 11 - 11 = 14 - 11
This simplifies to:
3x = 3

We have:
3x + 11 = 14

### Step 1: Eliminate the constant (+11) on the left-hand side.
Subtract 11 from both sides:
3x + 11 - 11 = 14 - 11
This simplifies to:
3x = 3

### Step 2: Solve for x.
Divide both sides by 3:
3x / 3 = 3 / 3
This simplifies to:
x = 1

### Final Answer:
x = 1
--------------------------------------------------


========================================================
====================== END OF RESULTS ======================
========================================================

完全な サンプル ソース コード を使用できます。

| リファレンス ドキュメント | サンプル | ライブラリ ソース コード | パッケージ (Maven) |

Prerequisites

  • エージェント環境のセットアップ
  • SDK または Agent Playground を使用してエージェントを作成または編集する必要がある各チーム メンバーに Azure AI ユーザーRBAC ロール を割り当てる
    • このロールはプロジェクト スコープで割り当てる必要があります
    • 最低限必要なアクセス許可: agents/*/readagents/*/actionagents/*/delete

エージェントを構成して実行する

まず、新しい Java コンソール プロジェクトを作成します。 コードを実行するには、次の依存関係が必要です。

<dependencies>
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-agents-persistent</artifactId>
        <version>1.0.0-beta.2</version>
    </dependency>
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-identity</artifactId>
        <version>1.17.0-beta.1</version>
    </dependency>
</dependencies>

次に、API 要求を認証してプログラムを実行するために、az login コマンドを使用して Azure サブスクリプションにサインインします。

az login

次のコードを使用して、エージェントを作成し実行します。 このコードを実行するには、プロジェクトのエンドポイントを取得する必要があります。 この文字列の形式は次のとおりです。

https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>

Important

2025 年 5 月以降、Azure AI エージェント サービスでは、ハブベースのプロジェクトで以前に使用されていた接続文字列ではなく 、Foundry プロジェクト のエンドポイントが使用されます。 ハブベースのプロジェクトを使用している場合、SDK と REST API の現在のバージョンを使用することはできません。 詳細については、 ハブベースのプロジェクトでの SDK の使用に関する説明を参照してください。

エンドポイントは、プロジェクトの 概要 にある Azure AI Foundry ポータルの [ ライブラリ>Azure AI Foundry] にあります。

Azure AI Foundry ポータルのエンドポイントを示すスクリーンショット。

このエンドポイントは、 PROJECT_ENDPOINT という名前の環境変数に設定します。

また、モデルのデプロイ名も必要です。 左側のナビゲーション メニューの [モデルとエンドポイント ] で見つけることができます。

AI Foundry ポータルのモデルデプロイ画面を示すスクリーンショット。

モデル デプロイ名の名前を、 MODEL_DEPLOYMENT_NAMEという名前の環境変数として保存します。

コード例

package com.example.agents;

import com.azure.ai.agents.persistent.MessagesClient;
import com.azure.ai.agents.persistent.PersistentAgentsAdministrationClient;
import com.azure.ai.agents.persistent.PersistentAgentsClient;
import com.azure.ai.agents.persistent.PersistentAgentsClientBuilder;
import com.azure.ai.agents.persistent.RunsClient;
import com.azure.ai.agents.persistent.ThreadsClient;
import com.azure.ai.agents.persistent.models.CodeInterpreterToolDefinition;
import com.azure.ai.agents.persistent.models.CreateAgentOptions;
import com.azure.ai.agents.persistent.models.CreateRunOptions;
import com.azure.ai.agents.persistent.models.MessageImageFileContent;
import com.azure.ai.agents.persistent.models.MessageRole;
import com.azure.ai.agents.persistent.models.MessageTextContent;
import com.azure.ai.agents.persistent.models.PersistentAgent;
import com.azure.ai.agents.persistent.models.PersistentAgentThread;
import com.azure.ai.agents.persistent.models.RunStatus;
import com.azure.ai.agents.persistent.models.ThreadMessage;
import com.azure.ai.agents.persistent.models.ThreadRun;
import com.azure.ai.agents.persistent.models.MessageContent;
import com.azure.core.http.rest.PagedIterable;
import com.azure.identity.DefaultAzureCredentialBuilder;
import java.util.Arrays;

public class AgentSample {

    public static void main(String[] args) {
        // variables for authenticating requests to the agent service 
        String projectEndpoint = System.getenv("PROJECT_ENDPOINT");
        String modelName = System.getenv("MODEL_DEPLOYMENT_NAME");

        // initialize clients to manage various aspects of agent runtime
        PersistentAgentsClientBuilder clientBuilder = new PersistentAgentsClientBuilder()
            .endpoint(projectEndpoint)
            .credential(new DefaultAzureCredentialBuilder().build());
        PersistentAgentsClient agentsClient = clientBuilder.buildClient();
        PersistentAgentsAdministrationClient administrationClient = agentsClient.getPersistentAgentsAdministrationClient();
        ThreadsClient threadsClient = agentsClient.getThreadsClient();
        MessagesClient messagesClient = agentsClient.getMessagesClient();
        RunsClient runsClient = agentsClient.getRunsClient();
        
        
        String agentName = "my-agent"; // the name of the agent
        CreateAgentOptions createAgentOptions = new CreateAgentOptions(modelName)
            .setName(agentName)
            .setInstructions("You are a helpful agent") // system insturctions
            .setTools(Arrays.asList(new CodeInterpreterToolDefinition()));
        PersistentAgent agent = administrationClient.createAgent(createAgentOptions);

        PersistentAgentThread thread = threadsClient.createThread();
        ThreadMessage createdMessage = messagesClient.createMessage(
            thread.getId(),
            MessageRole.USER,
            "I need to solve the equation `3x + 11 = 14`. Can you help me?"); // The message to the agent

        try {
            //run the agent
            CreateRunOptions createRunOptions = new CreateRunOptions(thread.getId(), agent.getId())
                .setAdditionalInstructions("");
            ThreadRun threadRun = runsClient.createRun(createRunOptions);
            // wait for the run to complete before printing the message
            waitForRunCompletion(thread.getId(), threadRun, runsClient);
            printRunMessages(messagesClient, thread.getId());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //cleanup - uncomment these lines if you want to delete the agent
            //threadsClient.deleteThread(thread.getId());
            //administrationClient.deleteAgent(agent.getId());
        }
    }

    // A helper function to print messages from the agent
    public static void printRunMessages(MessagesClient messagesClient, String threadId) {

        PagedIterable<ThreadMessage> runMessages = messagesClient.listMessages(threadId);
        for (ThreadMessage message : runMessages) {
            System.out.print(String.format("%1$s - %2$s : ", message.getCreatedAt(), message.getRole()));
            for (MessageContent contentItem : message.getContent()) {
                if (contentItem instanceof MessageTextContent) {
                    System.out.print((((MessageTextContent) contentItem).getText().getValue()));
                } else if (contentItem instanceof MessageImageFileContent) {
                    String imageFileId = (((MessageImageFileContent) contentItem).getImageFile().getFileId());
                    System.out.print("Image from ID: " + imageFileId);
                }
                System.out.println();
            }
        }
    }

    // a helper function to wait until a run has completed running
    public static void waitForRunCompletion(String threadId, ThreadRun threadRun, RunsClient runsClient)
        throws InterruptedException {

        do {
            Thread.sleep(500);
            threadRun = runsClient.getRun(threadId, threadRun.getId());
        }
        while (
            threadRun.getStatus() == RunStatus.QUEUED
                || threadRun.getStatus() == RunStatus.IN_PROGRESS
                || threadRun.getStatus() == RunStatus.REQUIRES_ACTION);

        if (threadRun.getStatus() == RunStatus.FAILED) {
            System.out.println(threadRun.getLastError().getMessage());
        }
    }
}

| リファレンス ドキュメント |

Prerequisites

  • エージェント環境のセットアップ
  • SDK または Agent Playground を使用してエージェントを作成または編集する必要がある各チーム メンバーに Azure AI ユーザーRBAC ロール を割り当てる
    • このロールはプロジェクト スコープで割り当てる必要があります
    • 最低限必要なアクセス許可: agents/*/readagents/*/actionagents/*/delete

エージェントを構成して実行する

API 要求を認証するために、az login コマンドを使用して Azure サブスクリプションにサインインします。

az login

次に、API 呼び出しの認証として使用するために、Entra ID トークンを取得する必要があります。 トークンのフェッチには次の CLI コマンドを使用します。

az account get-access-token --resource 'https://ai.azure.com' | jq -r .accessToken | tr -d '"'

このアクセス トークンを AGENT_TOKEN という名前の環境変数として設定します。

Azure AI Foundry Agent Service に対する REST API 呼び出しを正常に行うには、プロジェクトのエンドポイントを使用する必要があります。

https://<your_ai_service_name>.services.ai.azure.com/api/projects/<your_project_name>

たとえば、エンドポイントは次のようになります。

https://exampleaiservice.services.ai.azure.com/api/projects/project

このエンドポイントを AZURE_AI_FOUNDRY_PROJECT_ENDPOINT という名前の環境変数として設定します。

Note

  • api-version パラメーターの場合、GA API バージョンは2025-05-01され、最新のプレビュー API バージョンは2025-05-15-preview。 プレビュー段階のツールには、プレビュー API を使用する必要があります。
  • api バージョンを環境変数 ( $API_VERSION など) にすることを検討してください。

エージェントを作成する

Note

Azure AI Agents Service では、model パラメーターにモデル デプロイ名が必要です。 モデル デプロイ名が基になるモデル名と異なる場合は、コードを "model": "{your-custom-model-deployment-name}"に調整します。

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/assistants?api-version=2025-05-01 \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "instructions": "You are a helpful agent.",
    "name": "my-agent",
    "tools": [{"type": "code_interpreter"}],
    "model": "gpt-4o-mini"
  }'

スレッドを作成する

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads?api-version=2025-05-01 \
  -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=2025-05-01 \
  -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=2025-05-01 \
  -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=2025-05-01 \
  -H "Authorization: Bearer $AGENT_TOKEN"

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

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

次のステップ

Web へのアクセス、接地情報の提供など、エージェントの機能を拡張するために使用できる ツール について説明します。