본문 바로가기
WIKI 기술 지식 베이스

Plan-execute-reflect agents

원문 보기 위키 갱신

출처: 문서

본문

Plan-execute-reflect 에이전트

3.0에 도입됨 {: .label .label-purple }

Plan-execute-reflect 에이전트는 반복적인 추론과 단계별 실행이 필요한 복잡한 작업을 해결하도록 설계되었어요. 이 에이전트는 하나의 대규모 언어 모델(LLM)인 _planner_를 사용해 계획을 만들고 업데이트하고, 다른 LLM(기본값으로는 동일한 LLM)을 사용해 내장된 대화형 에이전트로 각 개별 단계를 실행해요.

Plan-execute-reflect 에이전트는 세 단계로 동작해요:

  • Planning – planner LLM이 사용 가능한 도구를 이용해 초기 단계별 계획을 생성해요.
  • Execution – 대화형 에이전트와 사용 가능한 도구를 사용해 각 단계를 순차적으로 실행해요.
  • Re-evaluation – 각 단계를 실행한 후 planner LLM이 중간 결과를 바탕으로 계획을 다시 평가해요. LLM은 새로운 컨텍스트에 따라 단계를 건너뛰거나, 추가하거나, 변경하도록 계획을 동적으로 조정할 수 있어요.

대화형 에이전트와 마찬가지로 plan-execute-reflect 에이전트는 LLM과 에이전트 간의 상호작용을 메모리 인덱스에 저장해요. 다음 예제에서 에이전트는 conversation_index를 사용해 사용자의 질문, 중간 결과, 최종 출력을 포함한 실행 기록을 유지해요.

에이전트는 도구 설명과 현재 컨텍스트를 바탕으로 각 단계에 가장 적합한 도구를 자동으로 선택해요.

에이전트는 각 단계가 끝난 후에만 재평가를 지원해요. 이를 통해 에이전트는 다음 단계로 진행하기 전에 중간 결과를 바탕으로 계획을 동적으로 조정할 수 있어요.

Plan-execute-reflect 에이전트 생성하기

다음 예제 요청은 세 개의 도구를 가진 plan-execute-reflect 에이전트를 생성해요:

POST /_plugins/_ml/agents/_register
{
  "name": "My Plan Execute Reflect Agent",
  "type": "plan_execute_and_reflect",
  "description": "Agent for dynamic task planning and reasoning",
  "llm": {
    "model_id": "YOUR_LLM_MODEL_ID",
    "parameters": {
      "prompt": "${parameters.question}"
    }
  },
  "memory": {
    "type": "conversation_index"
  },
  "parameters": {
    "_llm_interface": "YOUR_LLM_INTERFACE"
  },
  "tools": [
    { "type": "ListIndexTool" },
    { "type": "SearchIndexTool" },
    { "type": "IndexMappingTool" }
  ],
  "app_type": "os_chat"
}

LLM이 어떤 상황에서 해당 도구를 사용할지 판단할 수 있도록 도구에 대한 상세한 설명을 제공하는 것이 중요해요. {: .tip}

Register Agent API 요청 필드에 대한 자세한 내용은 요청 본문 필드를 참조하세요.

지원되는 LLM

Plan-execute-reflect 에이전트는 다음 LLM들을 위한 내장 function calling 인터페이스를 제공해요:

LLM에 대한 기본 지원을 요청하려면 ML Commons 저장소에 feature request 이슈를 생성하세요.

Plan-execute-reflect 에이전트 사용에 대한 단계별 튜토리얼은 plan-execute-reflect 에이전트 빌드하기를 참조하세요.

특정 모델로 plan-execute-reflect 에이전트를 구성하려면 Step 1(a): 커넥터 생성에서 커넥터를 수정하고, Step 2: 에이전트 생성에서 모델별 llm_interface 파라미터를 제공해야 해요:

"parameters": {
  "_llm_interface": "bedrock/converse/claude"
}

_llm_interface 필드의 유효한 값은 요청 본문 필드를 참조하세요.

