CrewAI 基础 01-GetStart

初次使用 CrewAI ,展示如何使用 CrewAI 库快速构建和运行一个简单的协作团队,以完成特定任务

  • 首先定义了一个搜索引擎工具并设置了本地语言模型与嵌入器。
  • 接着创建了两个代理角色 —— 高级研究员和作家,并为他们分别分配了研究和技术写作的任务。这些任务包括识别领域内的最新趋势以及撰写相关文章。
  • 最后,将这两个代理和任务组织成一个团队,并按照顺序执行流程以完成整个项目。
graph LR
    C[创建高级研究员代理]
    C --> D[分配研究任务给研究员]
    E[创建作家代理]
    E --> F[分配写作任务给作家]
    F --> G[组织团队并启动流程]
    D --> G
    G --> H{是否完成?}
    H -->|否| I[继续执行任务]
    H -->|是| J[输出结果]

首先,这里定义一个互联网查询工具,API 需要自行获取

1
2
3
4
5
6
from api_key import SERPER_API_KEY
import os
os.environ["SERPER_API_KEY"] = SERPER_API_KEY # serper.dev API key

from crewai_tools import SerperDevTool
search_tool = SerperDevTool(n_results=1)

为了让 crewai 在本地运行,通过以下代码设置 llm 及 embedding

1
2
3
4
5
6
7
8
9
10
11
12
from crewai.llm import LLM
llm=LLM(
model="ollama_chat/qwen2.5:latest",
base_url="http://localhost:11434")

embedder={
"provider": "ollama",
"config": {
"model": 'quentinz/bge-large-zh-v1.5:latest',
"base_url": 'http://localhost:11434'
}
}

这里假设团队由 2 个角色组成,1 个是相关领域的研究者、1 个作家,通过研究者的研究成功,作家编写文章

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 设置litellm,不然日志过长
import litellm
litellm.set_verbose=False


from crewai import Agent
# 创建一个带有内存和冗长模式的高级研究员代理人
researcher = Agent(
role='Senior Researcher',
goal='在 {topic} 领域发现突破性技术',
verbose=True,
memory=False,
backstory=(
"出于好奇心驱使,您处于创新的最前沿,渴望探索和分享可能改变世界的知识。"
),
llm=llm,
tools=[search_tool],
allow_delegation=True
)

# 创建一个作家代理人,具有自定义工具和委派能力
writer = Agent(
role='Writer',
goal='讲述关于 {topic} 的引人入胜的科技故事',
verbose=True,
memory=False,
backstory=(
"擅长简化复杂话题,您撰写引人入胜的叙述,吸引人并教育他人,在易于理解的方式中揭示新的发现。"
),
llm=llm,
tools=[search_tool],
allow_delegation=False
)

为团队的不同角色分配任务,指定执行任务可以使用的工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from crewai import Task

# 研究任务
research_task = Task(
description=(
"识别 {topic} 领域的下一个大趋势。"
"专注于识别利弊以及整体叙述。"
"您的最终报告应清楚地阐明关键点、市场机会和潜在风险。"
),
expected_output='一份关于最新人工智能趋势的全面报告,共 3 段。',
tools=[search_tool],
agent=researcher,
)

# 具有语言模型配置的写作任务
write_task = Task(
description=(
"撰写一篇关于 {topic} 的有见地的文章。"
"关注最新趋势及其对行业的影响。"
"这篇文章应易于理解、引人入胜且积极向上。"
),
expected_output='一篇关于 {topic} 进展的 4 段文章,格式为 markdown。',
tools=[search_tool],
agent=writer,
async_execution=False,
output_file='关于"{topic}的进展".md' # 输出定制的示例
)

通过角色(Agent)及任务(Task)定义一个团队,并为这个团队指定以下规则或配置:

  • Process:规定任务执行的顺序,可以假定为企业的标准 SOP,比如申请购买东西,按照填写申请单 -> 主管批准 -> 采购购买 -> 财务付款… 等标准流程
  • Memory:为团队配备存储系统,可以记录每个成员的活动记录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from crewai import Crew, Process

