跳转到内容

用于代理工作流程的人工输入

在 ADK 中得到支持。Python v2.0.0TypeScript v2.0.0Go v2.0.0

能够请求用户提供数据输入、决策验证或操作许可,是许多由智能代理驱动的工作流程中的重要环节。在 ADK(Agent Deployment Kit)中,基于图形的工作流程可以包含专门用于从用户那里获取输入的“Human in the Loop (HITL)”节点。这些节点无需依赖人工智能(AI)模型即可运行,从而使得输入过程更加可预测且可靠。

立即开始使用吧!

你可以在图中实现一个用于接收人类输入的节点(即用户输入数据的节点),具体方法如下: RequestInput 该代码示例展示了如何向工作流图(Workflow graph)中添加一个用于接收用户输入的节点。具体来说,这个节点允许用户输入文本信息。以下是相关的代码示例: ```python # 定义一个类,用于接收用户的文本输入 class UserInputNode: def __init__(self): self.input_text = "" def get_input_text(self): return self.input_text # 创建一个 UserInputNode 实例,并为用户提供相应的文本提示 user_input_node = UserInputNode("请输入您的文本:") # 将 UserInputNode 添加到工作流图中 workflow_graph.add_user_input_node(user_input_node) ``` 在这个示例中,我们首先定义了一个名为 `UserInputNode` 的类,该类用于存储用户的输入文本。然后,我们创建了一个该类的实例,并为用户提供了一个文本提示(例如:“请输入您的文本:”)。最后,我们将这个用户输入节点添加到了工作流图中。

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

def step1(): # Human input step
  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 中,一个用于接收用户输入的节点(human input node)会返回相应的输入数据。 RequestInputThe step1 该节点会暂停工作流程,直到用户作出回复;用户的回复会被作为输入传递给下一个节点。这种需要人工参与(即“人在回路中”)的节点并不需要任何模型来辅助其运行,因此这种暂停行为是完全可以预测的(即“确定性的”)。

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 **handoff:** 被中断的节点不会重新运行;它会以用户的回复作为输出结果来完成自己的任务。调用该功能的节点(即发起请求的节点)会继续执行后续操作。 ctx.runNode() 需要 rerunOnResume: true 改为……。如需更多信息,请参阅……。 在动态工作流程中,需要人工输入数据。.

在 ADK Go 中,一个用于接收用户输入的节点会发送一个请求。 workflow.NewRequestInputEvent 并返回结果。 workflow.ErrNodeInterruptedThe 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: 一种数据结构,人类的响应必须符合这种结构的要求。

The RequestInput 该类支持以下配置选项:

  • message: 显示给用户的文本,用于解释正在请求用户做什么。
  • payload: 结构化数据会随提示一起发送,以便客户端能够显示额外的相关信息(即“额外的上下文”)。
  • responseSchema: 回复应采用的格式。该格式信息会通过中断机制被传递出去。 functionCall.args.response_schema客户端会读取这些内容,以便生成用于回复的表单。

The rerunOnResume 该节点上的选项用于控制收到回复时会发生什么。

  • false (默认情况下):回复会被直接发送到该节点的“后继节点”作为输入数据,从而绕过出现故障的节点。
  • true节点的主体内容会从顶部开始重新执行。对于任何需要调用该功能的节点来说,这个设置都是必需的。 ctx.runNode()因此,它可以在需要时重新加载(即“恢复”)数据,并提供已缓存的子结果。

session.RequestInput 包含以下字段,这些字段可以直接映射到 Python 的相应结构/类型。 RequestInput parameters:

  • InterruptID (string): 该暂停点的唯一标识符。 应使用一个固定的前缀加上 UUID(Universally Unique Identifier),以避免在不同工作流程运行过程中发生标识冲突。 其功能相当于 Python 中的隐式中断(implicit interrupt)机制。
  • Message (string): 显示给用户的人类可读的提示信息。 相当于 Python 中的……(具体功能需根据上下文补充)。 message parameter.
  • Payload (any): 可选的结构化数据,会与提示信息(prompt)一起发送给客户端,以便客户端能够显示更多相关信息。这相当于 Python 中的相应功能。 payload parameter.
  • ResponseSchema (*jsonschema.Schema): 可选的 JSON 规范;回复内容必须符合该规范。这相当于 Python 中的相应机制。 response_schema parameter.

