planexecute

package
v0.7.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 16, 2026 License: Apache-2.0 Imports: 12 Imported by: 2

Documentation

Overview

Package planexecute implements a plan–execute–replan style agent.

Index

Constants

View Source
const (
	// UserInputSessionKey is the session key for the user input.
	UserInputSessionKey = "UserInput"

	// PlanSessionKey is the session key for the plan.
	PlanSessionKey = "Plan"

	// ExecutedStepSessionKey is the session key for the execute result.
	ExecutedStepSessionKey = "ExecutedStep"

	// ExecutedStepsSessionKey is the session key for the execute results.
	ExecutedStepsSessionKey = "ExecutedSteps"
)

Variables

View Source
var (
	// PlanToolInfo defines the schema for the Plan tool that can be used with ToolCallingChatModel.
	// This schema instructs the model to generate a structured plan with ordered steps.
	PlanToolInfo = schema.ToolInfo{
		Name: "plan",
		Desc: "Plan with a list of steps to execute in order. Each step should be clear, actionable, and arranged in a logical sequence. The output will be used to guide the execution process.",
		ParamsOneOf: schema.NewParamsOneOfByParams(
			map[string]*schema.ParameterInfo{
				"steps": {
					Type:     schema.Array,
					ElemInfo: &schema.ParameterInfo{Type: schema.String},
					Desc:     "different steps to follow, should be in sorted order",
					Required: true,
				},
			},
		),
	}

	// RespondToolInfo defines the schema for the response tool that can be used with ToolCallingChatModel.
	// This schema instructs the model to generate a direct response to the user.
	RespondToolInfo = schema.ToolInfo{
		Name: "respond",
		Desc: "Generate a direct response to the user. Use this tool when you have all the information needed to provide a final answer.",
		ParamsOneOf: schema.NewParamsOneOfByParams(
			map[string]*schema.ParameterInfo{
				"response": {
					Type:     schema.String,
					Desc:     "The complete response to provide to the user",
					Required: true,
				},
			},
		),
	}

	// PlannerPrompt is the prompt template for the planner.
	// It provides context and guidance to the planner on how to generate the Plan.
	PlannerPrompt = prompt.FromMessages(schema.FString,
		schema.SystemMessage(`You are an expert planning agent. Given an objective, create a comprehensive step-by-step plan to achieve the objective.

## YOUR TASK
Analyze the objective and generate a strategic plan that breaks down the goal into manageable, executable steps.

## PLANNING REQUIREMENTS
Each step in your plan must be:
- **Specific and actionable**: Clear instructions that can be executed without ambiguity
- **Self-contained**: Include all necessary context, parameters, and requirements
- **Independently executable**: Can be performed by an agent without dependencies on other steps
- **Logically sequenced**: Arranged in optimal order for efficient execution
- **Objective-focused**: Directly contribute to achieving the main goal

## PLANNING GUIDELINES
- Eliminate redundant or unnecessary steps
- Include relevant constraints, parameters, and success criteria for each step
- Ensure the final step produces a complete answer or deliverable
- Anticipate potential challenges and include mitigation strategies
- Structure steps to build upon each other logically
- Provide sufficient detail for successful execution

## QUALITY CRITERIA
- Plan completeness: Does it address all aspects of the objective?
- Step clarity: Can each step be understood and executed independently?
- Logical flow: Do steps follow a sensible progression?
- Efficiency: Is this the most direct path to the objective?
- Adaptability: Can the plan handle unexpected results or changes?`),
		schema.MessagesPlaceholder("input", false),
	)

	// ExecutorPrompt is the prompt template for the executor.
	// It provides context and guidance to the executor on how to execute the Task.
	ExecutorPrompt = prompt.FromMessages(schema.FString,
		schema.SystemMessage(`You are a diligent and meticulous executor agent. Follow the given plan and execute your tasks carefully and thoroughly.`),
		schema.UserMessage(`## OBJECTIVE
{input}
## Given the following plan:
{plan}
## COMPLETED STEPS & RESULTS
{executed_steps}
## Your task is to execute the first step, which is: 
{step}`))

	// ReplannerPrompt is the prompt template for the replanner.
	// It provides context and guidance to the replanner on how to regenerate the Plan.
	ReplannerPrompt = prompt.FromMessages(schema.FString,
		schema.SystemMessage(
			`You are going to review the progress toward an objective. Analyze the current state and determine the optimal next action.

## YOUR TASK
Based on the progress above, you MUST choose exactly ONE action:

### Option 1: COMPLETE (if objective is fully achieved)
Call '{respond_tool}' with:
- A comprehensive final answer
- Clear conclusion summarizing how the objective was met
- Key insights from the execution process

### Option 2: CONTINUE (if more work is needed)
Call '{plan_tool}' with a revised plan that:
- Contains ONLY remaining steps (exclude completed ones)
- Incorporates lessons learned from executed steps
- Addresses any gaps or issues discovered
- Maintains logical step sequence

## PLANNING REQUIREMENTS
Each step in your plan must be:
- **Specific and actionable**: Clear instructions that can be executed without ambiguity
- **Self-contained**: Include all necessary context, parameters, and requirements
- **Independently executable**: Can be performed by an agent without dependencies on other steps
- **Logically sequenced**: Arranged in optimal order for efficient execution
- **Objective-focused**: Directly contribute to achieving the main goal

## PLANNING GUIDELINES
- Eliminate redundant or unnecessary steps
- Adapt strategy based on new information
- Include relevant constraints, parameters, and success criteria for each step

## DECISION CRITERIA
- Has the original objective been completely satisfied?
- Are there any remaining requirements or sub-goals?
- Do the results suggest a need for strategy adjustment?
- What specific actions are still required?`),
		schema.UserMessage(`## OBJECTIVE
{input}

## ORIGINAL PLAN
{plan}

## COMPLETED STEPS & RESULTS
{executed_steps}`),
	)
)

