📚

【Salesforce】Agent Script入門|Agentforceの従業員エージェントを作ってみた

に公開

はじめに

Agentforceの指示文に「必ず取引先を確認してから回答してください」と書いたのに、確認が飛ばされて、そのまま回答されてしまった。
Agentforceでエージェントを作っていると、こんな場面に出会うことがあります。

LLMは賢いですが、少し気まぐれなところがあります。
「必ず」と書いても、必ず動くとは限りません。業務で使うとなると、「ここだけは毎回同じ動きをしてほしい」という部分が出てきます。

そこで使えるのが Agent Script です。
気まぐれでもよい部分はLLMに任せ、毎回同じ動きをしてほしい部分はコードで書く。
Agent Scriptはその線引きができる言語です。

この記事では、Agent Scriptを使って、営業担当向けの従業員エージェントを、サブエージェント3つで実際に作っていきます。
合わせて「作る前に知っておきたい5つのこと」も紹介します。

Agentforceを触り始めた管理者・開発者の方にぜひ読んでいただきたい内容です。

Agent Scriptとは

エージェントの定義を、1つのファイルにコードで書く言語です。Dreamforce 2025で発表され、2025年11月にパブリックベータになりました。

Agent Scriptはざっくり言うと、次の3つができます。

  • 変数に状態を持たせる(LLMの記憶に頼らない)
  • サブエージェント間の遷移をコードで決める
  • 推論の前後に処理を挟む

今回作るのは、社内の従業員が使う「Agentforce Employee Agent」です。
顧客向けの「Agentforce Service Agent」とは別のもので、営業担当等が日々使うアシスタントを想定しています。

基本の書き方

Agent Scriptは、ブロックの集まりでできています。

ブロック 役割
system エージェント全体の指示、ウェルカム/エラーメッセージ
config エージェントのメタ情報
variables 変数の宣言
start_agent 入口。どのサブエージェントに振るかを判断する
subagent 個別の機能。アクションや推論の指示を持つ

変数は、文章の中では {!@variables.変数名}、式の中では @variables.変数名 と書きます。
値のセットは set @variables.変数名 = 値、別のサブエージェントへの遷移は @utils.transition to @subagent.サブエージェント名 です。

LLMへの指示文は |(パイプ)で書きますが、1行ごとに付ける必要はありません。ひとまとまりの先頭に1回だけ付けて、続きの行は字下げでつなぎます。

instructions: ->
    | あなたは従業員エージェントです。
      ユーザーの依頼に、丁寧に対応してください。
      わからないことは、推測せずに確認してください。

if や run を挟むときは、そのたびに新しい | を書いて、文脈のかたまりごとに分けます。

雛形は、Agentforce Builder(Agentforce スタジオ アプリケーションから開いたAgentforce作成用のツール)の「スクリプト」ビューで見ながら書くのが、いちばん早いと思います。全体のコードは、記事の最後に載せています。

作る前に知っておきたい5つのこと

Agent Scriptで作ったエージェントをうまく動かすために、知っておいてもらいたいことを5つ紹介します。

1. 推論の前後で変数を更新する

サブエージェントには、before_reasoning と after_reasoning というブロックを置けます。推論の前と後に、毎回実行される処理です。変数の更新、アクションの実行、別のサブエージェントへの遷移などが書けます。

# before_reasoningサンプル
before_reasoning:
    set @variables.current_subagent = "Account_Summary"
    if @variables.currentObjectApiName == "Account" and @variables.target_account_id == "":
        set @variables.target_account_id = @variables.currentRecordId

「毎回必ず記録したい」「この変数は必ず更新したい」。そういった処理は、LLMの判断に任せず、ここに置いておくと安心です。

つまずきやすい点

  • 中での遷移は @utils.transition to ではなく、transition to と書く
  • | による指示文は書けない
  • 推論の途中で別のサブエージェントに遷移すると、元の after_reasoning は実行されない

今回は、before_reasoning で「いま対応しているサブエージェント名」を変数に保存しています。使い道は、前準備のところでご紹介します。

2. 「毎回同じ動き」をコードで書く

指示文に「必ず」と書く代わりに、コードで書いてしまいます。よく使うのは、次の3つです。

① if で、指示文を出し分ける。

instructions: ->
    if @variables.target_account_id == "":
        | 取引先が特定できていません。
          取引先名をユーザーに確認してください。
    else:
        | 取引先ID {!@variables.target_account_id} のサマリーを作成してください。

② run で、アクションを確実に実行して、結果を変数に入れる。

run @actions.GetAccountSummaryData
    with accountId = @variables.target_account_id
    set @variables.opportunity_text = @outputs.opportunityText

③ available when で、アクションを使える条件を絞る。

actions:
    CreateTodo: @actions.CreateTodo
        available when @variables.summary_confirmed == True

自由に話してもらってよい部分と、ぶらしたくない部分を分けておく。これだけでも、動きがだいぶ安定します。

3. サブエージェントごとにモデルを選ぶ

model_config を使うと、エージェント単位でも、サブエージェント単位でもモデルを指定できます。サブエージェント側の指定が優先されます。

subagent Account_Summary:
    model_config:
        model: "model://sfdc_ai__DefaultBedrockAnthropicClaude45Haiku"
  • 決まった形で出力するだけのサブエージェントには、軽くて速いモデルを。
  • アジェンダを考えてもらうサブエージェントには、推論力の高いモデルを。

そのように使い分けています。コストと応答速度の両方に関わってくるので、早めに決めておくと、後がラクになります。

4. アクションの入力は、LLMに任せるか、コードで固定するか

アクションに渡す入力(with)には、2通りの書き方があります。

# LLMに埋めてもらう
with recordName=...

# 変数で固定する
with accountId = @variables.target_account_id
  • ...:LLMが、会話の内容から値を埋める
  • 変数を指定:コードで値を固定する。LLMは触れない

使い分けの目安

  • 会話から拾ってほしい値(取引先名など)は、... でLLMに任せる
  • 間違えると困る値(Idなど)は、変数でコードから渡す

この後紹介するサンプルサブエージェントのコードにも、両方が出てきます。
取引先名を検索する IdentifyRecordByName は、recordName=... でLLMに名前を拾ってもらいます。
サマリーを取得する GetAccountSummaryData は、accountId = @variables.target_account_id で、Idをコードから渡します。

流れとしては、こうなります。

  1. LLMが、会話から取引先名を拾う
  2. IdentifyRecordByName で検索して、Idを確定する
  3. set_target_account で、Idを変数に保存する
  4. 以降は、その変数をコードから渡す(LLMにIdを書かせない)

取引先ページを開いている場合も同じです。before_reasoning で、開いているページのIdを target_account_id に入れておけば、会話から推測させずに済みます。

ここでもうひとつ、気をつけたい点があります。
変数で固定した値が空のままアクションを呼んでしまうと、うまく動きません。
「空のときは、先に埋める」という分岐を、if を使って用意しておきましょう。

5. メモリを使う

会話から好みや事実を自動で抽出して、ユーザーごとに保存し、次回以降の応答に反映する機能です。毎回同じ前提を説明するのが大変、という場面で役に立ちます。

知っておくと便利な点

  • エージェント単位、ユーザー単位で保存される
  • 1ユーザーにつき最大50件。超えると古いものから消える
  • 会話ログとは別もの
  • 従業員エージェントをLightning Experienceで使う場合は、ユーザー個別のオプトインが必要
  • 保存したデータはSalesforce内にとどまり、LLMとは共有されない

設定方法

設定は、Scriptのcontextブロックに書きます。

context:
    memory:
        enabled: True
    user_profile:
        enabled: True

user_profile は、名前、メール、ロケール、タイムゾーンといったプロフィール情報を使うための設定です。メモリとは別の機能で、プロフィール情報がメモリとして保存されることはありません。

「覚えて」「覚えていることを見せて」「メモリをオフにして」と、会話で管理できるようにしたい場合は、アセットライブラリの標準サブエージェント「User Memory Management」を追加します。手順は後ほどご紹介します。

サブエージェントを3つ作ってみる

ここからは、実際に作っていきます。

  1. 取引先サマリー(商談・ToDo・行動を取得して、決まった形でサマリーを出す)
  2. 訪問準備のアジェンダ作成(取引先サマリーで取得したデータを引き継いで使う)
  3. メモリの記録(標準のサブエージェントを追加するだけ)

作る前に決めておくこと

Agent Scriptは、変数、ルーター、サブエージェントの順に考えると、書きやすくなります。

今回使う変数は、先にすべて書き出しておきます。

