AI个人学习
和实操指南

CrewAI + Command-R7B 百行代码实现智能生成新闻

本文于 2024-12-17 18:31 更新,部分内容具有时效性,如有失效,请留言

基于 CrewAI 多智能体协作和 Cohere Command-R7B 大模型,系统能自动完成从研究到写作的全流程,像拥有一个 24 小时运转的新闻工作室

CrewAI + Command-R7B 智能新闻生成-1


 

核心功能:

  1. 研究分析:由第一个 AI 助手负责搜索和整理与话题相关的所有资料,包括新闻、数据和专家观点。
  2. 内容创作:第二个 AI 助手将研究资料转化为结构完整的文章,确保专业性和可读性。
  3. 一键生成:用户只需输入话题,系统就会自动完成全部工作。

技术亮点:

  • 采用 crewAI,框架实现多 AI 协作
  • 使用 cohere,Command-R7B 大模型确保输出质量
  • 基于 streamlit,构建简洁易用的网页界面

使用流程:

  1. 在侧边栏输入想要了解的话题
  2. 可选择调整生成参数(如创造性程度)
  3. 点击生成按钮
  4. 等待系统完成研究和写作
  5. 可直接查看或下载生成的文章

 

下面展示的架构图展示了部分关键组件(智能体/任务/工具)以及它们如何相互作用!

接下来将详细描述每个组件及其代码:

-1

 

设置大语言模型(LLM)和网页搜索工具

同时创建一个 .env 文件用于存放它们相应的 API 密钥:

-1

 

高级研究分析员智能体

网页搜索智能体接受用户查询,然后使用 Serper 网页搜索工具从互联网上获取结果并进行整合。

看看这个👇

-1

 

研究分析员智能体任务

这是我们分配给高级研究分析员智能体的研究任务,包含任务描述和预期输出。

-1

 

内容编写智能体

内容编写智能体的角色是使用整理好的结果并将其转化为一篇精美的、可发布的新闻文章。

-1

 

内容编写智能体任务

这是我们如何描述写作任务,包括所有细节和预期输出:

-1

 

设置 Crew,完成了!✅

启动它!🚀

-1

 

部署教程

AI 新闻生成器

该项目利用 CrewAI 和 Cohere 的 Command-R:7B 模型构建了一个 AI 新闻生成器!

安装与设置

获取 API 密钥

安装依赖项
确保您已安装 Python 3.11 或更高版本。

pip install crewai crewai-tools

 

.env.example

SERPER_API_KEY=your_serper_api_key
COHERE_API_KEY=your_cohere_apikey

 

app.py

import os
import streamlit as st
from crewai import Agent, Task, Crew, LLM
from crewai_tools import SerperDevTool
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Streamlit page config
st.set_page_config(page_title="AI News Generator", page_icon="📰", layout="wide")

# Title and description
st.title("🤖 AI News Generator, powered by CrewAI and Cohere's Command R7B")
st.markdown("Generate comprehensive blog posts about any topic using AI agents.")

# Sidebar
with st.sidebar:
st.header("Content Settings")

# Make the text input take up more space
topic = st.text_area(
"Enter your topic",
height=100,
placeholder="Enter the topic you want to generate content about..."
)

# Add more sidebar controls if needed
st.markdown("### Advanced Settings")
temperature = st.slider("Temperature", 0.0, 1.0, 0.7)

# Add some spacing
st.markdown("---")

# Make the generate button more prominent in the sidebar
generate_button = st.button("Generate Content", type="primary", use_container_width=True)

# Add some helpful information
with st.expander("ℹ️ How to use"):
st.markdown("""
1. Enter your desired topic in the text area above
2. Adjust the temperature if needed (higher = more creative)
3. Click 'Generate Content' to start
4. Wait for the AI to generate your article
5. Download the result as a markdown file
""")

def generate_content(topic):
llm = LLM(
model="command-r",
temperature=0.7
)

search_tool = SerperDevTool(n_results=10)

