콘텐츠로 이동

추론 (Reasoning)

개념

에이전트에게 복잡한 작업을 하나하나 바로 실행하라고 시키면, 어디서 시작해야 할지 몰라 헤맬 때가 있어요. CrewAI의 추론(Reasoning) 기능은 이런 상황을 위해 준비된 건데요, 에이전트가 작업을 실행하기 전에 먼저 작업을 돌아보고 계획을 세우게 해주는 기능이에요. 작업을 체계적으로 접근하게 만들고, 막상 작업을 수행할 준비가 되었는지 스스로 확인하게 해주죠.

사용법

에이전트를 만들 때 reasoning=True만 설정하면 추론이 켜져요. 다른 복잡한 설정은 필요 없어요.

from crewai import Agent

agent = Agent(
    role="Data Analyst",
    goal="Analyze complex datasets and provide insights",
    backstory="You are an experienced data analyst with expertise in finding patterns in complex data.",
    reasoning=True,            # 추론 활성화
    max_reasoning_attempts=3   # 선택: 추론 시도 최대 횟수
)

동작 원리

추론이 켜져 있으면, 작업을 실행하기 전에 에이전트는 이렇게 동작해요.

  1. 작업을 돌아보고 상세한 계획을 세운다
  2. 작업을 실행할 준비가 되었는지 평가한다
  3. 준비가 되거나 max_reasoning_attempts에 도달할 때까지 계획을 다듬는다
  4. 실행 전에 추론 계획을 작업 설명에 주입한다

이 과정 덕분에 에이전트는 복잡한 작업을 관리 가능한 단계로 쪼개고, 시작하기 전에 잠재적인 난관을 미리 짚어낼 수 있어요.

설정 옵션

옵션 타입 기본값 설명
reasoning bool False 추론을 켜거나 끈다
max_reasoning_attempts int None 실행 전에 계획을 다듬을 최대 시도 횟수. 기본값인 None이면 준비될 때까지 계속 다듬는다

max_reasoning_attempts가 핵심인데요, 이 값을 줄이면 에이전트가 계획을 다듬는 데 쓸 수 있는 횟수에 제한이 생겨요. 기본값 그대로 두면 준비될 때까지 얼마든지 다듬으니까, 무한정 시도하게 하고 싶지 않다면 명시적으로 값을 넣어주는 걸 추천해요.

전체 예시

추론이 켜진 에이전트로 작업을 만들어 크루에 담아 실행하는 전체 흐름이에요.

from crewai import Agent, Task, Crew

# 추론이 활성화된 에이전트 생성
analyst = Agent(
    role="Data Analyst",
    goal="Analyze data and provide insights",
    backstory="You are an expert data analyst.",
    reasoning=True,
    max_reasoning_attempts=3  # 선택: 추론 시도 횟수 제한
)

# 작업 생성
analysis_task = Task(
    description="Analyze the provided sales data and identify key trends.",
    expected_output="A report highlighting the top 3 sales trends.",
    agent=analyst
)

# 크루를 만들어 작업 실행
crew = Crew(
    agents=[analyst],
    tasks=[analysis_task]
)
result = crew.kickoff()
print(result)

여기서 kickoff()를 호출하면 에이전트가 먼저 작업을 분석해 계획을 세우고, 그 계획을 바탕으로 실제 분석을 수행한 뒤 결과를 돌려줘요.

오류 처리

추론 과정은 처음부터 견고하게 설계되어 있어요. 추론 중에 오류가 발생하면 에이전트는 추론 계획 없이 그냥 작업을 실행하는 쪽으로 넘어가요. 즉 추론만 실패했다고 해서 작업 자체가 멈추는 일은 없어요. 오류를 확인하고 싶다면 로깅을 설정해두면 됩니다.

from crewai import Agent, Task
import logging

# 추론 오류를 잡기 위한 로깅 설정
logging.basicConfig(level=logging.INFO)

