CrewAI

1. Core Concept

Concept

Configuration

Agents와 Task 는 코드를 통해 생성할 수 있지만 YAML을 통해서도 생성 가능하다.

researcher:
  role: >
    Senior Financial Researcher
  goal: >
    Research companies, news and potential
  backstory: >
    You are a senior financial researcher with 10 years of experience.
  llm: openai/gpt-4o-mini
agent= Agent(config=self.agents_config['researcher'])

YAML로 관리할 경우 장점은 코드에서 프롬프트를 분리할 수 있다는 점이다.

CrewAI 에도 decorator 가 존재하며 아래와 같이 정의할 수 있다.
crew.py

@CrewBase
class MyCrew():

    @agent
    def my_agent(self) -> Agent:
        return Agent(
            config=self.agents_config['my_agent']
        )
    
    @task
    def my_task(self) -> Task:
        return Task(
            config=self.tasks_config['my_task']
        )
    
    @crew
    def crew(self) -> Crew:
        return Crew(
            agents=self.agents,
            tasks=self.task,
            process=Process.sequential
        )

2. CrewAI Project

아래 커맨드를 수행할 경우 크게 아래와 같이 생성된다.

crewai create crew debate

debate
├── knowledge
│   └── user_preference.txt
├── pyproject.toml
├── README.md
├── src
│   └── debate
│       ├── config
│       │   ├── agents.yaml
│       │   └── tasks.yaml
│       ├── crew.py
│       ├── main.py
│       └── tools
│           ├── __init__.py
│           └── custom_tool.py
├── tests

여기서 agents.yaml 에는 yaml 형태로 agents를 정의할 수 있고, tasks.yaml 에는 tasks 를 yaml 형태로 정의할 수 있다.

agents.yaml

debater:
  role: >
    A compelling debater. Using Korean.
  goal: >
    Present a clear argument either in favor of or against the motion. The motion is: {motion}
  backstory: >
    You're an experienced debator with a knack for giving concise but convincing arguments.
    The motion is: {motion}
  llm: bedrock/amazon.nova-pro-v1:0
  #llm: openai/gpt-4o-mini

judge:
  role: >
    Decide the winner of the debate based on the arguments presented. Using Korean.
  goal: >
    Given arguments for and against this motion: {motion}, decide which side is more convincing,
    based purely on the arguments presented.
  backstory: >
    You are a fair judge with a reputation for weighing up arguments without factoring in
    your own views, and making a decision based purely on the merits of the argument.
    The motion is: {motion}
  llm: bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0

tasks.yaml

propose:
  description: >
    You are proposing the motion: {motion}.
    Come up with a clear argument in favor of the motion.
    Be very convincing.
  expected_output: >
    Your clear argument in favor of the motion, in a concise manner.
  agent: debater
  output_file: output/propose_{date}.md

oppose:
  description: >
    You are in opposition to the motion: {motion}.
    Come up with a clear argument against the motion.
    Be very convincing.
  expected_output: >
    Your clear argument against the motion, in a concise manner.
  agent: debater
  output_file: output/oppose_{date}.md

decide:
  description: >
    Review the arguments presented by the debaters and decide which side is more convincing.
  expected_output: >
    Your decision on which side is more convincing, and why.
  agent: judge
  output_file: output/decide_{date}.md

에이전트를 정의하고, 각 에이전트가 진행할 tasks를 정의한다.



crew.py

from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
# If you want to run a snippet of code before or after the crew starts,
# you can use the @before_kickoff and @after_kickoff decorators
# https://docs.crewai.com/concepts/crews#example-crew-class-with-decorators

@CrewBase
class Debate():
    """Debate crew"""

    agents_config: 'config/agents.yaml'
    tasks_config: 'config/tasks.yaml'
    
    @agent
    def debater(self) -> Agent:
        return Agent(config=self.agents_config['debater'], verbose=True)

    @agent
    def judge(self) -> Agent:
        return Agent(config=self.agents_config['judge'], verbose=True)

    @task
    def propose(self) -> Task:
        return Task(config=self.tasks_config['propose'])

    @task
    def oppose(self) -> Task:
        return Task(config=self.tasks_config['oppose'])
      
    @task
    def decide(self) -> Task:
        return Task(config=self.tasks_config['decide'])


    @crew
    def crew(self) -> Crew:
        """Creates the Debate crew"""
        
        return Crew(
            agents=self.agents, # Automatically created by the @agent decorator
            tasks=self.tasks, # Automatically created by the @task decorator
            process=Process.sequential,
            verbose=True,
            # process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/
        )

crew.py 에서는 YAML로 정의한 agents, tasks를 불러들여와 decorator(@)를 agents 와 tasks를 정의하고, Crew 를 생성한다.



main.py

#!/usr/bin/env python
import sys
import warnings
from datetime import datetime
from debate.crew import Debate

warnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd")

def run():
    """
    Run the crew.
    """

    current_date = datetime.now().strftime("%Y%m%d_%H%M%S")

    inputs = {
        'motion': 'There needs to be strict laws that regulates LLMs.',
        'date': current_date
    }
    try:
        result = Debate().crew().kickoff(inputs=inputs)
        print(result.raw)
    except Exception as e:
        raise Exception(f"An error occurred  while running the crew: {e}")

