Skip to content

智能体工作流的人工输入

Supported in ADKPython v2.0.0TypeScript v2.0.0Go v2.0.0

能够在数据输入、决策验证或操作授权等环节请求人工输入,是许多智能体驱动工作流的重要组成部分。ADK 中基于图的工作流可以包含专门为获取人工输入而设计的人机交互(HITL)节点。这些节点不需要运行人工智能(AI)模型,从而使输入过程更具可预测性和可靠性。

开始使用

你可以使用 RequestInput 类和一个文本提示在图中实现人工输入节点。以下代码示例展示了如何在 Workflow 图中添加人工输入节点:

from google.adk.events import RequestInput
from google.adk import Workflow

def step1(): # 人工输入步骤
  yield RequestInput(message="Enter a number:")

def step2(node_input):
  return node_input * 2

root_agent = Workflow(
    name="root_agent",
    edges=[('START', step1, step2)],
)

在此代码示例中,step1 会暂停智能体的执行,直到系统收到用户的输入。一旦系统收到用户的输入,该输入就会被传递到下一个节点。

在 ADK TypeScript 中,人工输入节点会 yield 一个 RequestInput。 step1 节点暂停工作流直到用户回复,回复会作为输入传递给下一个节点。 人机协同 (HITL) 节点不需要模型,这使得暂停是确定性的。

import { node, NodeContext, RequestInput, Workflow } from '@google/adk';

const step1 = node(
  async function* () {
    yield new RequestInput({ message: 'Enter a number:' });
  },
  { name: 'step1' },
);

const step2 = node(
  (_ctx: NodeContext, nodeInput: string | number) => {
    const value = Number(nodeInput);
    return Number.isFinite(value)
      ? value * 2
      : `"${nodeInput}" is not a number.`;
  },
  { name: 'step2' },
);

export const rootAgent = new Workflow({
  name: 'root_agent',
  edges: [['START', step1, step2]],
});

此实现展示了默认的 rerunOnResume: false 交接方式: 被中断的节点不会重新运行。它以用户的回复作为输出完成。 调用 ctx.runNode() 的节点需要改为设置 rerunOnResume: true。 更多信息请参阅动态工作流中的人工输入。

在 ADK Go 中,人工输入节点通过 workflow.NewRequestInputEvent 发出请求并返回 workflow.ErrNodeInterrupted。 step1 节点暂停工作流直到用户回复。该节点不会再次运行。回复成为其输出并传递给下一个节点。

// newGraphHITLHandoffWorkflow demonstrates the handoff HITL pattern, which
// matches the Python example. step1Node emits a RequestInput event and pauses
// the workflow. RerunOnResume is left unset, so step1Node does not run again
// on resume. The human's reply becomes step1Node's output and flows to
// step2Node as its input.
func newGraphHITLHandoffWorkflow() (agent.Agent, error) {
    step1Node := workflow.NewEmittingFunctionNode[any, string]("step1",
        func(ctx agent.Context, _ any, emit func(*session.Event) error) (string, error) {
            // Leaving InterruptID empty generates a new UUID automatically.
            if err := emit(workflow.NewRequestInputEvent(ctx, session.RequestInput{
                Message: "Enter a number:",
            })); err != nil {
                return "", err
            }
            return "", workflow.ErrNodeInterrupted
        },
        workflow.NodeConfig{},
    )

    // step2Node takes any, because a reply that parses as JSON, such as "42",
    // arrives decoded (here as a float64).
    step2Node := workflow.NewFunctionNode("step2",
        func(_ agent.Context, input any) (string, error) {
            return fmt.Sprintf("You entered: %v", input), nil
        },
        workflow.NodeConfig{},
    )

    return workflowagent.New(workflowagent.Config{
        Name:        "root_agent",
        Description: "Pauses for a number from the user, then hands it to step2.",
        Edges:       workflow.Chain(workflow.Start, step1Node, step2Node),
    })
}

需要在收到回复后再次运行的节点请设置 RerunOnResume 并改用 workflow.ResumeOrRequestInput。更多信息请参阅动态工作流中的人工输入。

