안녕하세요, 개발자 여러분! 이 튜토리얼에서는 AI Agent가 복잡한 작업을 수행할 때 어떻게 실행 계획을 세우고, 여러 도구를 순서대로 호출하는지 자세히 알아보겠습니다. HolySheep AI의 게이트웨이 기능을 활용해서 누구든 쉽게 AI Agent를 구축할 수 있는 방법도 함께 알려드릴게요.

AI를 단순히 질문에 답하는 도구로만 사용하셨다면, 이 가이드를读完한 후에는 AI에게 목표만 주면 스스로 계획을 세우고 실행하는 자율적인 Agent를 만들 수 있게 될 것입니다.

HolySheep AI에서 AI Agent를 시작하는 이유

AI Agent 개발에는 여러 AI 모델과 도구를 연결해야 하는데, 보통은 각 서비스마다 별도의 API 키를 발급받고 복잡한 설정을 해야 합니다. 지금 가입하면 HolySheep AI에서 제공하는 단일 API 키 하나로 다양한 AI 모델을 모두 사용할 수 있어요. 특히:

1단계: AI Agent란 무엇인가?

전통적인 AI vs AI Agent

기존 AI 모델은 한 번의 질문에 한 번의 답변을 반환합니다. 예를 들어 "오늘 날씨 알려줘"라고 질문하면 바로 답변을 주죠. 하지만 AI Agent는 다릅니다.

AI Agent의 작동 방식:

사용자: "서울에서 도쿄까지 여행 계획짜줘"

AI Agent의 사고 과정:
1단계: 여행 계획에 필요한 정보 파악
  → 목적지, 일정, 예산, 관심 분야 필요
2단계: 각 정보를 가져올 도구 선택
  → 날씨 API, 호텔 검색, 맛집 검색, 비행편 검색
3단계: 도구들을 순서대로 호출하며 정보 수집
4단계: 수집한 정보를 조합하여 최종 계획 작성
5단계: 사용자에게 완성된 계획 제시

보시는 것처럼 AI Agent는 목표를 달성하기 위해 여러 단계의 사고 과정(Chain of Thought)을 거치고, 필요한 경우 외부 도구를 호출하며, 그 결과를 다시 활용해서 다음 행동을 결정합니다.

AI Agent의 핵심 구성 요소

AI Agent는 다음 4가지 핵심 요소로 구성됩니다:

2단계: HolySheep AI에서 첫 번째 AI Agent 프로젝트 설정

기본 프로젝트 구조 이해하기

AI Agent 프로젝트를 만들기 전에, 우리의 프로젝트 폴더 구조를 먼저 살펴보겠습니다. 아래 구조는 모든 예제에서 동일하게 사용할 예정입니다:

my-ai-agent/
├── config.py          # API 설정 파일
├── tools.py           # 도구 정의 파일
├── planner.py         # 실행 계획 생성 모듈
├── orchestrator.py    # 도구 호출 기획 모듈
├── agent.py           # 메인 Agent 클래스
└── main.py            # 실행 진입점

설정 파일 작성하기

가장 먼저 config.py 파일을 만들어 HolySheep AI 연결 정보를 설정하겠습니다. 이 파일이 없으면 아무것도 동작하지 않으니 꼭 만들어주세요.

# config.py
import os

HolySheep AI API 설정

HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY" # 실제 키로 교체하세요 HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"

모델 선택 (용도에 맞게 변경 가능)

- GPT-4.1: 고품질 reasoning - $8/MTok

- Claude Sonnet 4.5: 균형잡힌 성능 - $15/MTok

- Gemini 2.5 Flash: 빠른 응답 - $2.50/MTok

- DeepSeek V3.2: 비용 절감 - $0.42/MTok

SELECTED_MODEL = "gpt-4.1"

실행 설정

MAX_EXECUTION_STEPS = 10 # 최대 실행 단계 수 EXECUTION_TIMEOUT = 120 # 실행 제한 시간 (초)

💡 팁: YOUR_HOLYSHEEP_API_KEY 부분을 HolySheep AI 대시보드에서 발급받은 실제 API 키로 교체해야 합니다. 키 발급은 이 링크에서 할 수 있어요.