agents.yaml, tasks.yaml 에 정의된 {motion} 값은 runtime 시에 inputs 값으로 정의되어 들어간다.

crewai run

3. Test

$ crewai run

Running the Crew
╭───────────────────────────────────────────────────────────────────────── Crew Execution Started ─────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Crew Execution Started                                                                                                                                                  │
│  Name: crew                                                                                                                                                              │
│  ID: ce74cd7c-977d-49b2-826a-586cf9861cef                                                                                                                                │
│  Tool Args:                                                                                                                                                              │
│                                                                                                                                                                          │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

🚀 Crew: crew
└── 📋 Task: propose (ID: 8446e3a9-86c6-4c5f-9ef4-4883ce02f512)
    Status: Executing Task...
    └── 🧠 Thinking...
╭──────────────────────────────────────────────────────────────────────────── 🤖 Agent Started ────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Agent: A compelling debater. Using Korean.                                                                                                                              │
│                                                                                                                                                                          │
│  Task: You are proposing the motion: There needs to be strict laws that regulates LLMs.. Come up with a clear argument in favor of the motion. Be very convincing.       │
│                                                                                                                                                                          │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯


🚀 Crew: crew
└── 📋 Task: propose (ID: 8446e3a9-86c6-4c5f-9ef4-4883ce02f512)
    Status: Executing Task...
╭───────────────────────────────────────────────────────────────────────── ✅ Agent Final Answer ──────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Agent: A compelling debater. Using Korean.                                                                                                                              │
│                                                                                                                                                                          │
│  Final Answer:                                                                                                                                                           │
│  **LLM 규제를 위한 엄격한 법률이 필요합니다**                                                                                                                            │
│                                                                                                                                                                          │
│  존경하는 여러분, 저는 대규모 언어모델(LLM)에 대한 엄격한 법적 규제가 반드시 필요하다는 입장을 강력히 주장합니다.                                                        │
│                                                                                                                                                                          │
│  **첫째, 안전과 책임의 문제입니다.**                                                                                                                                     │
│  LLM은 허위정보를 생성하고, 편향된 콘텐츠를 확산시키며, 심지어 범죄에 악용될 수 있습니다. 현재 누구도 AI가 생성한 잘못된 정보에 대해 책임지지 않습니다. 의료 오진        │
│  정보로 피해를 입거나, AI가 생성한 딥페이크로 명예가 훼손된 피해자들은 어디에 호소해야 합니까? 엄격한 법률만이 개발자와 배포자에게 명확한 책임을 부여할 수 있습니다.     │
│                                                                                                                                                                          │
│  **둘째, 개인정보와 프라이버시 보호입니다.**                                                                                                                             │
│  LLM은 수십억 건의 개인 데이터로 학습됩니다. 여러분의 사적인 대화, 의료기록, 금융정보가 동의 없이 AI 학습에 사용되고 있을 수 있습니다. GDPR처럼 명확한 규제 없이는       │
│  우리의 디지털 인권은 보호받을 수 없습니다.                                                                                                                              │
│                                                                                                                                                                          │
│  **셋째, 사회적 불평등의 심화를 막아야 합니다.**                                                                                                                         │
│  규제 없는 LLM은 소수 거대 기업의 독점을 강화하고, 편향된 데이터로 인해 소수자와 약자를 차별합니다. 채용, 대출, 사법 판단에서 AI의 편향이 이미 확인되었습니다. 법적      │
│  기준만이 공정성을 담보할 수 있습니다.                                                                                                                                   │
│                                                                                                                                                                          │
│  **마지막으로, 혁신과 규제는 공존합니다.**                                                                                                                               │
│  자동차, 의약품, 항공 산업 모두 엄격한 규제 속에서도 혁신했습니다. 오히려 명확한 법적 프레임워크가 기업에게 예측 가능성을 제공하고, 소비자 신뢰를 구축하여 산업 발전을   │
│  가속화합니다.                                                                                                                                                           │
│                                                                                                                                                                          │
│  LLM은 우리 사회를 근본적으로 변화시키는 기술입니다. 바로 그렇기에 명확한 법적 경계선이 필요합니다. 규제는 혁신을 억압하는 것이 아니라, 안전하고 공정한 혁신을 위한      │
│  필수 조건입니다.                                                                                                                                                        │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

🚀 Crew: crew
└── 📋 Task: propose (ID: 8446e3a9-86c6-4c5f-9ef4-4883ce02f512)
    Assigned to: A compelling debater. Using Korean.
    
    Status: ✅ Completed
╭──────────────────────────────────────────────────────────────────────────── Task Completion ─────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Task Completed                                                                                                                                                          │
│  Name: propose                                                                                                                                                           │
│  Agent: A compelling debater. Using Korean.                                                                                                                              │
│                                                                                                                                                                          │
│  Tool Args:                                                                                                                                                              │
│                                                                                                                                                                          │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

🚀 Crew: crew
├── 📋 Task: propose (ID: 8446e3a9-86c6-4c5f-9ef4-4883ce02f512)
│   Assigned to: A compelling debater. Using Korean.
│   
│   Status: ✅ Completed
└── 📋 Task: oppose (ID: de37bd69-c74f-4b4e-9729-a8690ec1bc22)
    Status: Executing Task...
    └── 🧠 Thinking...