配置选项

人工输入节点可以使用 RequestInput 类,支持以下配置选项:

  • message: 向用户提供的说明人工输入请求的文本。
  • payload: 作为人工输入请求一部分的结构化数据。
  • response_schema: 人工响应必须遵循的数据结构。

RequestInput 类接受以下配置选项:

  • message: 向用户显示的解释正在请求什么的文本。
  • payload: 与提示一起发送的结构化数据,以便客户端渲染额外的上下文。
  • responseSchema: 期望回复采用的数据形状。该 Schema 随中断一起 作为 functionCall.args.response_schema 传递,客户端读取它来渲染 回复的表单。

节点上的 rerunOnResume 选项控制回复到达时的行为:

  • false(叶子节点的默认值):回复被路由到节点的后继节点作为输入, 绕过被中断的节点。
  • true:节点主体从头重新运行。任何调用 ctx.runNode() 的节点 都需要此设置,以便在恢复时传递缓存的子节点结果。

session.RequestInput 携带以下字段,它们与 Python 的 RequestInput 参数直接对应:

  • InterruptID (string):此暂停点的唯一标识符。使用稳定的前缀加 UUID 来避免跨工作流运行时的冲突。等同于 Python 中的隐式中断 ID。
  • Message (string):显示给用户的人类可读提示。等同于 Python 的 message 参数。
  • Payload (any):可选的结构化数据,随提示一起发送,以便客户端渲染额外的上下文。等同于 Python 的 payload 参数。
  • ResponseSchema (*jsonschema.Schema):回复必须符合的可选 JSON schema。等同于 Python 的 response_schema 参数。

workflow.NodeConfig.RerunOnResume 字段控制恢复时的行为:

  • &true:节点主体从顶部重新执行;ResumeOrRequestInput 在第二次执行时返回人工回复。使用 ResumeOrRequestInput 的节点必须设置此项。
  • &false 或 nil(叶子节点默认值):回复被路由到节点的后继节点作为输入,跳过被中断的节点。

注意:响应 Schema 输入限制

响应 Schema 不会将人工回复重新格式化为指定的结构。 回复必须已经是该格式。为了获得更好的用户体验,请在客户端界面中收集结构化数据, 或在暂停后放置一个智能体节点来将回复转换为所需格式。

人工输入示例

以下代码示例展示了更详细的人工输入请求。

请求带消息和负载的输入

以下代码示例展示了如何在工作流节点中构建 RequestInput 对象,包括 负载 和 响应 schema。在此示例中,ActivitiesList 预期由一个组成活动列表的智能体节点完成,而 get_user_feedback() 节点向用户请求反馈。

class ActivitiesList(BaseModel):
   """行程应为每个活动的字典列表。每个活动包含名称和描述"""
   itinerary: List[Dict[str, str]]

class UserFeedback(BaseModel):
   """用户预期的响应结构。"""
   user_response: str

async def get_user_feedback(node_input: ActivitiesList):
   """
   获取用户对智能体初始行程的意见,以便扩展、更改列表或退出循环
   """
   message = (
       f"""
       这是你推荐的基础行程:\n{node_input}\n\n
       这些项目中哪些吸引了你(如果有)?
       """
   )

   yield RequestInput(
       message=message,
       payload=node_input,
        response_schema=UserFeedback,
   )

以下三节点图构建了一个结构化行程,将其作为 payload 与提示一起发送, 以便客户端可以渲染它,然后根据用户的反馈执行操作:

import { node, NodeContext, RequestInput, Workflow } from '@google/adk';
import { z } from 'zod';

/**
 * Itinerary is a list of activities. Each activity has a name and a
 * description.
 */
const activitiesListSchema = z.object({
  itinerary: z.array(z.object({ name: z.string(), description: z.string() })),
});
type ActivitiesList = z.infer<typeof activitiesListSchema>;

/** Expected response structure from the user. */
const userFeedbackSchema = z.object({
  userResponse: z.string(),
});