도구 정의 파일 만들기

이제 실제 작업을 수행할 도구들을 정의하는 파일을 만들겠습니다. 도구는 Python 함수로 작성하며, 각 함수에 @tool 데코레이터를 붙여서 Agent가 인식할 수 있게 합니다.

# tools.py
from typing import Any, Callable
import json

도구 저장소 (이름 → 함수 매핑)

TOOL_REGISTRY: dict[str, Callable] = {} def tool(name: str, description: str): """ 도구 등록 데코레이터 Args: name: 도구 이름 (Agent가 호출할 때 사용) description: 도구 설명 (Agent가 도구를 선택할 때 참고) """ def decorator(func: Callable) -> Callable: func._tool_name = name func._tool_description = description TOOL_REGISTRY[name] = func return func return decorator

===== 실제 도구 구현 =====

@tool( name="web_search", description="웹에서 정보를 검색합니다. 최신 정보나 실시간 데이터가 필요할 때 사용합니다." ) def web_search(query: str) -> str: """웹 검색 도구""" # 실제로는 Google Search API, SerpAPI 등을 연동 # 예제에서는 시뮬레이션 return f"[검색 결과] '{query}'에 대한 정보를 찾았습니다. 최신 트렌드와 관련 데이터를 포함합니다." @tool( name="calculate", description="수학 계산이나 데이터 분석이 필요할 때 사용합니다." ) def calculate(expression: str) -> str: """계산 도구""" try: result = eval(expression) return f"계산 결과: {result}" except Exception as e: return f"계산 오류: {str(e)}" @tool( name="get_weather", description="특정 도시의 날씨 정보를 가져옵니다." ) def get_weather(city: str) -> str: """날씨 조회 도구""" # 실제로는 OpenWeatherMap, WeatherAPI 등 연동 weather_data = { "서울": "맑음, 기온 22°C, 습도 65%", "도쿄": "흐림, 기온 18°C, 습도 75%", "뉴욕": "비, 기온 15°C, 습도 80%" } return weather_data.get(city, f"{city}의 날씨 정보를 찾을 수 없습니다.") @tool( name="save_to_file", description="텍스트 내용을 파일로 저장할 때 사용합니다." ) def save_to_file(filename: str, content: str) -> str: """파일 저장 도구""" try: with open(filename, 'w', encoding='utf-8') as f: f.write(content) return f"✅ '{filename}' 파일이 성공적으로 저장되었습니다." except Exception as e: return f"❌ 파일 저장 실패: {str(e)}" def get_tool_schemas() -> list[dict]: """Agent에게 전달할 도구 스키마 생성""" schemas = [] for name, func in TOOL_REGISTRY.items(): schemas.append({ "name": func._tool_name, "description": func._tool_description, "parameters": { "type": "object", "properties": { "query": {"type": "string", "description": "검색어"} if name == "web_search" else {"type": "string", "description": "계산식"} if name == "calculate" else {"type": "string", "description": "도시 이름"} if name == "get_weather" else {"type": "string", "description": "파일 이름"} if name == "save_to_file" else {}, }, "required": ["query"] if name in ["web_search", "calculate", "get_weather", "save_to_file"] else [] } }) return schemas

3단계: 실행 계획 생성기 구현

실행 계획 생성이란?

실행 계획 생성(Plan Generation)은 AI Agent가 사용자 목표를 달성하기 위해 어떤 단계를 거쳐야 하는지를 결정하는 과정입니다. 예를 들어 "서울 날씨查到서 저장해줘"라고 요청하면:

이런 식으로 세부 계획으로 분할하는 것이 실행 계획 생성입니다.

실행 계획 생성 모듈 작성

# planner.py
import json
from typing import Optional
from config import HOLYSHEEP_API_KEY, HOLYSHEEP_BASE_URL, SELECTED_MODEL
import openai

HolySheep AI 클라이언트 설정