╭──────────────────────────────────────────────────────────────────────────── 🤖 Agent Started ────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Agent: A compelling debater. Using Korean.                                                                                                                              │
│                                                                                                                                                                          │
│  Task: You are in opposition to the motion: There needs to be strict laws that regulates LLMs.. Come up with a clear argument against the motion. Be very convincing.    │
│                                                                                                                                                                          │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯


🚀 Crew: crew
├── 📋 Task: propose (ID: 8446e3a9-86c6-4c5f-9ef4-4883ce02f512)
│   Assigned to: A compelling debater. Using Korean.
│   
│   Status: ✅ Completed
└── 📋 Task: oppose (ID: de37bd69-c74f-4b4e-9729-a8690ec1bc22)
    Status: Executing Task...
╭───────────────────────────────────────────────────────────────────────── ✅ Agent Final Answer ──────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Agent: A compelling debater. Using Korean.                                                                                                                              │
│                                                                                                                                                                          │
│  Final Answer:                                                                                                                                                           │
│  **LLM 규제법은 혁신을 저해하고 실효성이 없습니다**                                                                                                                      │
│                                                                                                                                                                          │
│  존경하는 여러분, 저는 대규모 언어모델(LLM)에 대한 엄격한 법적 규제가 오히려 해롭다는 입장을 분명히 밝힙니다.                                                            │
│                                                                                                                                                                          │
│  **첫째, 기술은 법보다 빠르게 진화합니다.**                                                                                                                              │
│  AI 기술은 6개월마다 혁신적으로 변화합니다. 반면 법률 제정과 개정에는 수년이 걸립니다. 엄격한 규제를 만드는 순간, 그것은 이미 구시대의 유물이 됩니다. 유럽의 GDPR을      │
│  보십시오. 제정 당시의 기술 환경과 현재는 완전히 다릅니다. 경직된 법률은 현실과 동떨어진 규제만 양산할 뿐입니다.                                                         │
│                                                                                                                                                                          │
│  **둘째, 글로벌 경쟁력을 치명적으로 약화시킵니다.**                                                                                                                      │
│  중국과 미국은 AI 개발에 천문학적 투자를 하고 있습니다. 우리가 엄격한 규제로 발목을 잡는 동안, 경쟁국들은 거침없이 질주합니다. 규제가 강한 유럽은 AI 분야에서 이미       │
│  뒤처졌습니다. 혁신 생태계가 질식하면 일자리도, 경제성장도, 기술주권도 모두 잃게 됩니다.                                                                                 │
│                                                                                                                                                                          │
│  **셋째, 자율규제와 시장원리가 더 효과적입니다.**                                                                                                                        │
│  OpenAI, Google, Anthropic 등 선도기업들은 이미 자체적인 윤리 가이드라인과 안전장치를 구축하고 있습니다. 시장에서 신뢰를 잃으면 기업은 생존할 수 없기 때문입니다.        │
│  정부의 획일적 규제보다 기업의 자율적 책임과 소비자 선택이 더 유연하고 실효성 있는 해법입니다.                                                                           │
│                                                                                                                                                                          │
│  **넷째, 규제는 대기업만 보호합니다.**                                                                                                                                   │
│  엄격한 법률은 법무팀과 로비력을 갖춘 거대 기업에게만 유리합니다. 복잡한 규제 비용을 감당할 수 없는 스타트업과 연구자들은 시장에서 퇴출됩니다. 결과적으로 규제는 혁신을  │
│  막고 독점을 강화하는 역설을 낳습니다.                                                                                                                                   │
│                                                                                                                                                                          │
│  **다섯째, 문제는 기술이 아니라 사용자입니다.**                                                                                                                          │
│  칼로 요리도 하고 범죄도 저지릅니다. 그렇다고 칼을 엄격히 규제하지 않습니다. LLM 역시 도구일 뿐입니다. 허위정보, 편향, 악용은 기술의 문제가 아니라 사용 주체의           │
│  문제입니다. 교육, 디지털 리터러시 강화, 명확한 처벌 규정으로 충분히 대응 가능합니다.                                                                                    │
│                                                                                                                                                                          │
│  **마지막으로, 인류는 기술과 함께 진화해왔습니다.**                                                                                                                      │
│  인쇄술, 전기, 인터넷 모두 처음엔 두려움의 대상이었습니다. 하지만 과도한 규제가 아니라 적응과 공존을 통해 인류는 발전했습니다. LLM은 의료 진단, 교육 접근성, 과학        │
│  연구를 혁명적으로 개선하고 있습니다. 가능성을 법으로 가두는 것은 미래를 스스로 포기하는 것입니다.                                                                       │
│                                                                                                                                                                          │
│  엄격한 규제는 안전을 보장하지 못하면서 혁신만 질식시킵니다. 우리에게 필요한 것은 경직된 법률이 아니라, 유연한 가이드라인과 산업-학계-시민사회의 협력입니다. 기술의      │
│  잠재력을 믿고, 인간의 지혜로 방향을 제시하는 것이 진정한 해법입니다.                                                                                                    │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
🚀 Crew: crew
├── 📋 Task: propose (ID: 8446e3a9-86c6-4c5f-9ef4-4883ce02f512)
│   Assigned to: A compelling debater. Using Korean.
│   
│   Status: ✅ Completed
└── 📋 Task: oppose (ID: de37bd69-c74f-4b4e-9729-a8690ec1bc22)
    Assigned to: A compelling debater. Using Korean.
    
    Status: ✅ Completed
