Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 37 additions & 3 deletions core/src/agents/llm_agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import {BaseLlmConnection} from '../models/base_llm_connection.js';
import {LlmRequest} from '../models/llm_request.js';
import {LlmResponse} from '../models/llm_response.js';
import {LLMRegistry} from '../models/registry.js';
import type {BasePlanner} from '../planners/base_planner.js';
import {isBuiltInPlanner} from '../planners/built_in_planner.js';

import {BaseTool, isBaseTool} from '../tools/base_tool.js';
import {BaseToolset} from '../tools/base_toolset.js';
Expand Down Expand Up @@ -77,6 +79,10 @@ import {ContextCompactorRequestProcessor} from './processors/context_compactor_r
import {IDENTITY_LLM_REQUEST_PROCESSOR} from './processors/identity_llm_request_processor.js';
import {INSTRUCTIONS_LLM_REQUEST_PROCESSOR} from './processors/instructions_llm_request_processor.js';
import {INTERACTIONS_REQUEST_PROCESSOR} from './processors/interactions_request_processor.js';
import {
NL_PLANNING_REQUEST_PROCESSOR,
NL_PLANNING_RESPONSE_PROCESSOR,
} from './processors/nl_planning_processor.js';
import {REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR} from './processors/request_confirmation_llm_request_processor.js';
import {REQUEST_INPUT_LLM_REQUEST_PROCESSOR} from './processors/request_input_llm_request_processor.js';
import {TOOL_FILTER_REQUEST_PROCESSOR} from './processors/tool_filter_request_processor.js';
Expand Down Expand Up @@ -318,7 +324,9 @@ export interface LlmAgentConfig extends BaseAgentConfig {
* Three fields are rejected by the constructor, because the agent owns them:
* `tools` (set them through `tools`), `systemInstruction` (through
* `instruction`) and `responseSchema` (through `outputSchema`). Every other
* field is forwarded to the model as given — `thinkingConfig` included.
* field is forwarded to the model as given. That includes `thinkingConfig`,
* unless `planner` is a `BuiltInPlanner` with its own `thinkingConfig`: the
* planner's `thinkingConfig` then takes precedence.
*
* For example: use this config to adjust model temperature, configure safety
* settings, etc.
Expand Down Expand Up @@ -414,6 +422,14 @@ export interface LlmAgentConfig extends BaseAgentConfig {
* Instructs the agent to make a plan and execute it step by step.
*/
codeExecutor?: BaseCodeExecutor;

/**
* Instructs the agent to make a plan and execute it step by step.
*
* NOTE: to use the model's built-in thinking features, set `thinkingConfig`
* on a `BuiltInPlanner`.
*/
planner?: BasePlanner;
}

async function convertToolUnionToTools(
Expand Down Expand Up @@ -503,6 +519,7 @@ export class LlmAgent extends BaseAgent<LlmAgentConfig> {
requestProcessors: BaseLlmRequestProcessor[];
responseProcessors: BaseLlmResponseProcessor[];
codeExecutor?: BaseCodeExecutor;
planner?: BasePlanner;

constructor(config: LlmAgentConfig) {
// Node defaults for an agent used in a graph, matching adk-python's
Expand Down Expand Up @@ -538,9 +555,11 @@ export class LlmAgent extends BaseAgent<LlmAgentConfig> {
this.beforeToolCallback = config.beforeToolCallback;
this.afterToolCallback = config.afterToolCallback;
this.codeExecutor = config.codeExecutor;
this.planner = config.planner;

// TODO - b/425992518: Define these processor arrays.
// Orders matter, don't change. Append new processors to the end
// The order is load-bearing: processors depend on what earlier ones
// wrote to the request. Place a new processor where its inputs are ready.
this.requestProcessors = config.requestProcessors ?? [
BASIC_LLM_REQUEST_PROCESSOR,
AUTH_PREPROCESSOR,
Expand All @@ -549,6 +568,10 @@ export class LlmAgent extends BaseAgent<LlmAgentConfig> {
REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
REQUEST_INPUT_LLM_REQUEST_PROCESSOR,
CONTENT_REQUEST_PROCESSOR,
// Planning clears the thought flags that the planning response
// processor sets, so it must run after the contents are built and
// before code execution rewrites them.
NL_PLANNING_REQUEST_PROCESSOR,
INTERACTIONS_REQUEST_PROCESSOR,
CODE_EXECUTION_REQUEST_PROCESSOR,
TOOL_FILTER_REQUEST_PROCESSOR,
Expand Down Expand Up @@ -576,7 +599,9 @@ export class LlmAgent extends BaseAgent<LlmAgentConfig> {
}
}

this.responseProcessors = config.responseProcessors ?? [];
this.responseProcessors = config.responseProcessors ?? [
NL_PLANNING_RESPONSE_PROCESSOR,
];

// Preserve the agent transfer behavior.
const agentTransferDisabled =
Expand All @@ -602,6 +627,15 @@ export class LlmAgent extends BaseAgent<LlmAgentConfig> {
'Response schema must be set via LlmAgent.output_schema.',
);
}
if (
config.generateContentConfig.thinkingConfig &&
isBuiltInPlanner(this.planner) &&
this.planner.thinkingConfig
) {
logger.warn(
`Agent ${this.name}: both generateContentConfig.thinkingConfig and planner.thinkingConfig are set. The planner's thinkingConfig takes precedence.`,
);
}
} else {
this.generateContentConfig = {};
}
Expand Down
121 changes: 121 additions & 0 deletions core/src/agents/processors/nl_planning_processor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/

import {Content, Part} from '@google/genai';

import {Event} from '../../events/event.js';
import {appendInstructions, LlmRequest} from '../../models/llm_request.js';
import {LlmResponse} from '../../models/llm_response.js';
import {BasePlanner, isBasePlanner} from '../../planners/base_planner.js';
import {isBuiltInPlanner} from '../../planners/built_in_planner.js';
import {Context} from '../context.js';
import {InvocationContext} from '../invocation_context.js';
import {isLlmAgent} from '../llm_agent.js';
import {ReadonlyContext} from '../readonly_context.js';
import {
BaseLlmRequestProcessor,
BaseLlmResponseProcessor,
} from './base_llm_processor.js';

/**
* Returns the planner of the invocation's agent, or undefined when the agent
* is not an LlmAgent or has no planner.
*/
function getPlanner(
invocationContext: InvocationContext,
): BasePlanner | undefined {
const agent = invocationContext.agent;
if (!isLlmAgent(agent) || !isBasePlanner(agent.planner)) {
return undefined;
}
return agent.planner;
}

/**
* Returns a copy of `part` without the `thought` flag.
*/
function removeThought(part: Part): Part {
const {thought: _thought, ...rest} = part;
return rest;
}

/**
* Returns copies of `contents` whose parts carry no `thought` flag.
*
* The request contents can share part objects with the session's stored
* events, so the parts are copied rather than changed in place.
*/
function removeThoughtFromContents(contents: Content[]): Content[] {
return contents.map((content) =>
content.parts
? {...content, parts: content.parts.map(removeThought)}
: content,
);
}

/**
* Prepares the LLM request for the agent's planner.
*
* Applies a `BuiltInPlanner`'s thinking config, appends the planner's
* planning instruction, and clears the `thought` flag on every request part
* so that earlier planning output goes back to the model as plain text.
*/
export class NlPlanningRequestProcessor extends BaseLlmRequestProcessor {
// eslint-disable-next-line require-yield -- this processor only mutates the request and has no event to emit
override async *runAsync(
invocationContext: InvocationContext,
llmRequest: LlmRequest,
): AsyncGenerator<Event, void, void> {
const planner = getPlanner(invocationContext);
if (!planner) {
return;
}

if (isBuiltInPlanner(planner)) {
planner.applyThinkingConfig(llmRequest);
}

const planningInstruction = planner.buildPlanningInstruction(
new ReadonlyContext(invocationContext),
llmRequest,
);
if (planningInstruction) {
appendInstructions(llmRequest, [planningInstruction]);
}

llmRequest.contents = removeThoughtFromContents(llmRequest.contents);
}
}

/**
* Replaces the LLM response parts with the planner's processed parts.
*
* Partial responses are processed too.
*/
export class NlPlanningResponseProcessor extends BaseLlmResponseProcessor {
// eslint-disable-next-line require-yield -- this processor only rewrites the response and has no event to emit
override async *runAsync(
invocationContext: InvocationContext,
llmResponse: LlmResponse,
): AsyncGenerator<Event, void, void> {
const planner = getPlanner(invocationContext);
if (!planner || !llmResponse.content?.parts?.length) {
return;
}

const processedParts = planner.processPlanningResponse(
new Context({invocationContext}),
llmResponse.content.parts,
);
if (processedParts !== undefined) {
llmResponse.content = {...llmResponse.content, parts: processedParts};
}
}
}

export const NL_PLANNING_REQUEST_PROCESSOR = new NlPlanningRequestProcessor();

export const NL_PLANNING_RESPONSE_PROCESSOR = new NlPlanningResponseProcessor();
4 changes: 2 additions & 2 deletions core/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,8 @@ export {LLMRegistry} from './models/registry.js';
export type {BaseLlmType} from './models/registry.js';
export {RoutedLlm} from './models/routed_llm.js';
export type {LlmRouter} from './models/routed_llm.js';
export {BasePlanner} from './planners/base_planner.js';
export {BuiltInPlanner} from './planners/built_in_planner.js';
export {BasePlanner, isBasePlanner} from './planners/base_planner.js';
export {BuiltInPlanner, isBuiltInPlanner} from './planners/built_in_planner.js';
export {PlanReActPlanner} from './planners/plan_re_act_planner.js';
export {
GLOBAL_SCOPE_KEY,
Expand Down
23 changes: 23 additions & 0 deletions core/src/planners/base_planner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,36 @@ import {Context} from '../agents/context.js';
import {ReadonlyContext} from '../agents/readonly_context.js';
import {LlmRequest} from '../models/llm_request.js';

/**
* A unique symbol to identify ADK planner classes.
* Defined once and shared by all BasePlanner instances.
*/
const BASE_PLANNER_SIGNATURE_SYMBOL = Symbol.for('google.adk.basePlanner');

/**
* Type guard to check if an object is an instance of BasePlanner.
* @param obj The object to check.
* @returns True if the object is an instance of BasePlanner, false otherwise.
*/
export function isBasePlanner(obj: unknown): obj is BasePlanner {
return (
typeof obj === 'object' &&
obj !== null &&
BASE_PLANNER_SIGNATURE_SYMBOL in obj &&
obj[BASE_PLANNER_SIGNATURE_SYMBOL] === true
);
}

/**
* Abstract base class for all planners.
*
* The planner allows the agent to generate plans for the queries to guide its
* action.
*/
export abstract class BasePlanner {
/** A unique symbol to identify ADK base planner class. */
readonly [BASE_PLANNER_SIGNATURE_SYMBOL] = true;

/**
* Builds the system instruction to be appended to the LLM request for
* planning.
Expand Down
26 changes: 26 additions & 0 deletions core/src/planners/built_in_planner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,36 @@ import {LlmRequest} from '../models/llm_request.js';

import {BasePlanner} from './base_planner.js';

/**
* A unique symbol to identify ADK built-in planner classes.
* Defined once and shared by all BuiltInPlanner instances.
*/
const BUILT_IN_PLANNER_SIGNATURE_SYMBOL = Symbol.for(
'google.adk.builtInPlanner',
);

/**
* Type guard to check if an object is an instance of BuiltInPlanner.
* @param obj The object to check.
* @returns True if the object is an instance of BuiltInPlanner, false
* otherwise.
*/
export function isBuiltInPlanner(obj: unknown): obj is BuiltInPlanner {
return (
typeof obj === 'object' &&
obj !== null &&
BUILT_IN_PLANNER_SIGNATURE_SYMBOL in obj &&
obj[BUILT_IN_PLANNER_SIGNATURE_SYMBOL] === true
);
}

/**
* The built-in planner that uses model's built-in thinking features.
*/
export class BuiltInPlanner extends BasePlanner {
/** A unique symbol to identify ADK built-in planner class. */
readonly [BUILT_IN_PLANNER_SIGNATURE_SYMBOL] = true;

/**
* Config for model built-in thinking features. An error will be returned if
* this field is set for models that don't support thinking.
Expand Down
Loading
Loading