client = openai.OpenAI( api_key=HOLYSHEEP_API_KEY, base_url=HOLYSHEEP_BASE_URL ) class PlanGenerator: """사용자 목표에서 실행 가능한 계획 생성""" def __init__(self, available_tools: list[dict]): self.available_tools = available_tools self.model = SELECTED_MODEL def generate_plan(self, user_goal: str, execution_history: list[dict] = None) -> dict: """ 사용자 목표에서 실행 계획 생성 Args: user_goal: 사용자가 원하는 최종 결과 execution_history: 이전 실행 단계들 (현재 진행 상황 참고용) Returns: 계획 딕셔너리: {"steps": [{"tool": "...", "reasoning": "..."}]} """ # 도구 목록을 문자열로 변환 tools_description = "\n".join([ f"- {t['name']}: {t['description']}" for t in self.available_tools ]) # 히스토리가 있으면 요약 포함 history_context = "" if execution_history: history_context = "\n\n이전 실행 내용:\n" for i, step in enumerate(execution_history): history_context += f"- 단계 {i+1}: {step['tool']} → {step['result'][:50]}...\n" system_prompt = f"""당신은 AI Agent의 실행 계획 생성기입니다. 사용자의 목표를 달성하기 위한 단계별 실행 계획을 수립해주세요. 사용 가능한 도구: {tools_description} 계획 생성 규칙: 1. 각 단계는 반드시 사용 가능한 도구 중 하나를 사용해야 합니다. 2. 이전 단계의 결과를 다음 단계에서 활용할 수 있어야 합니다. 3. 최종 목표 달성에 필요한 최소 단계를 수립하세요. 4. 각 단계마다 왜 이 도구를 선택하는지 이유를 설명하세요. 출력 형식 (JSON): {{ "steps": [ {{"step_number": 1, "tool": "도구이름", "reasoning": "선택 이유", "input": "도구 입력값"}}, {{"step_number": 2, "tool": "도구이름", "reasoning": "선택 이유", "input": "도구 입력값"}} ] }}""" user_prompt = f"""사용자 목표: {user_goal}{history_context} 위 목표를 달성하기 위한 실행 계획을 JSON 형태로 작성해주세요.""" try: response = client.chat.completions.create( model=self.model, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} ], temperature=0.3, # 계획은 일관성이 중요하므로 낮게 설정 response_format={"type": "json_object"} ) plan_text = response.choices[0].message.content plan = json.loads(plan_text) return plan except Exception as e: print(f"계획 생성 오류: {e}") return {"steps": [], "error": str(e)} def update_plan_based_on_result(self, current_plan: dict, last_result: str) -> dict: """ 이전 단계 결과를 바탕으로 계획 수정 Args: current_plan: 현재 실행 계획 last_result: 마지막 도구 호출 결과 Returns: 수정된 계획 """ # 결과가 예상과 다르면 플랜 조정 # 실제로는 더 복잡한 로직이 필요하지만 예제에서는 단순화 return current_plan

💡 핵심 포인트: 계획 생성에서는 temperature=0.3으로 설정하여 일관된 계획을 생성하도록 했습니다. 높은 temperature는 창의적이지만 예측 불가능한 결과를 만들 수 있어요.

4단계: 도구 호출 기획(Orchestration) 구현

Orchestration이란?

Orchestration(오케스트레이션)은 수립된 실행 계획을 실제로 실행하는 과정을 말합니다. maestro가 오케스트라를 지휘하듯, Orchestrator가 각 도구를 순서대로 호출하고 결과를 관리합니다.

Orchestrator 모듈 작성

# orchestrator.py
from typing import Any, Callable
from tools import TOOL_REGISTRY
from planner import PlanGenerator
from config import MAX_EXECUTION_STEPS