Functions

func New

func New(ctx context.Context, cfg *Config) (adk.ResumableAgent, error)

New creates a new plan-execute-replan agent with the given configuration. The plan-execute-replan pattern works in three phases: 1. Planning: Generate a structured plan with clear, actionable steps 2. Execution: Execute the first step of the plan 3. Replanning: Evaluate progress and either complete the task or revise the plan This approach enables complex problem-solving through iterative refinement.

func NewExecutor

func NewExecutor(ctx context.Context, cfg *ExecutorConfig) (adk.Agent, error)

NewExecutor creates a new executor agent.

func NewPlanner

func NewPlanner(_ context.Context, cfg *PlannerConfig) (adk.Agent, error)

NewPlanner creates a new planner agent based on the provided configuration. The planner agent uses either ChatModelWithFormattedOutput or ToolCallingChatModel+ToolInfo to generate structured Plan output.

If ChatModelWithFormattedOutput is provided, it will be used directly. If ToolCallingChatModel is provided, it will be configured with ToolInfo (or PlanToolInfo by default) to generate structured Plan output.

func NewReplanner

func NewReplanner(_ context.Context, cfg *ReplannerConfig) (adk.Agent, error)

NewReplanner creates a plan-execute-replan agent wired with plan and respond tools. It configures the provided ToolCallingChatModel with the tools and returns an Agent.

Types

type Config

type Config struct {
	// Planner specifies the agent that generates the plan.
	// You can use provided NewPlanner to create a planner agent.
	Planner adk.Agent

	// Executor specifies the agent that executes the plan generated by planner or replanner.
	// You can use provided NewExecutor to create an executor agent.
	Executor adk.Agent

	// Replanner specifies the agent that replans the plan.
	// You can use provided NewReplanner to create a replanner agent.
	Replanner adk.Agent

	// MaxIterations defines the maximum number of loops for 'execute-replan'.
	// Optional. If not provided, 10 will be used as the default.
	MaxIterations int
}

Config provides configuration options for creating a plan-execute-replan agent.

type ExecutedStep

type ExecutedStep struct {
	Step   string
	Result string
}

type ExecutionContext

type ExecutionContext struct {
	UserInput     []adk.Message
	Plan          Plan
	ExecutedSteps []ExecutedStep
}

ExecutionContext is the input information for the executor and the planner.

type ExecutorConfig