variables:
    currentObjectApiName: mutable string
        description: "ユーザーが開いているレコードのオブジェクトAPI名(AccountやOpportunityなど)。ユーザーが別のオブジェクトの話をしている場合は使わない。"
        visibility: "External"
    currentRecordId: mutable string
        description: "ユーザーが開いているレコードのId。「これ」「現在の」といった指示があるときだけ使う。迷う場合は使わない。"
        visibility: "External"
    current_subagent: mutable string = ""
        description: "直前のやり取りで対応していたサブエージェント名。各サブエージェントのbefore_reasoningで設定する。ルーターが2回目以降の振り分けのヒントとして使う。"
    target_account_id: mutable string = ""
        description: "サマリー対象の取引先Id。取引先ページを開いている場合はそのId、それ以外は検索で特定したId。"
    opportunity_text: mutable string = ""
        description: "GetAccountSummaryDataで取得した、取引先に紐づく商談のテキスト。"
    todo_text: mutable string = ""
        description: "GetAccountSummaryDataで取得した、取引先に紐づくToDoのテキスト。"
    event_text: mutable string = ""
        description: "GetAccountSummaryDataで取得した、取引先に紐づく行動のテキスト。"
    summary_account_id: mutable string = ""
        description: "サマリーのデータ(opportunity_textなど)を取得済みの取引先Id。取得済みかどうかの判定に使う。"

変数のポイント

  • descriptionは、必ず書いておきましょう。LLMが、その変数をいつ使うかを判断する材料になります。
  • currentObjectApiName と currentRecordId は、ユーザーが開いているページの情報を受け取る変数なので、visibility: "External" を付けます。
  • データを一時的に持たせる変数は、初期値を "" にしておきます。

current_subagent が地味に効く

サマリーを出したあとに、「もう少し詳しく」「商談だけ見せて」と言われたとします。
ルーターが毎回、その一言だけで振り分けると、別のサブエージェントに振られてしまうことがあります。短い追加の質問ほど、起こりやすいです。

そこで、次のようにしました。

  1. 各サブエージェントの before_reasoning で、自分の名前を current_subagent に保存する
  2. ルーターは、これが空でなければ、「直前は〇〇が対応していた」とLLMに伝える
  3. 続きの発言なら、同じサブエージェントに振る。明らかに別の依頼のときは、この変数に頼らず、新しく振り分け先を決める
  4. 受け皿(依頼が曖昧 ambiguous_question / 対応範囲外 off_topic)に入ったら、変数を空に戻す

ルーター

ルーターは、start_agent に遷移用のアクションを並べて書きます。

start_agent agent_router:
    label: "Agent Router"
    description: "ユーザーを歓迎し、依頼に基づいて適切なサブエージェントを決定する"
    reasoning:
        instructions: ->
            | あなたは従業員エージェントのルーターです。
              ユーザーの依頼に応じて、最適なアクションを1つ選択してください。
            if @variables.current_subagent != "":
                | 直前のやり取りでは、サブエージェント「{!@variables.current_subagent}」が対応していました。
                  ユーザーの発言がその続き(追加の質問、絞り込み、修正依頼など)であれば、
                  新しく判断せず、そのサブエージェントに対応する go_to_ のアクションを選択してください。
                  明らかに別の依頼である場合は、この情報には頼らず、依頼の内容から新しく振り分け先を決めてください。
            if @variables.currentObjectApiName == "Account":
                | ユーザーは取引先ページを開いています。
                  「この取引先」「サマリー」といった依頼は{!@actions.go_to_Account_Summary}を選択してください。
        actions:
            go_to_Account_Summary: @utils.transition to @subagent.Account_Summary
                description: "取引先のサマリー(商談・ToDo・行動のまとめ)を依頼されたときに使用する。「〇〇社の状況をまとめて」など。"
            go_to_Visit_Prep: @utils.transition to @subagent.Visit_Prep
                description: "取引先への次回訪問の準備(アジェンダや、先方に確認したい質問の作成)を依頼されたときに使用する。「次回訪問の準備をしたい」など。"
            go_to_UserMemoryManagement: @utils.transition to @subagent.UserMemoryManagement
                description: "記憶している内容の確認・変更・削除や、メモリのオン/オフを求められたときに使用する。「私について覚えていることを見せて」など。"
            go_to_ambiguous_question: @utils.transition to @subagent.ambiguous_question
                description: "依頼の意図が曖昧で、どのサブエージェントが適切か判断できないときに使用する。"
            go_to_off_topic: @utils.transition to @subagent.off_topic
                description: "営業業務に関係のない雑談や、一般的な知識の質問のときに使用する。"

振り分けの判断材料になるのは、各アクションの description です。どんな依頼のときに使うのかを、発話例まで書いておくと、振り分けが安定します。
「対応範囲外(off_topic)」と「依頼が曖昧(ambiguous_question)」の受け皿も、忘れずに用意しておきましょう。受け皿がないと、どこかのサブエージェントに無理やり振られてしまいます。

サブエージェント① 取引先サマリー

取引先に紐づく商談、ToDo、行動を取得して、決まった形でサマリーを出すサブエージェントです。

方針

  • データの取得は、フローのアクションにして確実に実行する
  • 取得結果は変数に入れて、LLMには整形と要約だけをお願いする
  • 決まった形の出力なので、軽いモデルを指定する

作る順番は、先にフロー、次にサブエージェントです。

STEP1:フローを作る

商談、ToDo、行動を取得して、テキストにして返すフローを作ります。

フローの仕様は、次のようにします。

  • 種類:自動起動フロー (トリガなし)
  • API参照名:Get_Account_Summary_Data
  • 入力:accountId(テキスト)
  • 出力:opportunityText、todoText、eventText(すべてテキスト)
作り方
  1. 「設定」を開き、クイック検索で「フロー」を探して選ぶ
  2. 「新規フロー」→「最初から開始」→「次へ」の順に進み、「自動起動フロー (トリガなし)」を選んで「作成」
  3. 「新規リソース」から、リソース種別「変数」を4つ作る。すべてデータ型は「テキスト」。accountId は「入力で使用可能」、残りの3つは「出力で使用可能」にチェックを入れる(このチェックを入れた変数だけが、アクションの入力・出力になります)
フロー処理部分
  1. 「+」→「要素を追加」→「レコードを取得」を選ぶ。
  2. オブジェクトは「商談」。条件は「取引先 ID」が {!accountId} と等しい、かつ「完了」が {!$GlobalConstant.False} と等しい。
  3. 並び替えは「完了予定日」の昇順。「保存するレコード数」は「すべてのレコード」にして、保存する項目は、商談名、フェーズ、金額、完了予定日くらいに絞る
  4. 「ループ」を追加して、取得したコレクションを1件ずつ処理する
  5. 「新規リソース」で「テキストテンプレート」を作り、1行ぶんの文章にする。
    例:・{!Loop_Opportunities.Name}({!Loop_Opportunities.StageName}/{!Loop_Opportunities.Amount}円/完了予定日 {!Loop_Opportunities.CloseDate})。
  6. ループの中の「割り当て」で、opportunityText にテンプレートを、演算子「追加」で足していく

ToDoと行動も、同じ流れで作ります。

  • ToDo:オブジェクトは「ToDo」。
    条件は「関連先 ID」が {!accountId}、かつ「完了」が {!$GlobalConstant.False}。
    期日の昇順。
    件名、期日、状況を todoText へ
  • 行動:オブジェクトは「行動」。
    条件は「関連先 ID」が {!accountId}、かつ「開始日時」が直近3か月以内。
    開始日時の降順。
    件名、開始日時を eventText へ

「直近3か月以内」は、「新規リソース」で「数式」(データ型は「日付/時間」)を作って、
NOW() - 90
とします。

最後に、0件のときの対応を入れておきます。0件だとテキストが空になり、LLMが「データがない」のか「取得に失敗した」のか判断できなくなってしまいます。
それぞれの「レコードを取得」の後ろに「決定」を置いて、0件のときは「割り当て」で「該当なし」と入れます。

最後に「保存」します。
「表示ラベル」「API 参照名」を入れて、「説明」にアクションとして使うときの説明を書き、保存したら「有効化」します。

以下、完成形のフローイメージです。

商談取得部分


ToDo取得部分


行動取得部分

