From 8a25b278e75633fe38298b6314c799a7a5d9f6c3 Mon Sep 17 00:00:00 2001 From: Scott Mansfield Date: Thu, 24 Sep 2026 18:07:20 +0000 Subject: [PATCH] feat(planners): port BasePlanner, BuiltInPlanner and PlanReActPlanner ## Task Port the planners package of adk-python v0.1.0 (src/google/adk/planners: base_planner.py, built_in_planner.py, plan_re_act_planner.py) into adk-js as core/src/planners. This is a new capability. No planner code exists in adk-js today. Wiring a planner into LlmAgent and a planning request/response processor is NOT part of this task (see open_questions). Produced by Foundry (task c1351db8-b98b-4369-907a-0b6fee584dc8). Reviewed by an automated reviewer before upload; still needs human review. --- core/src/common.ts | 3 + core/src/planners/base_planner.ts | 46 +++ core/src/planners/built_in_planner.ts | 62 ++++ core/src/planners/plan_re_act_planner.ts | 211 +++++++++++++ core/test/planners/built_in_planner_test.ts | 95 ++++++ .../test/planners/plan_re_act_planner_test.ts | 293 ++++++++++++++++++ 6 files changed, 710 insertions(+) create mode 100644 core/src/planners/base_planner.ts create mode 100644 core/src/planners/built_in_planner.ts create mode 100644 core/src/planners/plan_re_act_planner.ts create mode 100644 core/test/planners/built_in_planner_test.ts create mode 100644 core/test/planners/plan_re_act_planner_test.ts diff --git a/core/src/common.ts b/core/src/common.ts index 1e980a1148..5a86d491a7 100644 --- a/core/src/common.ts +++ b/core/src/common.ts @@ -237,6 +237,9 @@ 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 {PlanReActPlanner} from './planners/plan_re_act_planner.js'; export { GLOBAL_SCOPE_KEY, REFLECT_AND_RETRY_RESPONSE_TYPE, diff --git a/core/src/planners/base_planner.ts b/core/src/planners/base_planner.ts new file mode 100644 index 0000000000..f68df01f05 --- /dev/null +++ b/core/src/planners/base_planner.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import {Part} from '@google/genai'; + +import {Context} from '../agents/context.js'; +import {ReadonlyContext} from '../agents/readonly_context.js'; +import {LlmRequest} from '../models/llm_request.js'; + +/** + * 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 { + /** + * Builds the system instruction to be appended to the LLM request for + * planning. + * + * @param readonlyContext The readonly context of the invocation. + * @param llmRequest The LLM request. Readonly. + * @returns The planning system instruction, or undefined if no instruction is + * needed. + */ + abstract buildPlanningInstruction( + readonlyContext: ReadonlyContext, + llmRequest: LlmRequest, + ): string | undefined; + + /** + * Processes the LLM response for planning. + * + * @param callbackContext The callback context of the invocation. + * @param responseParts The LLM response parts. Readonly. + * @returns The processed response parts, or undefined if no processing is + * needed. + */ + abstract processPlanningResponse( + callbackContext: Context, + responseParts: Part[], + ): Part[] | undefined; +} diff --git a/core/src/planners/built_in_planner.ts b/core/src/planners/built_in_planner.ts new file mode 100644 index 0000000000..6699404f04 --- /dev/null +++ b/core/src/planners/built_in_planner.ts @@ -0,0 +1,62 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import {Part, ThinkingConfig} from '@google/genai'; + +import {Context} from '../agents/context.js'; +import {ReadonlyContext} from '../agents/readonly_context.js'; +import {LlmRequest} from '../models/llm_request.js'; + +import {BasePlanner} from './base_planner.js'; + +/** + * The built-in planner that uses model's built-in thinking features. + */ +export class BuiltInPlanner extends BasePlanner { + /** + * Config for model built-in thinking features. An error will be returned if + * this field is set for models that don't support thinking. + */ + thinkingConfig: ThinkingConfig; + + /** + * Initializes the built-in planner. + * + * @param options.thinkingConfig Config for model built-in thinking features. + * An error will be returned if this field is set for models that don't + * support thinking. + */ + constructor(options: {thinkingConfig: ThinkingConfig}) { + super(); + this.thinkingConfig = options.thinkingConfig; + } + + /** + * Applies the thinking config to the LLM request. + * + * @param llmRequest The LLM request to apply the thinking config to. + */ + applyThinkingConfig(llmRequest: LlmRequest): void { + if (this.thinkingConfig) { + llmRequest.config = llmRequest.config ?? {}; + llmRequest.config.thinkingConfig = this.thinkingConfig; + } + } + + buildPlanningInstruction( + _readonlyContext: ReadonlyContext, + _llmRequest: LlmRequest, + ): string | undefined { + return undefined; + } + + processPlanningResponse( + _callbackContext: Context, + _responseParts: Part[], + ): Part[] | undefined { + return undefined; + } +} diff --git a/core/src/planners/plan_re_act_planner.ts b/core/src/planners/plan_re_act_planner.ts new file mode 100644 index 0000000000..64fd0bcf32 --- /dev/null +++ b/core/src/planners/plan_re_act_planner.ts @@ -0,0 +1,211 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import {Part} from '@google/genai'; + +import {Context} from '../agents/context.js'; +import {ReadonlyContext} from '../agents/readonly_context.js'; +import {LlmRequest} from '../models/llm_request.js'; + +import {BasePlanner} from './base_planner.js'; + +const PLANNING_TAG = '/*PLANNING*/'; +const REPLANNING_TAG = '/*REPLANNING*/'; +const REASONING_TAG = '/*REASONING*/'; +const ACTION_TAG = '/*ACTION*/'; +const FINAL_ANSWER_TAG = '/*FINAL_ANSWER*/'; + +const THOUGHT_PREFIX_TAGS: readonly string[] = [ + PLANNING_TAG, + REASONING_TAG, + ACTION_TAG, + REPLANNING_TAG, +]; + +/** + * Plan-Re-Act planner that constrains the LLM response to generate a plan + * before any action/observation. + * + * Note: this planner does not require the model to support built-in thinking + * features or setting the thinking config. + */ +export class PlanReActPlanner extends BasePlanner { + buildPlanningInstruction( + _readonlyContext: ReadonlyContext, + _llmRequest: LlmRequest, + ): string { + return buildNlPlannerInstruction(); + } + + processPlanningResponse( + _callbackContext: Context, + responseParts: Part[], + ): Part[] | undefined { + if (!responseParts || responseParts.length === 0) { + return undefined; + } + + const preservedParts: Part[] = []; + let firstFcPartIndex = -1; + for (let i = 0; i < responseParts.length; i++) { + const part = responseParts[i]; + // Stop at the first (group of) function calls. + if (part.functionCall) { + // Ignore and filter out function calls with empty names. + if (!part.functionCall.name) { + continue; + } + preservedParts.push(part); + firstFcPartIndex = i; + break; + } + + handleNonFunctionCallPart(part, preservedParts); + } + + if (firstFcPartIndex > 0) { + for (let j = firstFcPartIndex + 1; j < responseParts.length; j++) { + if (!responseParts[j].functionCall) { + break; + } + preservedParts.push(responseParts[j]); + } + } + + return preservedParts; + } +} + +/** + * Splits the text by the last occurrence of the separator. + * + * @param text The text to split. + * @param separator The separator to split on. + * @returns The text up to and including the last separator, and the text after + * the last separator. + */ +function splitByLastPattern(text: string, separator: string): [string, string] { + const index = text.lastIndexOf(separator); + if (index === -1) { + return [text, '']; + } + const end = index + separator.length; + return [text.slice(0, end), text.slice(end)]; +} + +/** + * Handles a non-function-call part of the response. + * + * @param responsePart The response part to handle. It is not modified. + * @param preservedParts The list to append the processed parts to. + */ +function handleNonFunctionCallPart( + responsePart: Part, + preservedParts: Part[], +): void { + if (responsePart.text && responsePart.text.includes(FINAL_ANSWER_TAG)) { + const [reasoningText, finalAnswerText] = splitByLastPattern( + responsePart.text, + FINAL_ANSWER_TAG, + ); + if (reasoningText) { + preservedParts.push(markAsThought({text: reasoningText})); + } + if (finalAnswerText) { + preservedParts.push({text: finalAnswerText}); + } + return; + } + + const responseText = responsePart.text ?? ''; + // A text part that starts with a planning/reasoning/action tag is reasoning. + if ( + responseText && + THOUGHT_PREFIX_TAGS.some((tag) => responseText.startsWith(tag)) + ) { + preservedParts.push(markAsThought(responsePart)); + return; + } + preservedParts.push(responsePart); +} + +/** + * Returns a copy of the response part marked as thought, if it has text. + * + * The response parts are read-only, so the part is copied rather than changed + * in place. + * + * @param responsePart The response part to mark as thought. + * @returns The marked copy, or the original part if it has no text. + */ +function markAsThought(responsePart: Part): Part { + if (responsePart.text) { + return {...responsePart, thought: true}; + } + return responsePart; +} + +/** + * Builds the NL planner instruction for the Plan-Re-Act planner. + * + * The wording is part of the planner's behaviour and matches the Python ADK + * text exactly. + * + * @returns NL planner system instruction. + */ +function buildNlPlannerInstruction(): string { + const highLevelPreamble = ` +When answering the question, try to leverage the available tools to gather the information instead of your memorized knowledge. + +Follow this process when answering the question: (1) first come up with a plan in natural language text format; (2) Then use tools to execute the plan and provide reasoning between tool code snippets to make a summary of current state and next step. Tool code snippets and reasoning should be interleaved with each other. (3) In the end, return one final answer. + +Follow this format when answering the question: (1) The planning part should be under ${PLANNING_TAG}. (2) The tool code snippets should be under ${ACTION_TAG}, and the reasoning parts should be under ${REASONING_TAG}. (3) The final answer part should be under ${FINAL_ANSWER_TAG}. +`; + + const planningPreamble = ` +Below are the requirements for the planning: +The plan is made to answer the user query if following the plan. The plan is coherent and covers all aspects of information from user query, and only involves the tools that are accessible by the agent. The plan contains the decomposed steps as a numbered list where each step should use one or multiple available tools. By reading the plan, you can intuitively know which tools to trigger or what actions to take. +If the initial plan cannot be successfully executed, you should learn from previous execution results and revise your plan. The revised plan should be be under ${REPLANNING_TAG}. Then use tools to follow the new plan. +`; + + const reasoningPreamble = ` +Below are the requirements for the reasoning: +The reasoning makes a summary of the current trajectory based on the user query and tool outputs. Based on the tool outputs and plan, the reasoning also comes up with instructions to the next steps, making the trajectory closer to the final answer. +`; + + const finalAnswerPreamble = ` +Below are the requirements for the final answer: +The final answer should be precise and follow query formatting requirements. Some queries may not be answerable with the available tools and information. In those cases, inform the user why you cannot process their query and ask for more information. +`; + + // Only contains the requirements for custom tool/libraries. + const toolCodeWithoutPythonLibrariesPreamble = ` +Below are the requirements for the tool code: + +**Custom Tools:** The available tools are described in the context and can be directly used. +- Code must be valid self-contained Python snippets with no imports and no references to tools or Python libraries that are not in the context. +- You cannot use any parameters or fields that are not explicitly defined in the APIs in the context. +- The code snippets should be readable, efficient, and directly relevant to the user query and reasoning steps. +- When using the tools, you should use the library name together with the function name, e.g., vertex_search.search(). +- If Python libraries are not provided in the context, NEVER write your own code other than the function calls using the provided tools. +`; + + const userInputPreamble = ` +VERY IMPORTANT instruction that you MUST follow in addition to the above instructions: + +You should ask for clarification if you need more information to answer the question. +You should prefer using the information available in the context instead of repeated tool use. +`; + + return [ + highLevelPreamble, + planningPreamble, + reasoningPreamble, + finalAnswerPreamble, + toolCodeWithoutPythonLibrariesPreamble, + userInputPreamble, + ].join('\n\n'); +} diff --git a/core/test/planners/built_in_planner_test.ts b/core/test/planners/built_in_planner_test.ts new file mode 100644 index 0000000000..ea3f465e02 --- /dev/null +++ b/core/test/planners/built_in_planner_test.ts @@ -0,0 +1,95 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + BuiltInPlanner, + Context, + createSession, + InvocationContext, + LlmAgent, + LlmRequest, + PluginManager, + ReadonlyContext, +} from '@google/adk'; +import {describe, expect, it} from 'vitest'; + +function makeInvocationContext(): InvocationContext { + return new InvocationContext({ + invocationId: 'inv-1', + agent: new LlmAgent({name: 'test_agent'}), + session: createSession({id: 'session-1', appName: 'test-app'}), + pluginManager: new PluginManager(), + }); +} + +function makeLlmRequest(overrides: Partial = {}): LlmRequest { + return {contents: [], toolsDict: {}, liveConnectConfig: {}, ...overrides}; +} + +describe('BuiltInPlanner', () => { + it('stores the thinking config passed to the constructor', () => { + const thinkingConfig = {includeThoughts: true, thinkingBudget: 1024}; + const planner = new BuiltInPlanner({thinkingConfig}); + + expect(planner.thinkingConfig).toBe(thinkingConfig); + }); + + it('creates the request config when it is absent', () => { + const thinkingConfig = {includeThoughts: true}; + const planner = new BuiltInPlanner({thinkingConfig}); + const llmRequest = makeLlmRequest(); + + planner.applyThinkingConfig(llmRequest); + + expect(llmRequest.config).toEqual({thinkingConfig}); + }); + + it('keeps the other config fields', () => { + const thinkingConfig = {thinkingBudget: 512}; + const planner = new BuiltInPlanner({thinkingConfig}); + const llmRequest = makeLlmRequest({ + config: {temperature: 0.5, systemInstruction: 'Be brief.'}, + }); + + planner.applyThinkingConfig(llmRequest); + + expect(llmRequest.config).toEqual({ + temperature: 0.5, + systemInstruction: 'Be brief.', + thinkingConfig, + }); + }); + + it('overwrites an existing thinking config', () => { + const thinkingConfig = {thinkingBudget: 2048}; + const planner = new BuiltInPlanner({thinkingConfig}); + const llmRequest = makeLlmRequest({ + config: {thinkingConfig: {includeThoughts: true, thinkingBudget: 0}}, + }); + + planner.applyThinkingConfig(llmRequest); + + expect(llmRequest.config?.thinkingConfig).toBe(thinkingConfig); + }); + + it('returns no planning instruction', () => { + const planner = new BuiltInPlanner({thinkingConfig: {}}); + const readonlyContext = new ReadonlyContext(makeInvocationContext()); + + expect( + planner.buildPlanningInstruction(readonlyContext, makeLlmRequest()), + ).toBeUndefined(); + }); + + it('does not process the planning response', () => { + const planner = new BuiltInPlanner({thinkingConfig: {}}); + const context = new Context({invocationContext: makeInvocationContext()}); + + expect( + planner.processPlanningResponse(context, [{text: 'hello'}]), + ).toBeUndefined(); + }); +}); diff --git a/core/test/planners/plan_re_act_planner_test.ts b/core/test/planners/plan_re_act_planner_test.ts new file mode 100644 index 0000000000..da4df9b938 --- /dev/null +++ b/core/test/planners/plan_re_act_planner_test.ts @@ -0,0 +1,293 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + Context, + createSession, + InvocationContext, + LlmAgent, + LlmRequest, + PlanReActPlanner, + PluginManager, + ReadonlyContext, +} from '@google/adk'; +import {Part} from '@google/genai'; +import {describe, expect, it} from 'vitest'; + +function makeInvocationContext(): InvocationContext { + return new InvocationContext({ + invocationId: 'inv-1', + agent: new LlmAgent({name: 'test_agent'}), + session: createSession({id: 'session-1', appName: 'test-app'}), + pluginManager: new PluginManager(), + }); +} + +function makeContext(): Context { + return new Context({invocationContext: makeInvocationContext()}); +} + +function functionCallPart(name: string): Part { + return {functionCall: {name, args: {}}}; +} + +// The planner instruction from the Python ADK, one array entry per line. The +// wording is the planner's behaviour, so the test pins every character. +const EXPECTED_INSTRUCTION = [ + '', + 'When answering the question, try to leverage the available tools to gather the information instead of your memorized knowledge.', + '', + 'Follow this process when answering the question: (1) first come up with a plan in natural language text format; (2) Then use tools to execute the plan and provide reasoning between tool code snippets to make a summary of current state and next step. Tool code snippets and reasoning should be interleaved with each other. (3) In the end, return one final answer.', + '', + 'Follow this format when answering the question: (1) The planning part should be under /*PLANNING*/. (2) The tool code snippets should be under /*ACTION*/, and the reasoning parts should be under /*REASONING*/. (3) The final answer part should be under /*FINAL_ANSWER*/.', + '', + '', + '', + 'Below are the requirements for the planning:', + 'The plan is made to answer the user query if following the plan. The plan is coherent and covers all aspects of information from user query, and only involves the tools that are accessible by the agent. The plan contains the decomposed steps as a numbered list where each step should use one or multiple available tools. By reading the plan, you can intuitively know which tools to trigger or what actions to take.', + 'If the initial plan cannot be successfully executed, you should learn from previous execution results and revise your plan. The revised plan should be be under /*REPLANNING*/. Then use tools to follow the new plan.', + '', + '', + '', + 'Below are the requirements for the reasoning:', + 'The reasoning makes a summary of the current trajectory based on the user query and tool outputs. Based on the tool outputs and plan, the reasoning also comes up with instructions to the next steps, making the trajectory closer to the final answer.', + '', + '', + '', + 'Below are the requirements for the final answer:', + 'The final answer should be precise and follow query formatting requirements. Some queries may not be answerable with the available tools and information. In those cases, inform the user why you cannot process their query and ask for more information.', + '', + '', + '', + 'Below are the requirements for the tool code:', + '', + '**Custom Tools:** The available tools are described in the context and can be directly used.', + '- Code must be valid self-contained Python snippets with no imports and no references to tools or Python libraries that are not in the context.', + '- You cannot use any parameters or fields that are not explicitly defined in the APIs in the context.', + '- The code snippets should be readable, efficient, and directly relevant to the user query and reasoning steps.', + '- When using the tools, you should use the library name together with the function name, e.g., vertex_search.search().', + '- If Python libraries are not provided in the context, NEVER write your own code other than the function calls using the provided tools.', + '', + '', + '', + 'VERY IMPORTANT instruction that you MUST follow in addition to the above instructions:', + '', + 'You should ask for clarification if you need more information to answer the question.', + 'You should prefer using the information available in the context instead of repeated tool use.', + '', +].join('\n'); + +describe('PlanReActPlanner', () => { + describe('processPlanningResponse', () => { + it('returns undefined for empty response parts', () => { + const planner = new PlanReActPlanner(); + + expect( + planner.processPlanningResponse(makeContext(), []), + ).toBeUndefined(); + }); + + it('passes text-only parts through unchanged', () => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [{text: 'first'}, {text: 'second'}]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + {text: 'first'}, + {text: 'second'}, + ]); + }); + + it('drops the parts after the first function call', () => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [ + {text: 'intro'}, + functionCallPart('tool_a'), + {text: 'after call'}, + functionCallPart('tool_b'), + ]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + {text: 'intro'}, + functionCallPart('tool_a'), + ]); + }); + + it('keeps consecutive function calls after a leading text part', () => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [ + {text: 'intro'}, + functionCallPart('tool_a'), + functionCallPart('tool_b'), + functionCallPart('tool_c'), + {text: 'after calls'}, + functionCallPart('tool_d'), + ]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + {text: 'intro'}, + functionCallPart('tool_a'), + functionCallPart('tool_b'), + functionCallPart('tool_c'), + ]); + }); + + it('keeps only the first call when the response starts with a call', () => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [ + functionCallPart('tool_a'), + functionCallPart('tool_b'), + ]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + functionCallPart('tool_a'), + ]); + }); + + it('skips a function call with an empty name', () => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [ + {text: 'intro'}, + functionCallPart(''), + {text: 'more'}, + functionCallPart('tool_a'), + ]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + {text: 'intro'}, + {text: 'more'}, + functionCallPart('tool_a'), + ]); + }); + + it('splits a final answer part into a thought and an answer', () => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [ + {text: '/*REASONING*/All done./*FINAL_ANSWER*/The answer is 42.'}, + ]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + {text: '/*REASONING*/All done./*FINAL_ANSWER*/', thought: true}, + {text: 'The answer is 42.'}, + ]); + }); + + it('splits at the last final answer tag', () => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [{text: 'a/*FINAL_ANSWER*/b/*FINAL_ANSWER*/c'}]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + {text: 'a/*FINAL_ANSWER*/b/*FINAL_ANSWER*/', thought: true}, + {text: 'c'}, + ]); + }); + + it('keeps only the reasoning part when the final answer tag ends the text', () => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [{text: 'thinking/*FINAL_ANSWER*/'}]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + {text: 'thinking/*FINAL_ANSWER*/', thought: true}, + ]); + }); + + it.each(['/*PLANNING*/', '/*REASONING*/', '/*ACTION*/', '/*REPLANNING*/'])( + 'marks a part starting with %s as a thought', + (tag) => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [{text: `${tag} step one`}]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + {text: `${tag} step one`, thought: true}, + ]); + }, + ); + + it('does not mark a part whose tag is not at the start', () => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [{text: ' /*PLANNING*/ step one'}]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + {text: ' /*PLANNING*/ step one'}, + ]); + }); + + it('does not mark the answer after a leading final answer tag', () => { + const planner = new PlanReActPlanner(); + const parts: Part[] = [{text: '/*FINAL_ANSWER*/The answer.'}]; + + expect(planner.processPlanningResponse(makeContext(), parts)).toEqual([ + {text: '/*FINAL_ANSWER*/', thought: true}, + {text: 'The answer.'}, + ]); + }); + + it('does not mutate the input parts', () => { + const planner = new PlanReActPlanner(); + const planningPart: Part = {text: '/*PLANNING*/ plan'}; + const answerPart: Part = {text: 'why/*FINAL_ANSWER*/what'}; + + const result = planner.processPlanningResponse(makeContext(), [ + planningPart, + answerPart, + ]); + + expect(planningPart).toEqual({text: '/*PLANNING*/ plan'}); + expect(answerPart).toEqual({text: 'why/*FINAL_ANSWER*/what'}); + expect(result?.[0]).not.toBe(planningPart); + expect(result?.[0]).toEqual({text: '/*PLANNING*/ plan', thought: true}); + }); + }); + + describe('buildPlanningInstruction', () => { + it('returns the instruction text verbatim', () => { + const planner = new PlanReActPlanner(); + const readonlyContext = new ReadonlyContext(makeInvocationContext()); + const llmRequest: LlmRequest = { + contents: [], + toolsDict: {}, + liveConnectConfig: {}, + }; + + expect( + planner.buildPlanningInstruction(readonlyContext, llmRequest), + ).toBe(EXPECTED_INSTRUCTION); + }); + + it('contains all five tags and ignores its arguments', () => { + const planner = new PlanReActPlanner(); + const readonlyContext = new ReadonlyContext(makeInvocationContext()); + const emptyRequest: LlmRequest = { + contents: [], + toolsDict: {}, + liveConnectConfig: {}, + }; + const otherRequest: LlmRequest = { + model: 'gemini-2.5-flash', + contents: [{role: 'user', parts: [{text: 'hi'}]}], + toolsDict: {}, + liveConnectConfig: {}, + }; + + const instruction = planner.buildPlanningInstruction( + readonlyContext, + emptyRequest, + ); + + for (const tag of [ + '/*PLANNING*/', + '/*REPLANNING*/', + '/*REASONING*/', + '/*ACTION*/', + '/*FINAL_ANSWER*/', + ]) { + expect(instruction).toContain(tag); + } + expect( + planner.buildPlanningInstruction(readonlyContext, otherRequest), + ).toBe(instruction); + }); + }); +});