跳转到内容

回调函数:观察、自定义并控制代理的行为

在 ADK 中得到支持。Python v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.1.0Kotlin v0.1.0

回调(Callbacks)是 ADK(Android Development Kit)的核心功能之一,它提供了一种强大的机制,用于拦截并控制代理(agent)的执行过程。通过回调,你可以在特定的、预先定义的时机观察、自定义甚至直接控制代理的行为,而无需修改 ADK 的核心框架代码。

它们是什么? 从本质上讲,回调函数就是你自己定义的普通函数。在创建代理(agent)时,你需要将这些函数与该代理关联起来。ADK框架会在关键阶段自动调用这些函数,从而让你能够观察代理的运行过程或对其进行干预。你可以把它们想象成代理执行过程中的“检查点”(checkpoints)。

  • 在代理开始处理请求的主要工作之前,以及在工作完成后: 当你要求某个代理执行某项任务(例如回答问题)时,该代理会使用其内部的逻辑来生成相应的回答。
  • The Before Agent 回调函数会被执行。 就在……之前 这项主要工作正是基于那个特定的请求而开始的。
  • The After Agent 回调函数会被执行。 紧接着;马上 代理已经完成了该请求的所有处理步骤,并准备好了最终结果,但在结果即将被返回之前……
  • 这项“主要工作”涵盖了代理的所有职责/功能。 整个;全部的 用于处理该单个请求的流程。这个流程可能包括:决定是否调用大型语言模型(LLM),实际调用该模型;决定是否使用某个工具,使用该工具;处理模型返回的结果;最后将处理后的结果整合成最终的答案。这些回调函数实际上涵盖了从接收输入到生成最终输出的全部过程,即整个交互环节。
  • 在向大型语言模型(LLM)发送请求之前,或从大型语言模型接收响应之后: 这些回调函数()Before Model, After Model)允许您专门检查或修改发送到大型语言模型(LLM)的数据,以及从该模型接收到的数据。
  • 在执行某个工具(例如 Python 函数或其他代理程序)之前,或在其执行完成后: 同样地, Before Tool 和 After Tool 回调功能允许你在代理程序调用的工具执行过程中,对这些工具的执行过程进行精确的控制(即设置特定的控制点)。

intro_components.png

为什么要使用它们呢? 回调机制(Callbacks)为系统带来了极大的灵活性,并使得代理(Agents)能够具备更高级的功能。

  • 观察与调试(Observe & Debug): 在关键步骤中记录详细信息,以便进行监控和故障排除。
  • 自定义与控制: 根据您的逻辑,您可以修改通过该代理传输的数据(例如来自大型语言模型(LLM)的请求或工具产生的结果),甚至完全跳过某些处理步骤。
  • 实施安全防护措施(即“Guardrails”): 执行安全规则,验证输入/输出数据,或阻止被禁止的操作。
  • 管理状态(Manage State): 在执行过程中,可以读取或动态更新代理的会话状态。
  • **整合与优化:** 触发外部操作(API 调用、通知)或添加诸如缓存之类的功能。

提示(Tip)

在实施安全防护措施和政策时,建议使用 ADK 插件(ADK Plugins),因为它们比传统的回调机制(Callbacks)具有更好的模块化和灵活性。详情请参阅…… 用于安全防护机制的回调函数(Callbacks)和插件(Plugins).

它们是如何被添加的?

代码
from google.adk.agents import LlmAgent
from google.adk.agents.callback_context import CallbackContext
from google.adk.models import LlmResponse, LlmRequest
from typing import Optional

# --- Define your callback function ---
def my_before_model_logic(
    callback_context: CallbackContext, llm_request: LlmRequest
) -> Optional[LlmResponse]:
    print(f"Callback running before model call for agent: {callback_context.agent_name}")
    # ... your custom logic here ...
    return None # Allow the model call to proceed

# --- Register it during Agent creation ---
my_agent = LlmAgent(
    name="MyCallbackAgent",
    model="gemini-2.0-flash", # Or your desired model
    instruction="Be helpful.",
    # Other agent parameters...
    before_model_callback=my_before_model_logic # Pass the function here
)
import { LlmAgent, InMemoryRunner, Context, LlmRequest, LlmResponse, Event, isFinalResponse } from '@google/adk';
import { createUserContent } from "@google/genai";
import type { Content } from "@google/genai";

