: LlmRequest ) -> Optional [LlmResponse ]: """ 最新のユーザーメッセージに 'BLOCK' が含まれているかを検査します。 含まれていれば、 LLM の呼び出しをブロックし、あらかじめ定義された LlmResponse を返します。 含まれていなければ None を返し、そのまま処理を継続します。 """ agent_name = callback_context.agent_name # モデル呼び出しをフックしているエージェント名を取得 # --- ガードレールロジック --- keyword_to_block = "BLOCK" if keyword_to_block in last_user_message_text.upper (): # 大文字小文字を無視して検査 # オプション:ステートにフラグを立ててブロックイベントを記録 callback_context.state ["guardrail_block_keyword_triggered" ] = True # フローを中断してこのレスポンスを返す return LlmResponse ( content=types.Content ( role= "model", # エージェントからの応答として扱われるよう設定 parts= [types.Part (text=f"リクエストに禁止キーワード '{keyword_to_block }' が含まれているため、処理できませ ん。")], ) # 必要に応じて error_message を設定することも可能 ) else: # キーワードが見つからなかった場合は処理を続行 print(f"--- コールバック : キーワードが見つかりませんでした。 {agent_name } の LLM 呼び出しを許可します。 ---") return None # None を返すと ADK は通常通り LLM にリクエストを送信する コールバックの実装
18
root_agent_model_guardrail = Agent ( # コールバックを呼び出すエージェント name="weather_agent_model_guardrail" , model=root_agent_model , description= "メインエージェント:天気の提供、挨拶と別れの委任、入力キーワー ドのガードレールを含む。 ", instruction= "あなたはメインの天気エージェントです。 'get_weather_stateful' を使って天気を提供してください。単純な挨拶は 'greeting_agent' に、別れの挨拶は 'farewell_agent' に委任してください。天 気、挨拶、別れのリクエストのみを処理してください。 ", tools=[get_weather ], sub_agents= [greeting_agent , farewell_agent ], output_key= "last_weather_report" , before_model_callback=block_keyword_guardrail # <<< ガードレール コールバックを指定 )