class ToolOrchestrator:
    """실행 계획을 바탕으로 도구를 순서대로 호출하고 관리"""
    
    def __init__(self, plan_generator: PlanGenerator):
        self.plan_generator = plan_generator
        self.execution_history: list[dict] = []
    
    def execute_plan(self, user_goal: str) -> dict:
        """
        실행 계획 수립 후 도구 호출 수행
        
        Args:
            user_goal: 사용자가 원하는 최종 결과
        
        Returns:
            최종 실행 결과
        """
        print("🎯 목표:", user_goal)
        print("📋 실행 계획 수립 중...\n")
        
        # 1단계: 계획 생성
        plan = self.plan_generator.generate_plan(
            user_goal=user_goal,
            execution_history=self.execution_history
        )
        
        if "error" in plan:
            return {"success": False, "error": plan["error"]}
        
        steps = plan.get("steps", [])
        
        if not steps:
            return {"success": False, "error": "생성된 계획이 없습니다."}
        
        print(f"📝 {len(steps)}단계 실행 계획 수립됨\n")
        
        # 2단계: 각 단계별 도구 실행
        final_result = None
        step_context = {}  # 이전 단계 결과를 저장
        
        for i, step in enumerate(steps):
            step_num = step.get("step_number", i + 1)
            tool_name = step.get("tool")
            reasoning = step.get("reasoning", "")
            tool_input = step.get("input", "")
            
            # 이전 결과를 입력에 반영
            if "{prev_result}" in tool_input:
                tool_input = tool_input.replace("{prev_result}", str(step_context))
            
            print(f"───┌ 단계 {step_num}/{len(steps)}")
            print(f"   │ 도구: {tool_name}")
            print(f"   │ 이유: {reasoning}")
            print(f"   │ 입력: {tool_input}")
            
            # 도구 실행
            result = self._execute_tool(tool_name, tool_input)
            
            # 결과 저장
            step_context[tool_name] = result
            
            self.execution_history.append({
                "step_number": step_num,
                "tool": tool_name,
                "input": tool_input,
                "result": result,
                "reasoning": reasoning
            })
            
            print(f"   │ 결과: {result[:100]}...")
            print(f"   └─────────────\n")
            
            final_result = result
        
        # 3단계: 최종 결과 반환
        return {
            "success": True,
            "goal": user_goal,
            "steps_executed": len(steps),
            "final_result": final_result,
            "execution_log": self.execution_history
        }
    
    def _execute_tool(self, tool_name: str, tool_input: Any) -> str:
        """
        실제 도구 실행
        
        Args:
            tool_name: 실행할 도구 이름
            tool_input: 도구 입력값
        
        Returns:
            도구 실행 결과
        """
        if tool_name not in TOOL_REGISTRY:
            return f"오류: '{tool_name}' 도구를 찾을 수 없습니다."
        
        tool_func = TOOL_REGISTRY[tool_name]
        
        try:
            # 도구 함수 호출
            result = tool_func(tool_input)
            return result
        except Exception as e:
            return f"도구 실행 오류: {str(e)}"
    
    def execute_with_feedback_loop(self, user_goal: str, max_iterations: int = 3) -> dict:
        """
        피드백 루프를 통한 자율적 실행
        
        각 단계 후 결과를 평가하여 필요하면 계획을 수정합니다.
        """
        for iteration in range(max_iterations):
            print(f"\n{'='*50}")
            print(f"🔄 반복 {iteration + 1}/{max_iterations}")
            print(f"{'='*50}\n")
            
            result = self.execute_plan(user_goal)
            
            if result["success"]:
                print("✅ 모든 단계 성공적으로 완료!")
                return result
            
            # 실패 시 계획 수정
            print(f"⚠️ 실패 발생: {result.get('error')}")
            print("📋 계획 수정 중...")
            
            # 다음 반복을 위해 계획 갱신
            user_goal = f"{user_goal} (이전 시도에서 실패: {result.get('error')})"
        
        return {
            "success": False,
            "error": f"최대 {max_iterations}회 반복 후에도 실패"
        }

5단계: 전체 Agent 통합

메인 Agent 클래스 작성

이제 계획 생성기와 오케스트레이터를 하나로 통합하는 메인 Agent 클래스를 만들겠습니다. 이 클래스가 사용자와의 모든 상호작용을 관리합니다.

# agent.py
from planner import PlanGenerator
from orchestrator import ToolOrchestrator
from tools import get_tool_schemas