다음 예제는 지원되는 모델들에 대한 커넥터 및 에이전트 생성 요청을 보여줘요.

Amazon Bedrock의 Anthropic Claude

Amazon Bedrock에서 호스팅되는 Anthropic Claude 3.7 Sonnet 모델용 커넥터를 생성하려면 다음 요청을 사용하세요:

POST /_plugins/_ml/connectors/_create
{
    "name": "Amazon Bedrock Claude 3.7-sonnet connector",
    "description": "Connector to Amazon Bedrock service for the Claude model",
    "version": 1,
    "protocol": "aws_sigv4",
    "parameters": {
      "region": "your_aws_region",
      "service_name": "bedrock",
      "model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0"
    },
    "credential": {
      "access_key": "your_aws_access_key",
      "secret_key": "your_aws_secret_key",
      "session_token": "your_aws_session_token"
    },
    "actions": [
      {
        "action_type": "predict",
        "method": "POST",
        "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse",
        "headers": {
          "content-type": "application/json"
        },
        "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.prompt}\"}]}${parameters._interactions:-}]${parameters.tool_configs:-} }"
      }
    ]
}

{% include copy-curl.html %}

Anthropic Claude 3.7 Sonnet 모델로 plan-execute-reflect 에이전트를 생성하려면 다음 요청을 사용하세요:

POST _plugins/_ml/agents/_register
{
  "name": "My Plan Execute and Reflect agent with Claude 3.7",
  "type": "plan_execute_and_reflect",
  "description": "this is a test agent",
  "llm": {
    "model_id": "your_llm_model_id",
    "parameters": {
      "prompt": "${parameters.question}"
  }},
  "memory": {
    "type": "conversation_index"
  },
  "parameters": {
    "_llm_interface": "bedrock/converse/claude"
  },
  "tools": [
    {
      "type": "ListIndexTool"
    },
    {
      "type": "SearchIndexTool"
    },
    {
      "type": "IndexMappingTool"
    }
  ]
}

{% include copy-curl.html %}

OpenAI GPT-4o

OpenAI GPT-4o 모델용 커넥터를 생성하려면 다음 요청을 사용하세요:

POST /_plugins/_ml/connectors/_create
{
    "name": "My openai connector: gpt-4o-mini",
    "description": "The connector to openai chat model",
    "version": 1,
    "protocol": "http",
    "parameters": {
        "model": "gpt-4o"
    },
    "credential": {
        "openAI_key": "your_open_ai_key"
    },
    "actions": [
        {
        "action_type": "predict",
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "headers": {
            "Authorization": "Bearer ${credential.openAI_key}"
        },
        "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\":\"developer\",\"content\":\"${parameters.system_prompt}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}${parameters._interactions:-}]${parameters.tool_configs:-} }"
        }
    ]
}

{% include copy-curl.html %}

그런 다음 모델을 등록하고 에이전트를 등록할 때 _llm_interface 필드에 openai/v1/chat/completions를 지정하세요.

Amazon Bedrock의 Deepseek-R1

Amazon Bedrock에서 호스팅되는 DeepSeek-R1 모델용 커넥터를 생성하려면 다음 요청을 사용하세요:

POST /_plugins/_ml/connectors/_create
{
    "name": "My DeepSeek R1 connector",
    "description": "my test connector",
    "version": 1,
    "protocol": "aws_sigv4",
    "parameters": {
        "region": "your_region",
        "service_name": "bedrock",
        "model": "us.deepseek.r1-v1:0"
    },
    "credential": {
        "access_key": "your_access_key",
        "secret_key": "your_secret_key",
        "session_token": "your_session_token"
    },
    "actions": [
        {
        "action_type": "predict",
        "method": "POST",
        "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse",
        "headers": {
            "content-type": "application/json"
        },
        "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.prompt}\"}]}${parameters._interactions:-}] }"
        }
    ]
}

{% include copy-curl.html %}

그런 다음 모델을 등록하고 에이전트를 등록할 때 _llm_interface 필드에 bedrock/converse/deepseek_r1을 지정하세요.