完成形のフローメタデータサンプル(長いので折りたたんでいます)
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>68.0</apiVersion>
    <areMetricsLoggedToDataCloud>false</areMetricsLoggedToDataCloud>
    <assignments>
        <description>行動1件ぶんの行を eventText に追記する</description>
        <name>Add_Event_Line</name>
        <label>行動の行を追加</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignmentItems>
            <assignToReference>eventText</assignToReference>
            <operator>Add</operator>
            <value>
                <elementReference>EventLineTemplate</elementReference>
            </value>
        </assignmentItems>
        <connector>
            <targetReference>Loop_Events</targetReference>
        </connector>
    </assignments>
    <assignments>
        <description>商談1件ぶんの行を opportunityText に追記する</description>
        <name>Add_Opportunity_Line</name>
        <label>商談の行を追加</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignmentItems>
            <assignToReference>opportunityText</assignToReference>
            <operator>Add</operator>
            <value>
                <elementReference>OpportunityLineTemplate</elementReference>
            </value>
        </assignmentItems>
        <connector>
            <targetReference>Loop_Opportunities</targetReference>
        </connector>
    </assignments>
    <assignments>
        <description>ToDo1件ぶんの行を todoText に追記する</description>
        <name>Add_Task_Line</name>
        <label>ToDoの行を追加</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignmentItems>
            <assignToReference>todoText</assignToReference>
            <operator>Add</operator>
            <value>
                <elementReference>TaskLineTemplate</elementReference>
            </value>
        </assignmentItems>
        <connector>
            <targetReference>Loop_Tasks</targetReference>
        </connector>
    </assignments>
    <assignments>
        <description>行動の取得失敗時に原因を残す</description>
        <name>Assign_Event_Error</name>
        <label>行動の取得失敗を設定</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignmentItems>
            <assignToReference>eventText</assignToReference>
            <operator>Assign</operator>
            <value>
                <stringValue>取得に失敗しました({!$Flow.FaultMessage})</stringValue>
            </value>
        </assignmentItems>
    </assignments>
    <assignments>
        <description>0件のとき明示的に「該当なし」を入れる</description>
        <name>Assign_No_Events</name>
        <label>行動なしを設定</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignmentItems>
            <assignToReference>eventText</assignToReference>
            <operator>Assign</operator>
            <value>
                <stringValue>該当なし</stringValue>
            </value>
        </assignmentItems>
    </assignments>
    <assignments>
        <description>0件のとき空文字を返すとLLMが「データなし」と「取得失敗」を区別できないため、明示的に「該当なし」を入れる</description>
        <name>Assign_No_Opportunities</name>
        <label>商談なしを設定</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignmentItems>
            <assignToReference>opportunityText</assignToReference>
            <operator>Assign</operator>
            <value>
                <stringValue>該当なし</stringValue>
            </value>
        </assignmentItems>
        <connector>
            <targetReference>Get_Open_Tasks</targetReference>
        </connector>
    </assignments>
    <assignments>
        <description>0件のとき明示的に「該当なし」を入れる</description>
        <name>Assign_No_Tasks</name>
        <label>ToDoなしを設定</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignmentItems>
            <assignToReference>todoText</assignToReference>
            <operator>Assign</operator>
            <value>
                <stringValue>該当なし</stringValue>
            </value>
        </assignmentItems>
        <connector>
            <targetReference>Get_Recent_Events</targetReference>
        </connector>
    </assignments>
    <assignments>
        <description>商談の取得失敗時に原因を残し、残りのデータ取得は続行する</description>
        <name>Assign_Opportunity_Error</name>
        <label>商談の取得失敗を設定</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignmentItems>
            <assignToReference>opportunityText</assignToReference>
            <operator>Assign</operator>
            <value>
                <stringValue>取得に失敗しました({!$Flow.FaultMessage})</stringValue>
            </value>
        </assignmentItems>
        <connector>
            <isGoTo>true</isGoTo>
            <targetReference>Get_Open_Tasks</targetReference>
        </connector>
    </assignments>
    <assignments>
        <description>ToDoの取得失敗時に原因を残し、残りのデータ取得は続行する</description>
        <name>Assign_Task_Error</name>
        <label>ToDoの取得失敗を設定</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignmentItems>
            <assignToReference>todoText</assignToReference>
            <operator>Assign</operator>
            <value>
                <stringValue>取得に失敗しました({!$Flow.FaultMessage})</stringValue>
            </value>
        </assignmentItems>
        <connector>
            <isGoTo>true</isGoTo>
            <targetReference>Get_Recent_Events</targetReference>
        </connector>
    </assignments>
    <decisions>
        <description>行動が1件以上あればループへ、0件なら「該当なし」へ</description>
        <name>Check_Events_Found</name>
        <label>行動があるか</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <defaultConnector>
            <targetReference>Assign_No_Events</targetReference>
        </defaultConnector>
        <defaultConnectorLabel>0件</defaultConnectorLabel>
        <rules>
            <name>Events_Found</name>
            <conditionLogic>and</conditionLogic>
            <conditions>
                <leftValueReference>Get_Recent_Events</leftValueReference>
                <operator>IsNull</operator>
                <rightValue>
                    <booleanValue>false</booleanValue>
                </rightValue>
            </conditions>
            <connector>
                <targetReference>Loop_Events</targetReference>
            </connector>
            <label>1件以上</label>
        </rules>
    </decisions>
    <decisions>
        <description>商談が1件以上あればループへ、0件なら「該当なし」へ</description>
        <name>Check_Opportunities_Found</name>
        <label>商談があるか</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <defaultConnector>
            <targetReference>Assign_No_Opportunities</targetReference>
        </defaultConnector>
        <defaultConnectorLabel>0件</defaultConnectorLabel>
        <rules>
            <name>Opportunities_Found</name>
            <conditionLogic>and</conditionLogic>
            <conditions>
                <leftValueReference>Get_Open_Opportunities</leftValueReference>
                <operator>IsNull</operator>
                <rightValue>
                    <booleanValue>false</booleanValue>
                </rightValue>
            </conditions>
            <connector>
                <targetReference>Loop_Opportunities</targetReference>
            </connector>
            <label>1件以上</label>
        </rules>
    </decisions>
    <decisions>
        <description>ToDoが1件以上あればループへ、0件なら「該当なし」へ</description>
        <name>Check_Tasks_Found</name>
        <label>ToDoがあるか</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <defaultConnector>
            <targetReference>Assign_No_Tasks</targetReference>
        </defaultConnector>
        <defaultConnectorLabel>0件</defaultConnectorLabel>
        <rules>
            <name>Tasks_Found</name>
            <conditionLogic>and</conditionLogic>
            <conditions>
                <leftValueReference>Get_Open_Tasks</leftValueReference>
                <operator>IsNull</operator>
                <rightValue>
                    <booleanValue>false</booleanValue>
                </rightValue>
            </conditions>
            <connector>
                <targetReference>Loop_Tasks</targetReference>
            </connector>
            <label>1件以上</label>
        </rules>
    </decisions>
    <description>Agentforceの取引先サマリー用アクション。取引先Idを受け取り、未完了の商談・未完了のToDo・直近3か月の行動をテキストに整形して返す。</description>
    <environments>Default</environments>
    <formulas>
        <description>行動の取得対象とする開始日時の下限(直近3か月=90日前)</description>
        <name>EventsFromDateTime</name>
        <dataType>DateTime</dataType>
        <expression>NOW() - 90</expression>
    </formulas>
    <interviewLabel>取引先サマリー用データ取得 {!$Flow.CurrentDateTime}</interviewLabel>
    <label>取引先サマリー用データ取得</label>
    <loops>
        <description>取得した行動を1件ずつテキスト化する</description>
        <name>Loop_Events</name>
        <label>行動のループ</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <collectionReference>Get_Recent_Events</collectionReference>
        <iterationOrder>Asc</iterationOrder>
        <nextValueConnector>
            <targetReference>Add_Event_Line</targetReference>
        </nextValueConnector>
    </loops>
    <loops>
        <description>取得した商談を1件ずつテキスト化する</description>
        <name>Loop_Opportunities</name>
        <label>商談のループ</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <collectionReference>Get_Open_Opportunities</collectionReference>
        <iterationOrder>Asc</iterationOrder>
        <nextValueConnector>
            <targetReference>Add_Opportunity_Line</targetReference>
        </nextValueConnector>
        <noMoreValuesConnector>
            <targetReference>Get_Open_Tasks</targetReference>
        </noMoreValuesConnector>
    </loops>
    <loops>
        <description>取得したToDoを1件ずつテキスト化する</description>
        <name>Loop_Tasks</name>
        <label>ToDoのループ</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <collectionReference>Get_Open_Tasks</collectionReference>
        <iterationOrder>Asc</iterationOrder>
        <nextValueConnector>
            <targetReference>Add_Task_Line</targetReference>
        </nextValueConnector>
        <noMoreValuesConnector>
            <targetReference>Get_Recent_Events</targetReference>
        </noMoreValuesConnector>
    </loops>
    <processMetadataValues>
        <name>BuilderType</name>
        <value>
            <stringValue>LightningFlowBuilder</stringValue>
        </value>
    </processMetadataValues>
    <processMetadataValues>
        <name>CanvasMode</name>
        <value>
            <stringValue>AUTO_LAYOUT_CANVAS</stringValue>
        </value>
    </processMetadataValues>
    <processMetadataValues>
        <name>OriginBuilderType</name>
        <value>
            <stringValue>LightningFlowBuilder</stringValue>
        </value>
    </processMetadataValues>
    <processType>AutoLaunchedFlow</processType>
    <recordLookups>
        <description>取引先に紐づく未完了の商談を完了予定日の昇順で取得する</description>
        <name>Get_Open_Opportunities</name>
        <label>未完了の商談を取得</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignNullValuesIfNoRecordsFound>false</assignNullValuesIfNoRecordsFound>
        <connector>
            <targetReference>Check_Opportunities_Found</targetReference>
        </connector>
        <faultConnector>
            <targetReference>Assign_Opportunity_Error</targetReference>
        </faultConnector>
        <filterLogic>and</filterLogic>
        <filters>
            <field>AccountId</field>
            <operator>EqualTo</operator>
            <value>
                <elementReference>accountId</elementReference>
            </value>
        </filters>
        <filters>
            <field>IsClosed</field>
            <operator>EqualTo</operator>
            <value>
                <booleanValue>false</booleanValue>
            </value>
        </filters>
        <getFirstRecordOnly>false</getFirstRecordOnly>
        <object>Opportunity</object>
        <queriedFields>Id</queriedFields>
        <queriedFields>Name</queriedFields>
        <queriedFields>StageName</queriedFields>
        <queriedFields>Amount</queriedFields>
        <queriedFields>CloseDate</queriedFields>
        <sortField>CloseDate</sortField>
        <sortOrder>Asc</sortOrder>
        <storeOutputAutomatically>true</storeOutputAutomatically>
    </recordLookups>
    <recordLookups>
        <description>取引先に直接紐づく未完了のToDoを期日の昇順で取得する</description>
        <name>Get_Open_Tasks</name>
        <label>未完了のToDoを取得</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignNullValuesIfNoRecordsFound>false</assignNullValuesIfNoRecordsFound>
        <connector>
            <targetReference>Check_Tasks_Found</targetReference>
        </connector>
        <faultConnector>
            <targetReference>Assign_Task_Error</targetReference>
        </faultConnector>
        <filterLogic>and</filterLogic>
        <filters>
            <field>WhatId</field>
            <operator>EqualTo</operator>
            <value>
                <elementReference>accountId</elementReference>
            </value>
        </filters>
        <filters>
            <field>IsClosed</field>
            <operator>EqualTo</operator>
            <value>
                <booleanValue>false</booleanValue>
            </value>
        </filters>
        <getFirstRecordOnly>false</getFirstRecordOnly>
        <object>Task</object>
        <queriedFields>Id</queriedFields>
        <queriedFields>Subject</queriedFields>
        <queriedFields>ActivityDate</queriedFields>
        <queriedFields>Status</queriedFields>
        <sortField>ActivityDate</sortField>
        <sortOrder>Asc</sortOrder>
        <storeOutputAutomatically>true</storeOutputAutomatically>
    </recordLookups>
    <recordLookups>
        <description>取引先に直接紐づく直近3か月の行動を開始日時の降順で取得する</description>
        <name>Get_Recent_Events</name>
        <label>直近の行動を取得</label>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <assignNullValuesIfNoRecordsFound>false</assignNullValuesIfNoRecordsFound>
        <connector>
            <targetReference>Check_Events_Found</targetReference>
        </connector>
        <faultConnector>
            <targetReference>Assign_Event_Error</targetReference>
        </faultConnector>
        <filterLogic>and</filterLogic>
        <filters>
            <field>WhatId</field>
            <operator>EqualTo</operator>
            <value>
                <elementReference>accountId</elementReference>
            </value>
        </filters>
        <filters>
            <field>StartDateTime</field>
            <operator>GreaterThanOrEqualTo</operator>
            <value>
                <elementReference>EventsFromDateTime</elementReference>
            </value>
        </filters>
        <getFirstRecordOnly>false</getFirstRecordOnly>
        <object>Event</object>
        <queriedFields>Id</queriedFields>
        <queriedFields>Subject</queriedFields>
        <queriedFields>StartDateTime</queriedFields>
        <sortField>StartDateTime</sortField>
        <sortOrder>Desc</sortOrder>
        <storeOutputAutomatically>true</storeOutputAutomatically>
    </recordLookups>
    <start>
        <locationX>0</locationX>
        <locationY>0</locationY>
        <connector>
            <targetReference>Get_Open_Opportunities</targetReference>
        </connector>
    </start>
    <status>Active</status>
    <textTemplates>
        <description>行動1件ぶんの行</description>
        <name>EventLineTemplate</name>
        <isViewedAsPlainText>true</isViewedAsPlainText>
        <text>・{!Loop_Events.Subject}(開始日時 {!Loop_Events.StartDateTime})</text>
    </textTemplates>
    <textTemplates>
        <description>商談1件ぶんの行</description>
        <name>OpportunityLineTemplate</name>
        <isViewedAsPlainText>true</isViewedAsPlainText>
        <text>・{!Loop_Opportunities.Name}({!Loop_Opportunities.StageName}/{!Loop_Opportunities.Amount}円/完了予定日 {!Loop_Opportunities.CloseDate})</text>
    </textTemplates>
    <textTemplates>
        <description>ToDo1件ぶんの行</description>
        <name>TaskLineTemplate</name>
        <isViewedAsPlainText>true</isViewedAsPlainText>
        <text>・{!Loop_Tasks.Subject}(期日 {!Loop_Tasks.ActivityDate}/{!Loop_Tasks.Status})</text>
    </textTemplates>
    <variables>
        <description>対象の取引先Id(エージェントから渡される)</description>
        <name>accountId</name>
        <dataType>String</dataType>
        <isCollection>false</isCollection>
        <isInput>true</isInput>
        <isOutput>false</isOutput>
    </variables>
    <variables>
        <description>直近3か月の行動のテキスト。0件なら「該当なし」、失敗時はエラー内容</description>
        <name>eventText</name>
        <dataType>String</dataType>
        <isCollection>false</isCollection>
        <isInput>false</isInput>
        <isOutput>true</isOutput>
    </variables>
    <variables>
        <description>未完了の商談のテキスト。0件なら「該当なし」、失敗時はエラー内容</description>
        <name>opportunityText</name>
        <dataType>String</dataType>
        <isCollection>false</isCollection>
        <isInput>false</isInput>
        <isOutput>true</isOutput>
    </variables>
    <variables>
        <description>未完了のToDoのテキスト。0件なら「該当なし」、失敗時はエラー内容</description>
        <name>todoText</name>
        <dataType>String</dataType>
        <isCollection>false</isCollection>
        <isInput>false</isInput>
        <isOutput>true</isOutput>
    </variables>
