使用 Swarm 构建多智能体新闻助理,利用Swarm 框架和 Llama 3.2 来自动化新闻处理工作流

本文将带你构建一个多智能体新闻助理,利用 OpenAI 的 Swarm 框架和 Llama 3.2 来自动化新闻处理工作流。在本地运行环境下,我们将实现一个多智能体系统,让不同的智能体各司其职,分步完成新闻搜索、信息综合与摘要生成等任务,而无需付费使用外部服务。

一、应用设计

相关技术

Swarm

OpenAI Swarm 是一个新兴的多智能体协作框架,旨在通过集成强化学习和分布式计算的优势来解决复杂问题。该框架允许多个智能体在共享环境中同时交互与学习,彼此共享信息,从而提高决策质量和学习效率。Swarm 框架采用先进的强化学习算法,使智能体能够在动态环境中持续适应和优化策略,同时通过分布式计算高效利用资源,加速训练过程。它具有很强的可扩展性,能够根据需求增加智能体数量,适应不同规模和复杂度的任务。应用场景广泛,包括智能交通系统、机器人群体和游戏开发等,OpenAI Swarm 为实现更高效的智能系统提供了灵活且强大的解决方案,推动各领域的智能化进程。

本文我们将使用 Swarm 框架来构建智能体。

DuckDuckGo

DuckDuckGo 是一家以隐私保护为核心的互联网搜索引擎公司。与其他主流搜索引擎不同,DuckDuckGo承诺不追踪用户的搜索历史,也不收集个人数据,从而提供更高的隐私保护。该搜索引擎通过结合多种来源的数据,包括自有的网络爬虫和第三方API,提供快速且相关的搜索结果。

DuckDuckGo 的主要特点包括:

  • 隐私保护:不记录用户的IP地址,不存储搜索历史,不使用个人数据进行广告定向。

  • 简洁界面:提供简洁、无广告干扰的用户界面,提升用户体验。

  • 即时答案:通过“零点击信息”功能,直接在搜索结果页面提供答案,减少用户点击次数。

  • 开源社区:鼓励开发者参与改进和扩展其服务,部分代码和数据源是开源的。

我们将使用 DuckDuckGo 进行实时新闻搜索,获取最新信息。将会有一个专门的智能体将负责向 DuckDuckGo 发送搜索请求并处理返回结果。

Llama

通过 Ollama 应用在本地运行 meta 公司的大模型 Llama 3.2。使之成为智能体的模型基座,用来处理与总结新闻内容。Llama 3.2 将作为专用的摘要生成智能体,处理从搜索结果中获取的文本信息,并生成精炼、易读的新闻摘要。

Streamlit

Streamlit 是一个开源的 Python 库,专为数据科学家和开发者设计,用于快速创建和分享美观的交互式数据应用。它通过简洁的 API,允许用户以极少的代码实现复杂的应用功能,无需前端开发知识。Streamlit 支持热重载,即代码一保存,应用即更新,极大地加快了开发和迭代过程。此外,它提供了丰富的内置组件和易于部署的特性,使得从数据可视化到机器学习模型演示都变得简单快捷,非常适合快速原型开发和结果展示。

二、工作流设计

整个流程将由三个智能体分工协作完成:

从 Searcher进行搜索 到 Synthesizer 进行合成,最后由 Summarizer 进行总结。

三个智能体的职责描述如下:

  1. Searcher:通过 DuckDuckGo 搜索与给定主题最相关且来源可靠的最新新闻,并以结构化格式返回结果。

  2. Synthesizer:分析提供的原始新闻报道,确定关键主题和重要信息,综合多种来源的信息,编写一份全面而简明的综述,注重事实,保持新闻的客观性,并以清晰、专业的写作风格呈现。

  3. Summarizer:以简洁明了的方式总结新闻,突出最重要的发展,包含关键利益相关者及其行动,添加相关数据,解释事件的重要性和直接影响,使用有力的动词和具体的描述,保持客观性,并在250-400字的段落中提供信息和吸引读者。

三、准备工作

下载 Llama3.2

通过 Ollama 下载 Llama3.2:

运行 Llama3.2 看看是否正常:

安装相关依赖项

创建如下 requirements.txt 文件:

git+https://github.com/openai/swarm.git  
streamlit   
duckduckgo-search  

在命令行执行命令 pip install -r requirements.txt,安装相关依赖项。

四、代码实现

智能体实现

Searcher
search_agent = Agent(  
    name="News Searcher",  
    instructions="""  
    You are a news search specialist. Your task is to:  
    1. Search for the most relevant and recent news on the given topic  
    2. Ensure the results are from reputable sources  
    3. Return the raw search results in a structured format  
    """,  
    functions=[search_news],  
    model=MODEL  
)  

