Agent 上下文是 Agno 的另一项强大功能。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 的热门故事。
参数:
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"),
# 上下文中的每个函数都会在 agent 运行时进行评估,
# 可以将其视为 Agent 的依赖注入
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,
)
设置 add_context=True
将整个上下文添加到用户消息中。这样您就不必手动将上下文添加到指令中了。
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"),
# 上下文中的每个函数都会在 agent 运行时解析,
# 可以将其视为 Agent 的依赖注入
context={"top_hackernews_stories": get_top_hackernews_stories},
# 我们可以将整个上下文字典添加到指令中
add_context=True,
markdown=True,
)
# 示例用法
agent.print_response(
"总结 HackerNews 的热门故事并识别任何有趣的趋势。",
stream=True,
)