Amazon Bedrock에서 호스팅되는 Deepseek-R1 모델은 기본 function calling 지원이 없기 때문에, 에이전트 등록 시 다음 프롬프트를 executor_system_prompt로 제공하세요:

"You are a helpful assistant. You can ask Human to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n[${parameters._tools.toString()}]\n\nIf need to use tool, return which tool should be used and the input to user is enough. User will run the tool to get information. To make it easier for user to parse the response to know whether they should invoke a tool or not, please also return \"stop_reason\", it only return one of two enum values: [end_turn, tool_use], add a random tool call id to differenciate in case same tool invoked multiple times. Tool call id follow this pattern \"tool_use_<random string>\". The random string should be some UUID.\n\nFor example, you should return a json like this if need to use tool:\n{\"stop_reason\": \"tool_use\", \"tool_calls\": [{\"id\":\"tool_use_IIHBxMgOTjGb6ascCiOILg\",tool_name\":\"search_opensearch_index\",\"input\": {\"index\":\"population_data\",\"query\":{\"query\":{\"match\":{\"city\":\"New York City\"}}}}}]}\n\nIf don't need to use tool, return a json like this:\n{\"stop_reason\": \"end_turn\", \"message\": {\"role\":\"user\",\"content\":[{\"text\":\"What is the most popular song on WZPZ?\"}]}}\n\nNOTE: Don't wrap response in markdown ```json<response>```. For example don't return ```json\\n{\"stop_reason\": \"end_turn\", \"message\": {\"role\":\"user\",\"content\":[{\"text\":\"What is the most popular song on WZPZ?\"}]}}```\n"

{% include copy.html %}

에이전트 실행 및 메모리 추적

Agent Execute API를 사용해 plan-execute-reflect 에이전트를 비동기적으로 실행하면, 에이전트가 시작되는 즉시 API가 planner 에이전트의 memory_id와 parent_interaction_id를 반환해요.

최종 응답에서 API는 또한 계획의 각 단계를 수행하는 내부 executor 에이전트에 해당하는 executor_agent_memory_id와 executor_agent_parent_interaction_id를 반환해요. executor_agent_memory_id와 executor_agent_parent_interaction_id는 에이전트가 실행을 완료하기 전이라도 사용 가능해지는 즉시 task에서 업데이트돼요. 이를 통해 실행 과정을 실시간으로 추적할 수 있어요.

전체 예제는 plan-execute-reflect 에이전트 빌드하기를 참조하세요.

기본 프롬프트

Plan-execute-reflect 에이전트는 다음과 같은 사전 정의된 프롬프트를 사용해요. 다음 방법으로 새 프롬프트를 제공해 커스터마이즈할 수 있어요:

  • 에이전트 등록 시 parameters 객체에서
  • 에이전트 실행 중 동적으로

Planner 템플릿과 프롬프트

커스텀 planner 프롬프트 템플릿을 만들려면 planner_prompt_template 파라미터를 수정하세요. 다음 템플릿은 LLM에게 주어진 작업에 대한 계획을 수립하도록 요청하는 데 사용돼요:

${parameters.tools_prompt} \n${parameters.planner_prompt} \nObjective: ${parameters.user_prompt} \n\nRemember: Respond only in JSON format following the required schema.

커스텀 planner 프롬프트를 만들려면 planner_prompt 파라미터를 수정하세요. 다음 프롬프트는 LLM에게 주어진 작업에 대한 계획을 수립하도록 요청하는 데 사용돼요:

For the given objective, generate a step-by-step plan composed of simple, self-contained steps. The final step should directly yield the final answer. Avoid unnecessary steps.

히스토리 템플릿이 포함된 Planner 프롬프트

히스토리 템플릿이 포함된 커스텀 planner 프롬프트를 만들려면 planner_with_history_template 파라미터를 수정하세요. 다음 템플릿은 에이전트 실행 중 memory_id가 제공될 때 LLM에게 이전 작업에 대한 컨텍스트를 제공하는 데 사용돼요::

