도약하다

[CrewAI] 에이전트 만들기 본문

데이터 사이언스/AI

[CrewAI] 에이전트 만들기

doyak1223 2024. 6. 25. 02:49

이번 시간에는 파이썬으로 토픽을 정해주면 그에 맞는 플랜을 짜고 플랜에 따라 글을 작성하고 편집까지 해주는 다중 에이전트 시스템을 만들어 보자. 

1. 준비 과정

개발을 시작하기 앞서서 필요한 라이브러리들을 아래 코드를 사용하여 설치 해 주어야 한다.

!pip install crewai==0.28.8 crewai_tools==0.1.6 langchain_community==0.0.29

 

설치가 되었다면 필요한 라이브러리들을 불러오자.

# Warning control
import warnings
warnings.filterwarnings('ignore')

# Import from the CrewAI library
from crewai import Agent, Task, Crew

# other libraries
import os
from utils import get_openai_api_key

 

우리는 OpenAI의 GPT 3.5 Turbo 라는 모델을 LLM으로 사용하여 에이전트를 만들 것이기 때문에, 이를 지정 해주어야 한다.

openai_api_key = get_openai_api_key()
os.environ["OPENAI_MODEL_NAME"] = 'gpt-3.5-turbo'

 

2. 에이전트 만들기

필요한 준비를 마쳤다면, 본격적으로 에이전트들을 만들어보자. crewAI를 사용하여 에이전트를 만들 때, role (역할), goal (목적), 그리고 backstory (배경)을 세팅 해 주어야 한다. 이는 LLM 모델들에게 역할을 부여 했을 때 더 성능이 좋다는 연구 결과를 바탕으로 한 것이다.

2a. Planner

블로그 글을 쓰기 위한 첫번째 에이전트로 Planner를 만들어 보자. 

planner = Agent(
    role="Content Planner",
    goal="Plan engaging and factually accurate content on {topic}",
    backstory="You're working on planning a blog article "
              "about the topic: {topic}."
              "You collect information that helps the "
              "audience learn something "
              "and make informed decisions. "
              "Your work is the basis for "
              "the Content Writer to write an article on this topic.",
    allow_delegation=False,
	verbose=True
)

 

위 코드에서 볼 수 있듯이, 세가지 (role, goal, backstory) 는 필수로 지정 해주어야 하고, 추가로 allow_deligation, 업무를 가장 적합한 에이전트에게 위임할 수 있도록 할 것인지, 그리고 verbose, 에이전트 들의 업무 처리 진행 상황을 볼 수 있도록 할 것인지를 지정 해 주었다. 이 외에도 여러 선택적으로 지정 해줄 수 있는 속성들이 있는데, crewAI 공식 문서에서 확인 할 수 있다.

 

한가지 눈여겨 볼 점은, 속성을 세팅 할 때 

varname = """line 1 of text
             line 2 of text
          """

 

이런식이 아닌,

varname = "line 1 of text"
          "line 2 of text"

 

 

이런식으로 지정을 해주었다는 점이다. 이렇게 하는 이유는 새로운 줄을 시작할 때 맨 앞에 생기는 띄어쓰기를 없에서 모델이 이해하기 쉽도록 포맷을 해줄 수 있기 때문이다.

 

2b. Writer

두번째 에이전트는 Planner의 결과를 바탕으로 글을 써 줄 Writer이다.

writer = Agent(
    role="Content Writer",
    goal="Write insightful and factually accurate "
         "opinion piece about the topic: {topic}",
    backstory="You're working on a writing "
              "a new opinion piece about the topic: {topic}. "
              "You base your writing on the work of "
              "the Content Planner, who provides an outline "
              "and relevant context about the topic. "
              "You follow the main objectives and "
              "direction of the outline, "
              "as provide by the Content Planner. "
              "You also provide objective and impartial insights "
              "and back them up with information "
              "provide by the Content Planner. "
              "You acknowledge in your opinion piece "
              "when your statements are opinions "
              "as opposed to objective statements.",
    allow_delegation=False,
    verbose=True
)

2c. Editor

그리고 마지막으로 Writer의 글을 수정 해 줄 Editor까지 만들어 주면된다.

editor = Agent(
    role="Editor",
    goal="Edit a given blog post to align with "
         "the writing style of the organization. ",
    backstory="You are an editor who receives a blog post "
              "from the Content Writer. "
              "Your goal is to review the blog post "
              "to ensure that it follows journalistic best practices,"
              "provides balanced viewpoints "
              "when providing opinions or assertions, "
              "and also avoids major controversial topics "
              "or opinions when possible.",
    allow_delegation=False,
    verbose=True
)

 

3. 업무 설정하기

모든 에이전트들을 만들었다면, 다음으로는 이 에이전트들을 사용하여 무엇을 할 것인지, Task를 설정해야한다. Task를 설정할 때 역시 정해주어야 하는 세가지의 필수 속성, description, expected_output, agent 가 있다. Description은 말 그대로 task를 LLM에게 설명 해 주는 것이고, expected_output은 결과 값이 어떤 내용이 어떤 형식으로 출력되길 원하는지 알려주는 것이고, 마지막으로 agent는 이 업무를 맡길 agent를 지정 해 주는 것이다.

3a. Plan