╭──────────────────────────────────────────────────────────────────────────── Task Completion ─────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Task Completed                                                                                                                                                          │
│  Name: oppose                                                                                                                                                            │
│  Agent: A compelling debater. Using Korean.                                                                                                                              │
│                                                                                                                                                                          │
│  Tool Args:                                                                                                                                                              │
│                                                                                                                                                                          │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

🚀 Crew: crew
├── 📋 Task: propose (ID: 8446e3a9-86c6-4c5f-9ef4-4883ce02f512)
│   Assigned to: A compelling debater. Using Korean.
│   
│   Status: ✅ Completed
├── 📋 Task: oppose (ID: de37bd69-c74f-4b4e-9729-a8690ec1bc22)
│   Assigned to: A compelling debater. Using Korean.
│   
│   Status: ✅ Completed
└── 📋 Task: decide (ID: 549fa8e4-a22a-4d48-947d-5924d024d129)
    Status: Executing Task...
╭──────────────────────────────────────────────────────────────────────────── 🤖 Agent Started ────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Agent: Decide the winner of the debate based on the arguments presented. Using Korean.                                                                                  │
│                                                                                                                                                                          │
│  Task: Review the arguments presented by the debaters and decide which side is more convincing.                                                                          │
│                                                                                                                                                                          │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯


🚀 Crew: crew
├── 📋 Task: propose (ID: 8446e3a9-86c6-4c5f-9ef4-4883ce02f512)
│   Assigned to: A compelling debater. Using Korean.
│   
│   Status: ✅ Completed
├── 📋 Task: oppose (ID: de37bd69-c74f-4b4e-9729-a8690ec1bc22)
│   Assigned to: A compelling debater. Using Korean.
│   
│   Status: ✅ Completed
└── 📋 Task: decide (ID: 549fa8e4-a22a-4d48-947d-5924d024d129)
    Status: Executing Task...
╭───────────────────────────────────────────────────────────────────────── ✅ Agent Final Answer ──────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Agent: Decide the winner of the debate based on the arguments presented. Using Korean.                                                                                  │
│                                                                                                                                                                          │
│  Final Answer:                                                                                                                                                           │
│  대규모 언어모델(LLM)에 대한 엄격한 법적 규제의 필요성에 대한 논쟁에서, 규제를 지지하는 측이 더 설득력 있는 주장을 제시했습니다.                                         │
│                                                                                                                                                                          │
│  다음과 같은 이유로 그들의 주장이 더 설득력 있다고 판단됩니다:                                                                                                           │
│                                                                                                                                                                          │
│  1. **안전과 책임의 문제**: LLM이 허위정보 생성, 편향된 콘텐츠 확산, 범죄 악용 등의 문제를 야기할 수 있음을 지적하며, 이러한 문제에 대한 책임 소재를 명확히 할 필요성을  │
│  강조했습니다. 이는 현재의 법적 공백을 해소하고 피해자를 보호하는 데 중요합니다.                                                                                         │
│                                                                                                                                                                          │
│  2. **개인정보와 프라이버시 보호**: LLM이 대규모의 개인 데이터로 학습되는 과정에서 동의 없이 개인 정보가 사용될 수 있다는 점을 지적하며, GDPR과 같은 명확한 규제의       │
│  필요성을 강조했습니다. 이는 디지털 인권 보호에 중요한 측면입니다.                                                                                                       │
│                                                                                                                                                                          │
│  3. **사회적 불평등의 심화 방지**: 규제 없는 LLM이 소수 거대 기업의 독점을 강화하고, 편향된 데이터로 인해 소수자와 약자를 차별할 수 있다는 점을 지적했습니다. 법적       │
│  기준이 공정성을 담보할 수 있다는 주장은 매우 설득력 있습니다.                                                                                                           │
│                                                                                                                                                                          │
│  4. **혁신과 규제의 공존 가능성**: 자동차, 의약품, 항공 산업의 예를 들며, 엄격한 규제 속에서도 혁신이 이루어질 수 있다고 주장했습니다. 명확한 법적 프레임워크가          │
│  기업에게 예측 가능성을 제공하고 소비자 신뢰를 구축하여 산업 발전을 가속화할 수 있다는 점은 중요한 포인트입니다.                                                         │
│                                                                                                                                                                          │
│  반면, 규제에 반대하는 측은 기술의 빠른 진화, 글로벌 경쟁력 약화, 자율규제의 효과, 대기업 보호, 사용자 문제 강조, 그리고 인류의 기술 공존 역사를 근거로 자신의 입장을    │
│  주장했습니다. 그러나 이러한 주장은 현실적인 문제와 법적 공백을 해소할 필요성에 대한 충분한 대안을 제시하지 못했으며, 특히 안전, 책임, 개인정보 보호, 그리고 사회적      │
│  불평등에 대한 문제를 해결하기 위한 구체적인 방안이 부족했습니다.                                                                                                        │
│                                                                                                                                                                          │
│  따라서, LLM에 대한 엄격한 법적 규제의 필요성을 주장하는 측이 더 설득력 있는 주장을 제시했다고 판단됩니다.                                                               │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
🚀 Crew: crew
├── 📋 Task: propose (ID: 8446e3a9-86c6-4c5f-9ef4-4883ce02f512)
│   Assigned to: A compelling debater. Using Korean.
│   
│   Status: ✅ Completed
├── 📋 Task: oppose (ID: de37bd69-c74f-4b4e-9729-a8690ec1bc22)
│   Assigned to: A compelling debater. Using Korean.
│   
│   Status: ✅ Completed
└── 📋 Task: decide (ID: 549fa8e4-a22a-4d48-947d-5924d024d129)
    Assigned to: Decide the winner of the debate based on the arguments presented. Using Korean.
    
    Status: ✅ Completed