const MODEL_NAME = "gemini-2.5-flash";
const APP_NAME = "basic_callback_app";
const USER_ID = "test_user_basic";
const SESSION_ID = "session_basic_001";


// --- Define your callback function ---
function myBeforeModelLogic({
  context,
  request,
}: {
  context: Context;
  request: LlmRequest;
}): LlmResponse | undefined {
  console.log(
    `Callback running before model call for agent: ${context.agentName}`
  );
  // ... your custom logic here ...
  return undefined; // Allow the model call to proceed
}

// --- Register it during Agent creation ---
const myAgent = new LlmAgent({
  name: "MyCallbackAgent",
  model: MODEL_NAME,
  instruction: "Be helpful.",
  beforeModelCallback: myBeforeModelLogic,
});
package main

import (
    "context"
    "fmt"
    "log"
    "strings"

    "google.golang.org/adk/v2/agent"
    "google.golang.org/adk/v2/agent/llmagent"
    "google.golang.org/adk/v2/model"
    "google.golang.org/adk/v2/model/gemini"
    "google.golang.org/adk/v2/runner"
    "google.golang.org/adk/v2/session"
    "google.golang.org/genai"
)



// onBeforeModel is a callback function that gets triggered before an LLM call.
func onBeforeModel(ctx agent.Context, req *model.LLMRequest) (*model.LLMResponse, error) {
    log.Println("--- onBeforeModel Callback Triggered ---")
    log.Printf("Model Request to be sent: %v\n", req)
    // Returning nil allows the default LLM call to proceed.
    return nil, nil
}