</Flow>
注意点
  • 件数が多いと、テキストが長くなってLLMの応答が遅くなります。条件や期間で、必要な件数に絞っておきましょう
  • ToDoと行動は、取引先に直接紐づくものだけです。商談に紐づくものも含めたい場合は、商談のIdも条件に足してください
  • エージェントを使うユーザーが、このフローを実行できる権限を持っているかも、確認しておきましょう
  • 作り方は一例です。項目やテキストの形は、業務に合わせて調整してみてください
補足

実は、レコードやレコードのコレクションのまま返すこともできます。(Scriptのアクション定義では、list[object] に complex_data_type_name: "lightning__recordInfoType" を指定します)
それでもテキストにしたのは、LLMに渡す中身を、自分で決めたかったからです。

  • レコードのまま渡すと、何が渡るかはレコードの構造次第になる。
  • テキストなら、項目も順番も件数も日付の書き方も、フロー側で決められる
  • 整形をLLMに任せないので、毎回同じ形になる

もちろん、デメリットもあります。テキストにすると、構造がなくなってしまいます。
取得したレコードのIdで更新したい、回答にレコードへのリンクを付けたい、といった場合には不便です。その場合は、レコードで返すか、テキストにIdを混ぜる形になります。
今回はLLMが要約するだけなので、テキストで十分でした。

STEP2:サブエージェントを作る

取引先サマリーのサブエージェントは、キャンバスではなく、Agentforce Builderの「スクリプト」ビューでコードを書いて作ります。フローのアクションも、コードの中で定義します。

  1. アプリケーションランチャーから「Agentforce スタジオ」を開く
  2. 「エージェント」タブで、対象のエージェントをクリックする(Agentforce Builderが新しいタブで開きます)
  3. エディターを「スクリプト」ビューに切り替える
  4. variables に、前準備の変数を追加する
  5. 下の subagent Account_Summary: のコードを追加する
  6. 「保存」して、構文エラーが出ていないか確認する
  7. 「プレビュー」で、取引先のサマリーを依頼して動かしてみる