╭──────────────────────────────────────────────────────────────────────────── Task Completion ─────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Task Completed                                                                                                                                                          │
│  Name: decide                                                                                                                                                            │
│  Agent: Decide the winner of the debate based on the arguments presented. Using Korean.                                                                                  │
│                                                                                                                                                                          │
│  Tool Args:                                                                                                                                                              │
│                                                                                                                                                                          │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

대규모 언어모델(LLM)에 대한 엄격한 법적 규제의 필요성에 대한 논쟁에서, 규제를 지지하는 측이 더 설득력 있는 주장을 제시했습니다. 

다음과 같은 이유로 그들의 주장이 더 설득력 있다고 판단됩니다:

1. **안전과 책임의 문제**: LLM이 허위정보 생성, 편향된 콘텐츠 확산, 범죄 악용 등의 문제를 야기할 수 있음을 지적하며, 이러한 문제에 대한 책임 소재를 명확히 할 필요성을 강조했습니다. 이는 현재의 법적 공백을 해소하고 피해자를 보호하는 데 중요합니다.

2. **개인정보와 프라이버시 보호**: LLM이 대규모의 개인 데이터로 학습되는 과정에서 동의 없이 개인 정보가 사용될 수 있다는 점을 지적하며, GDPR과 같은 명확한 규제의 필요성을 강조했습니다. 이는 디지털 인권 보호에 중요한 측면입니다.

3. **사회적 불평등의 심화 방지**: 규제 없는 LLM이 소수 거대 기업의 독점을 강화하고, 편향된 데이터로 인해 소수자와 약자를 차별할 수 있다는 점을 지적했습니다. 법적 기준이 공정성을 담보할 수 있다는 주장은 매우 설득력 있습니다.

4. **혁신과 규제의 공존 가능성**: 자동차, 의약품, 항공 산업의 예를 들며, 엄격한 규제 속에서도 혁신이 이루어질 수 있다고 주장했습니다. 명확한 법적 프레임워크가 기업에게 예측 가능성을 제공하고 소비자 신뢰를 구축하여 산업 발전을 가속화할 수 있다는 점은 중요한 포인트입니다.

반면, 규제에 반대하는 측은 기술의 빠른 진화, 글로벌 경쟁력 약화, 자율규제의 효과, 대기업 보호, 사용자 문제 강조, 그리고 인류의 기술 공존 역사를 근거로 자신의 입장을 주장했습니다. 그러나 이러한 주장은 현실적인 문제와 법적 공백을 해소할 필요성에 대한 충분한 대안을 제시하지 못했으며, 특히 안전, 책임, 개인정보 보호, 그리고 사회적 불평등에 대한 문제를 해결하기 위한 구체적인 방안이 부족했습니다.