const buildItinerary = node(
  (_ctx: NodeContext, city: string): ActivitiesList => {
    const place = city.trim() || 'your city';
    return {
      itinerary: [
        { name: 'Morning walk', description: `A stroll through old ${place}.` },
        { name: 'Local lunch', description: `Regional food in ${place}.` },
        { name: 'Museum visit', description: `The main museum of ${place}.` },
      ],
    };
  },
  { name: 'build_itinerary', outputSchema: activitiesListSchema },
);

/**
 * Retrieves the user's thoughts on the agent's initial itinerary in order to
 * either expand on it, change the list, or exit the loop.
 */
const getUserFeedback = node(
  async function* (_ctx: NodeContext, nodeInput: ActivitiesList) {
    const rendered = nodeInput.itinerary
      .map((a, i) => `  ${i + 1}. ${a.name} — ${a.description}`)
      .join('\n');

    yield new RequestInput({
      message:
        `Here is your recommended base itinerary:\n${rendered}\n\n` +
        'Which of these items appeal to you (if any)?',
      payload: nodeInput,
      responseSchema: userFeedbackSchema,
    });
  },
  { name: 'get_user_feedback' },
);

const applyFeedback = node(
  (_ctx: NodeContext, nodeInput: unknown) => {
    const feedback =
      typeof nodeInput === 'string'
        ? nodeInput
        : String(
            (nodeInput as { userResponse?: unknown } | null)?.userResponse ??
              JSON.stringify(nodeInput),
          );
    return `Noted. Building the final itinerary around: ${feedback}`;
  },
  { name: 'apply_feedback' },
);

export const rootAgent = new Workflow({
  name: 'concierge_workflow',
  edges: [['START', buildItinerary, getUserFeedback, applyFeedback]],
});

以下代码示例展示了一个三节点图:一个构建器节点生成结构化行程,一个 HITL 节点将其作为 Payload 与提示一起发送,最后一个节点根据用户的反馈执行操作。Payload 字段允许客户端在用户回复之前渲染完整的行程:

// ItineraryItem represents a single activity in a travel plan.
type ItineraryItem struct {
    Name        string `json:"name"`
    Description string `json:"description"`
}

// newItineraryReviewWorkflow demonstrates a graph HITL node that sends a
// structured payload alongside the input prompt so the client can render
// additional context for the user. This mirrors Python's:
//
//  async def get_user_feedback(node_input: ActivitiesList):
//      yield RequestInput(
//          message="Which items appeal to you?",
//          payload=node_input,
//          response_schema=UserFeedback,
//      )
func newItineraryReviewWorkflow() (agent.Agent, error) {
    rerun := true

    // buildItineraryNode: generates an itinerary and passes it to the HITL
    // node as its typed output via event.Output.
    buildItineraryNode := workflow.NewFunctionNode("build_itinerary",
        func(_ agent.Context, _ any) ([]ItineraryItem, error) {
            return []ItineraryItem{
                {Name: "Eiffel Tower", Description: "Iconic iron lattice tower."},
                {Name: "Louvre Museum", Description: "World's largest art museum."},
                {Name: "Seine River Cruise", Description: "Scenic boat tour of Paris."},
            }, nil
        },
        workflow.NodeConfig{},
    )

    // reviewNode: sends the itinerary as payload alongside the prompt so the
    // client can display it. On resume, the human's selection is returned.
    reviewNode := workflow.NewEmittingFunctionNode[[]ItineraryItem, string]("get_user_feedback",
        func(ctx agent.Context, itinerary []ItineraryItem, emit func(*session.Event) error) (string, error) {
            reply, err := workflow.ResumeOrRequestInput(ctx, emit, session.RequestInput{
                InterruptID: "itinerary_review",
                Message:     fmt.Sprintf("Here is your recommended itinerary (%d activities). Which items appeal to you?", len(itinerary)),
                Payload:     itinerary, // structured payload rendered by the client
            })
            if err != nil {
                // ErrNodeInterrupted on first pass — workflow pauses here.
                return "", err
            }
            feedback, _ := reply.(string)
            return feedback, nil
        },
        workflow.NodeConfig{RerunOnResume: &rerun},
    )

    // finalNode: receives the user's feedback and produces a confirmation.
    finalNode := workflow.NewFunctionNode("finalize",
        func(_ agent.Context, feedback string) (string, error) {
            return fmt.Sprintf("Itinerary finalised with your feedback: %q", feedback), nil
        },
        workflow.NodeConfig{},
    )

    return workflowagent.New(workflowagent.Config{
        Name:        "concierge_workflow",
        Description: "Builds an itinerary, asks the user for feedback, then finalises.",
        Edges:       workflow.Chain(workflow.Start, buildItineraryNode, reviewNode, finalNode),
    })
}