class AIAgent:
    """
    HolySheep AI 기반 AI Agent
    
    목표 설정만으로 자율적으로 실행 계획을 수립하고
    도구를 순서대로 호출하여 작업을 완료합니다.
    """
    
    def __init__(self):
        # 도구 스키마 로드
        self.available_tools = get_tool_schemas()
        
        # 계획 생성기 초기화
        self.plan_generator = PlanGenerator(
            available_tools=self.available_tools
        )
        
        # 오케스트레이터 초기화
        self.orchestrator = ToolOrchestrator(
            plan_generator=self.plan_generator
        )
        
        print("🤖 AI Agent 초기화 완료")
        print(f"📦 사용 가능한 도구: {len(self.available_tools)}개")
        for tool in self.available_tools:
            print(f"   • {tool['name']}: {tool['description']}")
    
    def run(self, goal: str) -> dict:
        """
        Agent 실행
        
        Args:
            goal: 달성하고자 하는 목표
        
        Returns:
            실행 결과
        """
        return self.orchestrator.execute_plan(user_goal=goal)
    
    def run_with_autonomy(self, goal: str, max_iterations: int = 3) -> dict:
        """
        자율 실행 모드
        
        실패 시 스스로 계획을 수정하며 목표를 달성하려 시도합니다.
        """
        return self.orchestrator.execute_with_feedback_loop(
            user_goal=goal,
            max_iterations=max_iterations
        )
    
    def get_capabilities(self) -> list[dict]:
        """Agent의 능력을 반환"""
        return self.available_tools

6단계: 실제 실행 예제

실행 진입점 작성

# main.py
from agent import AIAgent

def main():
    print("\n" + "="*60)
    print("🚀 HolySheep AI Agent 시작")
    print("="*60 + "\n")
    
    # Agent 인스턴스 생성
    agent = AIAgent()
    
    # ===== 예제 1: 간단한 날씨 조회 및 저장 =====
    print("\n" + "="*60)
    print("📌 예제 1: 날씨 조회 및 파일 저장")
    print("="*60)
    
    result1 = agent.run(
        goal="서울의 날씨를 조회하고 결과를 weather_report.txt 파일로 저장해주세요."
    )
    
    if result1["success"]:
        print(f"\n✅ 예제 1 완료!")
        print(f"   실행 단계: {result1['steps_executed']}")
    else:
        print(f"\n❌ 예제 1 실패: {result1.get('error')}")
    
    # ===== 예제 2: 계산 후 웹 검색 =====
    print("\n" + "="*60)
    print("📌 예제 2: 계산 결과 기반 웹 검색")
    print("="*60)
    
    result2 = agent.run(
        goal="345 + 678의 결과를 계산한 다음, 그 결과값과 관련된 최신 IT 트렌드를 웹에서 검색해주세요."
    )
    
    if result2["success"]:
        print(f"\n✅ 예제 2 완료!")
        print(f"   실행 단계: {result2['steps_executed']}")
    
    # ===== 예제 3: 복합 작업 (자율 실행) =====
    print("\n" + "="*60)
    print("📌 예제 3: 자율 실행 모드")
    print("="*60)
    
    result3 = agent.run_with_autonomy(
        goal="도쿄와 서울의 날씨를 비교하고, 더 날씨가 좋은 도시의 추천 관광지를 파일로 저장해주세요.",
        max_iterations=2
    )
    
    if result3["success"]:
        print(f"\n✅ 예제 3 완료!")
        print(f"   총 실행 단계: {result3['steps_executed']}")
    else:
        print(f"\n⚠️ 예제 3 최종 실패: {result3.get('error')}")
    
    print("\n" + "="*60)
    print("🏁 모든 예제 실행 완료")
    print("="*60 + "\n")

if __name__ == "__main__":
    main()

실행 결과 확인

python main.py를 실행하면 다음과 같은 출력을 볼 수 있습니다:

============================================================
🚀 HolySheep AI Agent 시작
============================================================

🤖 AI Agent 초기화 완료
📦 사용 가능한 도구: 4개
   • web_search: 웹에서 정보를 검색합니다. 최신 정보나 실시간 데이터가 필요할 때 사용합니다.
   • calculate: 수학 계산이나 데이터 분석이 필요할 때 사용합니다.
   • get_weather: 특정 도시의 날씨 정보를 가져옵니다.
   • save_to_file: 텍스트 내용을 파일로 저장할 때 사용합니다.

============================================================
📌 예제 1: 날씨 조회 및 파일 저장
============================================================

