agentscope.app.message_busRedisMessageBus
class RedisMessageBus(MessageBus)
agentscope/app/message_bus/_redis_message_bus.py:48–725Redis 消息总线,把智能体接入外部消息渠道与企业平台。位于 agentscope.app.message_bus 包,继承自 MessageBus。核心成员包括 aclose、get_client、queue_push、queue_drain、queue_delete、log_append。
Mapping of bus modes to Redis primitives:
- Mode A (drain queue) uses a Redis Stream per key.
XADDappends a payload whose single fieldpayloadcarries the JSON-serialised dict.queue_drainrunsXRANGEandXDELin one Lua script, so an entry is handed to exactly one consumer however many drain the key concurrently.ttl_secsis enforced viaEXPIREafter each push (sliding TTL). - Mode C (replay log) also uses a Redis Stream, but never
XDELs on read. Trimming happens viaXADD … MAXLEN ~N(approximate, for performance) on append, via thettl_secsEXPIREon the whole key, or explicitly via :meth:log_trim.log_readusesXRANGEwith an exclusive start id derived fromsince. - Mode D (transient broadcast) rides Redis Pub/Sub. Wake-ups are best-effort: payloads published before a subscription exists are not delivered.
The bus owns its own connection pool by default; an external pool may be supplied for tests or for sharing a pool across services.
构造器摘要Constructor Summary
| 构造器Constructor | 说明Description |
|---|---|
def __init__(host: str = 'localhost', port: int = 6379, db: int = 0, password: str | None = None, connection_pool: Conn… | 初始化 `RedisMessageBus` 实例。 Store connection parameters; the actual pool is created in :meth:`__aenter__`. |
方法摘要Method Summary
| 方法Method | 说明Description |
|---|---|
async def __aenter__() -> Selfasync | 进入异步上下文并返回自身。 Create the connection pool and Redis client. |
async def aclose() -> Noneasync | 返回 `aclose` 结果。 Close the connection pool if it was created internally. |
async def __aexit__(exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: Any) -> Noneasync | 退出异步上下文并清理资源。 Exit the async context manager and release resources. |
def get_client() -> Redis | 获取客户端。 Return the underlying Redis client. |
async def queue_push(key: str, payload: dict, *, ttl_secs: int | None = None) -> strasync | 执行队列推送相关操作。 Append ``payload`` to the drain queue at ``key``. |
async def queue_drain(key: str, max_count: int = 100) -> list[tuple[str, dict]]async | 执行 `queue_drain` 方法。 Drain up to ``max_count`` entries from the queue at ``key``. |
async def queue_delete(key: str) -> Noneasync | 设置队列删除。 Delete the drain queue at ``key``. |
async def log_append(key: str, payload: dict, *, ttl_secs: int | None = None, max_len: int | None = None) -> strasync | 执行日志追加相关操作。 Append ``payload`` to the replay log at ``key``. |
async def log_read(key: str, since: str | None = None, max_count: int = 100) -> list[tuple[str, dict]]async | 执行日志读取相关操作。 Read up to ``max_count`` entries newer than ``since``. |
async def log_trim(key: str, before_id: str | None = None) -> Noneasync | 执行日志裁剪相关操作。 Trim the replay log at ``key``. |
async def registry_set(namespace: str, field: str, value: str, *, ttl_secs: int | None = None) -> Noneasync | 执行注册表设置相关操作。 Set ``field`` in the Redis Hash at ``namespace``. |
async def registry_set_if(namespace: str, field: str, value: str, *, expected: str, ttl_secs: int | None = None) -> boolasync | 执行注册表设置 if相关操作。 Compare-and-set one Hash field via Lua. See base. |
async def registry_pop(namespace: str, field: str) -> str | Noneasync | 执行 `registry_pop` 方法。 ``HGET`` + ``HDEL`` as one Lua step. See base. |
async def registry_del(namespace: str, field: str) -> Noneasync | 执行 `registry_del` 方法。 Remove ``field`` from the Redis Hash at ``namespace``. |
async def registry_exists(namespace: str, field: str) -> boolasync | 执行 `registry_exists` 方法。 Return whether ``field`` exists in the Hash at ``namespace``. |
async def registry_getall(namespace: str) -> dict[str, str]async | 设置该参数。 Return all field-value pairs from the Hash at ``namespace``. |
async def registry_get(namespace: str, field: str) -> str | Noneasync | 执行注册表读取相关操作。 Return a single field value from the Hash at ``namespace``. |
async def registry_drop(namespace: str) -> Noneasync | 设置该参数。 Delete the entire Hash at ``namespace``. |
async def publish(key: str, payload: dict) -> Noneasync | 执行发布相关操作。 Publish ``payload`` on the broadcast channel ``key``. |
async def subscribe(key: str, *, on_ready: Callable[[], None] | None = None) -> AsyncGenerator[dict, None]async | 执行订阅相关操作。 Yield broadcast payloads on ``key`` until the consumer closes the generator. |
async def acquire_lock(key: str, *, ttl_secs: int = 600) -> AsyncGenerator[None, None]asyncasynccontextmanager | 执行 `acquire_lock` 方法。 Acquire ``key`` as a distributed mutex. |
async def is_locked(key: str) -> boolasync | 判断是否 `is_locked`。 Return whether ``key`` currently holds a lock. |
async def try_lock(key: str, *, ttl_secs: int = 600) -> boolasync | 执行 `try_lock` 方法。 Non-blocking claim via ``SET key NX EX``. See base. |
async def unlock(key: str) -> Noneasync | 设置该参数。 Release a ``try_lock`` claim (best-effort ``DEL``). |
构造器详情Constructor Detail
RedisMessageBus
def __init__(host: str = 'localhost', port: int = 6379, db: int = 0, password: str | None = None, connection_pool: ConnectionPool | None = None, **kwargs: Any) -> None
初始化 RedisMessageBus 实例。
Store connection parameters; the actual pool is created in :meth:__aenter__.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
host默认default 'localhost' | str | host(类型 `str`)。Redis server host. |
port默认default 6379 | int | port(类型 `int`)。Redis server port. |
db默认default 0 | int | 数据库(类型 `int`)。Redis logical database index. |
password默认default None | str | None | 密码(类型 `str | None`)。Redis password if required by the server. |
connection_pool默认default None | ConnectionPool | None | 连接连接池(类型 `ConnectionPool | None`)。An externally managed connection pool. When provided the pool is used as-is and **not** closed by :meth:`aclose` — the caller retains ownership of its lifecycle. When omitted a pool is created from *host*/*port*/*db*/*password* on :meth:`__aenter__` and closed on :meth:`aclose`. |
kwargs | Any | 关键字参数(类型 `Any`)。The kwargs. |
agentscope/app/message_bus/_redis_message_bus.py:73–116方法详情Method Detail
__aenter__
async def __aenter__() -> Self
进入异步上下文并返回自身。
If an external pool was supplied at construction time it is used directly and its lifecycle remains the caller's responsibility.
agentscope/app/message_bus/_redis_message_bus.py:118–153aclose
async def aclose() -> None
返回 aclose 结果。
Externally supplied pools are left open — the caller owns them.
agentscope/app/message_bus/_redis_message_bus.py:155–163__aexit__
async def __aexit__(exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: Any) -> None
退出异步上下文并清理资源。
Exit the async context manager and release resources.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
exc_type | type[BaseException] | None | exc 类型(类型 `type[BaseException] | None`)。Exception class raised inside the context, if any. |
exc_value | BaseException | None | exc 值(类型 `BaseException | None`)。Exception instance raised inside the context, if any. |
traceback | Any | traceback(类型 `Any`)。Traceback associated with the exception, if any. |
agentscope/app/message_bus/_redis_message_bus.py:165–181get_client
def get_client() -> Redis
获取客户端。
Only valid inside the async context (between :meth:__aenter__ and :meth:aclose).
agentscope/app/message_bus/_redis_message_bus.py:183–193queue_push
async def queue_push(key: str, payload: dict, *, ttl_secs: int | None = None) -> str
执行队列推送相关操作。
Append payload to the drain queue at key.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。Stream key for this drain queue. |
payload | dict | 负载(类型 `dict`)。JSON-serializable dict; encoded into the `payload` field of a Redis Stream entry. |
ttl_secskw默认default None | int | None | 存活时间 secs(类型 `int | None`)。If set, refresh the key's expiry on every push (sliding TTL). `None` means no TTL — the queue persists until drained or deleted explicitly. |
agentscope/app/message_bus/_redis_message_bus.py:225–255queue_drain
async def queue_drain(key: str, max_count: int = 100) -> list[tuple[str, dict]]
执行 queue_drain 方法。
Implementation: XRANGE and XDEL of the returned ids run as one Lua script, so nothing else observes the entries between the read and their removal.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。Stream key for the drain queue. |
max_count默认default 100 | int | 最大数量(类型 `int`)。Maximum entries to return in one call. |
agentscope/app/message_bus/_redis_message_bus.py:257–291queue_delete
async def queue_delete(key: str) -> None
设置队列删除。
Delete the drain queue at key.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。Stream key for the drain queue. `DEL` is a no-op when the key does not exist. |
agentscope/app/message_bus/_redis_message_bus.py:293–301log_append
async def log_append(key: str, payload: dict, *, ttl_secs: int | None = None, max_len: int | None = None) -> str
执行日志追加相关操作。
Append payload to the replay log at key.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。Stream key for this replay log. |
payload | dict | 负载(类型 `dict`)。JSON-serializable dict; encoded into the `payload` field of a Redis Stream entry. |
ttl_secskw默认default None | int | None | 存活时间 secs(类型 `int | None`)。If set, refresh the key's expiry on every append (sliding TTL). `None` means no TTL. |
max_lenkw默认default None | int | None | 最大 len(类型 `int | None`)。If set, cap the log at approximately this many entries using `XADD MAXLEN ~N`. The cap is approximate so Redis can use its O(1) trim-by-radix-tree-node mode. `None` means no cap. |
agentscope/app/message_bus/_redis_message_bus.py:307–348log_read
async def log_read(key: str, since: str | None = None, max_count: int = 100) -> list[tuple[str, dict]]
执行日志读取相关操作。
Read up to max_count entries newer than since.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。Stream key for the replay log. |
since默认default None | str | None | since(类型 `str | None`)。Exclusive cursor — return entries strictly newer than this id (typically the last id from a previous read). `None` reads from the beginning. |
max_count默认default 100 | int | 最大数量(类型 `int`)。Maximum entries to return. |
agentscope/app/message_bus/_redis_message_bus.py:350–384log_trim
async def log_trim(key: str, before_id: str | None = None) -> None
执行日志裁剪相关操作。
Trim the replay log at key.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。Stream key for the replay log. |
before_id默认default None | str | None | 之前标识(类型 `str | None`)。Drop all entries with id strictly older than this. `None` deletes the entire key. |
agentscope/app/message_bus/_redis_message_bus.py:386–404registry_set
async def registry_set(namespace: str, field: str, value: str, *, ttl_secs: int | None = None) -> None
执行注册表设置相关操作。
Set field in the Redis Hash at namespace.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
namespace | str | 命名空间(类型 `str`)。Hash key. |
field | str | field(类型 `str`)。Hash field. |
value | str | 值(类型 `str`)。Value to store. |
ttl_secskw默认default None | int | None | 存活时间 secs(类型 `int | None`)。Refresh the key's expiry (sliding TTL). |
agentscope/app/message_bus/_redis_message_bus.py:410–432registry_set_if
async def registry_set_if(namespace: str, field: str, value: str, *, expected: str, ttl_secs: int | None = None) -> bool
执行注册表设置 if相关操作。
Compare-and-set one Hash field via Lua.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
namespace | str | 命名空间(类型 `str`)。The namespace. |
field | str | field(类型 `str`)。The field. |
value | str | 值(类型 `str`)。The value. |
expectedkw | str | expected(类型 `str`)。The expected. |
ttl_secskw默认default None | int | None | 存活时间 secs(类型 `int | None`)。The ttl secs. |
agentscope/app/message_bus/_redis_message_bus.py:434–453registry_pop
async def registry_pop(namespace: str, field: str) -> str | None
执行 registry_pop 方法。
HGET + HDEL as one Lua step.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
namespace | str | 命名空间(类型 `str`)。The namespace. |
field | str | field(类型 `str`)。The field. |
agentscope/app/message_bus/_redis_message_bus.py:455–462registry_del
async def registry_del(namespace: str, field: str) -> None
执行 registry_del 方法。
Remove field from the Redis Hash at namespace.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
namespace | str | 命名空间(类型 `str`)。Hash key. |
field | str | field(类型 `str`)。Hash field to remove. |
agentscope/app/message_bus/_redis_message_bus.py:464–473registry_exists
async def registry_exists(namespace: str, field: str) -> bool
执行 registry_exists 方法。
Return whether field exists in the Hash at namespace.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
namespace | str | 命名空间(类型 `str`)。Hash key. |
field | str | field(类型 `str`)。Hash field to check. |
agentscope/app/message_bus/_redis_message_bus.py:475–488registry_getall
async def registry_getall(namespace: str) -> dict[str, str]
设置该参数。
Return all field-value pairs from the Hash at namespace.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
namespace | str | 命名空间(类型 `str`)。Hash key. |
agentscope/app/message_bus/_redis_message_bus.py:490–504registry_get
async def registry_get(namespace: str, field: str) -> str | None
执行注册表读取相关操作。
Return a single field value from the Hash at namespace.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
namespace | str | 命名空间(类型 `str`)。Hash key. |
field | str | field(类型 `str`)。Field to retrieve. |
agentscope/app/message_bus/_redis_message_bus.py:506–523registry_drop
async def registry_drop(namespace: str) -> None
设置该参数。
Delete the entire Hash at namespace.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
namespace | str | 命名空间(类型 `str`)。Hash key to delete. |
agentscope/app/message_bus/_redis_message_bus.py:525–532publish
async def publish(key: str, payload: dict) -> None
执行发布相关操作。
Publish payload on the broadcast channel key.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。Pub/Sub channel name. |
payload | dict | 负载(类型 `dict`)。JSON-serializable dict; encoded as the channel message body. |
agentscope/app/message_bus/_redis_message_bus.py:545–562subscribe
async def subscribe(key: str, *, on_ready: Callable[[], None] | None = None) -> AsyncGenerator[dict, None]
执行订阅相关操作。
Yield broadcast payloads on key until the consumer closes the generator.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。Pub/Sub channel name. |
on_readykw默认default None | Callable[[], None] | None | on 就绪(类型 `Callable[[], None] | None`)。Called once after `SUBSCRIBE` has been issued (and before any payload is yielded). Lets callers block on a "subscription is live" event so they can publish immediately after starting a subscriber without losing the first message to a SUBSCRIBE/PUBLISH race. |
agentscope/app/message_bus/_redis_message_bus.py:564–619acquire_lock
async def acquire_lock(key: str, *, ttl_secs: int = 600) -> AsyncGenerator[None, None]
执行 acquire_lock 方法。
Implementation: - SET key NX EX ttl_secs to claim the lock atomically.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。Lock identifier. |
ttl_secskw默认default 600 | int | 存活时间 secs(类型 `int`)。Lease duration; auto-renewed via heartbeat. |
agentscope/app/message_bus/_redis_message_bus.py:629–701is_locked
async def is_locked(key: str) -> bool
判断是否 is_locked。
Return whether key currently holds a lock.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。Lock identifier. |
agentscope/app/message_bus/_redis_message_bus.py:703–715try_lock
async def try_lock(key: str, *, ttl_secs: int = 600) -> bool
执行 try_lock 方法。
Non-blocking claim via SET key NX EX.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。The key. |
ttl_secskw默认default 600 | int | 存活时间 secs(类型 `int`)。The ttl secs. |
agentscope/app/message_bus/_redis_message_bus.py:717–721unlock
async def unlock(key: str) -> None
设置该参数。
Release a try_lock claim (best-effort DEL).
| 名称Name | 类型Type | 说明Description |
|---|---|---|
key | str | 键(类型 `str`)。The key. |
agentscope/app/message_bus/_redis_message_bus.py:723–725继承成员Inherited Members
MessageBussession_run, session_is_running, session_publish_event, session_read_events, session_subscribe_events, session_publish_cancel, session_subscribe_cancel, session_purge, inbox_push, inbox_drain, enqueue_wakeup, enqueue_input, dequeue_wakeups, subscribe_wakeup_signal, bg_task_register, bg_task_unregister, bg_task_exists, bg_task_list, bg_task_purge, task_publish_cancel, task_subscribe_cancel