工具确认:LLM 智能体中的审批提示

工具确认是一种独立的、LLM 智能体级别的机制,用于是/否审批提示。与图 HITL 节点不同,工具确认在 llmagent 工具函数内部工作,而不是作为独立的图节点。当你希望 LLM 智能体在执行特定工具调用之前暂停并请求审批时,这个机制非常有用。

使用 FunctionTool 包装该工具,并设置 require_confirmation=True, 以便在工具运行前进行静态的是/否审批;或者在工具内部调用 tool_context.request_confirmation() 来提供自定义提示消息。ADK 仅会在 require_confirmation=True 路径上替你拒绝调用,因此自行请求确认的 工具必须同时检查两处:先用 tool_context.tool_confirmation 询问 一次,再用 tool_confirmation.confirmed 处理拒绝:

from google.adk.agents import Agent
from google.adk.tools import FunctionTool, ToolContext

def book_flight(flight_id: str) -> str:
   """预订所选航班。"""
   ...

def refund(amount: float, tool_context: ToolContext) -> str:
   """对订单进行退款。"""
   if not tool_context.tool_confirmation:
       tool_context.request_confirmation(
           hint=f"批准 {amount} 的退款?"
       )
       return "等待审批。"
   elif not tool_context.tool_confirmation.confirmed:
       return "用户拒绝了退款。"
   ...

root_agent = Agent(
   name="concierge",
   model="gemini-flash-latest",
   tools=[FunctionTool(book_flight, require_confirmation=True), refund],
)

在 FunctionTool 上设置 requireConfirmation: true 可在该工具运行前使智能体 暂停以等待审批。图中的人机交互节点用途不同:它不是确认工具调用, 而是通过请求用户输入来启动工作流。responseSchema: z.string() 选项请求纯文本回复:

import { node, NodeContext, RequestInput, Workflow } from '@google/adk';
import { z } from 'zod';

/** Asks the user for itinerary information. */
const initialPrompt = node(
  async function* () {
    const inputMessage = `
        This is an interactive concierge workflow tasked with making you a great
        itinerary for you in your city of choice. If you give some details about
        yourself or what you are generally looking for I can better personalize
        your itinerary.
        For example, input your:
            City (Required),
            Age,
            Hobby,
            Example of attraction you liked
    `;
    yield new RequestInput({
      message: inputMessage,
      responseSchema: z.string(),
    });
  },
  { name: 'initial_prompt' },
);

const buildItinerary = node(
  (_ctx: NodeContext, nodeInput: string) => {
    const [city = 'your city'] = nodeInput.split(',');
    return (
      `Personalized itinerary for ${city.trim()}:\n` +
      '  1. Morning walk through the old town\n' +
      '  2. Lunch at a neighbourhood favourite\n' +
      '  3. An afternoon activity matched to your hobby\n\n' +
      `(based on: ${nodeInput.trim()})`
    );
  },
  { name: 'build_itinerary' },
);

export const rootAgent = new Workflow({
  name: 'concierge_workflow',
  edges: [['START', initialPrompt, buildItinerary]],
});

在 functiontool.Config 中设置 RequireConfirmation: true 可在工具执行前进行静态的是/否审批,或者从工具内部调用 ctx.RequestConfirmation 来设置自定义提示消息:

// DoubleNumberArgs holds the input for the doubleNumber tool.
type DoubleNumberArgs struct {
    Number int `json:"number" jsonschema:"The number to double."`
}

// DoubleNumberResults holds the output of the doubleNumber tool.
type DoubleNumberResults struct {
    Result int `json:"result"`
}