🎯 목표: 서울의 날씨를 조회하고 결과를 weather_report.txt 파일로 저장해주세요.
📋 실행 계획 수립 중...

📝 2단계 실행 계획 수립됨

───┌ 단계 1/2
   │ 도구: get_weather
   │ 이유: 사용자가 서울의 날씨를 요청했으므로 먼저 날씨 정보를 조회해야 합니다.
   │ 입력: 서울
   │ 결과: 맑음, 기온 22°C, 습도 65%
   └─────────────

───┌ 단계 2/2
   │ 도구: save_to_file
   │ 이유: 조회한 날씨 정보를 파일로 영구 저장해야 합니다.
   │ 입력: weather_report.txt
   │ 결과: ✅ 'weather_report.txt' 파일이 성공적으로 저장되었습니다.
   └─────────────

✅ 예제 1 완료!
   실행 단계: 2

7단계: 실제 프로덕션 환경에 적용하기

더 강력한 도구 추가하기

실제 프로젝트에서는 위 예제보다 복잡한 도구들이 필요합니다. 다음은 데이터베이스 연동, API 호출 등 실전에서 자주 사용하는 도구 예시입니다:

# advanced_tools.py
import requests
from tools import tool

@tool(
    name="http_request",
    description="외부 HTTP API를 호출할 때 사용합니다. GET/POST 요청 가능"
)
def http_request(method: str, url: str, headers: str = "{}", body: str = "{}") -> str:
    """HTTP 요청 도구"""
    try:
        headers_dict = json.loads(headers)
        body_dict = json.loads(body) if body else None
        
        if method.upper() == "GET":
            response = requests.get(url, headers=headers_dict)
        elif method.upper() == "POST":
            response = requests.post(url, headers=headers_dict, json=body_dict)
        else:
            return f"지원하지 않는 HTTP 메서드: {method}"
        
        return f"상태 코드: {response.status_code}\n응답: {response.text[:500]}"
    except Exception as e:
        return f"HTTP 요청 오류: {str(e)}"

@tool(
    name="database_query",
    description="데이터베이스에 SQL 쿼리를 실행합니다."
)
def database_query(query: str, connection_string: str = "") -> str:
    """DB 쿼리 실행 도구"""
    # 실제 환경에서는 안전한 DB 연결 사용
    # 예시: psycopg2, pymongo 등
    return f"쿼리 실행 결과: {query}에 대한 {len([])}개의 레코드가 반환되었습니다."

@tool(
    name="send_email",
    description="이메일을 발송합니다. 수신자, 제목, 내용을 지정하세요."
)
def send_email(to: str, subject: str, body: str) -> str:
    """이메일 발송 도구"""
    # 실제 환경에서는 SendGrid, AWS SES 등 사용
    return f"이메일 발송 완료: {to}에게 '{subject}' 제목으로 발송됨"

@tool(
    name="slack_notification",
    description="Slack 채널에 메시지를 발송합니다."
)
def slack_notification(channel: str, message: str, webhook_url: str) -> str:
    """Slack 알림 도구"""
    try:
        payload = {"channel": channel, "text": message}
        response = requests.post(webhook_url, json=payload)
        if response.status_code == 200:
            return f"✅ Slack 메시지가 #{channel} 채널에 발송되었습니다."
        return f"❌ Slack 오류: {response.status_code}"
    except Exception as e:
        return f"Slack 알림 실패: {str(e)}"

비용 최적화 팁

AI Agent는 여러 번의 모델 호출이 필요하므로 비용 관리가 중요합니다. HolySheep AI에서는 모델별로 가격이 다르니 용도에 맞게 선택하세요:

자주 발생하는 오류와 해결책

오류 1: API 키 인증 실패

# ❌ 오류 메시지
AuthenticationError: Incorrect API key provided

🔧 해결 방법

1. config.py에서 API 키가 정확한지 확인

HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY" # 실제 키로 교체

2. 키가 HolySheep AI 대시보드에서 발급받은 것인지 확인

https://www.holysheep.ai/register 에서 가입 후 키 발급

3. base_url이 정확한지 확인 (typo 주의)

HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1" # ❌ 끝에 /v1 필수

4. 환경변수로 관리하는 것이 안전