${parameters.tools_prompt} \n${parameters.planner_prompt} \nObjective: ```${parameters.user_prompt}``` \n\nYou have currently executed the following steps: \n[${parameters.completed_steps}] \n\nRemember: Respond only in JSON format following the required schema.

Reflection 프롬프트와 템플릿

커스텀 reflection 프롬프트 템플릿을 만들려면 reflect_prompt_template 파라미터를 수정하세요. 다음 템플릿은 LLM에게 완료된 단계를 바탕으로 원래 계획을 다시 생각하도록 요청하는 데 사용돼요:

${parameters.tools_prompt} \n${parameters.planner_prompt} \n\nObjective: ```${parameters.user_prompt}```\n\nOriginal plan:\n[${parameters.steps}] \n\nYou have currently executed the following steps from the original plan: \n[${parameters.completed_steps}] \n\n${parameters.reflect_prompt} \n\n.Remember: Respond only in JSON format following the required schema.

커스텀 reflection 프롬프트를 만들려면 reflect_prompt 파라미터를 수정하세요. 다음 프롬프트는 LLM에게 원래 계획을 다시 생각하도록 요청하는 데 사용돼요:

Update your plan based on the latest step results. If the task is complete, return the final answer. Otherwise, include only the remaining steps. Do not repeat previously completed steps.

Planner 시스템 프롬프트

커스텀 planner 시스템 프롬프트를 만들려면 system_prompt 파라미터를 수정하세요. 다음은 planner 시스템 프롬프트예요:

You are a thoughtful and analytical planner agent in a plan-execute-reflect framework. Your job is to design a clear, step-by-step plan for a given objective.

Instructions:
- Break the objective into an ordered list of atomic, self-contained Steps that, if executed, will lead to the final result or complete the objective.
- Each Step must state what to do, where, and which tool/parameters would be used. You do not execute tools, only reference them for planning.
- Use only the provided tools; do not invent or assume tools. If no suitable tool applies, use reasoning or observations instead.
- Base your plan only on the data and information explicitly provided; do not rely on unstated knowledge or external facts.
- If there is insufficient information to create a complete plan, summarize what is known so far and clearly state what additional information is required to proceed.
- Stop and summarize if the task is complete or further progress is unlikely.
- Avoid vague instructions; be specific about data sources, indexes, or parameters.
- Never make assumptions or rely on implicit knowledge.
- Respond only in JSON format.

Step examples:
Good example: "Use Tool to sample documents from index: 'my-index'"
Bad example: "Use Tool to sample documents from each index"
Bad example: "Use Tool to sample documents from all indices"
Response Instructions: 
Only respond in JSON format. Always follow the given response instructions. Do not return any content that does not follow the response instructions. Do not add anything before or after the expected JSON. 
Always respond with a valid JSON object that strictly follows the below schema:
{
	"steps": array[string], 
	"result": string 
}
Use "steps" to return an array of strings where each string is a step to complete the objective, leave it empty if you know the final result. Please wrap each step in quotes and escape any special characters within the string. 
Use "result" return the final response when you have enough information, leave it empty if you want to execute more steps. Please escape any special characters within the result. 
Here are examples of valid responses following the required JSON schema:

Example 1 - When you need to execute steps:
{
	"steps": ["This is an example step", "this is another example step"],
	"result": ""
}

Example 2 - When you have the final result:
{
	"steps": [],
	"result": "This is an example result\n with escaped special characters"
}
Important rules for the response:
1. Do not use commas within individual steps 
2. Do not add any content before or after the JSON 
3. Only respond with a pure JSON object 

When you deliver your final result, include a comprehensive report. This report must:
1. List every analysis or step you performed.
2. Summarize the inputs, methods, tools, and data used at each step.
3. Include key findings from all intermediate steps — do NOT omit them.
4. Clearly explain how the steps led to your final conclusion. Only mention the completed steps.
5. Return the full analysis and conclusion in the 'result' field, even if some of this was mentioned earlier. Ensure that special characters are escaped in the 'result' field.
6. The final response should be fully self-contained and detailed, allowing a user to understand the full investigation without needing to reference prior messages and steps.

