MENU
  • HOME
  • 取引実績
  • 会社概要
  • 資料DL
  • お問い合わせ
  • FAQ
  • BigQuery記事
  • Struccle記事
データ流通、検索エンジン開発のプロフェッショナル
DataStructor
  • HOME
  • 取引実績
  • 会社概要
  • 資料DL
  • お問い合わせ
  • FAQ
  • BigQuery記事
  • Struccle記事
DataStructor
  • HOME
  • 取引実績
  • 会社概要
  • 資料DL
  • お問い合わせ
  • FAQ
  • BigQuery記事
  • Struccle記事
  1. ホーム
  2. 当ブログのコーディング実行環境設定
  3. AI Agent開発日記 2025/06/07

AI Agent開発日記 2025/06/07

2025 6/07
当ブログのコーディング実行環境設定
2025年6月7日

やりたいこと

データを読み込むだけで、以下が自動で行われる仕組みを構築したい。

  • 読み込んだデータがElasticsearchに自動登録される
  • データと指示内容がGeminiに渡され、PlaybookやTool/Schemaが自動生成される
  • 生成された内容が自動でPlaybookやToolに反映され、管理用エージェントと紐づいて構成される

前回の調査日記

あわせて読みたい
AI Agent開発日記 2025/06/06 やりたいこと データを読み込むだけで、以下が自動で行われる仕組みを構築したい。 読み込んだデータがElasticsearchに自動登録される データと指示内容がGeminiに渡さ...
目次

Agentbuilderの既存playbookを編集するpythonコードを作成する

  • やりたいこと
    • 下記の Python クライアントライブラリドキュメントを参考にして、既存playbookを編集するpythonコードを作成したい
  • 現状
    • ツールの参照設定がない状態の Playbook に対して編集できるコードは作成済み。
    • ただし、Playbook にツールの参照設定がある場合、事前に Web UI でその参照を削除しないと 400 エラーが発生するという問題があるため、解決したい。
      • 以下のコードを用意して対応が出来た。
        • playbookのtoolの参照設定を解除する
          playbookに特定のtoolを参照させる

参考ドキュメント

あわせて読みたい

playbookのtoolの参照設定を解除し
playbookに特定のtoolを参照させるコード

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import re

# 必要情報(すべてプレースホルダです)
PROJECT_ID = 'your-project-id'
LOCATION_ID = 'global'
AGENT_ID = 'your-agent-id'
PLAYBOOK_ID = 'your-playbook-id'

# 削除対象の Tool ID(存在しないものも含めておく)
TOOL_IDS_TO_REMOVE_LIST = [
    'tool-id-to-remove-1',
    'tool-id-to-remove-2'
]

def get_tool_resource_name(project_id, location_id, agent_id, tool_id):
    return f'projects/{project_id}/locations/{location_id}/agents/{agent_id}/tools/{tool_id}'

def get_tool_name_id_map(project_id, location_id, agent_id, dialogflow_service):
    parent = f'projects/{project_id}/locations/{location_id}/agents/{agent_id}'
    tool_map = {}
    try:
        request = dialogflow_service.projects().locations().agents().tools().list(parent=parent)
        response = request.execute()
        for tool in response.get('tools', []):
            if 'displayName' in tool and 'name' in tool:
                tool_map[tool['displayName']] = tool['name']
        return tool_map
    except HttpError as e:
        print(f"ツール取得失敗: {e}")
        return None