func runBasicExample() {
    const (
        appName = "CallbackBasicApp"
        userID  = "test_user_123"
    )
    ctx := context.Background()
    geminiModel, err := gemini.NewModel(ctx, modelName, &genai.ClientConfig{})
    if err != nil {
        log.Fatalf("Failed to create model: %v", err)
    }

    // Register the callback function in the agent configuration.
    agentCfg := llmagent.Config{
        Name:                 "SimpleAgent",
        Model:                geminiModel,
        BeforeModelCallbacks: []llmagent.BeforeModelCallback{onBeforeModel},
    }
    simpleAgent, err := llmagent.New(agentCfg)
    if err != nil {
        log.Fatalf("Failed to create agent: %v", err)
    }

    sessionService := session.InMemoryService()
    r, err := runner.New(runner.Config{
        AppName:        appName,
        Agent:          simpleAgent,
        SessionService: sessionService,
    })
    if err != nil {
        log.Fatalf("Failed to create runner: %v", err)
    }
import com.google.adk.agents.CallbackContext;
import com.google.adk.agents.Callbacks;
import com.google.adk.agents.LlmAgent;
import com.google.adk.models.LlmRequest;
import java.util.Optional;

public class AgentWithBeforeModelCallback {

  public static void main(String[] args) {
    // --- Define your callback logic ---
    Callbacks.BeforeModelCallbackSync myBeforeModelLogic =
        (CallbackContext callbackContext, LlmRequest llmRequest) -> {
          System.out.println(
              "Callback running before model call for agent: " + callbackContext.agentName());
          // ... your custom logic here ...

          // Return Optional.empty() to allow the model call to proceed,
          // similar to returning None in the Python example.
          // If you wanted to return a response and skip the model call,
          // you would return Optional.of(yourLlmResponse).
          return Optional.empty();
        };

    // --- Register it during Agent creation ---
    LlmAgent myAgent =
        LlmAgent.builder()
            .name("MyCallbackAgent")
            .model("gemini-2.0-flash") // Or your desired model
            .instruction("Be helpful.")
            // Other agent parameters...
            .beforeModelCallbackSync(myBeforeModelLogic) // Pass the callback implementation here
            .build();
  }
}
val agent =
    LlmAgent(
        name = "callback_agent",
        model = Gemini(name = "gemini-flash-latest"),
        beforeAgentCallbacks =
            listOf(
                BeforeAgentCallback { context ->
                    println("Before Agent Callback triggered")
                    CallbackChoice.Continue(context.eventActions)
                },
            ),
        afterAgentCallbacks =
            listOf(
                AfterAgentCallback { context ->
                    println("After Agent Callback triggered")
                    CallbackChoice.Continue(Unit)
                },
            ),
        beforeModelCallbacks =
            listOf(
                BeforeModelCallback { context, request ->
                    println("Before Model Callback triggered")
                    CallbackChoice.Continue(request)
                },
            ),
        afterModelCallbacks =
            listOf(
                AfterModelCallback { context, response ->
                    println("After Model Callback triggered")
                    response
                },
            ),
        beforeToolCallbacks =
            listOf(
                BeforeToolCallback { context, tool, args ->
                    println("Before Tool Callback triggered for ${tool.name}")
                    CallbackChoice.Continue(args)
                },
            ),
        afterToolCallbacks =
            listOf(
                AfterToolCallback { context, tool, args, result ->
                    println("After Tool Callback triggered for ${tool.name}")
                    result
                },
            ),
    )

回调机制:拦截与控制

当 ADK 框架遇到可以执行回调函数的时机(例如,在调用 LLM 之前),它会检查你是否为该代理提供了相应的回调函数。如果提供了该函数,框架就会执行该函数。

“背景信息至关重要”(Context is Key)。 你的回调函数并不是单独被调用的。框架提供了相应的机制来确保回调函数能够在适当的时候被执行。 上下文对象(Context Objects) (CallbackContext 或者 ToolContext这些对象作为参数被传递给框架。它们包含了关于代理执行当前状态的重要信息,包括调用细节、会话状态,以及可能对某些服务(如工件或内存)的引用。你可以利用这些上下文对象来理解当前的情况,并与框架进行交互。(详情请参阅专门的“上下文对象”章节)。

控制数据流(核心机制): 回调函数最强大的功能在于它们……(The most powerful aspect of callbacks lies in how their……) 返回值 这些因素会影响代理后续的行为。这就是你拦截并控制执行流程的方式。

  1. return None (允许使用默认行为):

    • 具体的返回类型可能会因编程语言的不同而有所差异。在 Java 中,相应的返回类型是…… Optional.empty()在 Kotlin 中,它是…… CallbackChoice.Continue(value) (用于说明某个动作或过程的目的) before_* (用于回调函数);或者返回原始对象(用于其他情况)。 after_* 请参阅 API 文档以获取针对特定语言的指导信息。
    • 这是标准的信号方式,用于表示您的回调函数已经完成了其工作(例如:记录日志、对输入参数进行简单修改等),并且此时 ADK 代理应该…… 继续其正常运行。.
    • 对于…… before_* `callbacks`(回调函数)before_agent, before_model, before_tool),然后返回结果。 None 这意味着序列中的下一步即将执行,无论该步骤是运行代理逻辑、调用大型语言模型(LLM),还是执行某个工具。
    • 对于…… after_* `callbacks`(回调函数)after_agent, after_model, after_tool),然后返回结果。 None 无论该结果是由代理程序生成的输出、大型语言模型(LLM)给出的响应,还是工具产生的结果,系统都会保持该结果原样不变(即不对该结果进行任何修改或处理)。在 Python 中,应该直接返回该结果,而不是…… None “is not equivalent for” 表示“两者并不相等/等价”。 after_agent_callbackADK 发出了第二个事件,该事件携带的内容与第一个事件相同。
  2. return <Specific Object> (覆盖默认行为):

    • 返回一个…… 特定类型的对象 (而不是显示“继续”这个选项),你应该是这样做的…… `override` ADK代理的默认行为。在Kotlin中,这是通过返回某个值来实现的。 CallbackChoice.Break(value) (用于说明某个动作或过程的目的) before_* `callbacks`),或者一个替代对象(用于替换原来的对象)。 after_* (callbacks)。该框架会使用你返回的对象来进行后续处理。 `skip` 接下来通常会进行的步骤…… replace 刚刚生成的结果。
    • before_agent_callback → Content:跳过了代理的主要执行逻辑;返回的结果是…… Content 该对象会立即被视为代理在该轮次中的最终输出结果。这种处理方式适用于直接处理简单请求或实施访问控制。
    • before_model_callback → LlmResponse:跳过了对外部大型语言模型(Large Language Model)的调用;返回的结果为…… LlmResponse 该对象的处理方式就好像它是来自大型语言模型(LLM)的实际响应一样。这种处理方式非常适合用于实现输入验证机制、提示内容校验功能,或提供已缓存的响应内容。
    • before_tool_callback → Python: dict, Kotlin: Map<String, Any>:跳过实际工具功能(或子代理)的执行过程;返回的是…… dict 或者 Map 该结果作为工具调用的输出被返回给大型语言模型(LLM)。这种机制可用于验证工具参数、执行策略限制,或返回模拟/缓存的工具执行结果。
    • after_agent_callback → Content: 追加(数据) 返回的(值/结果等) Content 作为在代理运行逻辑产生的输出之后的一个额外事件。该事件不会替换原有的输出结果,请继续使用原有的输出结果。 after_model_callback 用于更改模型返回的结果(即模型生成的响应数据)。
    • after_model_callback → LlmResponse: 替换 the LlmResponse 该内容是从大型语言模型(LLM)中获取的。它可用于对输出内容进行清洗处理(例如去除不必要的信息)、添加标准的免责声明,或修改大型语言模型的响应格式。
    • after_tool_callback → Python: dict, Kotlin: Map<String, Any>: 替换 该工具返回的结果。在将这些结果发送回大型语言模型(LLM)之前,可以对工具的输出进行后处理或标准化操作。