# 추론이 활성화된 에이전트 생성
agent = Agent(
    role="Data Analyst",
    goal="Analyze data and provide insights",
    reasoning=True,
    max_reasoning_attempts=3
)

# 작업 생성
task = Task(
    description="Analyze the provided sales data and identify key trends.",
    expected_output="A report highlighting the top 3 sales trends.",
    agent=agent
)

# 작업 실행
# 추론 중 오류가 발생하면 로그에 남고, 실행은 계속된다
result = agent.execute_task(task)

로깅 레벨을 INFO로 맞춰두면 추론 과정에서 생긴 오류가 로그에 남아요. execute_task()를 호출했을 때 추론 중 문제가 생겨도 에이전트는 그대로 작업을 수행하니까, 결과물이 아예 사라질 걱정은 하지 않아도 되죠.

추론 결과 예시

데이터 분석 작업에서 추론 계획이 실제로 어떻게 생기는지 한번 볼게요.

 Task: Analyze the provided sales data and identify key trends.
 Reasoning Plan:
 I'll analyze the sales data to identify the top 3 trends.
 1. Understanding of the task:
    I need to analyze sales data to identify key trends that would be valuable for business decision-making.
 2. Key steps I'll take:
    - First, I'll examine the data structure to understand what fields are available
    - Then I'll perform exploratory data analysis to identify patterns
    - Next, I'll analyze sales by time periods to identify temporal trends
    - I'll also analyze sales by product categories and customer segments
    - Finally, I'll identify the top 3 most significant trends
 3. Approach to challenges:
    - If the data has missing values, I'll decide whether to fill or filter them
    - If the data has outliers, I'll investigate whether they're valid data points or errors
    - If trends aren't immediately obvious, I'll apply statistical methods to uncover patterns
 4. Use of available tools:
    - I'll use data analysis tools to explore and visualize the data
    - I'll use statistical tools to identify significant patterns
    - I'll use knowledge retrieval to access relevant information about sales analysis
 5. Expected outcome:
    A concise report highlighting the top 3 sales trends with supporting evidence from the data.
 READY: I am ready to execute the task.

이 계획을 보면 에이전트가 작업을 어떻게 이해했는지, 어떤 순서로 접근할지, 어떤 난관을 예상하고 대비하는지가 한눈에 드러나요. 마지막에 READY라고 표시된 건 계획이 완성되어 실행할 준비가 됐다는 뜻이에요. 이렇게 계획을 세워두면 실제 작업을 수행할 때 훨씬 체계적으로 접근하고, 기대하는 결과물을 제대로 낼 수 있어요.

실무 관점

추론 기능은 복잡하고 결과물이 어느 정도 정해져 있는 작업에서 진가를 발휘해요. 단순 반복 작업이라면 계획을 세우는 과정이 오히려 시간과 토큰을 더 쓰게 만드는 오버헤드가 될 수 있어요. 따라서 에이전트마다 일괄적으로 reasoning=True를 넣기보다, 데이터 분석이나 조사처럼 여러 단계를 거쳐야 하는 작업을 맡은 에이전트에만 켜는 걸 추천해요.

가격과 지연 시간에도 신경을 써야 해요. 추론이 켜져 있으면 실제 작업 전에 계획을 세우는 LLM 호출이 한 번 더 들어가니까, max_reasoning_attempts를 지정하지 않으면 준비될 때까지 계속 시도하면서 비용이 커질 수 있어요. 실무에서는 이 값을 2~3 정도로 제한해서 계획이 끝없이 돌지 않게 잡아두는 게 안전해요. 또 추론 과정이 실패해도 작업 자체는 계속 실행된다는 점(오류 처리 섹션) 덕분에, 이 옵션을 켰다고 해서 크루 전체가 멈출 위험은 크지 않다는 것도 알고 있으면 좋아요.

더 알아보기

  • CrewAI 에이전트 설정 전반: Agents
  • 에이전트가 수행하는 작업 단위: Tasks
  • 여러 에이전트를 묶어 실행하는 크루: Crews