创建新闻搜索智能体:

  • 专门用于新闻搜索

  • 专注于信誉良好的来源

  • 返回格式化的结果

Synthesizer
synthesis_agent = Agent(  
    name="News Synthesizer",  
    instructions="""  
    You are a news synthesis expert. Your task is to:  
    1. Analyze the raw news articles provided  
    2. Identify the key themes and important information  
    3. Combine information from multiple sources  
    4. Create a comprehensive but concise synthesis  
    5. Focus on facts and maintain journalistic objectivity  
    6. Write in a clear, professional style  
    Provide a 2-3 paragraph synthesis of the main points.  
    """,  
    model=MODEL  
)  

创建新闻合成智能体:

  • 分析多种来源
  • 确定关键主题
  • 创建连贯的叙述
Summarizer
summary_agent = Agent(  
    name="News Summarizer",  
    instructions="""  
    You are an expert news summarizer combining AP and Reuters style clarity with digital-age brevity.  
  
    Your task:  
    1. Core Information:  
       - Lead with the most newsworthy development  
       - Include key stakeholders and their actions  
       - Add critical numbers/data if relevant  
       - Explain why this matters now  
       - Mention immediate implications  
  
    2. Style Guidelines:  
       - Use strong, active verbs  
       - Be specific, not general  
       - Maintain journalistic objectivity  
       - Make every word count  
       - Explain technical terms if necessary  
  
    Format: Create a single paragraph of 250-400 words that informs and engages.  
    Pattern: [Major News] + [Key Details/Data] + [Why It Matters/What's Next]  
  
    Focus on answering: What happened? Why is it significant? What's the impact?  
  
    IMPORTANT: Provide ONLY the summary paragraph. Do not include any introductory phrases,   
    labels, or meta-text like "Here's a summary" or "In AP/Reuters style."  
    Start directly with the news content.  
    """,  
    model=MODEL  
)  

创建新闻摘要代理:

  • 美联社/路透社风格写作
  • 专业格式
  • 简明摘要

全套的AI大模型学习资源已经整理打包,有需要的小伙伴可以微信扫描下方优快云官方认证二维码,免费领取【保证100%免费

完整实现

import streamlit as st  
from duckduckgo_search import DDGS  
from swarm import Swarm, Agent  
from datetime import datetime  
from dotenv import load_dotenv  
  
# 加载环境变量  
load_dotenv()  
# 定义模型  
MODEL = "llama3.2:latest"  
# 初始化 Swarm 客户端  
client = Swarm()  
  
# 通过 Streamlit 创建用户界面,为页面和应用程序添加一个标题  
st.set_page_config(page_title="AI News Processor", page_icon="📰")  
st.title("📰 News Inshorts Agent")  
  
# 定义新闻搜索 Function,使用 DuckDuckGo 搜索 API,获取当月新闻,并返回结构化结果  
def search_news(topic):  
    """Search for news articles using DuckDuckGo"""  
    with DDGS() as ddg:  
        results = ddg.text(f"{topic} news {datetime.now().strftime('%Y-%m')}", max_results=3)  
        if results:  
            news_results = "\n\n".join([  
                f"Title: {result['title']}\nURL: {result['href']}\nSummary: {result['body']}"   
                for result in results  
            ])  
            return news_results  
        return f"No news found for {topic}."  
  
# 创建智能体  
search_agent = Agent(  
    name="News Searcher",  
    instructions="""  
    You are a news search specialist. Your task is to:  
    1. Search for the most relevant and recent news on the given topic  
    2. Ensure the results are from reputable sources  
    3. Return the raw search results in a structured format  
    """,  
    functions=[search_news],  
    model=MODEL  
)  
  
synthesis_agent = Agent(  
    name="News Synthesizer",  
    instructions="""  
    You are a news synthesis expert. Your task is to:  
    1. Analyze the raw news articles provided  
    2. Identify the key themes and important information  
    3. Combine information from multiple sources  
    4. Create a comprehensive but concise synthesis  
    5. Focus on facts and maintain journalistic objectivity  
    6. Write in a clear, professional style  
    Provide a 2-3 paragraph synthesis of the main points.  
    """,  
    model=MODEL  
)  
  
summary_agent = Agent(  
    name="News Summarizer",  
    instructions="""  
    You are an expert news summarizer combining AP and Reuters style clarity with digital-age brevity.  
  
    Your task:  
    1. Core Information:  
       - Lead with the most newsworthy development  
       - Include key stakeholders and their actions  
       - Add critical numbers/data if relevant  
       - Explain why this matters now  
       - Mention immediate implications  
  
    2. Style Guidelines:  
       - Use strong, active verbs  
       - Be specific, not general  
       - Maintain journalistic objectivity  
       - Make every word count  
       - Explain technical terms if necessary  
  
    Format: Create a single paragraph of 250-400 words that informs and engages.  
    Pattern: [Major News] + [Key Details/Data] + [Why It Matters/What's Next]  
  
    Focus on answering: What happened? Why is it significant? What's the impact?  
  
    IMPORTANT: Provide ONLY the summary paragraph. Do not include any introductory phrases,   
    labels, or meta-text like "Here's a summary" or "In AP/Reuters style."  
    Start directly with the news content.  
    """,  
    model=MODEL  
)  
  
