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

Scratchpad tools

원문 보기 위키 갱신

출처: 문서

본문

스크래치패드 도구

3.3에 도입 {: .label .label-purple }

스크래치패드 도구는 WriteToScratchPadTool과 ReadFromScratchPadTool로 구성되며, 에이전트가 런타임 동안 중간 사고와 결과를 저장하고 조회할 수 있게 해줘요. 이 도구들은 단일 에이전트 실행 세션을 위한 임시 메모리 역할을 하므로, 에이전트가 도구 실행 중에 메모를 남기고 중요한 발견 사항을 저장할 수 있어요.

스크래치패드는 단일 에이전트 실행 동안에만 유지되는 런타임 메모리 역할을 해요. 에이전트의 _execute API를 호출하면 해당 세션을 위한 새 스크래치패드가 만들어져요. persistent_notes를 제외한 모든 메모와 데이터는 실행이 완료되면 삭제되기 때문에, 각 실행이 항상 새 스크래치패드로 시작하게 돼요. {: .important}

사용 사례

  • 작업 분해: 단일 실행 내에서 여러 단계로 진행되는 작업 중에 리서치 계획, 중간 발견 사항, 진행 상황 메모를 저장해요.
  • 임시 상태 관리: 현재 에이전트 실행 세션 동안 컨텍스트와 누적된 지식을 유지해요.
  • 다단계 워크플로: 복잡한 작업에서 포괄적인 답변을 만들 수 있도록 검색이 끝날 때마다 핵심 발견 사항을 저장해요.
  • 실행 계획 수립: 복잡한 작업을 수행하는 동안 단계별 계획을 저장하고 참조해요.

스크래치패드 수명 주기

스크래치패드는 다음과 같은 간단한 수명 주기를 따라요:

  1. 생성: 에이전트 실행이 시작되면 새로운 빈 스크래치패드가 만들어져요.
  2. 사용: 실행 중에 에이전트는 스크래치패드를 여러 번 읽고 쓸 수 있어요.
  3. 정리: 실행이 완료되면 스크래치패드는 자동으로 삭제돼요.

에이전트의 _execute API를 호출할 때마다 새 스크래치패드가 만들어지므로, 각 실행은 서로 격리된 상태로 진행돼요.

모범 사례

  • 구조화된 메모: 에이전트가 스크래치패드에 체계적이고 구조화된 메모를 유지하도록 유도해요.
  • 정기적인 업데이트: 중요한 단계나 발견이 있을 때마다 에이전트가 스크래치패드를 업데이트하게 하세요.
  • 세션 인식: 스크래치패드 내용은 임시적이며 현재 실행에만 해당된다는 점을 기억하세요.
  • 효율적인 사용: 실행 중에 여러 번 참조해야 하는 중간 결과는 스크래치패드에 저장하세요.

예시: 스크래치패드 도구로 리서치 에이전트 만들기

다음 단계에 따라 스크래치패드 도구를 사용하는 리서치 에이전트를 만들어 보세요.

1단계: 모델 등록 및 배포

에이전트 프레임워크를 지원하는 대화형 모델을 등록해요. 다음 예시는 Anthropic Claude를 사용해요:

POST /_plugins/_ml/models/_register?deploy=true
{
  "name": "Claude Sonnet for Research Agent",
  "function_name": "remote",
  "description": "Claude model for research agent with scratchpad",
  "connector": {
    "name": "Bedrock Claude Sonnet Connector",
    "description": "Amazon Bedrock connector for Claude Sonnet",
    "version": 1,
    "protocol": "aws_sigv4",
    "parameters": {
      "region": "us-east-1",
      "service_name": "bedrock",
      "model": "anthropic.claude-3-5-sonnet-20241022-v2:0"
    },
    "credential": {
      "access_key": "${AWS_ACCESS_KEY_ID}",
      "secret_key": "${AWS_SECRET_ACCESS_KEY}",
      "session_token": "${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.messages}, "inferenceConfig": {"maxTokens": 8000, "temperature": 0}}"""
      }
    ]
  }
}

{% include copy-curl.html %}

2단계: 스크래치패드 도구가 포함된 에이전트 등록

스크래치패드 도구와 그 외 리서치 도구를 모두 포함하는 대화형 에이전트를 등록해요:

