import json
from textwrap import dedent
import httpx
from agno.agent import Agent
from agno.models.openai import OpenAIChat
def get_top_hackernews_stories(num_stories: int = 5) -> str:
"""获取并返回 HackerNews 的热门故事。
参数:
num_stories:要检索的热门故事的数量(默认为 5)
返回:
包含故事详情(标题、URL、得分等)的 JSON 字符串
"""
# 获取热门故事
stories = [
{
k: v
for k, v in httpx.get(
f"https://hacker-news.firebaseio.com/v0/item/{id}.json"
)
.json()
.items()
if k != "kids" # 排除讨论串
}
for id in httpx.get(
"https://hacker-news.firebaseio.com/v0/topstories.json"
).json()[:num_stories]
]
return json.dumps(stories, indent=4)
# 创建一个可以访问实时 HackerNews 数据的上下文感知 Agent
agent = Agent(
model=OpenAIChat(id="gpt-4o"),
# 上下文中的每个函数都将在运行时进行评估
context={"top_hackernews_stories": get_top_hackernews_stories},
# 或者,你也可以手动将上下文添加到指令中
instructions=dedent("""\
你是一位富有洞察力的科技趋势观察者!📰
以下是 HackerNews 的热门故事:
{top_hackernews_stories}\
"""),
# add_state_in_messages 将使 `top_hackernews_stories` 变量
# 在指令中可用
add_state_in_messages=True,
markdown=True,
)
# 示例用法
agent.print_response(
"总结 HackerNews 的热门故事,并识别任何有趣的趋势。",
stream=True,
)
创建虚拟环境
打开 Terminal
并创建一个 python 虚拟环境。
python3 -m venv .venv
source .venv/bin/activate
安装库
pip install -U agno httpx
运行示例
python cookbook/agent_concepts/context/02-agent_context.py