def remove_specific_referenced_tools(project_id, location_id, agent_id, playbook_id, tool_ids_to_remove):
    try:
        credentials, _ = google.auth.default()
        dialogflow_service = build('dialogflow', 'v3beta1', credentials=credentials)
        playbook_name = f'projects/{project_id}/locations/{location_id}/agents/{agent_id}/playbooks/{playbook_id}'

        tool_names_to_remove_set = {
            get_tool_resource_name(project_id, location_id, agent_id, tid)
            for tid in tool_ids_to_remove if tid
        }

        tool_name_to_resource_map = get_tool_name_id_map(project_id, location_id, agent_id, dialogflow_service)
        if tool_name_to_resource_map is None:
            return

        current_playbook = dialogflow_service.projects().locations().agents().playbooks().get(
            name=playbook_name
        ).execute()

        existing_referenced_tools = current_playbook.get('referencedTools', [])
        current_goal = current_playbook.get('goal')
        instruction_obj = current_playbook.get('instruction')
        current_instruction_text = instruction_obj.get('steps', [{}])[0].get('text') if instruction_obj else None

        updated_referenced_tools = [
            tool for tool in existing_referenced_tools if tool not in tool_names_to_remove_set
        ]

        def remove_tool_ref_from_text(text):
            if not text:
                return text, False
            modified = False
            tool_refs = re.findall(r'\$\{TOOL:([^}]+)\}', text)
            for ref in set(tool_refs):
                res = tool_name_to_resource_map.get(ref)
                if res in tool_names_to_remove_set:
                    text = re.sub(rf'\s*\$\{{TOOL:{re.escape(ref)}\}}\s*', '', text).strip()
                    modified = True
            return text, modified

        updated_goal, goal_modified = remove_tool_ref_from_text(current_goal)
        updated_instruction_text, instruction_modified = remove_tool_ref_from_text(current_instruction_text)

        update_body = {}
        update_mask_parts = []

        if set(updated_referenced_tools) != set(existing_referenced_tools):
            update_body['referencedTools'] = updated_referenced_tools
            update_mask_parts.append('referencedTools')

        if goal_modified:
            update_body['goal'] = updated_goal
            update_mask_parts.append('goal')

        if instruction_modified and instruction_obj:
            updated_steps = instruction_obj['steps']
            updated_steps[0]['text'] = updated_instruction_text
            update_body['instruction'] = {'steps': updated_steps}
            update_mask_parts.append('instruction.steps')

        if update_mask_parts:
            request = dialogflow_service.projects().locations().agents().playbooks().patch(
                name=playbook_name,
                updateMask=','.join(update_mask_parts),
                body=update_body
            )
            request.execute()
            print("更新完了: プレイブックの参照ツールを削除しました。")
        else:
            print("変更がないため更新不要です。")

    except HttpError as e:
        print(f"APIエラー: {e}")
    except Exception as e:
        print(f"エラー: {e}")

# 実行例
remove_specific_referenced_tools(
    project_id=PROJECT_ID,
    location_id=LOCATION_ID,
    agent_id=AGENT_ID,
    playbook_id=PLAYBOOK_ID,
    tool_ids_to_remove=TOOL_IDS_TO_REMOVE_LIST
)

人気記事

  • BigQueryの無料枠を活用しよう!制限と注意点、活用方法を解説
  • BigQueryでエラー解決!よくあるエラーと対処法
  • BigQueryのレベル別学習リソースまとめ!初心者から上級者まで役立つ情報源
  • 【SUUMOスクレイピング】Struccleで物件データを全件収集
  • BigQuery入門!無料データでSQLの基本文字列関数をマスター
当ブログのコーディング実行環境設定
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!
目次
カテゴリー
  • AI_Agent (112)
    • Agent開発 (112)
  • BigQuery (100)
    • BigQueryTips (11)
    • BigQueryでデータ分析 (49)
    • BigQueryのFAQ (1)
    • BigQuery入門 (8)
    • BigQuery学習教材 (22)
    • BigQuery導入ガイド (3)
    • BigQuery最新情報 (3)
    • BigQuery活用事例 (4)
  • Struccle (153)
    • Struccleでスクレイピング (10)
      • suumoの物件データを収集&分析 (1)
      • アニマルジョブの電話番号、メールアドレスを全件収集 (1)
      • データ集計 (6)
      • ホットペッパービューティーのヘアサロンデータを収集&分析 (1)
      • 食べログの飲食店データを収集&分析 (1)
    • Struccleデータ料金事例 (142)
      • 商品分析 (15)
      • 営業リスト (88)
      • 競合分析&市場調査 (58)
      • 自動車 (11)
      • 自社活用 (7)
    • Struccle活用企業様の紹介 (1)
  • 当ブログのコーディング実行環境設定 (2)
目次