概念性代码示例(安全防护机制):

这个示例展示了使用护栏(guardrail)时的常见设计模式。 before_model_callback.

代码
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio

from google.adk.agents import LlmAgent
from google.adk.agents.callback_context import CallbackContext
from google.adk.models import LlmResponse, LlmRequest
from google.adk.runners import Runner
from typing import Optional
from google.genai import types 
from google.adk.sessions import InMemorySessionService

GEMINI_2_FLASH="gemini-2.0-flash"

# --- Define the Callback Function ---
def simple_before_model_modifier(
    callback_context: CallbackContext, llm_request: LlmRequest
) -> Optional[LlmResponse]:
    """Inspects/modifies the LLM request or skips the call."""
    agent_name = callback_context.agent_name
    print(f"[Callback] Before model call for agent: {agent_name}")

    # Inspect the last user message in the request contents
    last_user_message = ""
    if llm_request.contents and llm_request.contents[-1].role == 'user':
         if llm_request.contents[-1].parts:
            last_user_message = llm_request.contents[-1].parts[0].text
    print(f"[Callback] Inspecting last user message: '{last_user_message}'")

    # --- Modification Example ---
    # Add a prefix to the system instruction
    original_instruction = llm_request.config.system_instruction or types.Content(role="system", parts=[])
    prefix = "[Modified by Callback] "
    # Ensure system_instruction is Content and parts list exists
    if not isinstance(original_instruction, types.Content):
         # Handle case where it might be a string (though config expects Content)
         original_instruction = types.Content(role="system", parts=[types.Part(text=str(original_instruction))])
    if not original_instruction.parts:
        original_instruction.parts.append(types.Part(text="")) # Add an empty part if none exist

    # Modify the text of the first part
    modified_text = prefix + (original_instruction.parts[0].text or "")
    original_instruction.parts[0].text = modified_text
    llm_request.config.system_instruction = original_instruction
    print(f"[Callback] Modified system instruction to: '{modified_text}'")

    # --- Skip Example ---
    # Check if the last user message contains "BLOCK"
    if "BLOCK" in last_user_message.upper():
        print("[Callback] 'BLOCK' keyword found. Skipping LLM call.")
        # Return an LlmResponse to skip the actual LLM call
        return LlmResponse(
            content=types.Content(
                role="model",
                parts=[types.Part(text="LLM call was blocked by before_model_callback.")],
            )
        )
    else:
        print("[Callback] Proceeding with LLM call.")
        # Return None to allow the (modified) request to go to the LLM
        return None


# Create LlmAgent and Assign Callback
my_llm_agent = LlmAgent(
        name="ModelCallbackAgent",
        model=GEMINI_2_FLASH,
        instruction="You are a helpful assistant.", # Base instruction
        description="An LLM agent demonstrating before_model_callback",
        before_model_callback=simple_before_model_modifier # Assign the function here
)

APP_NAME = "guardrail_app"
USER_ID = "user_1"
SESSION_ID = "session_001"

# Session and Runner
async def setup_session_and_runner():
    session_service = InMemorySessionService()
    session = await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
    runner = Runner(agent=my_llm_agent, app_name=APP_NAME, session_service=session_service)
    return session, runner


