此示例展示了如何将外部依赖项注入 Agent。Context 在 Agent 运行时进行评估,作用类似于 Agent 的依赖注入。
可以尝试的示例提示:
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 的热门新闻。
Args:
num_stories: 要检索的热门新闻数量(默认为 5)
Returns:
包含新闻详细信息(标题、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 数据的 Context-Aware Agent
agent = Agent(
model=OpenAIChat(id="gpt-4o"),
# Context 中的每个函数在 Agent 运行时都会被评估,
# 可以将其视为 Agent 的依赖注入
context={"top_hackernews_stories": get_top_hackernews_stories},
# add_context 会自动将 context 添加到用户消息中
# add_context=True,
# 或者,您可以手动将 context 添加到指令中
instructions=dedent("""\
你是一位敏锐的技术趋势观察者!📰
这是 HackerNews 的热门新闻:
{top_hackernews_stories}\
"""),
markdown=True,
)
# 示例用法
agent.print_response(
"总结 HackerNews 的热门新闻并找出任何有趣的趋势。",
stream=True,
)
创建虚拟环境
打开 Terminal
并创建一个 python 虚拟环境。
python3 -m venv .venv
source .venv/bin/activate
安装库
pip install openai httpx agno
运行 Agent
python agent_context.py