# 以一些增强配置形成以技术为中心的团队
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential, # 可选:顺序任务执行是默认设置
memory=True,
cache=False,
max_rpm=100,
share_crew=False,
verbose=True,
manager_llm=[llm],
embedder=embedder
)
1
2
3
# 让团队开始按照既定流程工作
result = crew.kickoff(inputs={'topic': '医疗人工智能'})
print(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Agent: Senior Researcher ## Task: 识别 医疗人工智能 领域的下一个大趋势。专注于识别利弊以及整体叙述。您的最终报告应清楚地阐明关键点、市场机会和潜在风险。 
# Agent: Senior Researcher ## Using tool: Search the internet ## Tool Input: "{\"search_query\": \"recent breakthroughs in medical AI\"}" ## Tool Output: {'searchParameters': {'q': 'recent breakthroughs in medical AI', 'type': 'search', 'num': 1, 'engine': 'google'}, 'organic': [{'title': 'Top 6 AI Breakthroughs in Healthcare - Docwire News', 'link': '[https://docwirenews.com/post/the-top-6-ai-breakthroughs-in-healthcare](https://docwirenews.com/post/the-top-6-ai-breakthroughs-in-healthcare)', 'snippet': 'Top 6 AI Breakthroughs in Healthcare · Google Creates AI that Detects Lung Cancer Better than Doctors · Discovering Causes of Autism in Uncharted DNA · How do ...', 'position': 1, 'sitelinks': [{'title': 'Google Creates Ai That...', 'link': '[https://docwirenews.com/post/the-top-6-ai-breakthroughs-in-healthcare#:~:text=Google%20Creates%20AI%20that%20Detects%20Lung%20Cancer%20Better%20than%20Doctors](https://docwirenews.com/post/the-top-6-ai-breakthroughs-in-healthcare#:~:text=Google%20Creates%20AI%20that%20Detects%20Lung%20Cancer%20Better%20than%20Doctors)'}, {'title': 'Researchers Use Machine...', 'link': '[https://docwirenews.com/post/the-top-6-ai-breakthroughs-in-healthcare#:~:text=Researchers%20Use%20Machine%20Learning%20and%20Wearable%20Sensor%20to%20Detect%20Heart%20Disease](https://docwirenews.com/post/the-top-6-ai-breakthroughs-in-healthcare#:~:text=Researchers%20Use%20Machine%20Learning%20and%20Wearable%20Sensor%20to%20Detect%20Heart%20Disease)'}, {'title': 'Medical Industry Takes An...', 'link': '[https://docwirenews.com/post/the-top-6-ai-breakthroughs-in-healthcare#:~:text=Medical%20Industry%20Takes%20an%20Important%20Step%20Towards%20Embracing%20AI](https://docwirenews.com/post/the-top-6-ai-breakthroughs-in-healthcare#:~:text=Medical%20Industry%20Takes%20an%20Important%20Step%20Towards%20Embracing%20AI)'}]}], 'relatedSearches': [{'query': 'Recent breakthroughs in medical ai today'}], 'credits': 1} Received None or empty response from LLM call.
# Agent: Senior Researcher ## Task: 识别 医疗人工智能 领域的下一个大趋势。专注于识别利弊以及整体叙述。您的最终报告应清楚地阐明关键点、市场机会和潜在风险。
# Agent: Senior Researcher ## Final Answer: To achieve breakthroughs in medical AI, we need to explore cutting-edge technologies that could significantly impact patient care and treatment methods. Here are some potential areas for research: 1. **Advanced Deep Learning Models**: Investigating novel deep learning architectures such as Transformers or Graph Neural Networks (GNNs) specifically tailored for healthcare applications can lead to improved accuracy in tasks like disease diagnosis, drug discovery, and personalized medicine. 2. **Explainable AI (XAI)**: Developing AI models that provide clear and understandable explanations for their predictions can enhance trust among clinicians and patients, ensuring the effective integration of AI into clinical workflows. 3. **Privacy-Preserving Techniques**: Researching methods to protect patient data while still allowing valuable insights to be extracted from it, such as federated learning or secure multi-party computation (SMPC), is crucial given stringent regulations like GDPR and HIPAA. 4. **Integration with Electronic Health Records (EHRs)**: Improving algorithms for efficient and accurate data extraction and analysis from EHRs can help in early disease detection, predictive analytics, and better patient management. 5. **Robotics and Automation**: Exploring the use of robotic systems and automation technologies to assist in surgeries, drug dispensing, or patient care tasks can improve efficiency and reduce human error. 6. **Bioinformatics and Genomics**: Applying advanced computational methods to genomics data for personalized medicine, predictive analytics, and precision health can lead to groundbreaking advancements in treatment strategies. 7. **Natural Language Processing (NLP)**: Enhancing NLP techniques to better understand clinical notes, research papers, and other unstructured textual data can improve diagnostic accuracy and facilitate knowledge discovery. 8. **IoT and Wearable Devices**: Developing AI algorithms that can effectively analyze data from IoT devices and wearable technology can provide real-time health monitoring and early warning systems for various conditions. By focusing on these areas, we can potentially revolutionize the field of medical AI and bring about significant improvements in healthcare delivery.
# Agent: Writer
## Task: 撰写一篇关于 医疗人工智能 的有见地的文章。关注最新趋势及其对行业的影响。这篇文章应易于理解、引人入胜且积极向上。
# Agent: Writer
## Final Answer: ## 医疗人工智能的下一个大趋势
当前,医疗AI正在以前所未有的速度发展,并为整个行业带来了显著的进步。在接下来的一段时间里,预计将会有一个关键的趋势——即AI将被广泛应用于个性化医疗、精准医学和药物研发领域(HITRUST, 2023)。本文将探讨这一趋势及其对行业的潜在影响。
### AI助力个性化医疗与精准医学
人工智能通过自动化分析大量的医疗数据,帮助医生更迅速地识别疾病并制定个性化的治疗方案。AI技术可以处理并分析来自不同来源的大量信息(如基因组学、影像学和电子病历),从而为患者提供定制化治疗建议。这种精确性不仅能够提高诊断准确性,还能减少不必要的药物使用和副作用。
### 加速药物研发过程
在药物开发方面,使用机器学习技术可以加速新药的研发过程,并降低成本(Medical Economics, 2023)。传统的药物发现方法通常需要数年甚至更长时间才能完成。然而,通过结合AI与先进的生物信息学工具,研究人员可以在短时间内筛选出具有潜在治疗效果的化合物,从而显著缩短开发周期。
### 数据隐私与偏见性问题
尽管医疗AI带来了诸多机遇,但同时也存在一些挑战和风险(MedPro, 2023)。首先,数据隐私问题是一个必须重视的问题。由于医疗保健提供者在接收、存储和传输大量敏感信息时涉及大量数据处理,因此需要谨慎对待以防止数据泄露或滥用。其次,偏见性数据和功能障碍也是人工智能领域的一大隐患,这可能会影响诊断结果的准确性和公平性。
为了使AI技术在医疗保健领域的应用更加安全可靠,必须确保所使用的数据集具有代表性,并通过严格的测试来验证其性能(HITRUST, 2023)。此外,还需要加强对算法公正性的评估和监督机制建设,以减少潜在偏差带来的负面影响。
### 结论
总之,医疗AI的应用无疑为整个行业带来了巨大的机遇与挑战。虽然存在一些风险,但我们仍需继续努力探索和完善相关技术,从而提高医疗服务质量和效率(Medical Economics, 2023)。随着科技的发展和社会的进步,我们相信未来将会有更多创新性的解决方案出现,帮助我们解决医疗领域的各种问题。
参考文献:
- HITRUST. (2023). The Pros and Cons of AI in Healthcare.
- Medical Economics. (2023). AI in health care: the risks and benefits.
- MedPro. (2023). Artificial Intelligence in Healthcare: Challenges and Risks.
通过详细描述AI在医疗领域的应用、带来的好处以及面临的挑战,我们可以更好地了解这一技术对未来的潜在影响。希望这篇文章能够为大家提供有价值的信息和启示。

以下是团队的最终工作成果,由作家输出,并且指定输出为 关于”医疗人工智能“的进展.md

CrewAI-GetStart-20250107105948