アクションの target には、フローのAPI参照名を指定します。

target: "flow://Get_Account_Summary_Data"

サブエージェントは、次のようになります。

subagent Account_Summary:
    label: "取引先サマリー"
    description: "取引先の商談・ToDo・行動をまとめて、定型のサマリーを出力する"
    model_config:
        model: "model://sfdc_ai__DefaultBedrockAnthropicClaude45Haiku"

    before_reasoning:
        set @variables.current_subagent = "Account_Summary"
        if @variables.currentObjectApiName == "Account" and @variables.target_account_id == "":
            set @variables.target_account_id = @variables.currentRecordId

    reasoning:
        instructions: ->
            if @variables.target_account_id == "":
                | 取引先が特定できていません。
                  取引先名をユーザーに確認し、{!@actions.IdentifyRecordByName}で検索してください。
                  候補が1件に絞れたら、そのIdを{!@actions.set_target_account}で設定してください。
            else:
                run @actions.GetAccountSummaryData
                    with accountId = @variables.target_account_id
                    set @variables.opportunity_text = @outputs.opportunityText
                    set @variables.todo_text = @outputs.todoText
                    set @variables.event_text = @outputs.eventText
                set @variables.summary_account_id = @variables.target_account_id
                | 以下のデータだけを根拠に、次の形式でサマリーを出力してください。
                  データにない内容は書かないでください。
                  1. 進行中の商談
                  2. 未完了のToDo
                  3. 直近の行動
                  4. 気になる点
                  【商談】{!@variables.opportunity_text}
                  【ToDo】{!@variables.todo_text}
                  【行動】{!@variables.event_text}
        actions:
            IdentifyRecordByName: @actions.IdentifyRecordByName
                description: "取引先をレコード名で検索する"
                with recordName=...
                with objectApiName="Account"
            set_target_account: @utils.setVariables
                description: "IdentifyRecordByNameで確定した取引先Idを保存する。ユーザーと確認した取引先のIdだけを設定すること。"
                with target_account_id=...

    actions:
        GetAccountSummaryData:
            description: "取引先に紐づく商談・ToDo・行動をテキストで取得する"
            label: "取引先サマリー用データ取得"
            require_user_confirmation: False
            include_in_progress_indicator: True
            progress_indicator_message: "データを取得中..."
            target: "flow://Get_Account_Summary_Data"
            inputs:
                "accountId": string
                    description: "対象の取引先Id"
                    label: "accountId"
                    is_required: True
                    is_user_input: False
            outputs:
                "opportunityText": string
                    description: "商談のテキスト"
                    label: "opportunityText"
                    is_displayable: False
                    filter_from_agent: False
                "todoText": string
                    description: "ToDoのテキスト"
                    label: "todoText"
                    is_displayable: False
                    filter_from_agent: False
                "eventText": string
                    description: "行動のテキスト"
                    label: "eventText"
                    is_displayable: False
                    filter_from_agent: False

        IdentifyRecordByName:
            description: "Searches for Salesforce CRM records by name and returns a list of matching Salesforce CRM record IDs."
            label: "Identify Record by Name"
            require_user_confirmation: False
            include_in_progress_indicator: True
            progress_indicator_message: "レコードを検索中..."
            source: "EmployeeCopilot__IdentifyRecordByName"
            target: "standardInvocableAction://identifyRecordByName"
            inputs:
                "recordName": string
                    description: "ユーザー入力から抽出したレコード名"
                    label: "recordName"
                    is_required: True
                    is_user_input: True
                "objectApiName": string
                    description: "検索対象のオブジェクトAPI名"
                    label: "objectApiName"
                    is_required: False
                    is_user_input: False
            outputs:
                "searchResults": list[object]
                    description: "一致したレコードのIdのリスト(関連度の高い順)"
                    label: "searchResults"
                    is_displayable: True
                    filter_from_agent: False
                    complex_data_type_name: "lightning__recordInfoType"

実際に実行してみたイメージはこんな感じです。

出力イメージ全文は以下です。

取引先サマリー

1. 進行中の商談
  • 保守契約更新(2027年度)
    ステータス:Negotiation/Review | 金額:1,800,000円 | 完了予定日:2026年10月27日
  • 生産管理システム刷新
    ステータス:Proposal/Price Quote | 金額:12,000,000円 | 完了予定日:2026年11月12日
  • 工場IoTセンサー導入
    ステータス:Needs Analysis | 金額:4,500,000円 | 完了予定日:2026年12月12日
  • 品質管理ダッシュボード
    ステータス:Qualification | 金額:2,400,000円 | 完了予定日:2027年1月11日
  • 海外拠点への横展開
    ステータス:Prospecting | 金額:30,000,000円 | 完了予定日:2027年4月11日
2. 未完了のToDo
  • 見積書の最終版を送付 → 期日:2026年10月16日(Not Started)
  • 保守契約の更新条件を法務に確認 → 期日:2026年10月18日(Waiting on someone else)
  • 品質管理部門へのヒアリング準備 → 期日:2026年10月25日(Not Started)
  • 海外拠点の担当者を紹介してもらう → 期日:2026年11月2日(Not Started)
3. 直近の行動
  • 生産管理システム刷新 提案説明会(2026年10月8日 14:00)
  • 工場見学(2026年9月25日 10:00)
  • 保守契約 更新条件の打ち合わせ(2026年9月13日 15:00)
4. 気になる点
  • 見積書の最終版送付が期日を迎えている(2026年10月16日)
  • 保守契約の更新条件確認が法務待ちの状態

どの商談や案件について詳しくお聞きになりたいことはありますか?

サブエージェント② 訪問準備のアジェンダ作成

取引先サマリーで取得したデータを使って、次回訪問のアジェンダと、先方に確認したい質問の案を作るサブエージェントです。
「次回の訪問の準備をしたい」と話しかけると案を出してくれて、そのあとは「もう少し短くして」「予算の話を入れて」といった壁打ちもできます。

方針

  • サブエージェント①で保存した変数(opportunity_text など)を、引き継いで使う
  • まだ取得していない取引先のときだけ、フローを実行する
  • アジェンダを考えてもらうので、推論力の高いモデルを指定する
  • データにないことは、推測しないようにお願いする

変数を引き継ぐしくみ

変数は、サブエージェントをまたいで共有されます。サブエージェント①でサマリーを出したあとなら、取得したテキストが変数に残っているので、サブエージェント②は同じデータをもう一度取りに行かずに済みます。

ただし、取引先を切り替えたときに、前の取引先のデータを使ってしまうと困ります。そこで、summary_account_id という変数に、「どの取引先のデータを取得済みか」を保存しておきます。

  1. サブエージェント①とサブエージェント②で、フローを実行したあとに、summary_account_id へ取引先Idを保存する
  2. サブエージェント②では、summary_account_id と target_account_id が違うときだけ、フローを実行する

「取得済みかどうか」の判定を、LLMに任せず、コードで書いている点がポイントです。

作り方

取引先サマリーと同じく、「スクリプト」ビューで書きます。

  1. 「Agentforce スタジオ」→「エージェント」タブで、対象のエージェントを開く
  2. エディターを「スクリプト」ビューに切り替える
  3. variables に summary_account_id を追加する(前準備の変数を参照)
  4. サブエージェント①の subagent Account_Summary: に、set @variables.summary_account_id = @variables.target_account_id が入っていることを確認する
  5. 下の subagent Visit_Prep: コードを追加する
  6. ルーターに go_to_Visit_Prep を追加する
  7. 「保存」して、構文エラーを確認する
  8. 「プレビュー」で、「〇〇社のサマリーを出して」→「次回訪問の準備をしたい」の順に話しかけてみる
