한 줄 요약: 루프 엔진(Loop Engine)이란, AI 에이전트가 주어진 목표를 달성할 때까지 “생각(Thought) → 행동(Action) → 관찰(Observation)” 사이클을 자율적으로 반복 실행하도록 조율하는 에이전트 실행 메커니즘이다.


1. 루프 엔진이란 무엇인가?

체스 AI를 생각해 보세요. “이기기”라는 목표를 향해 상황 분석 → 수 선택 → 결과 관찰의 사이클을 게임이 끝날 때까지 반복합니다. 루프 엔진은 AI 에이전트가 복잡한 작업을 수행할 때 이 사이클을 관리합니다.

루프 엔진은 에이전틱 AI의 심장부입니다. 에이전트가 무한루프에 빠지지 않도록 제어하고, 목표 달성 여부를 판단하며, 적절한 시점에 인간의 확인을 요청합니다.

루프 엔진의 핵심 질문:

  • 목표가 달성되었는가?
  • 다음에 무엇을 해야 하는가?
  • 언제 멈춰야 하는가?

2. 핵심 개념 이해하기

ReAct 루프 (가장 기본적인 패턴)

사용자 목표: "파이썬 프로젝트의 모든 테스트를 통과시켜줘"

Iteration 1:
  Thought: 먼저 현재 테스트 결과를 확인해야 한다.
  Action: bash("pytest tests/")
  Observation: "5 failed, 3 passed"
  
Iteration 2:
  Thought: test_auth.py가 실패했다. 코드를 읽어봐야겠다.
  Action: read_file("src/auth.py")
  Observation: "토큰 만료 처리 누락 발견"
  
Iteration 3:
  Thought: 토큰 만료 로직을 추가해야 한다.
  Action: edit_file("src/auth.py", ...)
  Observation: "파일 수정 완료"
  
Iteration 4:
  Thought: 다시 테스트를 실행해보자.
  Action: bash("pytest tests/")
  Observation: "8 passed, 0 failed"
  
Thought: 목표 달성! 모든 테스트 통과.
Final Answer: 5개 실패 테스트를 모두 수정했습니다.

루프 엔진 제어 메커니즘

메커니즘 역할 예시
최대 반복 횟수 무한루프 방지 max_iterations=20
목표 달성 판단 언제 멈출지 결정 “테스트 100% 통과 시”
에러 감지 반복 실패 처리 3회 연속 실패 시 중단
타임아웃 시간 제한 timeout=300s
Human-in-the-loop 확인 요청 파일 삭제 전 승인 요청

3. 실무 적용 예시

커스텀 루프 엔진 구현입니다.

import anthropic
from typing import Callable, Any

class AgentLoopEngine:
    def __init__(
        self,
        tools: list[dict],
        tool_executors: dict[str, Callable],
        max_iterations: int = 20,
        system_prompt: str = "당신은 유능한 AI 에이전트입니다."
    ):
        self.client = anthropic.Anthropic()
        self.tools = tools
        self.tool_executors = tool_executors
        self.max_iterations = max_iterations
        self.system_prompt = system_prompt

    def run(self, goal: str) -> str:
        """목표를 향해 에이전트 루프를 실행합니다."""
        messages = [{"role": "user", "content": goal}]
        iteration = 0

        while iteration < self.max_iterations:
            iteration += 1
            print(f"\n[반복 {iteration}/{self.max_iterations}]")

            # LLM 추론
            response = self.client.messages.create(
                model="claude-3-5-sonnet-20241022",
                max_tokens=4096,
                system=self.system_prompt,
                tools=self.tools,
                messages=messages
            )

            messages.append({"role": "assistant", "content": response.content})

            # 종료 조건: 도구 호출 없이 텍스트만 반환
            if response.stop_reason == "end_turn":
                final_text = next(
                    (b.text for b in response.content if hasattr(b, "text")), ""
                )
                print(f"[완료] {iteration}번 반복 후 목표 달성")
                return final_text

            # 도구 실행
            if response.stop_reason == "tool_use":
                tool_results = []
                for block in response.content:
                    if block.type == "tool_use":
                        tool_name = block.name
                        tool_input = block.input
                        print(f"  → 도구 실행: {tool_name}({tool_input})")

                        executor = self.tool_executors.get(tool_name)
                        if executor:
                            result = executor(**tool_input)
                            print(f"  ← 결과: {str(result)[:100]}")
                        else:
                            result = f"오류: {tool_name} 도구를 찾을 수 없음"

                        tool_results.append({
                            "type": "tool_result",
                            "tool_use_id": block.id,
                            "content": str(result)
                        })

                messages.append({"role": "user", "content": tool_results})

        return f"최대 반복 횟수({self.max_iterations}) 초과 — 목표를 완료하지 못했습니다."

# 사용 예시
import subprocess, os

engine = AgentLoopEngine(
    tools=[
        {
            "name": "bash",
            "description": "쉘 명령어 실행",
            "input_schema": {
                "type": "object",
                "properties": {"command": {"type": "string"}},
                "required": ["command"]
            }
        }
    ],
    tool_executors={
        "bash": lambda command: subprocess.run(
            command, shell=True, capture_output=True, text=True
        ).stdout or subprocess.run(command, shell=True, capture_output=True, text=True).stderr
    }
)

result = engine.run("현재 디렉토리의 Python 파일 목록을 확인하고 개수를 알려줘")
print(result)

4. 루프 엔진 vs 유사 개념 비교

구분 루프 엔진 단일 LLM 호출 RPA
반복 처리 ✅ 자율 반복 ❌ 1회 ✅ 스크립트 반복
자율성 ✅ 동적 결정 ❌ 고정 흐름
목표 지향 부분
예외 처리 ✅ 적응적 제한적
종료 조건 AI가 판단 없음 개발자 정의

5. 마치며

루프 엔진은 에이전틱 AI를 가능하게 하는 핵심 메커니즘입니다. 효과적인 루프 엔진은 에이전트가 목표에 집중하면서도 무한루프, 반복 실패, 예산 초과를 방지합니다. 게임 루프(Game Loop)와 개념이 유사하며, 휴먼 인 더 루프(Human-in-the-Loop)와 결합하면 안전한 자율 에이전트를 구축할 수 있습니다.

참고 자료

함께 읽으면 좋은 용어

이 개념과 함께 알아두면 이해가 깊어지는 관련 용어들입니다.

댓글 남기기