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

# 使用 PostgreSQL 存储

`postgresql` 后端把会话存储到 PostgreSQL 数据库。多个智能体实例可连接同一数据库，实现会话共享与分布式持久化。

## 何时使用

* 生产环境、多实例或分布式部署；
* 团队已使用 PostgreSQL 作为统一存储。

## 使用示例

连接信息通过 `config.yaml`（或对应环境变量）提供，不要把密码写进代码。

```python lines theme={null}
from veadk import Agent, Runner
from veadk.memory.short_term_memory import ShortTermMemory

stm = ShortTermMemory(backend="postgresql")  # 连接信息来自 config.yaml / 环境变量

agent = Agent(name="demo")
runner = Runner(agent=agent, short_term_memory=stm, app_name="memory_demo")
```

如需透传连接池等 SQLAlchemy 驱动参数，可使用 `db_kwargs`：

```python lines theme={null}
stm = ShortTermMemory(
    backend="postgresql",
    db_kwargs={"pool_size": 10, "pool_recycle": 3600},
)
```

也可以用 `backend_configs` 在代码中直接注入 `PostgreSqlConfig`，覆盖环境变量：

```python lines theme={null}
import os

from veadk.configs.database_configs import PostgreSqlConfig

stm = ShortTermMemory(
    backend="postgresql",
    backend_configs={
        "postgresql_config": PostgreSqlConfig(
            host="127.0.0.1",
            port=5432,
            user="veadk",
            password=os.environ["DATABASE_POSTGRESQL_PASSWORD"],
            database="veadk_sessions",
        )
    },
)
```

## 参数

### ShortTermMemory 构造参数（postgresql 场景）

| 参数 | 类型 | 默认值 | 对 postgresql 是否生效 | 说明 |
| :- | :- | :- | :- | :- |
| `backend` | `str` | `"local"` | 生效 | 设为 `"postgresql"` 选择本后端。 |
| `backend_configs` | `dict` | `{}` | 生效 | PostgreSQL 专用配置；可包含 `postgresql_config`（一个 `PostgreSqlConfig` 实例），用于覆盖默认从环境变量读取的配置。 |
| `db_kwargs` | `dict` | `{}` | 生效 | 传给 SQLAlchemy 引擎，常用于连接池设置，如 `pool_size`、`pool_recycle`、`pool_pre_ping` 等。 |
| `db_url` | `str` | `""` | 生效（覆盖） | 直接给出连接串。一旦设置，将忽略 `backend` 与 `backend_configs`，并采用 `db_url` 与 `db_kwargs`。 |
| `local_database_path` | `str` | `/tmp/veadk_local_database.db` | 不生效 | 仅 `sqlite` 使用。 |
| `after_load_memory_callback` | `Callable \| None` | `None` | 生效 | 读取会话后触发的回调，入参为加载到的 `Session`。 |

### PostgreSqlConfig 字段与环境变量

配置类 `PostgreSqlConfig` 的环境变量前缀为 `DATABASE_POSTGRESQL_`。

```yaml config.yaml lines theme={null}
database:
  postgresql:
    host:       # 主机或 IP
    port: 5432
    user:
    password:
    database:
```

| 配置项 | 环境变量 | 类型 | 默认值 | 说明 |
| :- | :- | :- | :- | :- |
| `host` | `DATABASE_POSTGRESQL_HOST` | `str` | `""` | 数据库主机或 IP。 |
| `port` | `DATABASE_POSTGRESQL_PORT` | `int` | `5432` | 端口。 |
| `user` | `DATABASE_POSTGRESQL_USER` | `str` | `""` | 用户名。 |
| `password` | `DATABASE_POSTGRESQL_PASSWORD` | `str` | `""` | 密码。 |
| `database` | `DATABASE_POSTGRESQL_DATABASE` | `str` | `""` | 数据库名。 |
| `secret_token` | `DATABASE_POSTGRESQL_SECRET_TOKEN` | `str` | `""` | PostgreSQL 鉴权用的 STS 临时令牌，暂未支持。 |

<Note>
  VeADK 会选择与当前 Google ADK 版本兼容的 PostgreSQL 驱动，并自动编码用户名与密码中的特殊字符。可在火山引擎[开通 PostgreSQL 数据库](https://www.volcengine.com/product/rds-pg)。
</Note>