# Agent Interaction
async def call_agent_async(query):
    content = types.Content(role='user', parts=[types.Part(text=query)])
    session, runner = await setup_session_and_runner()
    events = runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=content)

    async for event in events:
        if event.is_final_response() and event.content and event.content.parts:
            final_response = event.content.parts[0].text
            print("Agent Response: ", final_response)

async def main():
    await call_agent_async("write a joke on BLOCK")

# Note: In Colab, you can directly 'await call_agent_async(...)' at the top level.
if __name__ == "__main__":
    asyncio.run(main())
/**
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { LlmAgent, InMemoryRunner, Context, isFinalResponse } from '@google/adk';
import { createUserContent } from "@google/genai";

const MODEL_NAME = "gemini-2.5-flash";
const APP_NAME = "before_model_callback_app";
const USER_ID = "test_user_before_model";
const SESSION_ID_BLOCK = "session_block_model_call";
const SESSION_ID_NORMAL = "session_normal_model_call";

// --- Define the Callback Function ---
function simpleBeforeModelModifier({
  context,
  request,
}: {
  context: Context;
  request: any;
}): any | undefined {
  console.log(`[Callback] Before model call for agent: ${context.agentName}`);

  // Inspect the last user message in the request contents
  const lastUserMessage = request.contents?.at(-1)?.parts?.[0]?.text ?? "";
  console.log(`[Callback] Inspecting last user message: '${lastUserMessage}'`);

  // --- Modification Example ---
  // Add a prefix to the system instruction.
  // We create a deep copy to avoid modifying the original agent's config object.
  const modifiedConfig = JSON.parse(JSON.stringify(request.config));
  const originalInstructionText =
    modifiedConfig.systemInstruction?.parts?.[0]?.text ?? "";
  const prefix = "[Modified by Callback] ";
  modifiedConfig.systemInstruction = {
    role: "system",
    parts: [{ text: prefix + originalInstructionText }],
  };
  request.config = modifiedConfig; // Assign the modified config back to the request
  console.log(
    `[Callback] Modified system instruction to: '${modifiedConfig.systemInstruction.parts[0].text}'`
  );

  // --- Skip Example ---
  // Check if the last user message contains "BLOCK"
  if (lastUserMessage.toUpperCase().includes("BLOCK")) {
    console.log("[Callback] 'BLOCK' keyword found. Skipping LLM call.");
    // Return an LlmResponse to skip the actual LLM call
    return {
      content: {
        role: "model",
        parts: [
          { text: "LLM call was blocked by the before_model_callback." },
        ],
      },
    };
  }

  console.log("[Callback] Proceeding with LLM call.");
  // Return undefined to allow the (modified) request to go to the LLM
  return undefined;
}

// --- Create LlmAgent and Assign Callback ---
const myLlmAgent = new LlmAgent({
  name: "ModelCallbackAgent",
  model: MODEL_NAME,
  instruction: "You are a helpful assistant.", // Base instruction
  description: "An LLM agent demonstrating before_model_callback",
  beforeModelCallback: simpleBeforeModelModifier, // Assign the function here
});

// --- Agent Interaction Logic ---
async function callAgentAndPrint(
  runner: InMemoryRunner,
  query: string,
  sessionId: string
) {
  console.log(`\n>>> Calling Agent with query: "${query}"`);

  let finalResponseContent = "No final response received.";
  const events = runner.runAsync({ userId: USER_ID, sessionId, newMessage: createUserContent(query) });

  for await (const event of events) {
    if (isFinalResponse(event) && event.content?.parts?.length) {
      finalResponseContent = event.content.parts
        .map((part: { text?: string }) => part.text ?? "")
        .join("");
    }
  }
  console.log("<<< Agent Response: ", finalResponseContent);
}

// --- Run Interactions ---
async function main() {
  const runner = new InMemoryRunner({ agent: myLlmAgent, appName: APP_NAME });

  // Scenario 1: The callback will find "BLOCK" and skip the model call
  await runner.sessionService.createSession({
    appName: APP_NAME,
    userId: USER_ID,
    sessionId: SESSION_ID_BLOCK,
  });
  await callAgentAndPrint(
    runner,
    "write a joke about BLOCK",
    SESSION_ID_BLOCK
  );

  // Scenario 2: The callback will modify the instruction and proceed
  await runner.sessionService.createSession({
    appName: APP_NAME,
    userId: USER_ID,
    sessionId: SESSION_ID_NORMAL,
  });
  await callAgentAndPrint(runner, "write a short poem", SESSION_ID_NORMAL);
}

main();
package main

import (
    "context"
    "fmt"
    "log"
    "strings"

    "google.golang.org/adk/v2/agent"
    "google.golang.org/adk/v2/agent/llmagent"
    "google.golang.org/adk/v2/model"
    "google.golang.org/adk/v2/model/gemini"
    "google.golang.org/adk/v2/runner"
    "google.golang.org/adk/v2/session"
    "google.golang.org/genai"
)



// onBeforeModelGuardrail is a callback that inspects the LLM request.
// If it contains a forbidden topic, it blocks the request and returns a
// predefined response. Otherwise, it allows the request to proceed.
func onBeforeModelGuardrail(ctx agent.Context, req *model.LLMRequest) (*model.LLMResponse, error) {
    log.Println("--- onBeforeModelGuardrail Callback Triggered ---")

    // Inspect the request content for forbidden topics.
    for _, content := range req.Contents {
        for _, part := range content.Parts {
            if strings.Contains(part.Text, "finance") {
                log.Println("Forbidden topic 'finance' detected. Blocking LLM call.")
                // By returning a non-nil response, we override the default behavior
                // and prevent the actual LLM call.
                return &model.LLMResponse{
                    Content: &genai.Content{
                        Parts: []*genai.Part{{Text: "I'm sorry, but I cannot discuss financial topics."}},
                        Role:  "model",
                    },
                }, nil
            }
        }
    }

    log.Println("No forbidden topics found. Allowing LLM call to proceed.")
    // Returning nil allows the default LLM call to proceed.
    return nil, nil
}

func runGuardrailExample() {
    const (
        appName = "GuardrailApp"
        userID  = "test_user_456"
    )
    ctx := context.Background()
    geminiModel, err := gemini.NewModel(ctx, modelName, &genai.ClientConfig{})
    if err != nil {
        log.Fatalf("Failed to create model: %v", err)
    }

    agentCfg := llmagent.Config{
        Name:                 "ChatAgent",
        Model:                geminiModel,
        BeforeModelCallbacks: []llmagent.BeforeModelCallback{onBeforeModelGuardrail},
    }
    chatAgent, err := llmagent.New(agentCfg)
    if err != nil {
        log.Fatalf("Failed to create agent: %v", err)
    }

    sessionService := session.InMemoryService()
    r, err := runner.New(runner.Config{
        AppName:        appName,
        Agent:          chatAgent,
        SessionService: sessionService,
    })
    if err != nil {
        log.Fatalf("Failed to create runner: %v", err)
    }
import com.google.adk.agents.CallbackContext;
import com.google.adk.agents.LlmAgent;
import com.google.adk.events.Event;
import com.google.adk.models.LlmRequest;
import com.google.adk.models.LlmResponse;
import com.google.adk.runner.InMemoryRunner;
import com.google.adk.sessions.Session;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class BeforeModelGuardrailExample {

  private static final String MODEL_ID = "gemini-2.0-flash";
  private static final String APP_NAME = "guardrail_app";
  private static final String USER_ID = "user_1";

  public static void main(String[] args) {
    BeforeModelGuardrailExample example = new BeforeModelGuardrailExample();
    example.defineAgentAndRun("Tell me about quantum computing. This is a test.");
  }

  // --- Define your callback logic ---
  // Looks for the word "BLOCK" in the user prompt and blocks the call to LLM if found.
  // Otherwise the LLM call proceeds as usual.
  public Optional<LlmResponse> simpleBeforeModelModifier(
      CallbackContext callbackContext, LlmRequest llmRequest) {
    System.out.println("[Callback] Before model call for agent: " + callbackContext.agentName());

    // Inspect the last user message in the request contents
    String lastUserMessageText = "";
    List<Content> requestContents = llmRequest.contents();
    if (requestContents != null && !requestContents.isEmpty()) {
      Content lastContent = requestContents.get(requestContents.size() - 1);
      if (lastContent.role().isPresent() && "user".equals(lastContent.role().get())) {
        lastUserMessageText =
            lastContent.parts().orElse(List.of()).stream()
                .flatMap(part -> part.text().stream())
                .collect(Collectors.joining(" ")); // Concatenate text from all parts
      }
    }
    System.out.println("[Callback] Inspecting last user message: '" + lastUserMessageText + "'");

    String prefix = "[Modified by Callback] ";
    GenerateContentConfig currentConfig =
        llmRequest.config().orElse(GenerateContentConfig.builder().build());
    Optional<Content> optOriginalSystemInstruction = currentConfig.systemInstruction();

    Content conceptualModifiedSystemInstruction;
    if (optOriginalSystemInstruction.isPresent()) {
      Content originalSystemInstruction = optOriginalSystemInstruction.get();
      List<Part> originalParts =
          new ArrayList<>(originalSystemInstruction.parts().orElse(List.of()));
      String originalText = "";

      if (!originalParts.isEmpty()) {
        Part firstPart = originalParts.get(0);
        if (firstPart.text().isPresent()) {
          originalText = firstPart.text().get();
        }
        originalParts.set(0, Part.fromText(prefix + originalText));
      } else {
        originalParts.add(Part.fromText(prefix));
      }
      conceptualModifiedSystemInstruction =
          originalSystemInstruction.toBuilder().parts(originalParts).build();
    } else {
      conceptualModifiedSystemInstruction =
          Content.builder()
              .role("system")
              .parts(List.of(Part.fromText(prefix)))
              .build();
    }

    // This demonstrates building a new LlmRequest with the modified config.
    llmRequest =
        llmRequest.toBuilder()
            .config(
                currentConfig.toBuilder()
                    .systemInstruction(conceptualModifiedSystemInstruction)
                    .build())
            .build();

    System.out.println(
        "[Callback] Conceptually modified system instruction is: '"
            + llmRequest.config().get().systemInstruction().get().parts().get().get(0).text().get());

    // --- Skip Example ---
    // Check if the last user message contains "BLOCK"
    if (lastUserMessageText.toUpperCase().contains("BLOCK")) {
      System.out.println("[Callback] 'BLOCK' keyword found. Skipping LLM call.");
      LlmResponse skipResponse =
          LlmResponse.builder()
              .content(
                  Content.builder()
                      .role("model")
                      .parts(
                          List.of(
                              Part.builder()
                                  .text("LLM call was blocked by before_model_callback.")
                                  .build()))
                      .build())
              .build();
      return Optional.of(skipResponse);
    }
    System.out.println("[Callback] Proceeding with LLM call.");
    // Return Optional.empty() to allow the (modified) request to go to the LLM
    return Optional.empty();
  }

  public void defineAgentAndRun(String prompt) {
    // --- Create LlmAgent and Assign Callback ---
    LlmAgent myLlmAgent =
        LlmAgent.builder()
            .name("ModelCallbackAgent")
            .model(MODEL_ID)
            .instruction("You are a helpful assistant.") // Base instruction
            .description("An LLM agent demonstrating before_model_callback")
            .beforeModelCallbackSync(this::simpleBeforeModelModifier) // Assign the callback here
            .build();

    // Session and Runner
    InMemoryRunner runner = new InMemoryRunner(myLlmAgent, APP_NAME);
    // InMemoryRunner automatically creates a session service. Create a session using the service
    Session session = runner.sessionService().createSession(APP_NAME, USER_ID).blockingGet();
    Content userMessage =
        Content.fromParts(Part.fromText(prompt));

    // Run the agent
    Flowable<Event> eventStream = runner.runAsync(USER_ID, session.id(), userMessage);

    // Stream event response
    eventStream.blockingForEach(
        event -> {
          if (event.finalResponse()) {
            System.out.println(event.stringifyContent());
          }
        });
  }
}
val guardrailCallback =
    BeforeModelCallback { context, request ->
        val userQuery = request.contents.lastOrNull()?.parts?.firstOrNull()?.text ?: ""

        if (userQuery.contains("sensitive info", ignoreCase = true)) {
            println("Guardrail triggered: Sensitive information requested.")
            CallbackChoice.Break(
                LlmResponse(
                    content =
                        Content(
                            role = Role.MODEL,
                            parts =
                                listOf(
                                    Part(
                                        text = "I'm sorry, I cannot provide sensitive information.",
                                    ),
                                ),
                        ),
                ),
            )
        } else {
            CallbackChoice.Continue(request)
        }
    }

通过理解这种返回数据的机制…… None 与返回特定对象的方法相比,你可以更精确地控制代理的执行路径。因此,回调(callbacks)成为使用 ADK 构建复杂且可靠的代理系统时的关键工具。