# エージェントのカスタマイズ

> エージェントのカスタマイズ - エージェントコードを修正し、ローカルでテストし、本番用にエージェントワークフローをデプロイする方法を学びます。

This Markdown file sits beside the HTML page at the same path (with a `.md` suffix). It summarizes the topic and lists links for tools and LLM context.

Companion generated at `2026-07-15T05:55:44.562887+00:00` (UTC).

## Primary page

- [エージェントのカスタマイズ](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md): Full documentation for this topic (Markdown sidecar).

## Sections on this page

- [エージェントコードの修正](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#modify-the-agent-code): In-page section heading.
- [エージェントプロンプトの修正](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#modify-agent-prompts): In-page section heading.
- [ストリーミングレスポンスを有効にする](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#enable-streaming-responses): In-page section heading.
- [ローカル開発中のエージェントのテスト](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#testing-the-agent-during-local-development): In-page section heading.
- [DataRobot LLMプレイグラウンドでテスト用のエージェントを構築する](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#build-an-agent-for-testing-in-the-datarobot-llm-playground): In-page section heading.
- [本番用エージェントのデプロイ](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#deploy-an-agent-for-production-use): In-page section heading.
- [デプロイされたエージェントのログとトレースを確認する](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#view-logs-and-traces-for-a-deployed-agent): In-page section heading.
- [Pulumiを使って手動でエージェントをデプロイする](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#manually-deploy-an-agent-using-pulumi): In-page section heading.
- [デプロイされたエージェントワークフローで予測を行う](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#make-predictions-with-a-deployed-agentic-workflow): In-page section heading.
- [次のステップ](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#next-steps): In-page section heading.

## Documentation content

エージェントの開発には、 `agent/agent/` ディレクトリ内のコード（主に `myagent.py` ）を編集する必要があります。 開発プロセスにおいて、エージェントのテストやデプロイに役立つさまざまなツールやコマンドが提供されています。

> [!NOTE] Generic Baseテンプレート
> generic_base`テンプレートを使用して、任意のフレームワークを使用してエージェントを構築することができます。しかし、このテンプレートには定義済みのエージェントコードが含まれていないため、エージェントのロジックと構造を自分で実装する必要があります。

## エージェントコードの修正

エージェント開発の最初のステップは、目的の機能を実装するようにエージェントコードを修正することです。 メインのエージェントコードは、アプリケーションプロジェクトの `agent/agent` ディレクトリにあります。

```
# agent/agent/ directory
agent/agent/
├── __init__.py           # Package initialization
├── myagent.py            # Main agent implementation, including prompts
├── config.py             # Configuration management
├── register.py           # DRAgent / NAT registration (framework-specific)
├── workflow.yaml         # Declarative workflow config for DRAgent (framework-specific)
└── model-metadata.yaml   # Agent metadata configuration 
```

| ファイル | 説明 |
| --- | --- |
| __init__.py | ディレクトリをPythonパッケージとして識別し、インポートを有効にします。 |
| model-metadata.yaml | エージェントの設定、ランタイムパラメーター、デプロイ設定を定義します。 |
| custom.py（親agent/内、1つ上のレベル） | エージェントを実行するためのDataRobot統合フック（load_model、chat）を実装します。 |
| myagent.py | フレームワークにおける主要なエージェントの実装が含まれています。 LangGraphでは、これは通常、手動で作成したMyAgentサブクラスではなく、graph_factory関数とMyAgent = datarobot_agent_class_from_langgraph(...)の組み合わせです（下のLangGraphタブを参照してください）。 |
| config.py | 環境変数、ランタイムパラメーター、およびDataRobotの資格情報からの設定読み込みを管理します。 |
| register.py | DRAgentのフロントサーバーをフレームワーク（LLM選択、MCPツール（mcp_tools_context）、およびオプションのワークフローツール）に接続します。 |
| workflow.yaml | DRAgentサーバーのワークフロータイプ、LLMコンポーネント、およびオプションのA2Aメタデータを宣言します。 |

主に編集する実装は `myagent.py` にあります。具体的なパターンはフレームワークによって異なります。

> [!NOTE] Agentic Starterテンプレートの更新（11.8.x）
> 現在の [Agentic Starter](https://github.com/datarobot-community/datarobot-agent-application) のリリースでは、エージェントテンプレート（汎用的な base テンプレートを除く）は、ヘルパーファクトリーを使用してネイティブフレームワークのプリミティブから `MyAgent` を構築しており、MCPツールはエージェントクラスから切り離されています。 古いクローンをアップグレードする場合、詳細については、リポジトリの `docs/agent/` にある [Migrate Agentic Starter agents to 11.8.8](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-starter-migration.html.md) および [framework migration guides](https://github.com/datarobot-community/datarobot-agent-application/tree/main/docs/agent) を参照してください。

エージェントのテンプレートには、単純な複数ステップの例が用意されています（例：LangGraphのPlannerノードとWriterノード）。 必要に応じて、このコードを修正して、エージェント、タスク、およびツールを追加できます。

LLMの選択は、手動で作成したクラスにおける `llm()` メソッドに限定されるものではありません。 通常、以下の組み合わせによって決定されます。

- DataRobotのランタイムと設定 — プラットフォームがワークフローにおいてチャットモデルおよび関連設定をどのように解決するか。
- アダプターヘルパー（LangGraph） — たとえば、DRUM/DRAgentアダプターパス内の get_llm など、グラフにモデルを提供するもの。
- 宣言型および環境設定 — たとえば、 workflow.yaml （DRAgent）や、プロバイダーとモデルの選択に影響を与える環境変数。

LLMの設定の詳細については、 [LLMプロバイダーの設定](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-llm-providers.html.md) を参照してください。 エージェントワークフローテンプレートの全体的な構造については、 [エージェントのコンポーネント](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-overview.html.md) を参照してください。

> [!NOTE] datarobot_genai package
> エージェントテンプレートは、 `datarobot_genai` パッケージを使用して開発を効率化します。 このパッケージは、LLM設定、回答形式、DataRobotサービスとの連携など、エージェントの実装を簡素化するヘルパー関数と基本クラスを提供します。 テンプレートにはこのパッケージが自動的に含まれるため、別途インストールする必要はありません。

## エージェントプロンプトの修正

各エージェントテンプレートは、プロンプトの定義とカスタマイズに異なるアプローチを使用します。 選択したフレームワークでプロンプトを変更する方法を理解することは、エージェントの動作を特定のユースケースに合わせるために非常に重要です。

**CrewAI:**
CrewAIテンプレートでは、プロンプトは `myagent.py` ファイル内の `MyAgent` クラスのいくつかのプロパティを通して定義されます。

エージェントのプロンプト
：role
、
goal
、
backstory`プロパティを使用して定義されます。
タスクプロンプト
：description
と
expected_output`プロパティを使用して定義されます。

```
@property
def agent_planner(self) -> Agent:
    return Agent(
        role="Content Planner",
        goal="Plan engaging and factually accurate content on {topic}",
        backstory="You're working on planning a blog article about the topic: {topic}. You collect "
        "information that helps the audience learn something and make informed decisions. Your work is "
        "the basis for the Content Writer to write an article on this topic.",
        allow_delegation=False,
        verbose=self.verbose,
        llm=self.llm,
    ) 
```

CrewAIエージェントのプロンプトを修正するには：

**エージェントの動作を更新する：エージェント定義の
role
、
goal
、
backstory
プロパティを変更します。
変数を使用する
：
{topic}
やその他の変数をプロンプトの動的なコンテンツに利用します。

```
@property
def task_plan(self) -> Task:
    return Task(
        description=(
            "1. Prioritize the latest trends, key players, and noteworthy news on {topic}.\n"
            "2. Identify the target audience, considering their interests and pain points.\n"
            "3. Develop a detailed content outline including an introduction, key points, and a call to action.\n"
            "4. Include SEO keywords and relevant data or sources."
        ),
        expected_output="A comprehensive content plan document with an outline, audience analysis, SEO keywords, "
        "and resources.",
        agent=self.agent_planner,
    ) 
```

CrewAIのタスクプロンプトを修正するには：

タスク指示のカスタマイズ
：タスク定義の
description
プロパティを更新します。
期待される出力の変更
：要件に合わせて
expected_output
プロパティを修正します。
変数を使用する
：
{topic}
やその他の変数をプロンプトの動的なコンテンツに利用します。

より高度なCrewAIプロンプトエンジニアリング技術については、 [CrewAIエージェントのドキュメント](https://docs.crewai.com/en/concepts/agents) と [CrewAIタスクのドキュメント](https://docs.crewai.com/en/concepts/tasks) を参照してください。

**LangGraph:**
現在のLangGraphテンプレートでは、プロンプトテンプレート（ `ChatPromptTemplate` ）を定義し、 `create_agent` ノードを構築して `StateGraph` を接続する `graph_factory(llm, tools, verbose)` を定義した後、 `MyAgent = datarobot_agent_class_from_langgraph(graph_factory, prompt_template)` と記述します。 [Agentic Starterのテンプレート](https://github.com/datarobot-community/datarobot-agent-application) は、 `myagent.py` ではこのパターンに従っています。レイアウトの詳細については、 [リポジトリ内のLangGraphガイド](https://github.com/datarobot-community/datarobot-agent-application/blob/main/docs/agent/frameworks/langgraph.md) を参照してください。

> [!NOTE] LangChainのcreate_agentと他のLangGraphの例との比較
> DataRobotのテンプレートでは、 `langchain.agents.create_agent` を `system_prompt=` （およびオプションの `make_system_prompt` ）と一緒に使用します。 コミュニティの例の中には `langgraph.prebuilt.create_react_agent` を使用するものがあります。これは `prompt=` 引数を代わりに取ります。 これらは異なるAPIです。DataRobotのエージェントコードを編集するときは、 `create_agent` / `system_prompt` に従ってください。

```
from datarobot_genai.core.agents import make_system_prompt
from datarobot_genai.langgraph.agent import datarobot_agent_class_from_langgraph
from langchain.agents import create_agent
from langgraph.graph import END, START, MessagesState, StateGraph

def graph_factory(llm, tools, verbose=False):
    planner = create_agent(
        llm,
        tools=tools,
        system_prompt=make_system_prompt("You are a content planner..."),
        name="planner_agent",
        debug=verbose,
    )
    writer = create_agent(
        llm,
        tools=tools,
        system_prompt=make_system_prompt("You are a content writer..."),
        name="writer_agent",
        debug=verbose,
    )
    workflow = StateGraph(MessagesState)
    workflow.add_node("planner_node", planner)
    workflow.add_node("writer_node", writer)
    workflow.add_edge(START, "planner_node")
    workflow.add_edge("planner_node", "writer_node")
    workflow.add_edge("writer_node", END)
    return workflow

MyAgent = datarobot_agent_class_from_langgraph(graph_factory, prompt_template) 
```

`tools` 引数には、MCPツールとオプションのワークフローツールが含まれます。DRUMパスでは、 `mcp_tools_context` を使用して `custompy_adaptor` 内でこれらを構築し、DRAgentパスでは、 `MyAgent` を呼び出す前に `register.py` 内で `workflow_tools` とMCPツールを結合します（テンプレートの `docs/agent/frameworks/langgraph.md` を参照してください）。

LangGraphのプロンプトを修正するには：

システムプロンプトを更新する
：
graph_factory
内の
make_system_prompt()
に渡される文字列を変更します。
タスク固有の手順を追加する
：それらのシステムプロンプト文字列内に詳細な手順を含めます。
グラフ構造を変更する
：
graph_factory
でノードやエッジを追加または再接続します。

より高度なLangGraphプロンプトエンジニアリング技術については、 [LangGraphのドキュメント](https://langchain-ai.github.io/langgraph/) を参照してください。

**LlamaIndex:**
LlamaIndexテンプレートでは、プロンプトは `MyAgent` クラス内の `FunctionAgent` 定義の `system_prompt` パラメーターを使って定義されます。

```
@property
def research_agent(self) -> FunctionAgent:
    return FunctionAgent(
        name="ResearchAgent",
        description="Useful for finding information on a given topic and recording notes on the topic.",
        system_prompt=(
            "You are the ResearchAgent that can find information on a given topic and record notes on the topic. "
            "Once notes are recorded and you are satisfied, you should hand off control to the "
            "WriteAgent to write a report on the topic. You should have at least some notes on a topic "
            "before handing off control to the WriteAgent."
        ),
        llm=self.llm,
        tools=[self.record_notes],
        can_handoff_to=["WriteAgent"],
    ) 
```

LlamaIndexのプロンプトを修正するには：

システムプロンプトを更新する
：
FunctionAgent
の定義で
system_prompt
文字列を変更します。
エージェントの説明をカスタマイズする
：エージェントの識別方法を変更するために
description
パラメーターを更新します。
ハンドオフ動作の変更
：エージェントのワークフローを制御するために、
can_handoff_to
リストとシステムプロンプトを更新しました。
ツール固有の説明
を追加する：特定の道具をいつ、どのように使うかについての指示を含めます。

より高度なLlamaIndexプロンプトエンジニアリングのテクニックについては、 [LlamaIndexプロンプトエンジニアリングのドキュメント](https://docs.llamaindex.ai/en/stable/module_guides/models/prompts/) を参照してください。

**NAT:**
NAT（NVIDIA NeMo Agent Toolkit）のテンプレートでは、プロンプトは `workflow.yaml` ファイルで、関数定義内の `system_prompt` フィールドを使用して定義されます。

```
functions:
  planner:
    _type: chat_completion
    llm_name: datarobot_llm
    system_prompt: |
      You are a content planner. You are working with a content writer colleague.
      You're working on planning a blog article about the topic.
      You collect information that helps the audience learn something and make informed decisions.
      Your work is the basis for the Content Writer to write an article on this topic.
      1. Prioritize the latest trends, key players, and noteworthy news on the topic.
      2. Identify the target audience, considering their interests and pain points.
      3. Develop a detailed content outline including an introduction, key points, and a call to action.
      4. Include SEO keywords and relevant data or sources. 
```

NATのプロンプトを変更するには：

システムプロンプトを更新する
：
workflow.yaml
内の関数定義の
system_prompt
フィールドを変更します。
関数ごとにLLMを設定する
：
workflow.yaml
の
llms
セクションで定義されたLLMを参照するように、
llm_name
フィールドを設定します。
ワークフローの構造を変更する
：
workflow
セクションを更新して、実行順序とツールリストを変更します。
新しい関数を追加する
：
functions
セクションに追加の関数を定義して、エージェントの機能を拡張します。

より高度なNATの使用方法については、 [NVIDIA NeMo Agent Toolkitのドキュメント](https://docs.nvidia.com/nemo/agent-toolkit/latest/index.html) を参照してください。


> [!TIP] 迅速な修正のためのベストプラクティス
> どのフレームワークでもプロンプトを修正する場合：
> 
> **具体的に：エージェントに達成してほしいことを明確かつ詳細に指示します。
> Use consistent formatting
> ：ワークフロー内のすべてのエージェントで一貫したプロンプト構造を維持します。
> インクリメンタルにテストする
> ：より大きな変更を実装する前に、小さな変更を行い、それをテストします。
> **コンテキストを考慮する：プロンプトがマルチエージェントワークフローでうまく機能するようにします。
> ドキュメントの変更
> ：将来の参照とチームコラボレーションのために、迅速な変更を追跡します。

## ストリーミングレスポンスを有効にする

ストリーミングを使用すると、エージェントは、完全なレスポンスを待機することなく、生成されたレスポンスを段階的に送信できます。 これにより、進捗状況がリアルタイムで表示され、認識される遅延が短縮されて、エージェントのアクションが発生したときにユーザーが確認できるようになるため、ユーザーエクスペリエンスが向上します。

ストリーミングのサポートは、エージェントフレームワークによって異なります。 ストリーミングの実装には3つのレベルがあります。

- チャンクストリーミング ：LLMからの各チャンクは、生成時にストリーミングされます（トークンや部分テキストなど）。
- ステップストリーミング ：各サブエージェントからのレスポンスは、準備ができた時点でストリーミングされます。
- イベントストリーミング ：個々のイベント（新しいステップの開始、ツールの呼び出し、推論）がストリーミングされます。

| フレームワーク | ストリーミング | 備考 |
| --- | --- | --- |
| LangGraph | 有効 | stream=Trueが渡されると、チャンクレベルのストリーミングが自動的に有効になります。 datarobot_agent_class_from_langgraphから生成されたMyAgentは、ストリーミングレスポンスを処理します。 |
| Generic Base | サポートされています | すべてのストリーミングレベル（チャンク、ステップ、イベント）にカスタム実装が必要です。 チャンクストリーミングのサンプルコードがmyagent.pyに用意されています。 |
| CrewAI | サポートされています | すべてのストリーミングレベル（チャンク、ステップ、イベント）にカスタム実装が必要です。 イベントリスナーは、エージェント実行とツール使用のイベントを段階的にキャプチャします。これにより、カスタムコードを用いたステップおよびイベントのストリーミングが容易になります。 チャンクストリーミングには、LLMから直接ストリーミングするためのカスタム実装が必要です。 |
| LlamaIndex | サポートされています | すべてのストリーミングレベル（チャンク、ステップ、イベント）にカスタム実装が必要です。 フレームワークはエージェントを段階的に実行するため、カスタムコードを用いたステップストリーミングが容易になります。 チャンクとイベントのストリーミングには、カスタム実装が必要です。 |
| NAT | サポートされています | すべてのストリーミングレベル（チャンク、ステップ、イベント）にカスタム実装が必要です。 |

> [!NOTE] インフラストラクチャのサポート
> すべてのエージェントテンプレートには、ストリーミングレスポンスを処理できるインフラストラクチャが `custom.py` に含まれています。 カスタム実装を必要とするフレームワーク（Generic Base、CrewAI、LlamaIndex、NAT）の場合、ストリーミングが要求されたときに `AsyncGenerator` を返すようにエージェントの `invoke()` メソッドを変更する必要があります。 エージェントの `invoke()` メソッドが `AsyncGenerator` を返すと、インフラストラクチャは自動的にそれを適切なストリーミングレスポンス形式に変換します。 `is_streaming` ヘルパー関数は、 `from datarobot_genai.core.agents import is_streaming` をインポートすることで、 `datarobot_genai` パッケージを通じて、すべてのフレームワークテンプレートで利用できます。 この関数は、チャット補完のリクエストボディパラメーターに `stream=True` が含まれているかどうかを確認します。

エージェントにストリーミングが実装されている場合は、ローカルでテストするとき（CLIを使用）、またはデプロイされたエージェントで予測を行うとき（APIを使用）にストリーミングを有効にします。

**CLI（ローカルテスト）:**
エージェントCLIを実行する際には、 `--stream` フラグを使用します。

```
task agent:cli -- execute --user_prompt 'Write a document about the history of AI.' --stream 
```

構造化クエリーでストリーミングを使うこともできます。

```
task agent:cli -- execute --user_prompt '{"topic":"Generative AI"}' --stream 
```

**API（デプロイ済みエージェント）:**
APIを呼び出す際、補完パラメーターに `stream=True` を設定します。

```
from openai import OpenAI

client = OpenAI(
    base_url=CHAT_API_URL,
    api_key=API_KEY,
)

completion = client.chat.completions.create(
    model="datarobot-deployed-llm",
    messages=[
        {"role": "user", "content": "What would it take to colonize Mars?"},
    ],
    stream=True,  # Enable streaming
)

# Process streaming response
for chunk in completion:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True) 
```


## ローカル開発中のエージェントのテスト

テンプレートで提供される開発サーバを使用して、ローカルでエージェントをテストすることができます。 これにより、DataRobotにデプロイすることなく、エージェントコードを実行してデバッグすることができます。

エージェントにテストクエリーを送信するには、開発サーバーが稼働している必要があります。 手動で起動するか、自動起動オプションを使用します。

**手動起動:**
複数のテストを実行する場合は、開発サーバーを手動で起動します。 開発サーバーは継続的に実行され、ターミナルをブロックするため、1つのターミナルで起動します。

```
task agent:dev 
```

このターミナルは起動したままにしておきます。 その後、別のターミナルでテストコマンドを実行します。

```
task agent:cli -- execute --user_prompt 'Write a document about the history of AI.' 
```

エージェントのワークフローが要求した場合、構造化クエリーをプロンプトとして送信することもできます。

```
task agent:cli -- execute --user_prompt '{"topic":"Generative AI"}' 
```

**自動起動:**
単一のテスト用に開発サーバーを自動起動します。 `START_DEV=1` を使用して、開発サーバーを自動的に起動および停止します。

```
task agent:cli START_DEV=1 -- execute --user_prompt 'Write a document about the history of AI.' 
```

エージェントのワークフローが要求した場合、構造化クエリーをプロンプトとして送信することもできます。

```
task agent:cli START_DEV=1 -- execute --user_prompt '{"topic":"Generative AI"}' 
```


このコマンドはエージェントをローカルで実行し、出力をコンソールに表示すします。 異なる入力やシナリオをテストするためにクエリーを変更することができます。

> [!TIP] 実行時依存関係を用いた高速イテレーション
> 開発を迅速に行うために、実行時依存関係を使用してDockerイメージを再構築することなく、Pythonの依存関係を追加できます。 このプロセスにより、イテレーションの速度が向上します。 実行時依存関係の追加の詳細については、 [Pythonパッケージの追加](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-python-packages.html.md) に関するドキュメントを参照してください。

## DataRobot LLMプレイグラウンドでテスト用のエージェントを構築する

DataRobot LLMプレイグラウンドを使って改良できるカスタムモデルを作成するには、テンプレートプロジェクトのルートから、 開発 インフラストラクチャ（プレイグラウンド関連のリソースを含む）をデプロイします。 これは、 `task dev` または `dr run dev` を使用した [ローカルでのスタックの実行](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-development.html.md#testing-the-agent-during-local-development) とは異なります。

```
dr run deploy-dev 
```

また、 `dr task run deploy-dev` （ `dr run deploy-dev` と同等）を実行することもできます。 このコマンドは、開発上のターゲット（たとえば、LLMプレイグラウンドや関連するカスタムモデルリソースなど）でPulumiを実行するものであり、本番環境への完全なデプロイは行いません。 これにより、反復的なクラウド開発とテストが大幅に高速化されます。 コマンドの詳細については、CLIドキュメントの [dr task](https://docs.datarobot.com/ja/docs/agentic-ai/cli/commands/task.html.md) および [dr run](https://docs.datarobot.com/ja/docs/agentic-ai/cli/commands/run.html.md) を参照してください。

DataRobot LLMプレイグラウンドでエージェントを扱う例については、 [エージェントプレイグラウンドのドキュメント](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-eval/agentic-playground.html.md) を参照してください。

> [!NOTE] ビルドコマンドに関する注意事項
> `deploy-dev` タスクは、スタックの既存のクラウドリソースを置き換えたり、更新したりすることができます。 実運用リソースをすべて作成するには、 `dr run deploy` （または `dr task run deploy` ）を使用します。 リソースが削除または再作成されると、新しいデプロイIDが適用される場合があります。

## 本番用エージェントのデプロイ

完全な運用レベルのデプロイを作成するには：

```
dr run deploy 
```

また、 `dr task run deploy` （ `dr run deploy` と同等）を実行することもできます。 これは、 [Agentic StarterテンプレートのREADME](https://github.com/datarobot-community/datarobot-agent-application#deploy-your-agent) （ `dr run deploy` ）と一致します。 このコマンドはカスタムモデルを構築し、必要なインフラストラクチャを備えた本番環境のデプロイを作成します。これには時間がかかりますが、完全な本番環境が提供されます。 その他のオプションについては、 [CLIのtaskおよびrunコマンド](https://docs.datarobot.com/ja/docs/agentic-ai/cli/commands/task.html.md) を参照してください。 デプロイは、完全な監視、ロギング、スケーリング機能を含む標準的なDataRobotデプロイです。 DataRobotのデプロイの詳細については、 [デプロイのドキュメント](https://docs.datarobot.com/ja/docs/workbench/nxt-console/nxt-overview/index.html.md) を参照してください。

### デプロイされたエージェントのログとトレースを確認する

エージェントがデプロイされたら、DataRobot UIでOpenTelemetry (OTel)のログとトレースを見ることができます。

ログを表示するには、 デプロイ タブでデプロイを検索してクリックし、 アクティビティログ タブ、 ログ の順にクリックします。 ログはOpenTelemetry形式で表示され、ログレベル（ `INFO` 、 `DEBUG` 、 `WARN` 、 `ERROR` ）、期間指定によるフィルター（直近 15 分、直近 1 時間、直近 1 日、またはカスタム範囲）、およびサードパーティ製のオブザーバビリティツール（Datadogなど）と連携するためのOTelログAPI経由でのエクスポート機能が含まれます。

> [!NOTE] アクセスと保持
> OTel logs are available for all deployment and target types. Only users with Owner and User roles on a deployment can view these logs. Logs data is stored for a retention period of 30 days, after which it is automatically deleted.

エージェントへのリクエストのエンドツーエンドのパスをたどるトレースを表示するには、デプロイの サービスの正常性 タブで、 予測の合計数 チャートの右上隅にある トレースを表示 をクリックします。 トレーステーブルには、タイムスタンプ、ステータス、トレースID、期間、スパン数、コスト、プロンプト、補完などのトレース情報が表示されます。 トレース行をクリックすると、チャートまたはリスト形式で詳細なスパンが表示されます。これにより、LLM APIの呼び出し、ツールの起動、エージェントのアクションなど、エージェントの実行における個々のステップを確認できます。

詳細については、 [ログのドキュメント](https://docs.datarobot.com/ja/docs/workbench/nxt-console/nxt-activity-log/nxt-otel-logs.html.md) と [トレースのドキュメント](https://docs.datarobot.com/ja/docs/workbench/nxt-console/nxt-monitoring/nxt-data-exploration.html.md#explore-deployment-data-tracing) を参照してください。

### Pulumiを使って手動でエージェントをデプロイする

必要に応じて、Pulumiコマンドを手動で実行して、Pulumiコードのデバッグや改良を行うことができます。

```
# Load environment variables
set -o allexport && source .env

# For build mode only (custom model without deployment)
export AGENT_DEPLOY=0

# Or for full deployment mode (default)
# export AGENT_DEPLOY=1

# Navigate to the infrastructure directory
cd ./infra

# Run Pulumi deployment
pulumi up 
```

環境変数 `AGENT_DEPLOY` は、Pulumi がカスタムモデルのみを作成するか（ `AGENT_DEPLOY=0` ）、カスタムモデルとプロダクションデプロイの両方を作成するか（ `AGENT_DEPLOY=1` ）を制御します。 設定されていない場合、Pulumiはデフォルトでフルデプロイモードになります。

Pulumiは、作成または更新するリソースを確認するよう促します。

## デプロイされたエージェントワークフローで予測を行う

エージェントワークフローがデプロイされたら、デプロイの 予測 > 予測API タブからリアルタイムの予測スニペットにアクセスします。 デプロイ予測の詳細については、 [予測APIスニペットに関するドキュメント](https://docs.datarobot.com/ja/docs/workbench/nxt-console/nxt-predictions/nxt-pred-api-snippets.html.md) を参照してください。

あるいは、以下のスクリプトを修正して、デプロイされたエージェントワークフローを予測し、変数 `API_KEY` 、 `DEPLOYMENT_ID` 、 `CHAT_API_URL` のプレースホルダーを置き換えることもできます。

```
# datarobot-llm-chat.py
import sys
import logging
import time
import os

from openai import OpenAI

API_KEY = '<API_KEY>' # Your API Key
DEPLOYMENT_ID = '<DEPLOYMENT_ID>' # The agentic workflow deployment ID
CHAT_API_URL = '<CHAT_API_URL>' # The chat API URL for the agentic workflow deployment
# For example, 'https://app.datarobot.com/api/v2/deployments/68824e9aa1946013exfc3415/'

logging.basicConfig(
    level=logging.INFO,
    stream=sys.stdout,
    format='%(asctime)s %(filename)s:%(lineno)d %(levelname)s %(message)s',
)
logger = logging.getLogger(__name__)


def main():
    openai_client = OpenAI(
        base_url=CHAT_API_URL,
        api_key=API_KEY,
        _strict_response_validation=False
    )

    prompt = "What would it take to colonize Mars?"
    logging.info(f"Trying Simple prompt first: \"{prompt}\"")
    completion = openai_client.chat.completions.create(
        model="datarobot-deployed-llm",
        messages=[
            {"role": "system", "content": "Explain your thoughts using at least 100 words."},
            {"role": "user", "content": prompt},
        ],
        max_tokens=512,  # omit if you want to use the model's default max
    )

    print(completion.choices[0].message.content)

    return 0

if __name__ == '__main__':
    sys.exit(main()) 
```

## 次のステップ

デプロイ後、エージェントはDataRobot環境で利用できるようになります。 以下を実行することが可能です。

1. task agent:cli -- execute-deployment`を使用して、デプロイしたエージェントをテストします。
2. エージェントを他のDataRobotサービスと連携します。
3. DataRobotのダッシュボードで使用状況とパフォーマンスを監視します。

このリポジトリで提供される例の範囲を超えたエージェントプラットフォーム固有の支援については、各フレームワークの公式ドキュメントを参照してください。

- CrewAI
- LangGraph
- LlamaIndex
- NVIDIA NeMo Agent Toolkit

また、特定のフレームワーク向けのパブリックリポジトリには、より複雑なエージェントの構築、ツールの追加、ワークフローやタスクの定義に役立つ、多くの例やドキュメントが用意されています。

- CrewAIのGitHubリポジトリ
- LangGraphのGitHubリポジトリ
- LlamaIndexのGitHubリポジトリ