subagent Visit_Prep:
    label: "訪問準備のアジェンダ作成"
    description: "取引先への次回訪問に向けて、アジェンダの案と、先方に確認したい質問を作る。サマリーで取得したデータを使う"
    model_config:
        model: "model://sfdc_ai__DefaultGPT56Terra"

    before_reasoning:
        set @variables.current_subagent = "Visit_Prep"
        if @variables.currentObjectApiName == "Account" and @variables.target_account_id == "":
            set @variables.target_account_id = @variables.currentRecordId

    reasoning:
        instructions: ->
            if @variables.target_account_id == "":
                | 取引先が特定できていません。
                  先に取引先を指定してもらうため、{!@actions.go_to_Account_Summary}を選択してください。
            if @variables.target_account_id != "" and @variables.summary_account_id != @variables.target_account_id:
                run @actions.GetAccountSummaryData
                    with accountId = @variables.target_account_id
                    set @variables.opportunity_text = @outputs.opportunityText
                    set @variables.todo_text = @outputs.todoText
                    set @variables.event_text = @outputs.eventText
                set @variables.summary_account_id = @variables.target_account_id
            if @variables.target_account_id != "":
                | 以下のデータだけを根拠に、次回訪問の準備を支援してください。
                  データにない内容は書かないでください。
                  1. 訪問の目的の案(1〜2個)
                  2. アジェンダの案(時間配分つき)
                  3. 先方に確認したい質問(3個程度)
                  4. 事前に準備しておくこと
                  ユーザーから修正の希望があれば、同じデータを根拠に調整してください。
                  【商談】{!@variables.opportunity_text}
                  【ToDo】{!@variables.todo_text}
                  【行動】{!@variables.event_text}
        actions:
            go_to_Account_Summary: @utils.transition to @subagent.Account_Summary
                description: "取引先が決まっていないときに、先に取引先を指定してもらうため、取引先サマリーへ移る"
                available when @variables.target_account_id == ""

    actions:
        GetAccountSummaryData:
            description: "取引先に紐づく商談・ToDo・行動をテキストで取得する"
            label: "取引先サマリー用データ取得"
            require_user_confirmation: False
            include_in_progress_indicator: True
            progress_indicator_message: "データを取得中..."
            target: "flow://Get_Account_Summary_Data"
            inputs:
                "accountId": string
                    description: "対象の取引先Id"
                    label: "accountId"
                    is_required: True
                    is_user_input: False
            outputs:
                "opportunityText": string
                    description: "商談のテキスト"
                    label: "opportunityText"
                    is_displayable: False
                    filter_from_agent: False
                "todoText": string
                    description: "ToDoのテキスト"
                    label: "todoText"
                    is_displayable: False
                    filter_from_agent: False
                "eventText": string
                    description: "行動のテキスト"
                    label: "eventText"
                    is_displayable: False
                    filter_from_agent: False

取引先が決まっていないときは、available when で「取引先サマリーへ移るアクション」だけを使えるようにしています。取引先を指定してもらってから、サマリーを経由して準備に進む流れです。

出力イメージはこんな感じです。

出力イメージ全文は以下です。

次回訪問の準備案

1. 訪問目的
  1. 生産管理システム刷新について、提案説明会後の評価・見積最終版に関する確認を行う。
  2. 保守契約更新(2027年度)の更新条件について、法務確認の進捗と今後の進め方をすり合わせる。
2. アジェンダ案(45分)
時間 内容
0〜5分 本日の目的と確認事項の共有
5〜20分 生産管理システム刷新:提案説明会後の所感、提案内容・見積最終版の確認
20〜30分 保守契約更新(2027年度):更新条件の確認状況と次の対応の整理
30〜40分 工場IoTセンサー導入:デモ日程の調整状況の確認
40〜45分 品質管理ダッシュボード、海外拠点への横展開に関する次のアクション確認
3. 先方に確認したい質問
  1. 生産管理システム刷新の提案説明会後、提案内容および見積最終版について確認・調整が必要な点はありますか。
  2. 保守契約更新の条件について、確認を進めるうえで先方側で必要な対応や判断はありますか。
  3. IoTセンサーのデモは、いつ頃の実施を想定されていますか。
  4. 海外拠点への横展開に向け、担当者をご紹介いただける時期はいつ頃になりそうですか。
4. 事前に準備しておくこと
  • 生産管理システム刷新の見積最終版を確認し、送付状況を整理する。
  • 生産管理システム刷新の提案書の社内レビューの進捗を確認する。
  • 保守契約更新の更新条件に関する法務確認の状況を確認する。
  • IoTセンサーのデモ日程候補を整理する。
  • 品質管理部門へのヒアリング準備の状況を確認する。
  • 海外拠点担当者の紹介依頼について、確認事項を整理する。

訪問では、生産管理システム刷新と保守契約更新を中心に進める構成でよいですか?

サブエージェント③ メモリの記録

これは、ほとんどコードを書きません。Agentforce Builderの「キャンバス」ビューで、アセットライブラリから標準のサブエージェントを追加するだけです。

  1. 「Agentforce スタジオ」→「エージェント」タブで、対象のエージェントを開く
  2. エディターを「キャンバス」にする
  3. 左の「エクスプローラー」の、検索ボックスの右にある「+」から「アセットライブラリから追加」を選ぶ
  4. 一覧から「User Memory Management」を探して、「選択 (Select)」→「エージェントに追加 (Add to Agent)」
  5. エクスプローラーのサブエージェント一覧に追加されたことを確認する

次に「スクリプト」ビューに切り替えます。

  1. contextブロックでメモリを有効にする
  2. before_reasoning を追加して、set @variables.current_subagent = "UserMemoryManagement" を書く
  3. ルーターから遷移できるように、go_to_UserMemoryManagement を入れる
  4. 「保存」して、「プレビュー」で「私について覚えていることを見せて」と話しかけてみる

追加されるアクションは、次の4つです。

  • 記憶の取得(Get User Memories)
  • 作成・更新・削除(Manage User Memory)
  • オンかどうかの確認(Get Agent Memory Preference)
  • オン/オフの切り替え(Update Agent Memory Preference)

自作せずに標準のサブエージェントを使うのも、立派な設計の選択肢です。

たとえばメモリに記録してほしいことがあるときは、以下のようにチャットで送信します。

メモリに記録されていることを確認しました。

改めてエージェントに私について聞いてみると、メモリを参照していることが分かります。

※ ちなみに自分のメモリは、チャットコンポーネント右上の「頭に歯車が入ったアイコン」から確認できます。

完成形のコード

ここまでの内容をまとめた、エージェント全体のコードです。

完成形のコード(長いので折りたたんでいます)
system:
    instructions: "あなたは営業担当を支援する社内アシスタントです。主に、取引先のサマリー作成、訪問準備のアジェンダ作成、メモリの管理を行います。"
    messages:
        welcome: "こんにちは!従業員エージェントです。取引先のサマリー作成、訪問準備のアジェンダ作成、メモリの管理をお手伝いします。"
        error: "問題が発生しました。もう一度お試しください。"

config:
    agent_label: "従業員エージェント"
    agent_type: "AgentforceEmployeeAgent"
    description: "営業担当を支援するエージェントです。"
    developer_name: "Sample_Employee_Agent"

context:
    memory:
        enabled: True
    user_profile:
        enabled: True

variables:
    currentObjectApiName: mutable string
        description: "ユーザーが開いているレコードのオブジェクトAPI名(AccountやOpportunityなど)。ユーザーが別のオブジェクトの話をしている場合は使わない。"
        visibility: "External"
    currentRecordId: mutable string
        description: "ユーザーが開いているレコードのId。「これ」「現在の」といった指示があるときだけ使う。迷う場合は使わない。"
        visibility: "External"
    current_subagent: mutable string = ""
        description: "直前のやり取りで対応していたサブエージェント名。各サブエージェントのbefore_reasoningで設定する。ルーターが2回目以降の振り分けのヒントとして使う。"
    target_account_id: mutable string = ""
        description: "サマリー対象の取引先Id。取引先ページを開いている場合はそのId、それ以外は検索で特定したId。"
    opportunity_text: mutable string = ""
        description: "GetAccountSummaryDataで取得した、取引先に紐づく商談のテキスト。"
    todo_text: mutable string = ""
        description: "GetAccountSummaryDataで取得した、取引先に紐づくToDoのテキスト。"
    event_text: mutable string = ""
        description: "GetAccountSummaryDataで取得した、取引先に紐づく行動のテキスト。"
    summary_account_id: mutable string = ""
        description: "サマリーのデータ(opportunity_textなど)を取得済みの取引先Id。取得済みかどうかの判定に使う。"

language:
    default_locale: "ja"
    all_additional_locales: False

