代码

cookbook/agent_concepts/context/03-context_in_instructions.py
import json
from textwrap import dedent

import httpx
from agno.agent import Agent
from agno.models.openai import OpenAIChat


def get_upcoming_spacex_launches(num_launches: int = 5) -> str:
    url = "https://api.spacexdata.com/v5/launches/upcoming"
    launches = httpx.get(url).json()
    launches = sorted(launches, key=lambda x: x["date_unix"])[:num_launches]
    return json.dumps(launches, indent=4)


# 创建一个可以访问实时 SpaceX 数据的 Agent
agent = Agent(
    model=OpenAIChat(id="gpt-4.1"),
    # 上下文中的每个函数都会在运行时进行评估
    context={"upcoming_spacex_launches": get_upcoming_spacex_launches},
    description=dedent("""\
        你是一名宇宙分析师和太空飞行爱好者。🚀

        这是接下来 SpaceX 的发射任务:
        {upcoming_spacex_launches}\
    """),
    # add_state_in_messages 会使 `upcoming_spacex_launches` 变量
    # 在描述和指令中可用
    add_state_in_messages=True,
    markdown=True,
)

agent.print_response(
    "告诉我关于即将到来的 SpaceX 任务。",
    stream=True,
)

用法

1

创建虚拟环境

打开 Terminal 并创建一个 python 虚拟环境。

python3 -m venv .venv
source .venv/bin/activate
2

安装库

pip install -U agno httpx
3

运行示例

python cookbook/agent_concepts/context/03-context_in_instructions.py