응답 형식 지침은 수정하지 않는 것을 권장해요. 프롬프트를 수정하려는 경우 ${parameters.plan_execute_reflect_response_format} 파라미터를 사용해 응답 형식 지침을 주입할 수 있어요. {: .tip}

Executor 시스템 프롬프트

커스텀 executor 시스템 프롬프트를 만들려면 executor_system_prompt 파라미터를 수정하세요. 다음은 executor 시스템 프롬프트예요:

You are a precise and reliable executor agent in a plan-execute-reflect framework. Your job is to execute the given instruction provided by the planner and return a complete, actionable result.

Instructions:
- Fully execute the given Step using the most relevant tools or reasoning.
- Include all relevant raw tool outputs (e.g., full documents from searches) so the planner has complete information; do not summarize unless explicitly instructed.
- Base your execution and conclusions only on the data and tool outputs available; do not rely on unstated knowledge or external facts.
- If the available data is insufficient to complete the Step, summarize what was obtained so far and clearly state the additional information or access required to proceed (do not guess).
- If unable to complete the Step, clearly explain what went wrong and what is needed to proceed.
- Avoid making assumptions and relying on implicit knowledge.
- Your response must be self-contained and ready for the planner to use without modification. Never end with a question.
- Break complex searches into simpler queries when appropriate.

기본 프롬프트 수정하기

프롬프트를 수정하려면 에이전트 등록 시 프롬프트를 제공하세요:

POST _plugins/_ml/agents/_register
{
  "name": "My Plan Execute and Reflect agent with Claude 3.7",
  "type": "plan_execute_and_reflect",
  "description": "this is a test agent",
  "llm": {
    "model_id": "your_llm_model_id_from_step1",
    "parameters": {
      "prompt": "${parameters.question}"
  }},
  "memory": {
    "type": "conversation_index"
  },
  "parameters": {
    "_llm_interface": "bedrock/converse/claude",
    "planner_prompt_template": "your_planner_prompt_template",
    "planner_prompt": "your_planner_prompt",
    "reflect_prompt_template": "your_reflect_prompt_template",
    "reflect_prompt": "your_reflect_prompt",
    "planner_with_history_template": "your_planner_with_history_template",
    "system_prompt": "your_planner_system_prompt",
    "executor_system_prompt": "your_executor_system_prompt"
  },
  "tools": [
    {
      "type": "ListIndexTool"
    },
    {
      "type": "SearchIndexTool"
    },
    {
      "type": "IndexMappingTool"
    }
  ],
}

{% include copy-curl.html %}

에이전트 실행 중에도 프롬프트를 수정할 수 있어요:

POST _plugins/_ml/agents/your_agent_id/_execute?async=true
{
  "parameters": {
    "question": "How many flights from Beijing to Seattle?",
    "planner_prompt_template": "your_planner_prompt_template",
    "planner_prompt": "your_planner_prompt"
  }
}

{% include copy-curl.html %}

토큰 사용량 추적

3.6에 도입됨 {: .label .label-purple }

Plan-execute-reflect 에이전트는 토큰 사용량 추적을 지원해요. 이를 통해 에이전트 실행 중 planning, execution(서브 에이전트 사용), reflection LLM 호출 등 각 LLM 호출에서의 토큰 소비에 대한 상세 지표를 제공받을 수 있어요. 서브 에이전트의 토큰 데이터는 부모 에이전트의 토큰 사용량 보고서에 자동으로 병합돼요.

토큰 사용량 추적을 활성화하려면 에이전트 실행 시 include_token_usage 파라미터를 true로 설정하세요. 응답에는 턴별 및 모델별 집계 지표가 담긴 token_usage 출력이 포함돼요. 토큰 사용량 필드와 여러 모델 제공자가 토큰을 계산하는 방식에 대한 자세한 내용은 Execute Agent API 문서의 토큰 사용량 추적을 참조하세요.

다음 단계

더 알아보기 (Learn more)