5分钟打造智能新闻助手:用Agno构建你的Hacker News资讯聚合工具

5分钟打造智能新闻助手:用Agno构建你的Hacker News资讯聚合工具

【免费下载链接】agno High-performance runtime for multi-agent systems. Build, run and manage secure multi-agent systems in your cloud. 【免费下载链接】agno 项目地址: https://gitcode.com/GitHub_Trending/ag/agno

你是否每天花费大量时间浏览各类科技资讯网站,却仍担心错过重要信息?本文将带你使用Agno框架快速构建一个智能Hacker News新闻聚合工具,自动获取并分析热门科技动态,让你轻松掌握业界脉搏。读完本文,你将学会如何创建自定义工具、配置智能代理以及实现自动化内容聚合与分析。

为什么选择Agno构建新闻助手

Agno作为高性能多智能体系统运行时,提供了简洁而强大的工具开发接口。与传统爬虫或API调用相比,基于Agno构建的新闻助手具有以下优势:

  • 智能化处理:内置的AI模型可自动分析和总结新闻内容
  • 灵活扩展:可轻松添加过滤、分类和推送功能
  • 多工具集成:支持与其他服务无缝对接,如邮件发送、Slack通知等
  • 简洁API:几行代码即可实现复杂功能,降低开发门槛

核心工具定义位于cookbook/getting_started/04_write_your_own_tool.py,该文件展示了如何创建一个完整的Hacker News工具。

准备工作:环境搭建与依赖安装

在开始之前,请确保你的开发环境满足以下要求:

  • Python 3.8+
  • pip包管理器
  • 网络连接(用于API调用)

首先安装必要的依赖包:

pip install openai httpx agno

Agno框架的核心库位于libs/agno/目录,其中包含了构建智能代理所需的所有组件。

构建Hacker News工具:核心代码解析

工具函数定义

Hacker News工具的核心是get_top_hackernews_stories函数,它负责从Hacker News API获取热门故事:

def get_top_hackernews_stories(num_stories: int = 10) -> str:
    """Use this function to get top stories from Hacker News.
    
    Args:
        num_stories (int): Number of stories to return. Defaults to 10.
        
    Returns:
        str: JSON string of top stories.
    """
    
    # Fetch top story IDs
    response = httpx.get("https://hacker-news.firebaseio.com/v0/topstories.json")
    story_ids = response.json()
    
    # Fetch story details
    stories = []
    for story_id in story_ids[:num_stories]:
        story_response = httpx.get(
            f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json"
        )
        story = story_response.json()
        if "text" in story:
            story.pop("text", None)
        stories.append(story)
    return json.dumps(stories)

这段代码实现了两个主要功能:首先获取热门故事ID列表,然后根据ID获取每个故事的详细信息,并返回JSON格式的结果。完整代码可查看cookbook/getting_started/04_write_your_own_tool.py

创建智能代理

接下来,我们需要创建一个Agno代理,将工具与其结合:

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    instructions=dedent("""\
        You are a tech-savvy Hacker News reporter with a passion for all things technology! 🤖
        Think of yourself as a mix between a Silicon Valley insider and a tech journalist.
        
        Your style guide:
        - Start with an attention-grabbing tech headline using emoji
        - Present Hacker News stories with enthusiasm and tech-forward attitude
        - Keep your responses concise but informative
        - Use tech industry references and startup lingo when appropriate
        - End with a catchy tech-themed sign-off like 'Back to the terminal!' or 'Pushing to production!'
        
        Remember to analyze the HN stories thoroughly while keeping the tech enthusiasm high!\
    """),
    tools=[get_top_hackernews_stories],
    markdown=True,
)

这个代理配置了以下关键元素:

  • 使用GPT-4o模型进行自然语言处理
  • 定义了特定的角色和风格指南
  • 集成了我们刚刚创建的Hacker News工具
  • 启用Markdown格式输出

完整的代理配置代码可在cookbook/getting_started/04_write_your_own_tool.py查看。

运行与使用:获取并分析新闻

配置完成后,只需一行代码即可获取并分析热门新闻:

agent.print_response("Summarize the top 5 stories on hackernews?", stream=True)

运行脚本后,你将看到类似以下的输出:

  • 一个引人注目的科技头条
  • 5个热门HN故事的简洁摘要
  • 带有科技行业术语的分析评论
  • 一个有趣的技术风格结束语

你可以尝试不同的问题,如:

  • "What are the trending tech discussions on HN right now?"
  • "What's the most upvoted story today?"
  • "Summarize stories about AI from the top 20"

这些示例问题在cookbook/getting_started/04_write_your_own_tool.py中提供。

高级扩展:定制你的新闻助手

Agno框架提供了丰富的扩展功能,让你可以根据需求定制新闻助手:

1. 添加工具钩子

通过工具钩子可以在工具调用前后执行自定义逻辑,如日志记录、性能监控或数据转换。示例代码可参考cookbook/tools/tool_hooks/pre_and_post_hooks.py,其中展示了如何实现:

def get_top_hackernews_stories(agent: Agent) -> Iterator[str]:
    # 前置逻辑
    start_time = time.time()
    agent.logger.info("Fetching top Hacker News stories...")
    
    # 实际工具调用
    result = original_get_top_hackernews_stories()
    
    # 后置逻辑
    duration = time.time() - start_time
    agent.logger.info(f"Fetched stories in {duration:.2f} seconds")
    
    yield result

2. 实现异步工具调用

对于需要处理大量数据或长时间运行的操作,可以使用异步工具调用提高性能:

async def get_top_hackernews_stories(agent: Agent) -> AsyncIterator[str]:
    async with httpx.AsyncClient() as client:
        # 异步获取故事ID
        response = await client.get("https://hacker-news.firebaseio.com/v0/topstories.json")
        story_ids = response.json()
        
        # 并发获取故事详情
        tasks = [
            client.get(f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json")
            for story_id in story_ids[:10]
        ]
        responses = await asyncio.gather(*tasks)
        
        # 处理结果
        stories = [resp.json() for resp in responses]
        yield json.dumps(stories)

完整示例可在cookbook/tools/tool_hooks/async_pre_and_post_hooks.py中找到。

3. 添加缓存功能

为避免重复请求和提高响应速度,可以为工具添加缓存功能:

@tool(cache=True, ttl=300)  # 缓存5分钟
def get_top_hackernews_stories(num_stories: int = 5) -> str:
    # 工具实现...

这个功能在cookbook/tools/tool_decorator/cache_tool_calls.py中有详细示例。

总结与下一步

通过本文,你已经学会了如何使用Agno框架创建一个智能Hacker News新闻聚合工具。我们从基础的工具函数开始,逐步构建了一个具有AI分析能力的智能代理,并探讨了多种高级扩展可能性。

接下来,你可以尝试:

  1. 添加更多新闻源,如TechCrunch、Wired等
  2. 实现新闻分类和个性化推荐功能
  3. 集成通知系统,如邮件或Slack提醒
  4. 创建Web界面,使用Streamlit或Chainlit构建交互式应用

Agno框架的更多高级功能和示例可在cookbook/目录中探索,包括多代理协作、持久化存储、状态管理等高级主题。

Happy coding,让你的新闻助手更智能、更强大!

【免费下载链接】agno High-performance runtime for multi-agent systems. Build, run and manage secure multi-agent systems in your cloud. 【免费下载链接】agno 项目地址: https://gitcode.com/GitHub_Trending/ag/agno

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值