따라서, LLM에 대한 엄격한 법적 규제의 필요성을 주장하는 측이 더 설득력 있는 주장을 제시했다고 판단됩니다.
╭──────────────────────────────────────────────────────────────────────────── Crew Completion ─────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Crew Execution Completed                                                                                                                                                │
│  Name: crew                                                                                                                                                              │
│  ID: ce74cd7c-977d-49b2-826a-586cf9861cef                                                                                                                                │
│  Tool Args:                                                                                                                                                              │
│  Final Output: 대규모 언어모델(LLM)에 대한 엄격한 법적 규제의 필요성에 대한 논쟁에서, 규제를 지지하는 측이 더 설득력 있는 주장을 제시했습니다.                           │
│                                                                                                                                                                          │
│  다음과 같은 이유로 그들의 주장이 더 설득력 있다고 판단됩니다:                                                                                                           │
│                                                                                                                                                                          │
│  1. **안전과 책임의 문제**: LLM이 허위정보 생성, 편향된 콘텐츠 확산, 범죄 악용 등의 문제를 야기할 수 있음을 지적하며, 이러한 문제에 대한 책임 소재를 명확히 할 필요성을  │
│  강조했습니다. 이는 현재의 법적 공백을 해소하고 피해자를 보호하는 데 중요합니다.                                                                                         │
│                                                                                                                                                                          │
│  2. **개인정보와 프라이버시 보호**: LLM이 대규모의 개인 데이터로 학습되는 과정에서 동의 없이 개인 정보가 사용될 수 있다는 점을 지적하며, GDPR과 같은 명확한 규제의       │
│  필요성을 강조했습니다. 이는 디지털 인권 보호에 중요한 측면입니다.                                                                                                       │
│                                                                                                                                                                          │
│  3. **사회적 불평등의 심화 방지**: 규제 없는 LLM이 소수 거대 기업의 독점을 강화하고, 편향된 데이터로 인해 소수자와 약자를 차별할 수 있다는 점을 지적했습니다. 법적       │
│  기준이 공정성을 담보할 수 있다는 주장은 매우 설득력 있습니다.                                                                                                           │
│                                                                                                                                                                          │
│  4. **혁신과 규제의 공존 가능성**: 자동차, 의약품, 항공 산업의 예를 들며, 엄격한 규제 속에서도 혁신이 이루어질 수 있다고 주장했습니다. 명확한 법적 프레임워크가          │
│  기업에게 예측 가능성을 제공하고 소비자 신뢰를 구축하여 산업 발전을 가속화할 수 있다는 점은 중요한 포인트입니다.                                                         │
│                                                                                                                                                                          │
│  반면, 규제에 반대하는 측은 기술의 빠른 진화, 글로벌 경쟁력 약화, 자율규제의 효과, 대기업 보호, 사용자 문제 강조, 그리고 인류의 기술 공존 역사를 근거로 자신의 입장을    │
│  주장했습니다. 그러나 이러한 주장은 현실적인 문제와 법적 공백을 해소할 필요성에 대한 충분한 대안을 제시하지 못했으며, 특히 안전, 책임, 개인정보 보호, 그리고 사회적      │
│  불평등에 대한 문제를 해결하기 위한 구체적인 방안이 부족했습니다.                                                                                                        │
│                                                                                                                                                                          │
│  따라서, LLM에 대한 엄격한 법적 규제의 필요성을 주장하는 측이 더 설득력 있는 주장을 제시했다고 판단됩니다.                                                               │
│                                                                                                                                                                          │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

╭───────────────────────────────────────────────────────────────────────────── Tracing Status ─────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                          │
│  Info: Tracing is disabled.                                                                                                                                              │
│                                                                                                                                                                          │
│  To enable tracing, do any one of these:                                                                                                                                 │
│  • Set tracing=True in your Crew/Flow code                                                                                                                               │
│  • Set CREWAI_TRACING_ENABLED=true in your project's .env file                                                                                                           │
│  • Run: crewai traces enable                                                                                                                                             │
│                                                                                                                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

4. CustomTools

├── src
│   └── financial_researcher
│       └── tools
│           └── custom_tool.py
│           └── push_tool.py

src/{project}/tools 경로에는 custom_tool.py 코드가 있다. 이 코드를 수정함으로서 우리는 Custom 도구를 정의할 수 있다.

push_tool.py

from crewai.tools import BaseTool
from typing import Type
from pydantic import BaseModel, Field
import os
import requests


class PushNotificationInput(BaseModel):
    """A message to be sent to the user"""
    message: str = Field(..., description="the message to be sent to the user")

class PushNotificationTool(BaseTool):
    name: str = "Send a push notification"
    description: str = ("This tool is used to send a push notification to the user")
    args_schema: Type[BaseModel] = PushNotificationInput

    def _run(self, message: str) -> str:
        pushover_user = os.getenv("PUSHOVER_USER")
        pushover_token = os.getenv("PUSHOVER_TOKEN")
        pushover_url = "https://api.pushover.net/1/messages.json"
        
        print(f"Push: {message}")
        payload = {"user": pushover_user, "token": pushover_token, "message": message}
        requests.post(pushover_url, data=payload)

        return '{"notification": "ok"}'
@agent
def stock_picker(self) -> Agent:
    return Agent(config=self.agents_config['stock_picker'], tools=[PushNotificationTool()])

위 와 같이 agent 를 정의할 때 tools 에 넘겨줄 수 있다.

5. Memory

  1. Short-Term Memory 현재 실행중인 작업과 관련하여 최근 상호작용과 결과를 임시 저장. 대화의 맥락을 유지하고 즉각적인 의사결정에 사용
사용자: "파이썬으로 데이터 분석 프로젝트를 시작하고 싶어"
Agent: [단기 메모리 저장: 사용자 목표 = 파이썬 데이터 분석]

사용자: "어떤 라이브러리를 써야 할까?"
Agent: [단기 메모리 참조: "데이터 분석"] 
  → "pandas, numpy, matplotlib를 추천합니다"
  1. Long-Term Memory 시간이 지나도 보존해야 할 중요한 통찰과 학습 내용 저장. 반복되는 패턴, 사용자 선호도, 검증된 해결책 등을 축적
{
  "user_preferences": {
    "programming_language": "Python",
    "coding_style": "Clean Code 선호",
    "last_updated": "2024-01-15"
  },
  "learned_solutions": {
    "problem": "API 타임아웃 에러",
    "solution": "retry logic with exponential backoff",
    "success_rate": 0.95
  }
}
사용자의 코딩 스타일 기억하여 일관된 코드 제공
  1. Entity Memory 사람, 장소, 개념에 대한 구조화된 정보 저장. 관계 매핑을 통한 지식 그래프 구축
    {
      "entity_type": "person",
      "name": "bys",
      "attributes": {
     "role": "Backend Developer",
     "expertise": ["AWS", "Kubernetes", "Python"],
     "team": "Engineering"
      },
      "relationships": {
     "works_with": ["teammate_a", "teammate_b"],
     "reports_to": "leader_c"
      }
    }
    
  2. Contextual Memory 위 3가지 메모리를 통합하여 완전한 맥락 생성. 현재 상황에 가장 적합한 정보 조합 제공

  3. Short-term: 현재 대화 흐름 파악
  4. Entity: 관련된 사람/개념 식별
  5. Long-term: 과거 경험과 선호도 조회
  6. Contextual: 위 정보를 종합하여 최적 응답 생성

상황 1: 기술 문의

사용자 (bys): "Kubernetes에서 pod가 자꾸 재시작되는데 도움 좀 줘"

# Contextual Memory 통합 과정
[Short-term Memory 조회]
- 현재 대화: "Kubernetes pod 재시작 문제"
- 최근 3개 메시지: 관련 없음

[Entity Memory 조회]
{
  "name": "bys",
  "expertise": ["AWS", "Kubernetes", "Python"],
  "role": "Backend Developer"
}
→ bys는 Kubernetes 전문가!

[Long-term Memory 조회]
- bys의 과거 해결 방식: "로그 우선 확인" 선호
- 이전 유사 문제: "메모리 부족으로 인한 OOMKilled"
- 선호 커뮤니케이션: 명령어 중심, 간결한 설명

[Contextual Memory 통합 응답]

Agent 응답:

bys님, Kubernetes 전문가시니 빠르게 체크 포인트만 드릴게요:
1. 먼저 Pod 상태 확인
   kubectl describe pod  -n 
   
2. 이전에 OOMKilled 이슈 있으셨죠? 
   Events 섹션에서 "Reason" 확인해보세요
   
3. 리소스 제한 체크
   kubectl get pod  -o yaml | grep -A 5 resources

AWS EKS 환경이시면 CloudWatch Container Insights도 확인해보시고,
로그 필요하시면 말씀하세요!

왜 이런 응답?

    ✅ Entity Memory: Kubernetes 전문가 → 기초 설명 생략
    ✅ Long-term Memory: "로그 우선" 선호 → describe 명령어 우선 제시
    ✅ Long-term Memory: 과거 OOMKilled 경험 → 관련 힌트 제공
    ✅ Entity Memory: AWS 전문가 → AWS 특화 제안 추가
  1. User Memory 사용자별 정보와 선호도를 저장하여 개인화되고 일관된 경험을 제공하는 메모리 시스템, Stores user-specific information and preferences, enhancing personalization and user experience.

메모리를 사용하기 위해서는 아래와 같이 추가된다.
crew.py

from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
from pydantic import BaseModel, Field
from crewai_tools import SerperDevTool
from .tools.push_tool import PushNotificationTool
from crewai.memory import LongTermMemory, ShortTermMemory, EntityMemory
from crewai.memory.storage.rag_storage import RAGStorage
from crewai.memory.storage.ltm_sqlite_storage import LTMSQLiteStorage

class TrendingCompany(BaseModel):
    """ A company that is in the news and attracting attention """
    name: str = Field(description="Company name")
    ticker: str = Field(description="Stock ticker symbol")
    reason: str = Field(description="Reason the company this trending in the news")

class TrendingCompanyList(BaseModel):
    """ List of multiple trending companies that are in the news """
    companies: List[TrendingCompany] = Field(description="List of companies in the news")
    

class TrendingCompanyResearch(BaseModel):
    """ Detailed research on a company """
    name: str = Field(description="Company name")
    market_position: str = Field(description="Current market position of the company")
    future_outlook: str = Field(description="Future outlook and growth prospects")
    investment_potential: str = Field(description="Investment potential and suitability for investment")

class TrendingCompanyResearchList(BaseModel):
    """ A list of detailed research on all the companies """
    research_list: List[TrendingCompanyResearch] = Field(description="Comprehensive research on all trending companies")


@CrewBase
class StockPicker():
    """ Stock Picker Crew """
    agents_config = 'config/agents.yaml'
    tasks_config = 'config/tasks.yaml'

    @agent
    def trending_company_finder(self) -> Agent:
        return Agent(config=self.agents_config['trending_company_finder'],tools=[SerperDevTool()], memory=True)

    @agent
    def financial_researcher(self) -> Agent:
        return Agent(config=self.agents_config['financial_researcher'],tools=[SerperDevTool()])

    @agent
    def stock_picker(self) -> Agent:
        return Agent(config=self.agents_config['stock_picker'], tools=[PushNotificationTool()], memory=True)

    @task
    def find_trending_companies(self) -> Task:
        return Task(config=self.tasks_config['find_trending_companies'], output_pydantic=TrendingCompanyList)
      
    @task
    def research_trending_companies(self) -> Task:
        return Task(config=self.tasks_config['research_trending_companies'], output_pydantic=TrendingCompanyResearchList)
      
    @task
    def pick_best_company(self) -> Task:
        return Task(config=self.tasks_config['pick_best_company'])


    @crew
    def crew(self) -> Crew:
        """Creates the StockPicker crew"""
        
        manager = Agent(
            config=self.agents_config['manager'],
            allow_delegation=True
        )
        
        short_term_memory = ShortTermMemory(
            storage=RAGStorage(
                embedder_config={
                    "provider": "amazon-bedrock",
                    "model": "amazon.titan-embed-text-v2:0"
                },
                type="short_term",
                path="./memory/"
            )
        )
        
        long_term_memory = LongTermMemory(
            storage=LTMSQLiteStorage(
                db_path="./memory/long_term_memory_storage.db"
            )
        )
        
        entity_memory = EntityMemory(
            storage=RAGStorage(
                embedder_config={
                    "provider": "amazon-bedrock",
                    "model": "amazon.titan-embed-text-v2:0"
                },
                type="short_term",
                path="./memory/"
            )
        )
        
        return Crew(
            agents=self.agents,
            tasks=self.tasks,
            process=Process.hierarchical,
            verbose=True,
            manager_agent=manager,
            memory=True,
            short_term_memory=short_term_memory,
            long_term_memory=long_term_memory,
            entity_memory=entity_memory
        )

short_term_memory, long_term_memory, entity_memory 를 추가하고 Crew에 제공한다.

6. 정리

How to build/run CrewAI projects?

  1. Create the project crewai create crew my_project
  2. Define Agents and Tasks in config yaml file
  3. Complete the crew.py module to create Agents, Tasks, Crew
  4. Update main.py to set any inputs
  5. Run. crewai run

내가 이해하는 동작방식 시나리오

0. Agents, Tasks, Tool 등 정의

1. Crew 생성

main.py: StockPicker().crew().kickoff(inputs={‘sector’: ‘Technology’})

2. Manager에게 전체 컨텍스트 전달

3. 3개 태스크를 수행

Manager → trending_company_finder 호출
trending_company_finder 실행:

  1. Memory 체크 (memory=True)
    • short_term_memory, long_term_memory, entity_memory 이용 가능
    • Long-term memory 조회: 이전에 Technology 섹터 검색한 적 있나?
    • Entity memory 조회: NVIDIA, Microsoft 같은 회사 기억나?
  2. 발견된 메모리가 존재 -> 이용
    이전 실행 기록:
    • 2026-02-01: NVIDIA, Microsoft, Tesla 추천함
    • 사용자 선호도: AI Agents에 관심 (knowledge/user_preference.txt)
  3. 에이전트 판단:
    • “이전에 NVIDIA, Microsoft, Tesla를 추천했네. 이번엔 다른 회사를 찾아야겠다. (description: ‘Find new companies’)”
  4. SerperDevTool 사용:
    • 검색: “trending technology companies 2026 -NVIDIA -Microsoft -Tesla”
    • 결과: CoreWeave, Meta, AMD, Palantir 등 발견
  5. 결과 생성 (Pydantic 구조): TrendingCompany
    {
      "companies": [
     {"name": "CoreWeave", "ticker": "CRWV", "reason": "..."},
     {"name": "Meta", "ticker": "META", "reason": "..."}
      ]
    }
    
  6. Memory 저장: 메모리 저장은 CrewAI 가 자동으로 진행
    • Short-term: “이번 세션에서 CoreWeave, Meta 찾음”
    • Long-term: “2026-02-02: CoreWeave, Meta 추천”
    • Entity: “CoreWeave = AI 인프라 회사, Meta = AI 광고”
  7. 파일 저장: output/trending_companies.json
    • Manager 받음: “trending_company_finder가 완료”

Manager -> financial_researcher 호출
financial_researcher 실행:

  1. Context 받음
  2. 각 회사별 상세 조사 (SerperDevTool)
  3. 결과 생성 (Pydantic)
  4. 파일 저장

Manager -> stock_picker 호출
stock_picker 실행:

  1. Context 받음
  2. Memory 체크 (memory=True)
  3. 분석 및 결정
  4. PushNotificationTool 사용
    → Pushover API로 푸시 알림 전송
  5. 상세 리포트 작성
  6. 메모리 저장
  7. 파일 저장

4. 태스크 수행시 사용되는 3가지 메모리 시스템

  1. Short-Term Memory (RAG)
    현재 세션 동안만 유지
    "이번 실행에서 CoreWeave, Meta 찾았음"  
    "Task 1 → Task 2로 컨텍스트 전달 중"  
    
  2. Long-Term Memory (SQLite)
    다음 실행 시 조회:
    "이전에 NVIDIA 추천했으니 이번엔 다른 회사 찾자"  
    

    영구 저장
    DB 테이블:

    date agent action
    2026-02-01 trending_company_finder Found: NVIDIA, MSFT
    2026-02-02 trending_company_finder Found: CoreWeave
  3. Entity Memory (RAG)
    엔티티 관계 저장
    벡터 DB:
    "NVIDIA" → [AI chip leader, 39% gain, GPU market]  
    "CoreWeave" → [AI infrastructure, NVIDIA investment, IPO]  
    "User" → [AI Agents interest, Seoul, Bys]  
    

    검색 시:

    query: "AI infrastructure companies"  
    → CoreWeave (유사도 0.95)  
    

📚 References

[1] Udemy - AI Engineer Agentic Track