POST /_plugins/_ml/agents/_register
{
    "name": "Research Agent with Scratchpad",
    "type": "conversational",
    "description": "Research assistant with persistent scratchpad memory",
    "app_type": "rag",
    "llm": {
        "model_id": "your-model-id",
        "parameters": {
            "max_iteration": 50,
            "system_prompt": "You are a sophisticated research assistant with access to OpenSearch indices and a persistent scratchpad for note-taking.\n\nYour Research Workflow:\n1. Check Scratchpad: Before starting a new research task, check your scratchpad to see if you have any relevant information already saved\n2. Create Research Plan: Create a structured research plan\n3. Write to Scratchpad: Save the research plan and any important information to your scratchpad\n4. Use Search: Gather information using OpenSearch search queries\n5. Update Scratchpad: After each search, update your scratchpad with new findings\n6. Iterate: Repeat searching and updating until you have comprehensive information\n7. Complete Task: Provide a thorough response based on your accumulated research\n\nRemember: Your scratchpad is temporary memory for this execution session only. Use it to organize your thoughts and findings during this task.",
            "prompt": "${parameters.question}"
        }
    },
    "memory": {
        "type": "conversation_index"
    },
    "parameters": {
        "_llm_interface": "bedrock/converse/claude"
    },
    "tools": [
        {
            "type": "SearchIndexTool"
        },
        {
            "type": "ListIndexTool"
        },
        {
            "type": "IndexMappingTool"
        },
        {
            "type": "ReadFromScratchPadTool",
            "name": "ReadFromScratchPadTool",
            "parameters": {
                "persistent_notes": "You are a helpful researcher. Before making searches, use the ListIndexTool to discover available indices. Write down important notes after using tools."
            }
        },
        {
            "type": "WriteToScratchPadTool",
            "name": "WriteToScratchPadTool"
        }
    ]
}

{% include copy-curl.html %}

3단계: 에이전트 실행

리서치 질문으로 에이전트를 실행해요:

POST /_plugins/_ml/agents/{your-agent-id}/_execute?async=true
{
    "parameters": {
        "question": "How many residents are in New York?"
    }
}

{% include copy-curl.html %}

에이전트는 다음과 같이 동작해요:

  1. 스크래치패드를 읽어 기존에 관련 정보가 있는지 확인해요 (새 실행이라면 비어 있는 상태로 시작해요).
  2. 리서치 계획을 만들어 스크래치패드에 저장해요.
  3. 검색을 실행하고 발견 사항으로 스크래치패드를 업데이트해요.
  4. 누적된 리서치를 바탕으로 포괄적인 답변을 제공해요.

agents/<your-agent-id>/_execute API를 사용하면 응답에서 parent_interaction_id와 memory_id를 받게 돼요. 이후 트레이싱 단계를 위해 parent_interaction_id를 기록해 두세요. 자세한 내용은 스크래치패드 활동 보기를 참고하세요.

도구 파라미터

다음은 스크래치패드 도구의 파라미터예요.

ReadFromScratchPadTool

다음은 에이전트에 추가할 때 사용하는 등록 파라미터예요.

파라미터 타입 필수/선택 설명
persistent_notes String 선택 스크래치패드가 처음 만들어질 때 저장할 초기 메모 또는 지시문.

다음은 도구를 직접 호출할 때 사용하는 실행 파라미터예요.

파라미터 타입 필수/선택 설명
persistent_notes String 필수 스크래치패드에 저장할 초기 메모 또는 지시문.

WriteToScratchPadTool

다음은 에이전트에 추가할 때 사용하는 등록 파라미터예요.

파라미터 타입 필수/선택 설명
return_history Boolean 선택 true로 설정하면 쓰기 후 스크래치패드 전체 내용을 반환해요. false이거나 생략하면(기본값) 새로 추가된 메모와 확인 메시지를 반환해요.

다음은 도구를 직접 호출할 때 사용하는 실행 파라미터예요.

파라미터 타입 필수/선택 설명
notes String 필수 스크래치패드에 쓸 내용.
return_history Boolean 선택 true로 설정하면 쓰기 후 스크래치패드 전체 내용을 반환해요. false이거나 생략하면(기본값) 새로 추가된 메모와 확인 메시지를 반환해요.

도구 테스트하기

에이전트에 등록하기 전에 Tools API를 직접 사용해 두 스크래치패드 도구를 실행하고 응답을 테스트할 수 있어요.

ReadFromScratchPadTool 테스트하기

POST /_plugins/_ml/tools/_execute/ReadFromScratchPadTool
{
  "parameters": {
    "persistent_notes": "You are a helpful researcher to conduct searches in OpenSearch cluster. Before making the search, please remember to use the listIndexTool to figure out what are the available indices first. When using listIndexTool, remember the index name has to be in an array format. Please write down important notes after tool used."
  }
}

{% include copy-curl.html %}

