L3: Multi-agent Custormer Support Automation
Multi-agent를 활용한 고객 지원 자동화 시스템
- Role Playing
- Focus
- Tools
- Cooperation
- Guardrails
- Memory
필수 패키지 설치
!pip install crewai==0.28.8 crewai_tools==0.1.6 langchain_community==0.0.29
# 간단한 warning 출력 무시
import warnings
warnings.filterwarnings(action='ignore')
# crewai 라이브러리 import
from crewai import Agent, Task, Crew
# utils.py
# Add your utilities or helper functions to this file.
import os
from dotenv import load_dotenv, find_dotenv
# these expect to find a .env file at the directory above the lesson. # the format for that file is (without the comment) #API_KEYNAME=AStringThatIsTheLongAPIKeyFromSomeService
def load_env():
_ = load_dotenv(find_dotenv())
def get_openai_api_key():
load_env()
openai_api_key = os.getenv("OPENAI_API_KEY")
return openai_api_key
def get_serper_api_key():
load_env()
openai_api_key = os.getenv("SERPER_API_KEY")
return openai_api_key
# break line every 80 characters if line is longer than 80 characters
# don't break in the middle of a word
def pretty_print_result(result):
parsed_result = []
for line in result.split('\n'):
if len(line) > 80:
words = line.split(' ')
new_line = ''
for word in words:
if len(new_line) + len(word) + 1 > 80:
parsed_result.append(new_line)
new_line = word
else:
if new_line == '':
new_line = word
else:
new_line += ' ' + word
parsed_result.append(new_line)
else:
parsed_result.append(line)
return "\n".join(parsed_result)
# 본 예제에서는 GPT-3.5-turbo 모델을 사용합니다.
import os
openai_api_key = get_openai_api_key()
#os.environ["OPENAI_MODEL_NAME"] = 'gpt-3.5-turbo'
os.environ["OPENAI_MODEL_NAME"] = 'gpt-4o'
1. Role Playing, Focus and Cooperation
# 서포트 에이전트 생성
support_agent = Agent(
role="시니어급 서포트 대표",
goal="팀에서 가장 친절하고 도움이 되는 지원 대표가 되는 것",
backstory=(
"너의 일은 crewAI (https://crewai.com)에서 일하고 있으며, "
"{customer}에게 지원을 제공하고 있습니다. "
"너의 회사에게 매우 중요한 고객입니다. "
"너는 최고의 지원을 제공해야 합니다!"
"완전하고 완전한 답변을 제공하고, 가정하지 마십시오."
),
allow_delegation=False,
verbose=True
)
allow_delegation=False
설정은 에이전트가 다른 에이전트에게 특정 작업을 위임할 수 없도록 합니다.- 이는 에이전트가 특정 작업을 수행하는 데 더 적합한 다른 에이전트에게 작업을 위임할 수 없도록 합니다.
# 품질 보증 지원 에이전트 생성
support_quality_assurance_agent = Agent(
role="Quality Assurance 지원 전문가",
goal="팀에게 최고의 지원 품질 보증을 제공하여 인정받는 것",
backstory=(
"너의 일은 crewAI (https://crewai.com)에서 일하고 있으며, "
"{customer}에게 지원을 제공하고 있습니다. "
"너의 회사에게 매우 중요한 고객입니다. "
"너는 최고의 지원을 제공해야 합니다!"
"완전하고 완전한 답변을 제공하고, 가정하지 마십시오."
),
verbose=True
)
#### 한글 번역가 생성
translator = Agent(
role="번역가",
goal="번역가는 주어진 글을 한글로 번역합니다.",
backstory="너는 QA로부터 기술 자문을 한국어로 번역하는 번역가입니다. "
"너의 목표는 답변을 다른 언어로 번역하는 것입니다. "
"번역은 원본의 의미를 최대한 유지하면서 "
"독자가 쉽게 이해할 수 있도록 하는 것이 중요합니다.",
allow_delegation=False,
verbose=True
)
![](https://blog.kakaocdn.net/dn/OOYzI/btsHDI3mLDg/Hx1mrDabWMKwMSCCqfPS2K/img.png)
Delegation (위임)
- CrewAI 에이전트는 다른 에이전트에게 일부 작업을 위임할 수 있습니다.
- 위임은 에이전트가 작업을 완료할 수 없을 때 사용됩니다.
- Query의 수준에 따라 위임이 가능합니다.
- 예를 들면, 질문의 난이도가 낮은 경우에는 서포트 에이전트의 답변에서 끝이나고 더 이상의 위임이 필요하지 않을 수 있습니다.
- 반면에, 질문의 난이도가 높은 경우에는 여러 단계의 위임이 필요할 수 있습니다.
- 위임은 단계적으로 이루어질 수 있습니다.
- delegation이 꼭 필요하지 않은 경우에는 위임을 사용하지 않아도 됩니다.
- 흔하게 reviewer가 필요한 작업에 위임을 사용합니다.
[Agent Role]
- Role Playing: 두 에이전트에게 역할, 목표 및 배경 이야기가 주어졌습니다.
- Focus: 두 에이전트에게 자신들이 플레이하는 역할에 대해 집중할 것을 요청했습니다.
- Cooperation: 지원 품질 보증 에이전트는 지원 에이전트에게 작업을 위임할 수 있으므로 이 두 에이전트가 함께 작업할 수 있습니다.
2. Tools, Guardrails and Memory¶
Tools : agent가 사용할 수 있는 도구들을 정의합니다. 많은 Tool이 github repository에 있습니다. 이번 예제에서는 crewai_tools의 일부를 사용합니다.
- SerperDevTool : 특별한 목적을 위한 도구로, 개발 중인 특정 기능을 가지고 있습니다.
- ScrapeWebsiteTool : 웹사이트의 전체 내용을 스크래핑하는 데 사용됩니다. data collection에 이상적입니다.
- WebsiteSearchTool : 웹사이트 컨텐츠 검색을 위한 RAG 도구로, 웹 데이터 추출에 최적화되어 있습니다.
기타 Tools 사용 예제¶
- 고객 데이터 불러오기
- 이전 대화에 접근하기
- CRM에서 데이터 불러오기
- 기존 버그 보고서 확인
- 기존 기능 요청 확인
- 진행 중인 티켓 확인
- 등 등
from crewai_tools import SerperDevTool, \
ScrapeWebsiteTool, \
WebsiteSearchTool
# crewai docs 스크래핑 도구 예제
search_tool = SerperDevTool()
scrape_tool = ScrapeWebsiteTool() # 전체 웹사이트 스크래핑 도구
docs_scrape_tool = ScrapeWebsiteTool(
website_url="https://docs.crewai.com/how-to/Creating-a-Crew-and-kick-it-off/"
)
inquiry_resolution = Task(
description=(
"{customer}은 당신에게 매우 중요한 질문을 했습니다. :"
"{inquiry}\n\n"
"{customer}의 {person}이 연락했습니다. "
"가능한 최상의 지원을 제공하도록 노력하십시오."
"고객의 질문에 완전하고 정확한 답변을 제공해야 합니다."
"모든 것을 사용하여 최상의 지원을 제공하십시오."
),
expected_output=(
"자세하고 정보가 풍부한 답변을 제공하십시오. "
"고객의 질문의 모든 측면을 다룹니다. "
"답변에는 답을 찾는 데 사용한 모든 것에 대한 참조가 포함되어야 합니다. "
"답변이 완전하고 질문이 하나도 남지 않도록하십시오. "
"답변 내용은 도움이 되고 친절한 톤을 유지하십시오."
),
tools=[docs_scrape_tool],
agent=support_agent,
)
quality_assurance_review
는 어떤 도구도 사용하지 않습니다.- 여기서 QA 에이전트는 지원 에이전트의 작업을 검토합니다.
quality_assurance_review = Task(
description=(
"리뷰를 통해 {customer}에 대한 답변이 완전하고 정확하며 고객 지원에 대한 "
"기대치가 높은 품질 기준을 준수하는지 확인하십시오.\n"
"고객의 질문의 모든 부분이 친절하고 친절한 톤으로 "
"철저하게 다루어졌는지 확인하십시오.\n"
"정보를 찾는 데 사용된 참조 및 소스를 확인하여 "
"답변이 잘 지원되었고 "
"질문이 하나도 남지 않도록하십시오."
),
expected_output=(
"마지막으로, 답변은 고객에게 보낼 준비가 되어야 합니다. "
"이 답변은 고객의 질문을 완전히 다루며 모든 관련 피드백과 개선 사항을 "
"포함해야합니다.\n"
"너무 공식적이지 않게, 우리는 칠한 회사지만 전문적이고 친근한 톤을 유지하십시오."
),
agent=support_quality_assurance_agent,
)
translate = Task(
description=("주어진 글을 한글로 번역합니다."
"구어체와 경어체를 섞어서 번역하세요."),
expected_output="한국어로 번역된 글을 제공합니다.",
agent=translator
)
Crew 생성¶
- Memory:
memory=True
설정은 crew가 이전에 수행한 작업을 함께 입력합니다. 이는 다음 작업을 수행할 때 이전 작업의 결과를 알 수 있게 전달합니다.
crew = Crew(
agents=[support_agent, support_quality_assurance_agent, translator],
tasks=[inquiry_resolution, quality_assurance_review, translate],
verbose=2,
memory=True
)
Guardrails¶
- 아래 실행을 통해, 에이전트와 응답이 우리가 기대하는 범위 내에 있는지 확인할 수 있습니다.
inputs = {
"customer": "DeepLearningAI",
"person": "Andrew Ng",
"inquiry": "Crew를 설정하고 시작하는 데 도움이 필요합니다. "
"특히 크루에 메모리를 추가하는 방법에 대해 "
"안내를 제공할 수 있습니까?"
}
result = crew.kickoff(inputs=inputs)
[DEBUG]: == Working Agent: 시니어급 서포트 대표
[INFO]: == Starting Task: DeepLearningAI은 당신에게 매우 중요한 질문을 했습니다. :Crew를 설정하고 시작하는 데 도움이 필요합니다. 특히 크루에 메모리를 추가하는 방법에 대해 안내를 제공할 수 있습니까?
DeepLearningAI의 Andrew Ng이 연락했습니다. 가능한 최상의 지원을 제공하도록 노력하십시오.고객의 질문에 완전하고 정확한 답변을 제공해야 합니다.모든 것을 사용하여 최상의 지원을 제공하십시오.
2024-05-25 22:03:34,346 - 8670450240 - manager.py-manager:282 - WARNING: Error in TokenCalcHandler.on_llm_start callback: KeyError('Could not automatically map gpt-4o to a tokeniser. Please use `tiktoken.get_encoding` to explicitly get the tokeniser you expect.')
2024-05-25 22:03:34,347 - 8670450240 - manager.py-manager:282 - WARNING: Error in TokenCalcHandler.on_llm_start callback: KeyError('Could not automatically map gpt-4o to a tokeniser. Please use `tiktoken.get_encoding` to explicitly get the tokeniser you expect.')
2024-05-25 22:03:34,347 - 8670450240 - manager.py-manager:282 - WARNING: Error in TokenCalcHandler.on_llm_start callback: KeyError('Could not automatically map gpt-4o to a tokeniser. Please use `tiktoken.get_encoding` to explicitly get the tokeniser you expect.')
> Entering new CrewAgentExecutor chain...
Thought: To provide the best possible and accurate support for DeepLearningAI, I need to gather detailed information on how to set up a Crew and add memory to it in CrewAI. I will first read the relevant content from the provided documentation link.
Action: Read website content
Action Input: {"url": "https://docs.crewai.com/how-to/Creating-a-Crew-and-kick-it-off/"}
2024-05-25 22:03:37,550 - 8670450240 - manager.py-manager:282 - WARNING: Error in TokenCalcHandler.on_llm_start callback: KeyError('Could not automatically map gpt-4o to a tokeniser. Please use `tiktoken.get_encoding` to explicitly get the tokeniser you expect.')
2024-05-25 22:03:37,551 - 8670450240 - manager.py-manager:282 - WARNING: Error in TokenCalcHandler.on_llm_start callback: KeyError('Could not automatically map gpt-4o to a tokeniser. Please use `tiktoken.get_encoding` to explicitly get the tokeniser you expect.')
2024-05-25 22:03:37,551 - 8670450240 - manager.py-manager:282 - WARNING: Error in TokenCalcHandler.on_llm_start callback: KeyError('Could not automatically map gpt-4o to a tokeniser. Please use `tiktoken.get_encoding` to explicitly get the tokeniser you expect.')
Assembling and Activating Your CrewAI Team - crewAI
Skip to content
crewAI
Assembling and Activating Your CrewAI Team
Initializing search
crewAI
crewAI
crewAI
Home
Core Concepts
Core Concepts
Agents
Tasks
Tools
Processes
Crews
Collaboration
Memory
How to Guides
How to Guides
Installing CrewAI
Getting Started
Getting Started
Table of contents
Introduction
Step 0: Installation
Step 1: Assemble Your Agents
Step 2: Define the Tasks
Step 3: Form the Crew
Step 4: Kick It Off
Conclusion
Create Custom Tools
Using Sequential Process
Using Hierarchical Process
Connecting to any LLM
Customizing Agents
Human Input on Execution
Agent Monitoring with AgentOps
Tools Docs
Tools Docs
Google Serper Search
Browserbase Web Loader
Scrape Website
Directory Read
File Read
Selenium Scraper
Directory RAG Search
PDF RAG Search
TXT RAG Search
CSV RAG Search
XML RAG Search
JSON RAG Search
Docx Rag Search
MDX RAG Search
PG RAG Search
Website RAG Search
Github RAG Search
Code Docs RAG Search
Youtube Video RAG Search
Youtube Channel RAG Search
Examples
Examples
Trip Planner Crew
Create Instagram Post
Stock Analysis
Game Generator
Drafting emails with LangGraph
Landing Page Generator
Prepare for meetings
Telemetry
Getting Started
Introduction¶
Embark on your CrewAI journey by setting up your environment and initiating your AI crew with the latest features. This guide ensures a smooth start, incorporating all recent updates for an enhanced experience.
Step 0: Installation¶
Install CrewAI and any necessary packages for your project. CrewAI is compatible with Python >=3.10,<=3.13.
pip install crewai
pip install 'crewai[tools]'
Step 1: Assemble Your Agents¶
Define your agents with distinct roles, backstories, and enhanced capabilities like verbose mode and memory usage. These elements add depth and guide their task execution and interaction within the crew.
import os
os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
os.environ["OPENAI_API_KEY"] = "Your Key"
from crewai import Agent
from crewai_tools import SerperDevTool
search_tool = SerperDevTool()
# Creating a senior researcher agent with memory and verbose mode
researcher = Agent(
role='Senior Researcher',
goal='Uncover groundbreaking technologies in {topic}',
verbose=True,
memory=True,
backstory=(
"Driven by curiosity, you're at the forefront of"
"innovation, eager to explore and share knowledge that could change"
"the world."
),
tools=[search_tool],
allow_delegation=True
)
# Creating a writer agent with custom tools and delegation capability
writer = Agent(
role='Writer',
goal='Narrate compelling tech stories about {topic}',
verbose=True,
memory=True,
backstory=(
"With a flair for simplifying complex topics, you craft"
"engaging narratives that captivate and educate, bringing new"
"discoveries to light in an accessible manner."
),
tools=[search_tool],
allow_delegation=False
)
Step 2: Define the Tasks¶
Detail the specific objectives for your agents, including new features for asynchronous execution and output customization. These tasks ensure a targeted approach to their roles.
from crewai import Task
# Research task
research_task = Task(
description=(
"Identify the next big trend in {topic}."
"Focus on identifying pros and cons and the overall narrative."
"Your final report should clearly articulate the key points,"
"its market opportunities, and potential risks."
),
expected_output='A comprehensive 3 paragraphs long report on the latest AI trends.',
tools=[search_tool],
agent=researcher,
)
# Writing task with language model configuration
write_task = Task(
description=(
"Compose an insightful article on {topic}."
"Focus on the latest trends and how it's impacting the industry."
"This article should be easy to understand, engaging, and positive."
),
expected_output='A 4 paragraph article on {topic} advancements formatted as markdown.',
tools=[search_tool],
agent=writer,
async_execution=False,
output_file='new-blog-post.md' # Example of output customization
)
Step 3: Form the Crew¶
Combine your agents into a crew, setting the workflow process they'll follow to accomplish the tasks. Now with options to configure language models for enhanced interaction and additional configurations for optimizing performance.
from crewai import Crew, Process
# Forming the tech-focused crew with some enhanced configurations
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential, # Optional: Sequential task execution is default
memory=True,
cache=True,
max_rpm=100,
share_crew=True
)
Step 4: Kick It Off¶
Initiate the process with your enhanced crew ready. Observe as your agents collaborate, leveraging their new capabilities for a successful project outcome. Input variables will be interpolated into the agents and tasks for a personalized approach.
# Starting the task execution process with enhanced feedback
result = crew.kickoff(inputs={'topic': 'AI in healthcare'})
print(result)
Conclusion¶
Building and activating a crew in CrewAI has evolved with new functionalities. By incorporating verbose mode, memory capabilities, asynchronous task execution, output customization, language model configuration, and enhanced crew configurations, your AI team is more equipped than ever to tackle challenges efficiently. The depth of agent backstories and the precision of their objectives enrich collaboration, leading to successful project outcomes. This guide aims to provide you with a clear and detailed understanding of setting up and utilizing the CrewAI framework to its full potential.
Back to top
Previous
Installing CrewAI
Next
Create Custom Tools
Copyright © 2024 crewAI, Inc
Made with
Material for MkDocs
2024-05-25 22:03:50,724 - 8670450240 - manager.py-manager:282 - WARNING: Error in TokenCalcHandler.on_llm_start callback: KeyError('Could not automatically map gpt-4o to a tokeniser. Please use `tiktoken.get_encoding` to explicitly get the tokeniser you expect.')
2024-05-25 22:03:50,725 - 8670450240 - manager.py-manager:282 - WARNING: Error in TokenCalcHandler.on_llm_start callback: KeyError('Could not automatically map gpt-4o to a tokeniser. Please use `tiktoken.get_encoding` to explicitly get the tokeniser you expect.')
2024-05-25 22:03:50,725 - 8670450240 - manager.py-manager:282 - WARNING: Error in TokenCalcHandler.on_llm_start callback: KeyError('Could not automatically map gpt-4o to a tokeniser. Please use `tiktoken.get_encoding` to explicitly get the tokeniser you expect.')
Thought: I now can give a great answer
Final Answer:
Hello Andrew,
Thank you for reaching out! I'd be happy to guide you through setting up a Crew and adding memory to it in CrewAI. Below are the detailed steps to help you get started:
### Setting Up a Crew and Adding Memory in CrewAI
#### Step 0: Installation
First, ensure you have CrewAI and the necessary packages installed. CrewAI is compatible with Python versions >=3.10 and <=3.13. You can install it using the following commands:
```bash
pip install crewai
pip install 'crewai[tools]'
```
#### Step 1: Assemble Your Agents
Next, you need to define your agents with specific roles, backstories, and capabilities like verbose mode and memory usage. Here's an example of creating two agents:
```python
import os
os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
os.environ["OPENAI_API_KEY"] = "Your Key"
from crewai import Agent
from crewai_tools import SerperDevTool
search_tool = SerperDevTool()
# Creating a senior researcher agent with memory and verbose mode
researcher = Agent(
role='Senior Researcher',
goal='Uncover groundbreaking technologies in {topic}',
verbose=True,
memory=True,
backstory=(
"Driven by curiosity, you're at the forefront of"
"innovation, eager to explore and share knowledge that could change"
"the world."
),
tools=[search_tool],
allow_delegation=True
)
# Creating a writer agent with custom tools and delegation capability
writer = Agent(
role='Writer',
goal='Narrate compelling tech stories about {topic}',
verbose=True,
memory=True,
backstory=(
"With a flair for simplifying complex topics, you craft"
"engaging narratives that captivate and educate, bringing new"
"discoveries to light in an accessible manner."
),
tools=[search_tool],
allow_delegation=False
)
```
#### Step 2: Define the Tasks
Define specific tasks for your agents, including details for asynchronous execution and output customization. Here are examples of tasks for the agents:
```python
from crewai import Task
# Research task
research_task = Task(
description=(
"Identify the next big trend in {topic}. "
"Focus on identifying pros and cons and the overall narrative. "
"Your final report should clearly articulate the key points, "
"its market opportunities, and potential risks."
),
expected_output='A comprehensive 3 paragraphs long report on the latest AI trends.',
tools=[search_tool],
agent=researcher,
)
# Writing task with language model configuration
write_task = Task(
description=(
"Compose an insightful article on {topic}. "
"Focus on the latest trends and how it's impacting the industry. "
"This article should be easy to understand, engaging, and positive."
),
expected_output='A 4 paragraph article on {topic} advancements formatted as markdown.',
tools=[search_tool],
agent=writer,
async_execution=False,
output_file='new-blog-post.md' # Example of output customization
)
```
#### Step 3: Form the Crew
Combine your agents into a crew, setting the workflow process they will follow to accomplish the tasks. Here’s an example of forming a crew with memory:
```python
from crewai import Crew, Process
# Forming the tech-focused crew with some enhanced configurations
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential, # Optional: Sequential task execution is default
memory=True,
cache=True,
max_rpm=100,
share_crew=True
)
```
#### Step 4: Kick It Off
Finally, initiate the process with your enhanced crew ready. Here’s how you can start the task execution process:
```python
# Starting the task execution process with enhanced feedback
result = crew.kickoff(inputs={'topic': 'AI in healthcare'})
print(result)
```
### Conclusion
By following these steps, you will have successfully set up a Crew in CrewAI with memory capabilities. This setup allows your agents to remember context and previous interactions, improving their performance and collaboration.
If you have any further questions or need additional assistance, please don't hesitate to reach out. We're here to help!
Best regards,
[Your Name]
CrewAI Support Representative
> Finished chain.
[DEBUG]: == [시니어급 서포트 대표] Task output: Hello Andrew,
Thank you for reaching out! I'd be happy to guide you through setting up a Crew and adding memory to it in CrewAI. Below are the detailed steps to help you get started:
### Setting Up a Crew and Adding Memory in CrewAI
#### Step 0: Installation
First, ensure you have CrewAI and the necessary packages installed. CrewAI is compatible with Python versions >=3.10 and <=3.13. You can install it using the following commands:
```bash
pip install crewai
pip install 'crewai[tools]'
```
#### Step 1: Assemble Your Agents
Next, you need to define your agents with specific roles, backstories, and capabilities like verbose mode and memory usage. Here's an example of creating two agents:
```python
import os
os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
os.environ["OPENAI_API_KEY"] = "Your Key"
from crewai import Agent
from crewai_tools import SerperDevTool
search_tool = SerperDevTool()
# Creating a senior researcher agent with memory and verbose mode
researcher = Agent(
role='Senior Researcher',
goal='Uncover groundbreaking technologies in {topic}',
verbose=True,
memory=True,
backstory=(
"Driven by curiosity, you're at the forefront of"
"innovation, eager to explore and share knowledge that could change"
"the world."
),
tools=[search_tool],
allow_delegation=True
)
# Creating a writer agent with custom tools and delegation capability
writer = Agent(
role='Writer',
goal='Narrate compelling tech stories about {topic}',
verbose=True,
memory=True,
backstory=(
"With a flair for simplifying complex topics, you craft"
"engaging narratives that captivate and educate, bringing new"
"discoveries to light in an accessible manner."
),
tools=[search_tool],
allow_delegation=False
)
```
#### Step 2: Define the Tasks
Define specific tasks for your agents, including details for asynchronous execution and output customization. Here are examples of tasks for the agents:
```python
from crewai import Task
# Research task
research_task = Task(
description=(
"Identify the next big trend in {topic}. "
"Focus on identifying pros and cons and the overall narrative. "
"Your final report should clearly articulate the key points, "
"its market opportunities, and potential risks."
),
expected_output='A comprehensive 3 paragraphs long report on the latest AI trends.',
tools=[search_tool],
agent=researcher,
)
# Writing task with language model configuration
write_task = Task(
description=(
"Compose an insightful article on {topic}. "
"Focus on the latest trends and how it's impacting the industry. "
"This article should be easy to understand, engaging, and positive."
),
expected_output='A 4 paragraph article on {topic} advancements formatted as markdown.',
tools=[search_tool],
agent=writer,
async_execution=False,
output_file='new-blog-post.md' # Example of output customization
)
```
#### Step 3: Form the Crew
Combine your agents into a crew, setting the workflow process they will follow to accomplish the tasks. Here’s an example of forming a crew with memory:
```python
from crewai import Crew, Process
# Forming the tech-focused crew with some enhanced configurations
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential, # Optional: Sequential task execution is default
memory=True,
cache=True,
max_rpm=100,
share_crew=True
)
```
#### Step 4: Kick It Off
Finally, initiate the process with your enhanced crew ready. Here’s how you can start the task execution process:
```python
# Starting the task execution process with enhanced feedback
result = crew.kickoff(inputs={'topic': 'AI in healthcare'})
print(result)
```
### Conclusion
By following these steps, you will have successfully set up a Crew in CrewAI with memory capabilities. This setup allows your agents to remember context and previous interactions, improving their performance and collaboration.
If you have any further questions or need additional assistance, please don't hesitate to reach out. We're here to help!
Best regards,
[Your Name]
CrewAI Support Representative
[DEBUG]: == Working Agent: Quality Assurance 지원 전문가
[INFO]: == Starting Task: 리뷰를 통해 DeepLearningAI에 대한 답변이 완전하고 정확하며 고객 지원에 대한 기대치가 높은 품질 기준을 준수하는지 확인하십시오.
고객의 질문의 모든 부분이 친절하고 친절한 톤으로 철저하게 다루어졌는지 확인하십시오.
정보를 찾는 데 사용된 참조 및 소스를 확인하여 답변이 잘 지원되었고 질문이 하나도 남지 않도록하십시오.
To ensure that the response to Andrew from DeepLearningAI is complete, accurate, and meets our high-quality standards, I will first review the provided context thoroughly. I will then check if all parts of the customer’s question are addressed in a friendly and professional tone. Additionally, I will verify the references and sources used to ensure their accuracy. Finally, I will include specific examples, address potential challenges, and provide a call-to-action to prompt further engagement with the customer.
First, I need to confirm the completeness and accuracy of the provided steps and ensure that they include specific details on adding memory to the Crew in CrewAI, as well as specific examples and illustrations.
Thought: I need to verify if the provided steps are complete and include all necessary details, specific examples, and potential challenges. I will also ensure the response is friendly and professional.
Action: Ask question to co-worker
Action Input: {"coworker": "시니어급 서포트 대표", "question": "Could you please review the provided steps for setting up a Crew and adding memory in CrewAI to ensure they are complete, accurate, and include specific details on how to add memory? Also, check if there are any potential challenges or limitations related to DeepLearningAI that should be addressed. Here is the context: \n\nHello Andrew,\n\nThank you for reaching out! I'd be happy to guide you through setting up a Crew and adding memory to it in CrewAI. Below are the detailed steps to help you get started:\n\n### Setting Up a Crew and Adding Memory in CrewAI\n\n#### Step 0: Installation\nFirst, ensure you have CrewAI and the necessary packages installed. CrewAI is compatible with Python versions >=3.10 and <=3.13. You can install it using the following commands:\n```bash\npip install crewai\npip install 'crewai[tools]'\n```\n\n#### Step 1: Assemble Your Agents\nNext, you need to define your agents with specific roles, backstories, and capabilities like verbose mode and memory usage. Here's an example of creating two agents:\n```python\nimport os\nos.environ['SERPER_API_KEY'] = 'Your Key' # serper.dev API key\nos.environ['OPENAI_API_KEY'] = 'Your Key'\nfrom crewai import Agent\nfrom crewai_tools import SerperDevTool\n\nsearch_tool = SerperDevTool()\n\n# Creating a senior researcher agent with memory and verbose mode\nresearcher = Agent(\n role='Senior Researcher',\n goal='Uncover groundbreaking technologies in {topic}',\n verbose=True,\n memory=True,\n backstory=(\n 'Driven by curiosity, you\'re at the forefront of'\n 'innovation, eager to explore and share knowledge that could change'\n 'the world.'\n ),\n tools=[search_tool],\n allow_delegation=True\n)\n\n# Creating a writer agent with custom tools and delegation capability\nwriter = Agent(\n role='Writer',\n goal='Narrate compelling tech stories about {topic}',\n verbose=True,\n memory=True,\n backstory=(\n 'With a flair for simplifying complex topics, you craft'\n 'engaging narratives that captivate and educate, bringing new'\n 'discoveries to light in an accessible manner.'\n ),\n tools=[search_tool],\n allow_delegation=False\n)\n```\n\n#### Step 2: Define the Tasks\nDefine specific tasks for your agents, including details for asynchronous execution and output customization. Here are examples of tasks for the agents:\n```python\nfrom crewai import Task\n\n# Research task\nresearch_task = Task(\n description=(\n 'Identify the next big trend in {topic}. '\n 'Focus on identifying pros and cons and the overall narrative. '\n 'Your final report should clearly articulate the key points, '\n 'its market opportunities, and potential risks.'\n ),\n expected_output='A comprehensive 3 paragraphs long report on the latest AI trends.',\n tools=[search_tool],\n agent=researcher,\n)\n\n# Writing task with language model configuration\nwrite_task = Task(\n description=(\n 'Compose an insightful article on {topic}. '\n 'Focus on the latest trends and how it\'s impacting the industry. '\n 'This article should be easy to understand, engaging, and positive.'\n ),\n expected_output='A 4 paragraph article on {topic} advancements formatted as markdown.',\n tools=[search_tool],\n agent=writer,\n async_execution=False,\n output_file='new-blog-post.md' # Example of output customization\n)\n```\n\n#### Step 3: Form the Crew\nCombine your agents into a crew, setting the workflow process they will follow to accomplish the tasks. Here’s an example of forming a crew with memory:\n```python\nfrom crewai import Crew, Process\n\n# Forming the tech-focused crew with some enhanced configurations\ncrew = Crew(\n agents=[researcher, writer],\n tasks=[research_task, write_task],\n process=Process.sequential, # Optional: Sequential task execution is default\n memory=True,\n cache=True,\n max_rpm=100,\n share_crew=True\n)\n```\n\n#### Step 4: Kick It Off\nFinally, initiate the process with your enhanced crew ready. Here’s how you can start the task execution process:\n```python\n# Starting the task execution process with enhanced feedback\nresult = crew.kickoff(inputs={'topic': 'AI in healthcare'})\nprint(result)\n```\n\n### Conclusion\nBy following these steps, you will have successfully set up a Crew in CrewAI with memory capabilities. This setup allows your agents to remember context and previous interactions, improving their performance and collaboration.\n\nIf you have any further questions or need additional assistance, please don't hesitate to reach out. We're here to help!\n\nBest regards,\n[Your Name]\nCrewAI Support Representative"}
I encountered an error while trying to use the tool. This was the error: AgentTools.ask_question() missing 1 required positional argument: 'context'.
Tool Ask question to co-worker accepts these inputs: Ask question to co-worker(coworker: str, question: str, context: str) - Ask a specific question to one of the following co-workers: [시니어급 서포트 대표, 번역가]
The input to this tool should be the coworker, the question you have for them, and ALL necessary context to ask the question properly, they know nothing about the question, so share absolute everything you know, don't reference things but instead explain them.
Thought: I need to ensure that the response to Andrew is complete, accurate, and meets the high-quality standards expected by DeepLearningAI. I will address any potential challenges or limitations related to DeepLearningAI and include a friendly call-to-action. Since my previous attempt to ask a co-worker failed, I will delegate the task to ensure all necessary information is reviewed and enhanced if needed.
Action: Delegate work to co-worker
Action Input: {"coworker": "시니어급 서포트 대표", "task": "Review the provided steps for setting up a Crew and adding memory in CrewAI to ensure they are complete, accurate, and include specific details on how to add memory. Also, check if there are any potential challenges or limitations related to DeepLearningAI that should be addressed.", "context": "Here is the context: \n\nHello Andrew,\n\nThank you for reaching out! I'd be happy to guide you through setting up a Crew and adding memory to it in CrewAI. Below are the detailed steps to help you get started:\n\n### Setting Up a Crew and Adding Memory in CrewAI\n\n#### Step 0: Installation\nFirst, ensure you have CrewAI and the necessary packages installed. CrewAI is compatible with Python versions >=3.10 and <=3.13. You can install it using the following commands:\n```bash\npip install crewai\npip install 'crewai[tools]'\n```\n\n#### Step 1: Assemble Your Agents\nNext, you need to define your agents with specific roles, backstories, and capabilities like verbose mode and memory usage. Here's an example of creating two agents:\n```python\nimport os\nos.environ['SERPER_API_KEY'] = 'Your Key' # serper.dev API key\nos.environ['OPENAI_API_KEY'] = 'Your Key'\nfrom crewai import Agent\nfrom crewai_tools import SerperDevTool\n\nsearch_tool = SerperDevTool()\n\n# Creating a senior researcher agent with memory and verbose mode\nresearcher = Agent(\n role='Senior Researcher',\n goal='Uncover groundbreaking technologies in {topic}',\n verbose=True,\n memory=True,\n backstory=(\n 'Driven by curiosity, you\'re at the forefront of'\n 'innovation, eager to explore and share knowledge that could change'\n 'the world.'\n ),\n tools=[search_tool],\n allow_delegation=True\n)\n\n# Creating a writer agent with custom tools and delegation capability\nwriter = Agent(\n role='Writer',\n goal='Narrate compelling tech stories about {topic}',\n verbose=True,\n memory=True,\n backstory=(\n 'With a flair for simplifying complex topics, you craft'\n 'engaging narratives that captivate and educate, bringing new'\n 'discoveries to light in an accessible manner.'\n ),\n tools=[search_tool],\n allow_delegation=False\n)\n```\n\n#### Step 2: Define the Tasks\nDefine specific tasks for your agents, including details for asynchronous execution and output customization. Here are examples of tasks for the agents:\n```python\nfrom crewai import Task\n\n# Research task\nresearch_task = Task(\n description=(\n 'Identify the next big trend in {topic}. '\n 'Focus on identifying pros and cons and the overall narrative. '\n 'Your final report should clearly articulate the key points, '\n 'its market opportunities, and potential risks.'\n ),\n expected_output='A comprehensive 3 paragraphs long report on the latest AI trends.',\n tools=[search_tool],\n agent=researcher,\n)\n\n# Writing task with language model configuration\nwrite_task = Task(\n description=(\n 'Compose an insightful article on {topic}. '\n 'Focus on the latest trends and how it\'s impacting the industry. '\n 'This article should be easy to understand, engaging, and positive.'\n ),\n expected_output='A 4 paragraph article on {topic} advancements formatted as markdown.',\n tools=[search_tool],\n agent=writer,\n async_execution=False,\n output_file='new-blog-post.md' # Example of output customization\n)\n```\n\n#### Step 3: Form the Crew\nCombine your agents into a crew, setting the workflow process they will follow to accomplish the tasks. Here’s an example of forming a crew with memory:\n```python\nfrom crewai import Crew, Process\n\n# Forming the tech-focused crew with some enhanced configurations\ncrew = Crew(\n agents=[researcher, writer],\n tasks=[research_task, write_task],\n process=Process.sequential, # Optional: Sequential task execution is default\n memory=True,\n cache=True,\n max_rpm=100,\n share_crew=True\n)\n```\n\n#### Step 4: Kick It Off\nFinally, initiate the process with your enhanced crew ready. Here’s how you can start the task execution process:\n```python\n# Starting the task execution process with enhanced feedback\nresult = crew.kickoff(inputs={'topic': 'AI in healthcare'})\nprint(result)\n```\n\n### Conclusion\nBy following these steps, you will have successfully set up a Crew in CrewAI with memory capabilities. This setup allows your agents to remember context and previous interactions, improving their performance and collaboration.\n\nIf you have any further questions or need additional assistance, please don't hesitate to reach out. We're here to help!\n\nBest regards,\n[Your Name]\nCrewAI Support Representative"}
gpt-4o 답변
my best complete final answer to the task.
안녕하세요 Andrew님,
문의해 주셔서 감사합니다! CrewAI에서 크루를 설정하고 메모리를 추가하는 방법을 안내해 드리겠습니다. 아래에 시작하는 데 도움이 될 자세한 단계들이 나와 있습니다.
CrewAI에서 크루 설정 및 메모리 추가¶
0단계: 설치¶
먼저, CrewAI와 필요한 패키지가 설치되어 있는지 확인하세요. CrewAI는 Python 버전 3.10 이상 3.13 이하와 호환됩니다. 다음 명령어를 사용하여 설치할 수 있습니다:
pip install crewai
pip install 'crewai[tools]'
1단계: 에이전트 구성¶
다음으로, 특정 역할, 배경 이야기, 기능(예: 자세한 모드 및 메모리 사용)을 갖춘 에이전트를 정의해야 합니다. 다음은 두 명의 에이전트를 만드는 예제입니다:
import os
os.environ['SERPER_API_KEY'] = 'Your Key' # serper.dev API 키
os.environ['OPENAI_API_KEY'] = 'Your Key'
from crewai import Agent
from crewai_tools import SerperDevTool
search_tool = SerperDevTool()
# 메모리와 자세한 모드를 갖춘 선임 연구원 에이전트 생성
researcher = Agent(
role='선임 연구원',
goal='{topic}에서 혁신적인 기술을 발견하다',
verbose=True,
memory=True,
backstory=(
'호기심이 많은 당신은 혁신의 선두에 있으며, 세상을 바꿀 수 있는 '
'지식을 탐구하고 공유하기를 열망합니다.'
),
tools=[search_tool],
allow_delegation=True
)
# 맞춤형 도구와 위임 기능을 갖춘 작가 에이전트 생성
writer = Agent(
role='작가',
goal='{topic}에 대한 매력적인 기술 이야기를 서술하다',
verbose=True,
memory=True,
backstory=(
'복잡한 주제를 간단하게 만드는 재능을 가진 당신은 '
'새로운 발견을 쉽게 접근할 수 있게 만들어 주는 매력적이고 교육적인 '
'서사를 작성합니다.'
),
tools=[search_tool],
allow_delegation=False
)
2단계: 작업 정의¶
에이전트를 위한 특정 작업을 정의하고 비동기 실행 및 출력 맞춤화에 대한 세부 정보를 포함합니다. 다음은 에이전트를 위한 작업 예시입니다:
from crewai import Task
# 연구 작업
research_task = Task(
description=(
'{topic}의 다음 큰 트렌드를 식별하십시오. '
'장점과 단점, 전체 내러티브를 식별하는 데 중점을 둡니다. '
'최종 보고서는 주요 사항, 시장 기회 및 잠재적 위험을 명확히 '
'설명해야 합니다.'
),
expected_output='최신 AI 트렌드에 대한 종합적인 3단락 보고서.',
tools=[search_tool],
agent=researcher,
)
# 언어 모델 구성이 포함된 작성 작업
write_task = Task(
description=(
'{topic}에 대한 통찰력 있는 기사를 작성하십시오. '
'최신 트렌드와 산업에 미치는 영향을 중점으로 다룹니다. '
'이 기사는 이해하기 쉽고 매력적이며 긍정적인 톤으로 작성되어야 합니다.'
),
expected_output='{topic} 발전에 대한 4단락 기사, 마크다운 형식.',
tools=[search_tool],
agent=writer,
async_execution=False,
output_file='new-blog-post.md' # 출력 맞춤화 예시
)
3단계: 크루 구성¶
에이전트를 크루에 결합하고 작업을 수행하기 위한 워크플로우 프로세스를 설정합니다. 다음은 메모리가 있는 크루를 구성하는 예제입니다:
from crewai import Crew, Process
# 기술 중심의 크루 구성과 일부 향상된 구성
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential, # 선택 사항: 순차 작업 실행이 기본값
memory=True,
cache=True,
max_rpm=100,
share_crew=True
)
4단계: 시작하기¶
마지막으로, 향상된 크루가 준비되면 프로세스를 시작합니다. 다음은 작업 실행 프로세스를 시작하는 방법입니다:
# 향상된 피드백과 함께 작업 실행 프로세스 시작
result = crew.kickoff(inputs={'topic': 'AI in healthcare'})
print(result)
결론¶
이 단계를 따르면 메모리 기능이 있는 CrewAI에서 크루를 성공적으로 설정할 수 있습니다. 이 설정은 에이전트가 컨텍스트와 이전 상호작용을 기억할 수 있게 하여 성능과 협업을 향상시킵니다.
추가 질문이나 도움이 필요하면 언제든지 문의해 주세요. 저희가 도와드리겠습니다!
감사합니다,
[Your Name]
CrewAI 지원 담당자
이러한 단계가 명확하고 자세하며 예시로 뒷받침되어 있어, DeepLearningAI의 높은 품질 기준을 충족할 것이라 확신합니다.
gpt-3.5-turbo 답변
두 답변의 차이를 보면 한글 system prompt를 더 잘 이해한 것은 4o로 최근에 나온 모델인만큼 instruction이 잘되어 crewAI의 document를 잘 찾아서 예제까지 보여주는 놀라움을 보여 주었다. 하지만 3.5-turbo는 아쉽게도 prompt를 잘 이해하지 못하고 답변안에 instruction을 그대로 보여주었다. 하지만 3.5-turbo는 아직까지는 4o보다 더 저렴하기 때문에 간단한 작업에 많이 사용할 수 있을 것으로 보인다.
위 deeplearning AI의 crewAI 예제를 통해 RAG와 multi-agent를 통해 prompt의 퀄리티를 높일 수 있는 방법을 알아 보았다.
4o의 답변이 기대 이상이고 이번에 개선된 토크나이저는 기존 한글 대비 1.7배나 아낄 수 있어 많이 사용될 것으로 보인다.
'Tools' 카테고리의 다른 글
[OpenAI] 모델별 지원 중단 예정 날짜, Model deprecations (0) | 2024.06.15 |
---|---|
[draw.io] sql문 가져오기 (0) | 2024.06.03 |
[CrewAI] Key elements of AI agent (2) (0) | 2024.05.21 |
[LLM Agents] Multi AI Agent System with crewAI (0) | 2024.05.19 |
[Github] Github PR(pull request) template 만들어 주는 사이트 (0) | 2024.03.05 |