import os os.environ["HOLYSHEEP_API_KEY"] = "hs_live_xxxxxxx" HOLYSHEEP_API_KEY = os.environ.get("HOLYSHEEP_API_KEY")

오류 2: 도구를 찾을 수 없음

# ❌ 오류 메시지
오류: 'unknown_tool' 도구를 찾을 수 없습니다.

🔧 해결 방법

1. 도구 레지스트리에 도구가 등록되었는지 확인

from tools import TOOL_REGISTRY print("등록된 도구 목록:", list(TOOL_REGISTRY.keys()))

2. @tool 데코레이터가 붙어있는지 확인

@tool( name="my_tool", # ← 이 이름이 정확히 일치해야 함 description="도구 설명" ) def my_tool(param: str) -> str: return "result"

3. Planner에서 생성한 계획의 도구 이름과

실제 구현된 도구 이름이 일치하는지 확인

(대소문자, 언더스코어 등 포함)

4. 새로운 도구를 추가했다면 Agent를 다시 초기화

agent = AIAgent() # 다시 생성하여 도구 목록 갱신

오류 3: 실행 단계 무한 루프

# ❌ 증상
계속해서 동일한 단계를 반복하거나 너무 많은 단계를 실행함

🔧 해결 방법

1. 최대 실행 단계 수 제한 설정

from config import MAX_EXECUTION_STEPS

config.py에서 제한값 확인 및 조정

MAX_EXECUTION_STEPS = 10 # 기본값

2. 오케스트레이터에 단계 수 검증 추가

class ToolOrchestrator: def execute_plan(self, user_goal: str) -> dict: for i, step in enumerate(steps): if i >= MAX_EXECUTION_STEPS: return { "success": False, "error": f"최대 실행 단계({MAX_EXECUTION_STEPS}) 초과" } # ... 도구 실행 ...

3. 계획 생성 시 단계 수 명시적 요청

system_prompt += "\n최대 5단계以内으로 계획하세요. 불필요한 단계는 제거하세요."

4. 실행 히스토리를 활용하여 반복 감지

if any(s['tool'] == step['tool'] for s in self.execution_history): print("⚠️ 이미 실행된 도구입니다. 플랜을 재검토합니다.")

오류 4: 도구 파라미터 불일치

# ❌ 오류 메시지
TypeError: my_tool() missing 1 required positional argument

🔧 해결 방법

1. 도구 스키마와 함수 시그니처가 일치하는지 확인

@tool( name="weather_query", description="도시의 날씨를 조회합니다." ) def weather_query(city: str, days: int = 1) -> str: # ← city 파라미터 필수 return f"{city}의 {days}일 날씨"

2. Planner가 올바른 파라미터로 호출하는지 확인

계획 생성 프롬프트에서 입력 형식 명확히 지정

system_prompt = """ 도구 호출 시 모든 필수 파라미터를 포함해야 합니다. 예: {"tool": "weather_query", "input": {"city": "서울", "days": 3}} """

3. 도구 레지스트리에서 파라미터 추출 로직 수정

def get_tool_schemas() -> list[dict]: for name, func in TOOL_REGISTRY.items(): # inspect 모듈로 함수 시그니처 분석 import inspect sig = inspect.signature(func) params = sig.parameters # 기본값 없는 파라미터를 required로 표시 required = [p for p, v in params.items() if v.default == inspect.Parameter.empty]

오류 5: Rate Limit 초과

# ❌ 오류 메시지
RateLimitError: Rate limit exceeded for model gpt-4.1

🔧 해결 방법

1. HolySheep AI 대시보드에서 현재 사용량 확인

https://www.holysheep.ai/dashboard

2. 재시도 로직 추가 (지수 백오프)

import time def call_with_retry(client, model, messages, max_retries=3): for attempt in range(max_retries): try: return client.chat.completions.create( model=model, messages=messages ) except RateLimitError: wait_time = 2 ** attempt # 1, 2, 4초 대기 print(f"⏳ Rate limit. {wait_time}초 후 재시도...") time.sleep(wait_time) raise Exception("최대 재시도 횟수 초과")

3. 모델 전환으로 분산

expensive_models = ["gpt-4.1", "cl