start_agent agent_router:
    label: "Agent Router"
    description: "ユーザーを歓迎し、依頼に基づいて適切なサブエージェントを決定する"
    reasoning:
        instructions: ->
            | あなたは従業員エージェントのルーターです。
              ユーザーの依頼に応じて、最適なアクションを1つ選択してください。
            if @variables.current_subagent != "":
                | 直前のやり取りでは、サブエージェント「{!@variables.current_subagent}」が対応していました。
                  ユーザーの発言がその続き(追加の質問、絞り込み、修正依頼など)であれば、
                  新しく判断せず、そのサブエージェントに対応する go_to_ のアクションを選択してください。
                  明らかに別の依頼である場合は、この情報には頼らず、依頼の内容から新しく振り分け先を決めてください。
            if @variables.currentObjectApiName == "Account":
                | ユーザーは取引先ページを開いています。
                  「この取引先」「サマリー」といった依頼は{!@actions.go_to_Account_Summary}を選択してください。
        actions:
            go_to_Account_Summary: @utils.transition to @subagent.Account_Summary
                description: "取引先のサマリー(商談・ToDo・行動のまとめ)を依頼されたときに使用する。「〇〇社の状況をまとめて」など。"
            go_to_Visit_Prep: @utils.transition to @subagent.Visit_Prep
                description: "取引先への次回訪問の準備(アジェンダや、先方に確認したい質問の作成)を依頼されたときに使用する。「次回訪問の準備をしたい」など。"
            go_to_UserMemoryManagement: @utils.transition to @subagent.UserMemoryManagement
                description: "記憶している内容の確認・変更・削除や、メモリのオン/オフを求められたときに使用する。「私について覚えていることを見せて」など。"
            go_to_ambiguous_question: @utils.transition to @subagent.ambiguous_question
                description: "依頼の意図が曖昧で、どのサブエージェントが適切か判断できないときに使用する。"
            go_to_off_topic: @utils.transition to @subagent.off_topic
                description: "営業業務に関係のない雑談や、一般的な知識の質問のときに使用する。"

subagent Account_Summary:
    label: "取引先サマリー"
    description: "取引先の商談・ToDo・行動をまとめて、定型のサマリーを出力する"
    model_config:
        model: "model://sfdc_ai__DefaultBedrockAnthropicClaude45Haiku"

    before_reasoning:
        set @variables.current_subagent = "Account_Summary"
        if @variables.currentObjectApiName == "Account" and @variables.target_account_id == "":
            set @variables.target_account_id = @variables.currentRecordId

    reasoning:
        instructions: ->
            if @variables.target_account_id == "":
                | 取引先が特定できていません。
                  取引先名をユーザーに確認し、{!@actions.IdentifyRecordByName}で検索してください。
                  候補が1件に絞れたら、そのIdを{!@actions.set_target_account}で設定してください。
            else:
                run @actions.GetAccountSummaryData
                    with accountId = @variables.target_account_id
                    set @variables.opportunity_text = @outputs.opportunityText
                    set @variables.todo_text = @outputs.todoText
                    set @variables.event_text = @outputs.eventText
                set @variables.summary_account_id = @variables.target_account_id
                | 以下のデータだけを根拠に、次の形式でサマリーを出力してください。
                  データにない内容は書かないでください。
                  1. 進行中の商談
                  2. 未完了のToDo
                  3. 直近の行動
                  4. 気になる点
                  【商談】{!@variables.opportunity_text}
                  【ToDo】{!@variables.todo_text}
                  【行動】{!@variables.event_text}
        actions:
            IdentifyRecordByName: @actions.IdentifyRecordByName
                description: "取引先をレコード名で検索する"
                with recordName=...
                with objectApiName="Account"
            set_target_account: @utils.setVariables
                description: "IdentifyRecordByNameで確定した取引先Idを保存する。ユーザーと確認した取引先のIdだけを設定すること。"
                with target_account_id=...

    actions:
        GetAccountSummaryData:
            description: "取引先に紐づく商談・ToDo・行動をテキストで取得する"
            label: "取引先サマリー用データ取得"
            require_user_confirmation: False
            include_in_progress_indicator: True
            progress_indicator_message: "データを取得中..."
            target: "flow://Get_Account_Summary_Data"
            inputs:
                "accountId": string
                    description: "対象の取引先Id"
                    label: "accountId"
                    is_required: True
                    is_user_input: False
            outputs:
                "opportunityText": string
                    description: "商談のテキスト"
                    label: "opportunityText"
                    is_displayable: False
                    filter_from_agent: False
                "todoText": string
                    description: "ToDoのテキスト"
                    label: "todoText"
                    is_displayable: False
                    filter_from_agent: False
                "eventText": string
                    description: "行動のテキスト"
                    label: "eventText"
                    is_displayable: False
                    filter_from_agent: False

        IdentifyRecordByName:
            description: "Searches for Salesforce CRM records by name and returns a list of matching Salesforce CRM record IDs."
            label: "Identify Record by Name"
            require_user_confirmation: False
            include_in_progress_indicator: True
            progress_indicator_message: "レコードを検索中..."
            source: "EmployeeCopilot__IdentifyRecordByName"
            target: "standardInvocableAction://identifyRecordByName"
            inputs:
                "recordName": string
                    description: "ユーザー入力から抽出したレコード名"
                    label: "recordName"
                    is_required: True
                    is_user_input: True
                "objectApiName": string
                    description: "検索対象のオブジェクトAPI名"
                    label: "objectApiName"
                    is_required: False
                    is_user_input: False
            outputs:
                "searchResults": list[object]
                    description: "一致したレコードのIdのリスト(関連度の高い順)"
                    label: "searchResults"
                    is_displayable: True
                    filter_from_agent: False
                    complex_data_type_name: "lightning__recordInfoType"

subagent Visit_Prep:
    label: "訪問準備のアジェンダ作成"
    description: "取引先への次回訪問に向けて、アジェンダの案と、先方に確認したい質問を作る。サマリーで取得したデータを使う"
    model_config:
        model: "model://sfdc_ai__DefaultGPT56Terra"

    before_reasoning:
        set @variables.current_subagent = "Visit_Prep"
        if @variables.currentObjectApiName == "Account" and @variables.target_account_id == "":
            set @variables.target_account_id = @variables.currentRecordId

    reasoning:
        instructions: ->
            if @variables.target_account_id == "":
                | 取引先が特定できていません。
                  先に取引先を指定してもらうため、{!@actions.go_to_Account_Summary}を選択してください。
            if @variables.target_account_id != "" and @variables.summary_account_id != @variables.target_account_id:
                run @actions.GetAccountSummaryData
                    with accountId = @variables.target_account_id
                    set @variables.opportunity_text = @outputs.opportunityText
                    set @variables.todo_text = @outputs.todoText
                    set @variables.event_text = @outputs.eventText
                set @variables.summary_account_id = @variables.target_account_id
            if @variables.target_account_id != "":
                | 以下のデータだけを根拠に、次回訪問の準備を支援してください。
                  データにない内容は書かないでください。
                  1. 訪問の目的の案(1〜2個)
                  2. アジェンダの案(時間配分つき)
                  3. 先方に確認したい質問(3個程度)
                  4. 事前に準備しておくこと
                  ユーザーから修正の希望があれば、同じデータを根拠に調整してください。
                  【商談】{!@variables.opportunity_text}
                  【ToDo】{!@variables.todo_text}
                  【行動】{!@variables.event_text}
        actions:
            go_to_Account_Summary: @utils.transition to @subagent.Account_Summary
                description: "取引先が決まっていないときに、先に取引先を指定してもらうため、取引先サマリーへ移る"
                available when @variables.target_account_id == ""

    actions:
        GetAccountSummaryData:
            description: "取引先に紐づく商談・ToDo・行動をテキストで取得する"
            label: "取引先サマリー用データ取得"
            require_user_confirmation: False
            include_in_progress_indicator: True
            progress_indicator_message: "データを取得中..."
            target: "flow://Get_Account_Summary_Data"
            inputs:
                "accountId": string
                    description: "対象の取引先Id"
                    label: "accountId"
                    is_required: True
                    is_user_input: False
            outputs:
                "opportunityText": string
                    description: "商談のテキスト"
                    label: "opportunityText"
                    is_displayable: False
                    filter_from_agent: False
                "todoText": string
                    description: "ToDoのテキスト"
                    label: "todoText"
                    is_displayable: False
                    filter_from_agent: False
                "eventText": string
                    description: "行動のテキスト"
                    label: "eventText"
                    is_displayable: False
                    filter_from_agent: False