plan = Task(
    description=(
        "1. Prioritize the latest trends, key players, "
            "and noteworthy news on {topic}.\n"
        "2. Identify the target audience, considering "
            "their interests and pain points.\n"
        "3. Develop a detailed content outline including "
            "an introduction, key points, and a call to action.\n"
        "4. Include SEO keywords and relevant data or sources."
    ),
    expected_output="A comprehensive content plan document "
        "with an outline, audience analysis, "
        "SEO keywords, and resources.",
    agent=planner,
)

 

3b. Write

write = Task(
    description=(
        "1. Use the content plan to craft a compelling "
            "blog post on {topic}.\n"
        "2. Incorporate SEO keywords naturally.\n"
		"3. Sections/Subtitles are properly named "
            "in an engaging manner.\n"
        "4. Ensure the post is structured with an "
            "engaging introduction, insightful body, "
            "and a summarizing conclusion.\n"
        "5. Proofread for grammatical errors and "
            "alignment with the brand's voice.\n"
    ),
    expected_output="A well-written blog post "
        "in markdown format, ready for publication, "
        "each section should have 2 or 3 paragraphs.",
    agent=writer,
)

 

3c. Edit

edit = Task(
    description=("Proofread the given blog post for "
                 "grammatical errors and "
                 "alignment with the brand's voice."),
    expected_output="A well-written blog post in markdown format, "
                    "ready for publication, "
                    "each section should have 2 or 3 paragraphs.",
    agent=editor
)

 

이로써 각각의 에이전트들에게 맡길 세가지의 업무를 만들어보았다. 이제 본격적으로 크루를 만들어 일을 시켜보자.

4. 크루

크루는 우리가 만든 에이전트들로 구성하는 팀이라고 생각하면 된다. 그리고 누가 어떤 업무를 할 것인지 지정 해주어 순차적으로 일이 진행 되도록 하면 된다. 우리가 만들고 있는 시스템은 먼저 플랜을 하고 그 다음에 글을 쓰고 그 다음에 편집을 하는 상호의존적인 업무들로 이루어져있기 때문에, 순서를 제대로 하는 것이 중요하다. 

crew = Crew(
    agents=[planner, writer, editor],
    tasks=[plan, write, edit],
    verbose=2
)

 

planner가 plan을, writer가 write을, 마지막으로 editor가 edit을 할 수 있도록 다시 한번 순서를 확인 해준 뒤, 크루에게 일을 시작하라고 신호를 주고 결과를 기다리기만 하면된다! 이번 글에서는 Artificial Intelligence에 관한 글을 써달라고 해보자. 

result = crew.kickoff(inputs={"topic": "Artificial Intelligence"})

 

결과:

더보기

Unleashing the Power of Artificial Intelligence: Trends, Players, and News

Introduction

Artificial Intelligence (AI) has revolutionized various industries by offering innovative solutions and driving efficiency. From AI-powered chatbots to machine learning technologies, the impact of AI is undeniable. In this blog post, we will explore the latest trends, key players, and noteworthy news in the AI space, providing valuable insights to business professionals, technology enthusiasts, students, and researchers interested in AI.

The AI landscape is constantly evolving, with new trends shaping the industry. One significant trend is the rise of AI-powered chatbots and virtual assistants, which are transforming customer interactions and enhancing user experience. Additionally, there has been an increased adoption of machine learning and deep learning technologies, enabling companies to analyze vast amounts of data and make informed decisions. Furthermore, AI is being integrated into cybersecurity and fraud detection systems, enhancing security measures and reducing risks. In the healthcare sector, AI is expanding its reach, playing a crucial role in diagnosis and treatment processes.

Key Players in the Artificial Intelligence Industry

Several key players dominate the AI industry, each contributing to advancements in technology. Google's DeepMind is renowned for its cutting-edge research in AI, while IBM Watson offers cognitive computing solutions for various applications. Microsoft Azure AI provides cloud-based AI services, and Amazon Web Services (AWS) AI offers scalable machine learning solutions. NVIDIA specializes in AI hardware, driving innovations in the field.

Noteworthy News in Artificial Intelligence

In recent news, OpenAI's GPT-3 has made a breakthrough in natural language processing, showcasing the potential of AI in understanding human language. Advancements in computer vision technology have paved the way for autonomous vehicles, revolutionizing the transportation industry. However, with these advancements come ethical implications, raising concerns about the use of AI in decision-making processes and the need for responsible AI development.

Audience Analysis

Our target audience includes business professionals, technology enthusiasts, students, and researchers interested in AI trends, key players in the industry, and news updates. By providing comprehensive insights into the world of AI, we aim to address their pain points of understanding complex AI concepts, staying updated with the latest developments, and making informed decisions about AI technologies.

Conclusion with a Call to Action

In conclusion, Artificial Intelligence continues to shape the future of various industries, offering endless possibilities for innovation and growth. By staying informed about the latest trends, key players, and news in the AI space, our audience can harness the power of AI to drive success in their respective fields. Stay tuned for more updates on AI technology and its impact on industries.

By following this content plan and incorporating SEO keywords naturally, we have provided a comprehensive overview of Artificial Intelligence, catering to our target audience's interests and pain points. Let's continue to explore the limitless potential of AI together.

이로써 다중 에이전트 시스템의 기초를 구현 해보았다. 아주 간편하게 구현할 수 있다는 점이 인상 깊은데, 이에 창의적인 생각이 더해지면 아주 유용한 방법으로 사용할 수 있을 것 같다는 생각이든다!