// doubleNumber is a tool that doubles the given number.
// Because RequireConfirmation is true, the framework automatically pauses
// execution and emits an "adk_request_confirmation" event to the client before
// running the tool. The client must reply with a FunctionResponse confirming
// or denying the action.
func doubleNumber(_ agent.Context, args DoubleNumberArgs) (DoubleNumberResults, error) {
    return DoubleNumberResults{Result: args.Number * 2}, nil
}

// newSimpleHITLAgent creates an LLM agent with a tool that always requires
// user confirmation before it executes (tool-confirmation pattern).
func newSimpleHITLAgent(ctx context.Context) (agent.Agent, error) {
    model, err := gemini.NewModel(ctx, modelName, &genai.ClientConfig{})
    if err != nil {
        return nil, fmt.Errorf("failed to create model: %w", err)
    }

    doubleNumberTool, err := functiontool.New(
        functiontool.Config{
            Name:                "double_number",
            Description:         "Doubles the given number. Requires user approval before running.",
            RequireConfirmation: true,
        },
        doubleNumber,
    )
    if err != nil {
        return nil, fmt.Errorf("failed to create tool: %w", err)
    }

    return llmagent.New(llmagent.Config{
        Name:        "double_number_agent",
        Model:       model,
        Instruction: "You are a helpful assistant. When asked to double a number, use the double_number tool.",
        Tools:       []tool.Tool{doubleNumberTool},
    })
}

使用自定义提示和手动重入处理:

// BookFlightArgs holds the input for the bookFlight tool.
type BookFlightArgs struct {
    Origin      string `json:"origin"      jsonschema:"Departure airport code."`
    Destination string `json:"destination" jsonschema:"Arrival airport code."`
    Date        string `json:"date"        jsonschema:"Travel date in YYYY-MM-DD format."`
}

// BookFlightResults holds the outcome of the bookFlight tool.
type BookFlightResults struct {
    Status        string `json:"status"`
    ConfirmNumber string `json:"confirm_number,omitempty"`
}

// bookFlight is a tool that pauses for human approval before completing a
// booking (tool-confirmation pattern with a custom hint message).
func bookFlight(ctx agent.Context, args BookFlightArgs) (BookFlightResults, error) {
    if confirmation := ctx.ToolConfirmation(); confirmation != nil {
        if !confirmation.Confirmed {
            return BookFlightResults{Status: "Booking cancelled by user."}, nil
        }
        return BookFlightResults{
            Status:        "Booking confirmed.",
            ConfirmNumber: "FLT-20251031",
        }, nil
    }

    hint := fmt.Sprintf(
        "The agent wants to book a flight from %s to %s on %s. Do you approve?",
        args.Origin, args.Destination, args.Date,
    )
    if err := ctx.RequestConfirmation(hint, nil); err != nil {
        return BookFlightResults{}, fmt.Errorf("failed to request confirmation: %w", err)
    }
    return BookFlightResults{Status: "Awaiting user approval."}, nil
}

// newHITLWithHintAgent creates an LLM agent whose bookFlight tool manually
// requests confirmation with a descriptive hint (tool-confirmation pattern).
func newHITLWithHintAgent(ctx context.Context) (agent.Agent, error) {
    model, err := gemini.NewModel(ctx, modelName, &genai.ClientConfig{})
    if err != nil {
        return nil, fmt.Errorf("failed to create model: %w", err)
    }

    bookFlightTool, err := functiontool.New(
        functiontool.Config{
            Name:        "book_flight",
            Description: "Books a flight between two airports on a given date.",
        },
        bookFlight,
    )
    if err != nil {
        return nil, fmt.Errorf("failed to create tool: %w", err)
    }

    return llmagent.New(llmagent.Config{
        Name:        "flight_booking_agent",
        Model:       model,
        Instruction: "You are a flight booking assistant. Help the user book flights.",
        Tools:       []tool.Tool{bookFlightTool},
    })
}

有关完整的工具确认工作流(包括动态确认以及客户端如何回复),参见 获取 ADK 工具的操作确认。