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

# 感知环境

> 让智能体持续感知时间、任务与上下文用量的变化

智能体通过**运行时状态注入**感知不断变化的环境：在每次推理之前，随对话变化的信息（当前时间、计划任务、上下文用量）会以 `HintBlock` 的形式注入上下文，由 `Agent(...)` 的 `injection_config` 参数控制。

注入覆盖三个维度，各自有独立的触发时机：

| 维度    | 注入内容                          | 触发时机                                                                 |
| ----- | ----------------------------- | -------------------------------------------------------------------- |
| 时间    | 当前时间与时区                       | 上下文中没有时间记录（首次回复，或上下文压缩刚结束），或距上次记录的时间超过 `time_interval` 小时            |
| 计划任务  | 进行中与待处理任务的数量，并提醒调用 `TaskList` | 存在未完成任务，且上下文中既没有任务相关的工具调用（例如已被压缩掉），也没有此前的任务注入                        |
| 上下文用量 | 当前输入 token 数与压缩阈值             | 回复的第一轮迭代中，输入 token 数进入压缩阈值前 `context_buffer_ratio` 的缓冲区，让智能体预知压缩即将发生 |

## 注入机制

每个注入字段包装为 `<key>value</key>`，拼接后填入 `template`（默认是一个 `<system-reminder>` 包裹模板）。一条典型的注入提示如下：

```text 注入提示示例 theme={null}
<system-reminder>Treat the following as the ground truth at this point of the conversation. Anything stated earlier is outdated, and a later reminder, if any, supersedes this one:
<current-time>2026-07-22T10:30:00</current-time>
<timezone>Asia/Shanghai</timezone>
<tasks>You have 1 in-progress tasks and 2 pending tasks. Use `TaskList` to view them if you don't know.</tasks>
</system-reminder>
```

有三个设计要点值得了解：

* 注入**不是临时的**：它会追加到持久化上下文中，让智能体感知时间的流逝和每一步做了什么，建立时间感。
* 提示以 `HintBlock` 形式附加，而不是修改系统提示，因此提示词缓存依然有效，同时智能体持续感知变化的状态。
* 只有会话中**会变化**的信息才会被注入。固定信息（智能体身份、长期指令）应写入系统提示。

当注入发生且 `emit_hint_event` 开启时，`reply_stream` 会额外产出一个 `HintBlockEvent`，方便前端渲染注入的提示。

## 配置注入

向智能体构造函数传入 `InjectionConfig` 即可调整注入行为：

```python theme={null}
from agentscope.agent import Agent, InjectionConfig
from agentscope.model import DashScopeChatModel
from agentscope.credential import DashScopeCredential

agent = Agent(
    name="my_agent",
    system_prompt="你是一个有帮助的助手。",
    model=DashScopeChatModel(
        credential=DashScopeCredential(api_key="YOUR_API_KEY"),
        model="qwen-max",
    ),
    injection_config=InjectionConfig(
        timezone="Asia/Shanghai",  # 注入该时区的时间
        time_interval=1.0,         # 每小时至多刷新一次时间
    ),
)
```

`InjectionConfig` 的字段如下：

| 字段                     | 默认值                                                | 说明                                                             |
| ---------------------- | -------------------------------------------------- | -------------------------------------------------------------- |
| `inject_runtime_state` | `True`                                             | 总开关；设为 `False` 完全关闭运行时状态注入                                     |
| `timezone`             | `"UTC"`                                            | 注入时间的时区，遵循标准时区数据库格式（如 `"Asia/Shanghai"`）                       |
| `time_format`          | `"%Y-%m-%dT%H:%M:%S"`                              | 注入时间的格式；必须包含日期部分，以便记录的时间能还原为完整时间戳                              |
| `time_interval`        | `0.5`                                              | 距记录时间的最小间隔（小时），超过后触发新的时间注入                                     |
| `context_buffer_ratio` | `0.2`                                              | 压缩阈值前的缓冲区；当触发比例为 0.8、缓冲为 0.2 时，输入 token 数超过模型上下文的 60% 即注入上下文用量 |
| `template`             | `<system-reminder>` 包裹模板                           | 包裹注入字段的模板，必须包含 `{runtime_state}` 占位符                           |
| `injection_source`     | `{"label": "System", "sublabel": "Runtime State"}` | 注入的 `HintBlock` 的 `source`，用于在扫描上下文时识别智能体此前的注入                 |
| `task_tool_names`      | `TaskCreate`、`TaskGet`、`TaskList`、`TaskUpdate`     | 任务相关的工具名；它们的调用出现在上下文中，说明智能体已知晓任务，从而抑制任务注入                      |
| `extra_fields`         | `{}`                                               | 附加到每次注入的自定义字段（参见[注入自定义字段](#注入自定义字段)）                           |
| `emit_hint_event`      | `True`                                             | 注入发生时是否产出 `HintBlockEvent`                                     |

<Note>
  `context_buffer_ratio` 必须小于[上下文配置](/versions/2.0.5dev/zh/building-blocks/context/compress-context#配置压缩)的 `trigger_ratio`，以保证上下文用量在压缩发生之前注入。否则智能体构造函数会抛出 `ValueError`。
</Note>

## 注入自定义字段

除内置维度外，`extra_fields` 可以注入开发者自定义的信息，例如传感器读数、部署元数据：

```python theme={null}
from agentscope.agent import InjectionConfig

injection_config = InjectionConfig(
    extra_fields={
        "battery-level": "78%",       # 注入为 <battery-level>78%</battery-level>
        "location": "杭州办公室",
    },
)
```

自定义字段会附加到**每一次**注入中，但自身不会触发注入：只有当时间、任务或上下文维度触发时才会一并注入。

## 自定义模板

`template` 字段控制注入内容呈现给大模型的方式。它必须包含 `{runtime_state}` 占位符，占位符会被替换为拼接后的 `<key>value</key>` 字段：

```python theme={null}
from agentscope.agent import InjectionConfig

injection_config = InjectionConfig(
    template=(
        "[运行时更新] 以下内容反映当前环境：\n"
        "{runtime_state}"
    ),
)
```