subagent UserMemoryManagement:
    label: "User Memory Management"
    description: "Manages a user's stored memories and memory preferences, including viewing, creating, updating, and deleting specific memories, and enabling or disabling memory storage. Use this topic only when the user explicitly requests to customize, tailor, or direct what is remembered about them; don't use it for general CRM data or product knowledge questions."

    before_reasoning:
        set @variables.current_subagent = "UserMemoryManagement"

    reasoning:
        instructions: ->
            | When the user asks to see, list, or recall what has been remembered about them, you MUST call GetUserMemories and use only its returned data. Never fabricate, infer, or recall memories from context or prior turns without calling the action. Present the results to the user as a bulleted list containing only the "content" value of each returned memory, with one bullet per memory. Do not show the raw JSON or any other fields such as confidenceScore, scope, type, or count. If the action returns no memories, tell the user that nothing is stored yet.
              When a user explicitly shares, updates, or requests to delete personal information, preferences, or facts to customize their profile, you MUST call ManageUserMemory and never assume the memory was stored, changed, or deleted without calling it. For example, "Remember that I live in London," "Change my timezone to EST," or "Forget my phone number." This applies to any fact the user wants to store, modify, or clear to tailor their experience.
              When the user wants to know whether memory is turned on or to view their current memory preference, you MUST call GetAgentMemoryPreference and report only its returned value. Never guess or assume whether memory is enabled.
              When the user wants to turn memory storage on or off for their interactions with the AI agent, you MUST call UpdateAgentMemoryPreference and never assume the preference was changed without calling it.
              For any request to view, create, update, or delete memories, or to check or change the memory preference, you MUST call the corresponding action and base your response solely on that action's result. Never answer from memory, prior context, or assumptions, and never fabricate, invent, or infer memory content, counts, or the memory preference state. If an action fails or returns no data, tell the user rather than making up a response.
              Do not declare your intent. For example, don't say "I will now save the memory." Just acknowledge the user's request.
              Do not confirm that you stored, updated, or deleted any preference, fact, or memory. Just acknowledge the user's message.

        actions:
            GetUserMemories: @actions.GetUserMemories
                with searchQuery=...
                with authParticipantId=...
            ManageUserMemory: @actions.ManageUserMemory
                with userConversation=...
                with agentContext=...
                with authParticipantId=...
            GetAgentMemoryPreference: @actions.GetAgentMemoryPreference
                with userId=...
            UpdateAgentMemoryPreference: @actions.UpdateAgentMemoryPreference
                with memoryEnabled=...

    actions:
        GetUserMemories:
            description: |
                Retrieves a collection of user memories for a specific user and AI agent.
            label: "Get User Memories"
            require_user_confirmation: False
            include_in_progress_indicator: True
            progress_indicator_message: "Getting user memories"
            source: "EmployeeCopilot__GetUserMemories"
            target: "standardInvocableAction://getUserMemories"

            inputs:
                "searchQuery": string
                    description: |
                      The text used to search for and retrieve user memories for the agent.
                    label: "searchQuery"
                    is_required: False
                    is_user_input: True
                "authParticipantId": object
                    description: |
                      Optional. The Salesforce record ID of the authenticated participant (User, Contact, Lead, or Account) whose memories are retrieved. Applies to Einstein Service Agent (ASA) only. The runtime supplies this from the verified session context (for example $Context.AuthParticipantId); never ask the end user for it. When present and valid, memories are retrieved for this participant; otherwise the agent falls back to the authenticated user or participant from context.
                    label: "Authenticated Participant ID"
                    is_required: False
                    is_user_input: False
                    complex_data_type_name: "lightning__recordIdType"

            outputs:
                "agentUserMemories": string
                    description: |
                      The collection of AI agent user memories that were retrieved.
                    label: "AI Agent User Memories"
                    is_displayable: False
                    filter_from_agent: False

        ManageUserMemory:
            description: |
                Using generative AI, creates, updates, or deletes a memory about a specific user's information and preferences for an AI agent based on a conversation.
            label: "Manage User Memory"
            require_user_confirmation: False
            include_in_progress_indicator: True
            progress_indicator_message: "Updating user memory"
            source: "EmployeeCopilot__ManageUserMemory"
            target: "standardInvocableAction://manageUserMemory"

            inputs:
                "userConversation": string
                    description: |
                      The conversation between the user and agent that is sent to the LLM.
                    label: "Conversation"
                    is_required: False
                    is_user_input: True
                "agentContext": string
                    description: |
                      Sub-agents present in an Agent and their descriptions.
                    label: "agentContext"
                    is_required: False
                    is_user_input: True
                "authParticipantId": object
                    description: |
                      Optional. The Salesforce record ID of the authenticated participant (User, Contact, Lead, or Account) that owns the memory. Applies to Einstein Service Agent (ASA) only. The runtime supplies this from the verified session context (for example $Context.AuthParticipantId); never ask the end user for it. When present and valid, memory is stored and retrieved for this participant; otherwise the agent falls back to the authenticated user or participant from context.
                    label: "Authenticated Participant ID"
                    is_required: False
                    is_user_input: False
                    complex_data_type_name: "lightning__recordIdType"

            outputs:
                "resultMessage": string
                    description: |
                      A message sent to the user that describes what the action did.
                    label: "Message"
                    is_displayable: True
                    filter_from_agent: False
                "wasMemoryOperationPerformed": boolean
                    description: |
                      Indicates whether a memory create, update, or delete operation was executed.
                    label: "Was Memory Operation Performed"
                    is_displayable: False
                    filter_from_agent: False
                "userMemories": string
                    description: |
                      A JSON string that contains all memories for the user and agent.
                    label: "User Memories"
                    is_displayable: False
                    filter_from_agent: False
                "userMemoryEnabled": boolean
                    description: |
                      Indicates whether memory is enabled for the user and agent combination.
                    label: "Is Memory Enabled For User"
                    is_displayable: False
                    filter_from_agent: False

        GetAgentMemoryPreference:
            description: |
                Retrieves the agent memory preference for a user when interacting with this agent.
            label: "Get User Memory Preference"
            require_user_confirmation: False
            include_in_progress_indicator: True
            progress_indicator_message: "Getting user memory preference"
            source: "EmployeeCopilot__GetAgentMemoryPreference"
            target: "standardInvocableAction://getAgentMemoryPreference"

            inputs:
                "userId": string
                    description: |
                      User ID of the current agent user
                    label: "userId"
                    is_required: False
                    is_user_input: False

            outputs:
                "memoryEnabled": boolean
                    description: |
                      Indicates whether agent memory is enabled for the user when interacting with this agent.
                    label: "Memory Enabled"
                    is_displayable: True
                    filter_from_agent: False

        UpdateAgentMemoryPreference:
            description: |
                Enables or disables AI Agent memory for the current user and AI agent.
            label: "Update User Memory Preference"
            require_user_confirmation: False
            include_in_progress_indicator: True
            progress_indicator_message: "Updating memory preference"
            source: "EmployeeCopilot__UpdateAgentMemoryPreference"
            target: "standardInvocableAction://updateAgentMemoryPreference"

            inputs:
                "memoryEnabled": boolean
                    description: |
                      Specifies whether agent memory is enabled for the user when interacting with this agent.
                    label: "Memory Enabled"
                    is_required: True
                    is_user_input: True

            outputs:
                "memoryEnabled": boolean
                    description: |
                      Indicates whether agent memory is enabled for the user after the update.
                    label: "Memory Enabled"
                    is_displayable: True
                    filter_from_agent: False

subagent ambiguous_question:
    label: "Ambiguous Question"
    description: "依頼が曖昧なときに、ユーザーに具体的な内容を確認する"
    before_reasoning:
        set @variables.current_subagent = ""
    reasoning:
        instructions: ->
            | ユーザーの依頼が曖昧です。回答はせず、どの業務について知りたいのかを丁寧に確認してください。
              対応できる業務は、取引先のサマリー、訪問準備のアジェンダ作成、メモリの管理です。

subagent off_topic:
    label: "Off Topic"
    description: "営業業務と関係のない依頼のときに、対応できる業務を案内する"
    before_reasoning:
        set @variables.current_subagent = ""
    reasoning:
        instructions: ->
            | ユーザーの依頼は対応範囲外です。依頼の内容には回答せず、対応できる業務を案内してください。
              対応できる業務は、取引先のサマリー、訪問準備のアジェンダ作成、メモリの管理です。

フロー名(Get_Account_Summary_Data)やモデル名は、記事用の仮の値です。ご自身の環境に合わせて置き換えてください。

おわりに

ここまで読んでいただきありがとうございます。
コードで明確に分岐させるところやLLMに任せるところをAgent Scriptを使うことでハイブリッドに制御することができました。

大切なのは、設計時に先に線を引いておくことです。
どこまでをLLMに任せて、どこからを毎回同じ動きにするのか。これを決めてから書くと、意外にスムーズに書くことができます。

今回で言えば、

  • データを取ってくるところ
  • 変数を更新するところ
  • 振り分けのヒントを残すところ

がスクリプトによる毎回同じ動きをさせる動きです。
要約したり、アジェンダを考えたりするところは、LLMにお任せしました。

まずは小さなサブエージェントを当記事を参考にして1つ作ってみてください。それだけでも、エージェントの安定感はかなり変わってくるかと思います。

株式会社アクトビ

Discussion