> ## Documentation Index
> Fetch the complete documentation index at: https://ikun.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 指令中的上下文

## 代码

```python cookbook/agent_concepts/context/03-context_in_instructions.py theme={null}
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,
)
```

## 用法

<Steps>
  <Snippet file="create-venv-step.mdx" />

  <Step title="安装库">
    ```bash theme={null}
    pip install -U agno httpx
    ```
  </Step>

  <Step title="运行示例">
    <CodeGroup>
      ```bash Mac theme={null}
      python cookbook/agent_concepts/context/03-context_in_instructions.py
      ```

      ```bash Windows theme={null}
      python cookbook/agent_concepts/context/03-context_in_instructions.py
      ```
    </CodeGroup>
  </Step>
</Steps>