type ExecutorConfig struct {
	// Model is the chat model used by the executor.
	Model model.ToolCallingChatModel

	// ToolsConfig specifies the tools available to the executor.
	ToolsConfig adk.ToolsConfig

	// MaxIterations defines the upper limit of ChatModel generation cycles.
	// The agent will terminate with an error if this limit is exceeded.
	// Optional. Defaults to 20.
	MaxIterations int

	// GenInputFn generates the input messages for the Executor.
	// Optional. If not provided, defaultGenExecutorInputFn will be used.
	GenInputFn GenModelInputFn
}

ExecutorConfig provides configuration options for creating an executor agent.

type GenModelInputFn

type GenModelInputFn func(ctx context.Context, in *ExecutionContext) ([]adk.Message, error)

GenModelInputFn is a function that generates the input messages for the executor and the planner.

type GenPlannerModelInputFn

type GenPlannerModelInputFn func(ctx context.Context, userInput []adk.Message) ([]adk.Message, error)

GenPlannerModelInputFn is a function type that generates input messages for the planner.

type NewPlan

type NewPlan func(ctx context.Context) Plan

NewPlan is a function type that creates a new Plan instance.

type Plan

type Plan interface {
	// FirstStep returns the first step to be executed in the plan.
	FirstStep() string

	// Marshaler serializes the Plan into JSON.
	// The resulting JSON can be used in prompt templates.
	json.Marshaler
	// Unmarshaler deserializes JSON content into the Plan.
	// This processes output from structured chat models or tool calls into the Plan structure.
	json.Unmarshaler
}

Plan represents an execution plan with a sequence of actionable steps. It supports JSON serialization and deserialization while providing access to the first step.

type PlannerConfig

type PlannerConfig struct {
	// ChatModelWithFormattedOutput is a model pre-configured to output in the Plan format.
	// Create this by configuring a model to output structured data directly.
	// See example: https://github.com/cloudwego/eino-ext/blob/main/components/model/openai/examples/structured/structured.go
	ChatModelWithFormattedOutput model.BaseChatModel

	// ToolCallingChatModel is a model that supports tool calling capabilities.
	// When provided with ToolInfo, it will use tool calling to generate the Plan structure.
	ToolCallingChatModel model.ToolCallingChatModel

	// ToolInfo defines the schema for the Plan structure when using tool calling.
	// Optional. If not provided, PlanToolInfo will be used as the default.
	ToolInfo *schema.ToolInfo

	// GenInputFn is a function that generates the input messages for the planner.
	// Optional. If not provided, defaultGenPlannerInputFn will be used.
	GenInputFn GenPlannerModelInputFn

	// NewPlan creates a new Plan instance for JSON.
	// The returned Plan will be used to unmarshal the model-generated JSON output.
	// Optional. If not provided, defaultNewPlan will be used.
	NewPlan NewPlan
}

PlannerConfig provides configuration options for creating a planner agent. There are two ways to configure the planner to generate structured Plan output:

  1. Use ChatModelWithFormattedOutput: A model pre-configured to output in the Plan format
  2. Use ToolCallingChatModel + ToolInfo: A model that uses tool calling to generate the Plan structure

type ReplannerConfig

type ReplannerConfig struct {
	// ChatModel is the model that supports tool calling capabilities.
	// It will be configured with PlanTool and RespondTool to generate updated plans or responses.
	ChatModel model.ToolCallingChatModel

	// PlanTool defines the schema for the Plan tool that can be used with ToolCallingChatModel.
	// Optional. If not provided, the default PlanToolInfo will be used.
	PlanTool *schema.ToolInfo

	// RespondTool defines the schema for the response tool that can be used with ToolCallingChatModel.
	// Optional. If not provided, the default RespondToolInfo will be used.
	RespondTool *schema.ToolInfo

	// GenInputFn generates the input messages for the Replanner.
	// Optional. If not provided, buildGenReplannerInputFn will be used.
	GenInputFn GenModelInputFn

	// NewPlan creates a new Plan instance.
	// The returned Plan will be used to unmarshal the model-generated JSON output from PlanTool.
	// Optional. If not provided, defaultNewPlan will be used.
	NewPlan NewPlan
}

type Response

type Response struct {
	// Response is the complete response to provide to the user.
	// This field is required.
	Response string `json:"response"`
}

Response represents the final response to the user. This struct is used for JSON serialization/deserialization of the final response generated by the model.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL