주제나 주제에 대해 연구하고 보고서를 작성하는 간단한 크루를 만들어보자. 이를 통해 최신 AI 개발 동향을 파악할 수 있다.
시작하기 전에 crewai와 crewai-tools가 설치되어 있는지 확인한다. 아직 설치하지 않았다면 설치 가이드를 참고해 설치한다.
아래 단계를 따라 크루를 만들어보자! 🚣♂️
1
크루 생성
터미널에서 다음 커맨드를 실행해 새로운 크루 프로젝트를 생성한다. 이 명령어는 latest-ai-development라는 디렉토리를 만들고 기본 구조를 구성한다.
crewai create crew latest-ai-development
2
`agents.yaml` 파일 수정
필요에 따라 에이전트를 수정하거나 그대로 프로젝트에 복사해 사용할 수 있다. agents.yaml과 tasks.yaml 파일에서 {topic}과 같은 변수는 main.py 파일의 값으로 대체된다.
agents.yaml
# src/latest_ai_development/config/agents.yamlresearcher:role:>{topic} Senior Data Researchergoal:> Uncover cutting-edge developments in {topic}backstory:> You're a seasoned researcher with a knack for uncovering the latest developments in {topic}. Known for your ability to find the most relevant information and present it in a clear and concise manner.reporting_analyst:role:>{topic} Reporting Analystgoal:> Create detailed reports based on {topic} data analysis and research findingsbackstory:> You're a meticulous analyst with a keen eye for detail. You're known for your ability to turn complex data into clear and concise reports, making it easy for others to understand and act on the information you provide.
3
`tasks.yaml` 파일 수정
tasks.yaml
# src/latest_ai_development/config/tasks.yamlresearch_task:description:> Conduct a thorough research about {topic} Make sure you find any interesting and relevant information given the current year is 2025.expected_output:> A list with 10 bullet points of the most relevant information about {topic}agent: researcherreporting_task:description:> Review the context you got and expand each topic into a full section for a report. Make sure the report is detailed and contains any and all relevant information.expected_output:> A fully fledge reports with the mains topics, each with a full section of information. Formatted as markdown without '```'agent: reporting_analystoutput_file: report.md
4
`crew.py` 파일 수정
crew.py
# src/latest_ai_development/crew.pyfrom crewai import Agent, Crew, Process, Taskfrom crewai.project import CrewBase, agent, crew, taskfrom crewai_tools import SerperDevTool@CrewBaseclassLatestAiDevelopmentCrew():"""LatestAiDevelopment crew"""@agentdefresearcher(self)-> Agent:return Agent( config=self.agents_config['researcher'], verbose=True, tools=[SerperDevTool()])@agentdefreporting_analyst(self)-> Agent:return Agent( config=self.agents_config['reporting_analyst'], verbose=True)@taskdefresearch_task(self)-> Task:return Task( config=self.tasks_config['research_task'],)@taskdefreporting_task(self)-> Task:return Task( config=self.tasks_config['reporting_task'], output_file='output/report.md'# This is the file that will be contain the final report.)@crewdefcrew(self)-> Crew:"""Creates the LatestAiDevelopment 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,)
5
[선택 사항] 크루 실행 전후 함수 추가
crew.py
# src/latest_ai_development/crew.pyfrom crewai import Agent, Crew, Process, Taskfrom crewai.project import CrewBase, agent, crew, task, before_kickoff, after_kickofffrom crewai_tools import SerperDevTool@CrewBaseclassLatestAiDevelopmentCrew():"""LatestAiDevelopment crew"""@before_kickoffdefbefore_kickoff_function(self, inputs):print(f"Before kickoff function with inputs: {inputs}")return inputs # You can return the inputs or modify them as needed@after_kickoffdefafter_kickoff_function(self, result):print(f"After kickoff function with result: {result}")return result # You can return the result or modify it as needed# ... remaining code
6
크루에 커스텀 입력 전달
예를 들어 topic 입력을 전달해 연구와 보고서를 커스터마이즈할 수 있다.
main.py
#!/usr/bin/env python# src/latest_ai_development/main.pyimport sysfrom latest_ai_development.crew import LatestAiDevelopmentCrewdefrun():""" Run the crew.""" inputs ={'topic':'AI Agents'} LatestAiDevelopmentCrew().crew().kickoff(inputs=inputs)
7
환경 변수 설정
크루를 실행하기 전에 .env 파일에 다음 키를 환경 변수로 설정한다:
OpenAI API 키 (또는 다른 LLM API 키): OPENAI_API_KEY=sk-...
콘솔에서 출력을 확인하고 프로젝트 루트에 report.md 파일이 생성된다. 이 파일에 최종 보고서가 저장된다.
보고서 예시는 다음과 같다:
# Comprehensive Report on the Rise and Impact of AI Agents in 2025## 1. Introduction to AI AgentsIn 2025, Artificial Intelligence (AI) agents are at the forefront of innovation across various industries. As intelligent systems that can perform tasks typically requiring human cognition, AI agents are paving the way for significant advancements in operational efficiency, decision-making, and overall productivity within sectors like Human Resources (HR) and Finance. This report aims to detail the rise of AI agents, their frameworks, applications, and potential implications on the workforce.## 2. Benefits of AI AgentsAI agents bring numerous advantages that are transforming traditional work environments. Key benefits include:-**Task Automation**: AI agents can carry out repetitive tasks such as data entry, scheduling, and payroll processing without human intervention, greatly reducing the time and resources spent on these activities.-**Improved Efficiency**: By quickly processing large datasets and performing analyses that would take humans significantly longer, AI agents enhance operational efficiency. This allows teams to focus on strategic tasks that require higher-level thinking.-**Enhanced Decision-Making**: AI agents can analyze trends and patterns in data, provide insights, and even suggest actions, helping stakeholders make informed decisions based on factual data rather than intuition alone.## 3. Popular AI Agent FrameworksSeveral frameworks have emerged to facilitate the development of AI agents, each with its own unique features and capabilities. Some of the most popular frameworks include:-**Autogen**: A framework designed to streamline the development of AI agents through automation of code generation.-**Semantic Kernel**: Focuses on natural language processing and understanding, enabling agents to comprehend user intentions better.-**Promptflow**: Provides tools for developers to create conversational agents that can navigate complex interactions seamlessly.-**Langchain**: Specializes in leveraging various APIs to ensure agents can access and utilize external data effectively.-**CrewAI**: Aimed at collaborative environments, CrewAI strengthens teamwork by facilitating communication through AI-driven insights.-**MemGPT**: Combines memory-optimized architectures with generative capabilities, allowing for more personalized interactions with users.These frameworks empower developers to build versatile and intelligent agents that can engage users, perform advanced analytics, and execute various tasks aligned with organizational goals.## 4. AI Agents in Human ResourcesAI agents are revolutionizing HR practices by automating and optimizing key functions:-**Recruiting**: AI agents can screen resumes, schedule interviews, and even conduct initial assessments, thus accelerating the hiring process while minimizing biases.-**Succession Planning**: AI systems analyze employee performance data and potential, helping organizations identify future leaders and plan appropriate training.-**Employee Engagement**: Chatbots powered by AI can facilitate feedback loops between employees and management, promoting an open culture and addressing concerns promptly.As AI continues to evolve, HR departments leveraging these agents can realize substantial improvements in both efficiency and employee satisfaction.## 5. AI Agents in FinanceThe finance sector is seeing extensive integration of AI agents that enhance financial practices:-**Expense Tracking**: Automated systems manage and monitor expenses, flagging anomalies and offering recommendations based on spending patterns.-**Risk Assessment**: AI models assess credit risk and uncover potential fraud by analyzing transaction data and behavioral patterns.-**Investment Decisions**: AI agents provide stock predictions and analytics based on historical data and current market conditions, empowering investors with informative insights.The incorporation of AI agents into finance is fostering a more responsive and risk-aware financial landscape.## 6. Market Trends and InvestmentsThe growth of AI agents has attracted significant investment, especially amidst the rising popularity of chatbots and generative AI technologies. Companies and entrepreneurs are eager to explore the potential of these systems, recognizing their ability to streamline operations and improve customer engagement.Conversely, corporations like Microsoft are taking strides to integrate AI agents into their product offerings, with enhancements to their Copilot 365 applications. This strategic move emphasizes the importance of AI literacy in the modern workplace and indicates the stabilizing of AI agents as essential business tools.## 7. Future Predictions and ImplicationsExperts predict that AI agents will transform essential aspects of work life. As we look toward the future, several anticipated changes include:- Enhanced integration of AI agents across all business functions, creating interconnected systems that leverage data from various departmental silos for comprehensive decision-making.- Continued advancement of AI technologies, resulting in smarter, more adaptable agents capable of learning and evolving from user interactions.- Increased regulatory scrutiny to ensure ethical use, especially concerning data privacy and employee surveillance as AI agents become more prevalent.To stay competitive and harness the full potential of AI agents, organizations must remain vigilant about latest developments in AI technology and consider continuous learning and adaptation in their strategic planning.## 8. ConclusionThe emergence of AI agents is undeniably reshaping the workplace landscape in 5. With their ability to automate tasks, enhance efficiency, and improve decision-making, AI agents are critical in driving operational success. Organizations must embrace and adapt to AI developments to thrive in an increasingly digital business environment.
YAML 파일(agents.yaml과 tasks.yaml)에서 사용하는 이름은 Python 코드의 메서드 이름과 일치해야 한다. 예를 들어, tasks.yaml 파일에서 특정 작업에 대한 에이전트를 참조할 수 있다. 이렇게 이름을 일관되게 유지하면 CrewAI가 자동으로 설정과 코드를 연결할 수 있다. 그렇지 않으면 작업이 참조를 제대로 인식하지 못할 수 있다.
agents.yaml 파일의 에이전트 이름(email_summarizer)과 crew.py 파일의 메서드 이름(email_summarizer)이 동일하게 사용된 점을 확인하자.
agents.yaml
email_summarizer:role:> 이메일 요약 담당자goal:> 이메일을 간결하고 명확한 요약으로 정리backstory:> 보고서를 5개의 불릿 포인트로 요약llm: openai/gpt-4o
tasks.yaml 파일의 태스크 이름(email_summarizer_task)과 crew.py 파일의 메서드 이름(email_summarizer_task)이 동일하게 사용된 점을 확인하자.
tasks.yaml
email_summarizer_task:description:> 이메일을 5개의 불릿 포인트로 요약expected_output:> 이메일의 5개 불릿 포인트 요약agent: email_summarizer context:- reporting_task- research_task
특정 역할을 가진 전문 AI 에이전트를 정의할 때 사용한다. 다음 상황에서 활용할 수 있다:
특정 역할을 가진 전문 AI 에이전트를 생성해야 할 때
에이전트를 자동으로 수집하고 관리하고자 할 때
여러 작업에서 동일한 에이전트 설정을 재사용해야 할 때
@agentdefresearch_agent(self)-> Agent:return Agent( role="Research Analyst", goal="Conduct thorough research on given topics", backstory="Expert researcher with years of experience in data analysis", tools=[SerperDevTool()], verbose=True)
@taskdefresearch_task(self)-> Task:return Task( description="AI 기술의 최신 동향을 조사한다", expected_output="AI 발전 상황에 대한 종합 보고서", agent=self.research_agent(), output_file="output/research.md")
에이전트에게 특정 기능을 제공하기 위해 커스텀 도구를 생성할 때 사용한다. 다음과 같은 경우에 활용할 수 있다:
에이전트에게 웹 검색이나 데이터 분석 같은 특정 기능이 필요할 때
외부 API 호출이나 복잡한 작업을 캡슐화하고 싶을 때
여러 에이전트 간에 기능을 공유해야 할 때
@tooldefweb_search_tool(query:str, max_results:int=5)->list[str]:""" 웹에서 정보를 검색한다. Args: query: 검색어 max_results: 반환할 결과의 최대 개수 Returns: 검색 결과 리스트"""# 검색 로직을 구현한다return[f"Result {i} for: {query}"for i inrange(max_results)]
@after_kickoffdefprocess_results(self, result: CrewOutput)-> CrewOutput:"""크루 작업 완료 후 결과를 처리하고 형식화한다.""" result.raw = result.raw.strip() result.raw =f"""# 연구 결과 생성 시간:{datetime.now().isoformat()}{result.raw}"""return result
@callbackdeflog_task_completion(self, task: Task, output:str):"""모니터링을 위해 작업 완료 세부 사항을 기록한다."""print(f"작업 '{task.description}' 완료")print(f"출력 길이: {len(output)} 문자")print(f"사용한 에이전트: {task.agent.role}")print("-"*50)