persistent_notes가 제공되면 도구는 응답에 persistent notes를 표시하려고 시도해요:

{
  "inference_results": [
    {
      "output": [
        {
          "name": "response",
          "result": """Notes from scratchpad:
- You are a helpful researcher to conduct searches in OpenSearch cluster. Before making the search, please remember to use the listIndexTool to figure out what are the available indices first. When using listIndexTool, remember the index name has to be in an array format. Please write down important notes after tool used."""
        }
      ]
    }
  ]
}

빈 persistent_notes 필드로 테스트할 수도 있어요:

POST /_plugins/_ml/tools/_execute/ReadFromScratchPadTool
{
  "parameters": {
    "persistent_notes": ""
  }
}

{% include copy-curl.html %}

응답을 보면 스크래치패드가 비어 있다는 것을 알 수 있어요:

{
  "inference_results": [
    {
      "output": [
        {
          "name": "response",
          "result": "Scratchpad is empty."
        }
      ]
    }
  ]
}

WriteToScratchPadTool 테스트하기

에이전트에 등록하기 전에 Tools API를 직접 사용해 WriteToScratchPadTool을 실행하고 도구 응답을 테스트할 수 있어요.

POST /_plugins/_ml/tools/_execute/WriteToScratchPadTool
{
  "parameters": {
    "notes": "Research Plan for OpenSearch History and ML Evolution:\\n\\n1. OpenSearch version history, major releases after v2.0\\n2. For each major release:\\n    a. Key architectural upgrades\\n    b. New machine learning capabilities, especially ML Commons Agent framework \\n    c. Descriptions of major Agent tools added\\n    d. GitHub issue IDs tied to Agent framework features\\n3. Look for official OpenSearch documentation, release notes, blogs\\n4. Search code repositories for more technical details on ML changes\\n"
  }
}

{% include copy-curl.html %}

다음은 도구 출력의 예시 응답이에요:

{
  "inference_results": [
    {
      "output": [
        {
          "name": "response",
          "result": "Wrote to scratchpad: Research Plan for OpenSearch History and ML Evolution:\\n\\n1. OpenSearch version history, major releases after v2.0\\n2. For each major release:\\n    a. Key architectural upgrades\\n    b. New machine learning capabilities, especially ML Commons Agent framework \\n    c. Descriptions of major Agent tools added\\n    d. GitHub issue IDs tied to Agent framework features\\n3. Look for official OpenSearch documentation, release notes, blogs\\n4. Search code repositories for more technical details on ML changes\\n"
        }
      ]
    }
  ]
}

return_history 파라미터를 true로 설정하면 쓰기 후 스크래치패드 전체 내용을 받을 수 있어요:

POST /_plugins/_ml/tools/_execute/WriteToScratchPadTool
{
  "parameters": {
    "notes": "Research Plan for OpenSearch History and ML Evolution:\\n\\n1. OpenSearch version history, major releases after v2.0\\n2. For each major release:\\n    a. Key architectural upgrades\\n    b. New machine learning capabilities, especially ML Commons Agent framework \\n    c. Descriptions of major Agent tools added\\n    d. GitHub issue IDs tied to Agent framework features\\n3. Look for official OpenSearch documentation, release notes, blogs\\n4. Search code repositories for more technical details on ML changes\\n",
    "return_history": true
  }
}

{% include copy-curl.html %}

응답에는 스크래치패드 전체 내용이 담겨 있어요:

{
  "inference_results": [
    {
      "output": [
        {
          "name": "response",
          "result": """Scratchpad updated. Full content:
- Research Plan for OpenSearch History and ML Evolution:\n\n1. OpenSearch version history, major releases after v2.0\n2. For each major release:\n    a. Key architectural upgrades\n    b. New machine learning capabilities, especially ML Commons Agent framework \n    c. Descriptions of major Agent tools added\n    d. GitHub issue IDs tied to Agent framework features\n3. Look for official OpenSearch documentation, release notes, blogs\n4. Search code repositories for more technical details on ML changes\n"""
        }
      ]
    }
  ]
}

스크래치패드 활동 보기

실행 트레이스를 살펴보면 에이전트가 스크래치패드를 어떻게 사용하는지 모니터링할 수 있어요:

GET /_plugins/_ml/memory/message/{parent_interaction_id}/traces?next_token=0

{% include copy-curl.html %}

트레이스는 스크래치패드 읽기와 쓰기의 순서를 보여 주며, 실행 세션 동안 에이전트가 지식을 쌓아 가는 방식을 잘 드러내 줘요.

관련 문서

더 알아보기 (Learn more)