The workflow.NodeConfig.RerunOnResume 该字段决定了在简历中显示哪些内容(即控制简历的显示方式)。

  • &true节点的主体内容会从头开始重新执行(即整个处理流程会重新运行一次)。 ResumeOrRequestInput 在第二次处理时返回人类的回复。对于使用该功能的节点来说,这是必需的。 ResumeOrRequestInput.
  • &false 或者 nil (默认行为):回复会被发送到该节点的“后继节点”作为输入数据,从而绕过出现故障的节点。

注意:响应数据结构的输入存在限制。

响应模式不会重新格式化用户输入的回复内容,以使其符合指定的结构;用户输入的回复必须已经处于该格式中。为了提供更好的用户体验,您可以在客户端界面中收集结构化数据,或者在对话暂停后添加一个处理节点(agent node),将该回复转换为所需的格式。

人类输入的示例

以下代码示例展示了更详细的人类输入请求(即用户如何向系统提交数据或请求)。

请求用户输入信息,同时需要用户提供一条消息(message)以及相关的数据(payload)。

以下代码示例展示了如何构建一个……(请根据实际情况填写具体的内容)。 RequestInput 在工作流节点中,包括一个…… payload 和 响应数据结构(Response Data Structure)在这个例子中, ActivitiesList 预计该任务将由某个代理(agent)完成。 该代理负责生成一系列活动(activities)的列表。 get_user_feedback() 从用户那里获取反馈。

class ActivitiesList(BaseModel):
   """Itinerary should be a list of dictionaries for each activity. Each
   activity has a name and a description"""
   itinerary: List[Dict[str, str]]

class UserFeedback(BaseModel):
   """Expected response structure from the user."""
   user_response: str

async def get_user_feedback(node_input: ActivitiesList):
   """
   Retrieves the user's thoughts on the agents initial itinerary in order to
   either expand on, change the list, or exit the loop
   """
   message = (
       f"""
       Here is your recommended base itinerary:\n{node_input}\n\n
       Which of these items appeal to you (if any)?
       """
   )

   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]],
});

以下代码示例展示了一个由三个节点组成的图结构: - **Builder 节点** 负责生成结构化的旅行计划; - **HITL 节点** 负责将生成的旅行计划发送出去。 Payload 除了提示信息(prompt)之外,还有一个最终的节点(final node)用于处理用户的反馈。 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),
    })
}

Tool-confirmation:大型语言模型(LLM)代理中的审批提示功能

“Tool-Confirmation”是一种独立的机制,属于大型语言模型(LLM)代理的层级,用于处理“是/否”类型的审批请求。与图结构中的 HITL 节点不同,“Tool-Confirmation”是在大型语言模型代理的内部运行的。 llmagent 该工具函数不应被视为一个独立的图节点(即不应作为一个独立的组件存在于系统中);当您希望大型语言模型(LLM)在执行某个特定的工具调用之前暂停并请求您的批准时,这个功能就非常有用。

用……将工具包裹起来。 FunctionTool 并设置 require_confirmation=True 在工具运行之前,需要先获得一个静态的“是/否”批准;否则请直接调用相关函数(或系统接口)。 tool_context.request_confirmation() 从该工具内部生成一条自定义的提示信息。ADK 仅会在特定情况下才会拒绝你的请求。 require_confirmation=True 路径(path)是一个重要的因素;因此,任何需要用户自行确认操作的工具都必须同时检查这两个方面(即路径的正确性和用户确认信息的有效性)。 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:
   """Books the selected flight."""
   ...

def refund(amount: float, tool_context: ToolContext) -> str:
   """Refunds an order."""
   if not tool_context.tool_confirmation:
       tool_context.request_confirmation(
           hint=f"Approve a refund of {amount}?"
       )
       return "Waiting for approval."
   elif not tool_context.tool_confirmation.confirmed:
       return "Refund rejected by user."
   ...

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

`Set` requireConfirmation: true 在……的时候;当……的情况下 FunctionTool 为了让代理在运行该工具之前暂停并等待批准,可以使用一个“人工干预”(human-in-the-loop)节点。这个节点的作用有所不同:它不是用来确认工具调用的结果,而是通过请求用户的输入来启动工作流程。 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]],
});

`Set` RequireConfirmation: true 在……里面;处于……状态 functiontool.Config 在工具执行之前,需要先获得静态的(是/否)批准;否则可以跳过该步骤。 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 工具的操作确认信息.