Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(python-sdk): support event hooks and lifecycle reset (#3392)

Monday49ca3cdfe833
diff --git a/sdk/python/README.md b/sdk/python/README.md
index 17f4d2401..02e7b20eb 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -47,6 +47,7 @@ Common client fields:
- `user_id`: legacy alias for `user`
- `actor_peer_id`: optional actor peer override
- `agent_id`: legacy alias for `actor_peer_id`
+- `event_hooks`: optional `httpx.AsyncClient` event hooks, such as async request or response hooks
Compatibility notes:
@@ -86,6 +87,7 @@ client = SyncHTTPClient(
url="http://127.0.0.1:1933",
api_key="your-user-key",
)
+client.initialize()
healthy = client.health()
print("health:", healthy)
@@ -111,6 +113,7 @@ async def main() -> None:
url="http://127.0.0.1:1933",
api_key="your-user-key",
)
+ await client.initialize()
healthy = await client.health()
print("health:", healthy)
@@ -137,6 +140,7 @@ asyncio.run(main())
from openviking_sdk import SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+client.initialize()
result = client.create_session("demo-session")
print(result)
```
@@ -149,6 +153,7 @@ print(result)
from openviking_sdk import SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+client.initialize()
result = client.add_resource(
"/path/to/notes.md",
@@ -165,6 +170,7 @@ print(result)
from openviking_sdk import SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+client.initialize()
client.mkdir("viking://resources/demo-dir")
print(client.ls("viking://resources"))
@@ -177,6 +183,7 @@ print(client.read("viking://resources/demo-dir/example.md"))
from openviking_sdk import SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+client.initialize()
result = client.find("hello", limit=5)
print(result)
@@ -209,6 +216,7 @@ root_client = SyncHTTPClient(
url="http://127.0.0.1:1933",
api_key="your-root-key",
)
+root_client.initialize()
result = root_client.admin_create_account(
account_id="demo-account",
@@ -251,6 +259,7 @@ The SDK maps server-side error codes to Python exceptions.
from openviking_sdk import OpenVikingError, SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+client.initialize()
try:
print(client.read("viking://resources/not-exists.md"))
diff --git a/sdk/python/README_CN.md b/sdk/python/README_CN.md
index e4404528b..18b5ede27 100644
--- a/sdk/python/README_CN.md
+++ b/sdk/python/README_CN.md
@@ -47,6 +47,7 @@ SDK 支持三种配置方式,优先级从高到低如下:
- `user_id`:`user` 的兼容旧别名
- `actor_peer_id`:可选的 actor peer 覆盖
- `agent_id`:`actor_peer_id` 的兼容旧别名
+- `event_hooks`:可选的 `httpx.AsyncClient` 事件钩子,例如异步 request 或 response hook
兼容性说明:
@@ -86,6 +87,7 @@ client = SyncHTTPClient(
url="http://127.0.0.1:1933",
api_key="your-user-key",
)
+client.initialize()
healthy = client.health()
print("health:", healthy)
@@ -111,6 +113,7 @@ async def main() -> None:
url="http://127.0.0.1:1933",
api_key="your-user-key",
)
+ await client.initialize()
healthy = await client.health()
print("health:", healthy)
@@ -137,6 +140,7 @@ asyncio.run(main())
from openviking_sdk import SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+client.initialize()
result = client.create_session("demo-session")
print(result)
```
@@ -149,6 +153,7 @@ print(result)
from openviking_sdk import SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+client.initialize()
result = client.add_resource(
"/path/to/notes.md",
@@ -165,6 +170,7 @@ print(result)
from openviking_sdk import SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+client.initialize()
client.mkdir("viking://resources/demo-dir")
print(client.ls("viking://resources"))
@@ -177,6 +183,7 @@ print(client.read("viking://resources/demo-dir/example.md"))
from openviking_sdk import SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+client.initialize()
result = client.find("hello", limit=5)
print(result)
@@ -209,6 +216,7 @@ root_client = SyncHTTPClient(
url="http://127.0.0.1:1933",
api_key="your-root-key",
)
+root_client.initialize()
result = root_client.admin_create_account(
account_id="demo-account",
@@ -248,6 +256,7 @@ SDK 会把服务端错误码映射为 Python 异常。
from openviking_sdk import OpenVikingError, SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+client.initialize()
try:
print(client.read("viking://resources/not-exists.md"))
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index aef8efe4d..405ce6b42 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -9,7 +9,7 @@ import uuid
import zipfile
from enum import Enum
from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
+from typing import Any, Callable, Dict, List, Optional, Union
from urllib.parse import quote
import httpx
@@ -268,6 +268,7 @@ class AsyncHTTPClient:
extra_headers: Optional[Dict[str, str]] = None,
profile_enabled: Optional[bool] = None,
upload_mode: Optional[str] = None,
+ event_hooks: Optional[Dict[str, List[Callable[..., Any]]]] = None,
):
if actor_peer_id and agent_id:
raise ValueError("actor_peer_id cannot be used with agent_id")
@@ -294,6 +295,9 @@ class AsyncHTTPClient:
self._extra_headers = config.extra_headers
self._profile_enabled = config.profile_enabled
self._upload_mode = config.upload_mode
+ self._event_hooks = {
+ event: list(hooks) for event, hooks in (event_hooks or {}).items()
+ }
self._http: Optional[httpx.AsyncClient] = None
self._observer: Optional[_HTTPObserver] = None
self._snapshot: Optional["AsyncHTTPSnapshotNamespace"] = None
@@ -313,6 +317,7 @@ class AsyncHTTPClient:
base_url=self._url,
headers=headers,
timeout=self._timeout,
+ event_hooks=self._event_hooks,
params={"profile": "1"} if self._profile_enabled else None,
)
self._observer = _HTTPObserver(self)
diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.py
index 36bf86299..514e61a7e 100644
--- a/sdk/python/tests/test_async_client_behaviors.py
+++ b/sdk/python/tests/test_async_client_behaviors.py
@@ -7,6 +7,33 @@ from openviking_sdk import AsyncHTTPClient, SyncHTTPClient
from openviking_sdk.client import Session, SyncSession
from openviking_sdk.errors import NotFoundError
+async def test_async_http_client_initialize_forwards_event_hooks():
+ async def request_hook(_request):
+ return None
+
+ async def later_hook(_request):
+ return None
+
+ event_hooks = {"request": [request_hook]}
+ fake_http = SimpleNamespace(aclose=AsyncMock())
+
+ with patch(
+ "openviking_sdk.client.httpx.AsyncClient",
+ return_value=fake_http,
+ ) as mock_async_client:
+ client = AsyncHTTPClient(
+ url="http://localhost:1933",
+ event_hooks=event_hooks,
+ )
+ await client.initialize()
+ event_hooks["request"].append(later_hook)
+
+ assert mock_async_client.call_args.kwargs["event_hooks"] == {
+ "request": [request_hook]
+ }
+ await client.close()
+
@pytest.mark.asyncio
async def test_async_http_client_batch_add_messages_posts_batch_payload():