# 实施新闻处理工作流程,按顺序处理,显示进度指标  
def process_news(topic):  
    """Run the news processing workflow"""  
    with st.status("Processing news...", expanded=True) as status:  
        # Search  
        status.write("🔍 Searching for news...")  
        search_response = client.run(  
            agent=search_agent,  
            messages=[{"role": "user", "content": f"Find recent news about {topic}"}]  
        )  
        raw_news = search_response.messages[-1]["content"]  
          
        # Synthesize  
        status.write("🔄 Synthesizing information...")  
        synthesis_response = client.run(  
            agent=synthesis_agent,  
            messages=[{"role": "user", "content": f"Synthesize these news articles:\n{raw_news}"}]  
        )  
        synthesized_news = synthesis_response.messages[-1]["content"]  
          
        # Summarize  
        status.write("📝 Creating summary...")  
        summary_response = client.run(  
            agent=summary_agent,  
            messages=[{"role": "user", "content": f"Summarize this synthesis:\n{synthesized_news}"}]  
        )  
        return raw_news, synthesized_news, summary_response.messages[-1]["content"]  
  
# 用户交互界面  
topic = st.text_input("Enter news topic:", value="artificial intelligence")  
if st.button("Process News", type="primary"):  
    if topic:  
        try:  
            raw_news, synthesized_news, final_summary = process_news(topic)  
            st.header(f"📝 News Summary: {topic}")  
            st.markdown(final_summary)  
        except Exception as e:  
            st.error(f"An error occurred: {str(e)}")  
    else:  
        st.error("Please enter a topic!")  

五、运行效果

在命令行运行 streamlit run news_agent.py

Streamlit 应用网址 http://localhost:8501 会自动打开:

输入主题,并点击处理 Process News 按钮后,会得到搜索概述结果:


最后分享

AI大模型作为人工智能领域的重要技术突破,正成为推动各行各业创新和转型的关键力量。抓住AI大模型的风口,掌握AI大模型的知识和技能将变得越来越重要。

学习AI大模型是一个系统的过程,需要从基础开始,逐步深入到更高级的技术。

这里给大家精心整理了一份全面的AI大模型学习资源,包括:AI大模型全套学习路线图(从入门到实战)、精品AI大模型学习书籍手册、视频教程、实战学习、面试题等,资料免费分享

1. 成长路线图&学习规划

要学习一门新的技术,作为新手一定要先学习成长路线图方向不对,努力白费

这里,我们为新手和想要进一步提升的专业人士准备了一份详细的学习成长路线图和规划。可以说是最科学最系统的学习成长路线。
在这里插入图片描述

2. 大模型经典PDF书籍

书籍和学习文档资料是学习大模型过程中必不可少的,我们精选了一系列深入探讨大模型技术的书籍和学习文档,它们由领域内的顶尖专家撰写,内容全面、深入、详尽,为你学习大模型提供坚实的理论基础(书籍含电子版PDF)

在这里插入图片描述

3. 大模型视频教程

对于很多自学或者没有基础的同学来说,书籍这些纯文字类的学习教材会觉得比较晦涩难以理解,因此,我们提供了丰富的大模型视频教程,以动态、形象的方式展示技术概念,帮助你更快、更轻松地掌握核心知识

在这里插入图片描述

4. 2024行业报告

行业分析主要包括对不同行业的现状、趋势、问题、机会等进行系统地调研和评估,以了解哪些行业更适合引入大模型的技术和应用,以及在哪些方面可以发挥大模型的优势。

在这里插入图片描述

5. 大模型项目实战

学以致用 ,当你的理论知识积累到一定程度,就需要通过项目实战,在实际操作中检验和巩固你所学到的知识,同时为你找工作和职业发展打下坚实的基础。

在这里插入图片描述

6. 大模型面试题

面试不仅是技术的较量,更需要充分的准备。

在你已经掌握了大模型技术之后,就需要开始准备面试,我们将提供精心整理的大模型面试题库,涵盖当前面试中可能遇到的各种技术问题,让你在面试中游刃有余。

在这里插入图片描述

全套的AI大模型学习资源已经整理打包,有需要的小伙伴可以微信扫描下方优快云官方认证二维码,免费领取【保证100%免费

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值