# First Agent: Senior Research Analyst
senior_research_analyst = Agent(
role="Senior Research Analyst",
goal=f"Research, analyze, and synthesize comprehensive information on {topic} from reliable web sources",
backstory="You're an expert research analyst with advanced web research skills. "
"You excel at finding, analyzing, and synthesizing information from "
"across the internet using search tools. You're skilled at "
"distinguishing reliable sources from unreliable ones, "
"fact-checking, cross-referencing information, and "
"identifying key patterns and insights. You provide "
"well-organized research briefs with proper citations "
"and source verification. Your analysis includes both "
"raw data and interpreted insights, making complex "
"information accessible and actionable.",
allow_delegation=False,
verbose=True,
tools=[search_tool],
llm=llm
)

# Second Agent: Content Writer
content_writer = Agent(
role="Content Writer",
goal="Transform research findings into engaging blog posts while maintaining accuracy",
backstory="You're a skilled content writer specialized in creating "
"engaging, accessible content from technical research. "
"You work closely with the Senior Research Analyst and excel at maintaining the perfect "
"balance between informative and entertaining writing, "
"while ensuring all facts and citations from the research "
"are properly incorporated. You have a talent for making "
"complex topics approachable without oversimplifying them.",
allow_delegation=False,
verbose=True,
llm=llm
)

# Research Task
research_task = Task(
description=("""
1. Conduct comprehensive research on {topic} including:
- Recent developments and news
- Key industry trends and innovations
- Expert opinions and analyses
- Statistical data and market insights
2. Evaluate source credibility and fact-check all information
3. Organize findings into a structured research brief
4. Include all relevant citations and sources
"""),
expected_output="""A detailed research report containing:
- Executive summary of key findings
- Comprehensive analysis of current trends and developments
- List of verified facts and statistics
- All citations and links to original sources
- Clear categorization of main themes and patterns
Please format with clear sections and bullet points for easy reference.""",
agent=senior_research_analyst
)

# Writing Task
writing_task = Task(
description=("""
Using the research brief provided, create an engaging blog post that:
1. Transforms technical information into accessible content
2. Maintains all factual accuracy and citations from the research
3. Includes:
- Attention-grabbing introduction
- Well-structured body sections with clear headings
- Compelling conclusion
4. Preserves all source citations in [Source: URL] format
5. Includes a References section at the end
"""),
expected_output="""A polished blog post in markdown format that:
- Engages readers while maintaining accuracy
- Contains properly structured sections
- Includes Inline citations hyperlinked to the original source url
- Presents information in an accessible yet informative way
- Follows proper markdown formatting, use H1 for the title and H3 for the sub-sections""",
agent=content_writer
)

# Create Crew
crew = Crew(
agents=[senior_research_analyst, content_writer],
tasks=[research_task, writing_task],
verbose=True
)

return crew.kickoff(inputs={"topic": topic})

# Main content area
if generate_button:
with st.spinner('Generating content... This may take a moment.'):
try:
result = generate_content(topic)
st.markdown("### Generated Content")
st.markdown(result)

# Add download button
st.download_button(
label="Download Content",
data=result.raw,
file_name=f"{topic.lower().replace(' ', '_')}_article.md",
mime="text/markdown"
)
except Exception as e:
st.error(f"An error occurred: {str(e)}")

# Footer
st.markdown("---")
st.markdown("Built with CrewAI, Streamlit and powered by Cohere's Command R7B")
AI轻松学

普通人的AI入门指南

帮助你以低成本、零基础学会如何利用AI工具。AI就像办公软件一样,是每个人的必备技能。 掌握AI会让你在求职中占据优势,在未来的工作和学习中事半功倍。

查看详情>
未经允许不得转载:首席AI分享圈 » CrewAI + Command-R7B 百行代码实现智能生成新闻

首席AI分享圈

首席AI分享圈专注于人工智能学习,提供全面的AI学习内容、AI工具和实操指导。我们的目标是通过高质量的内容和实践经验分享,帮助用户掌握AI技术,一起挖掘AI的无限潜能。无论您是AI初学者还是资深专家,这里都是您获取知识、提升技能、实现创新的理想之地。

联系我们
zh_CN简体中文