Skip to content

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

fix(sdk): align compat client with SDK behavior (#4316)

zgy80f4ba1412b3
diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.md
index ff707bd7a..4ccd60b2e 100644
--- a/docs/en/api/05-sessions.md
+++ b/docs/en/api/05-sessions.md
@@ -1031,8 +1031,8 @@ Add a message to the session. Supports two modes: simple text mode and Parts mod
| role | str | Yes | - | Message role: "user" or "assistant" |
| parts | List[dict \| MessagePart] | Conditional | - | SDK part dictionaries or `TextPart`/`ContextPart`/`ImagePart`/`ToolPart` objects; HTTP API accepts dictionaries only; mutually exclusive with content |
| content | str | Conditional | - | Message text content (simple mode; mutually exclusive with parts) |
-| created_at | str | No | None | Optional ISO 8601 timestamp to persist on the message |
| peer_id | str | No | None | Optional stable interaction peer identity |
+| options | AddMessageOptions | No | None | Advanced message options such as `created_at`, `telemetry`, `turn_id`, `message_kind`, and `source_message_ids` |
> **Note**: HTTP API supports two modes:
> 1. **Simple mode**: Use `content` string (backward compatible)
@@ -1136,6 +1136,7 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \
```python
import openviking as ov
+from openviking_sdk import ContextPart, ImagePart, TextPart
client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")
await client.initialize()
@@ -1236,7 +1237,7 @@ Add multiple messages to a session in a single request. Suitable for scenarios t
|------|------|------|--------|------|
| session_id | str | Yes | - | Session ID |
| messages | List[AddMessageRequest] | Yes | - | List of messages, each following the same format as `add_message()`, max 100 |
-| telemetry | bool | No | False | Whether to attach operation telemetry data |
+| options | BatchAddMessagesOptions | No | None | Advanced batch options such as `telemetry`; pass `options={"telemetry": true}` to include operation telemetry data |
> **Note**: Each message follows the exact same format as `add_message()`, supporting both `content` (simple mode) and `parts` (Parts mode). If you need to add more than 100 messages, call in batches.
diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.md
index e61ac1e16..8c7acfd11 100644
--- a/docs/zh/api/05-sessions.md
+++ b/docs/zh/api/05-sessions.md
@@ -1028,8 +1028,8 @@ ov session delete a1b2c3d4
| role | str | 是 | - | 消息角色:"user" 或 "assistant" |
| parts | List[dict \| MessagePart] | 条件必填 | - | SDK 可传消息片段字典或 `TextPart`/`ContextPart`/`ImagePart`/`ToolPart` 对象;HTTP API 仅接受字典;与 content 二选一 |
| content | str | 条件必填 | - | 消息文本内容(简单模式,与 parts 二选一) |
-| created_at | str | 否 | None | 可选的 ISO 8601 时间戳,会原样保存到消息中 |
| peer_id | str | 否 | None | 可选的稳定交互对象 ID |
+| options | AddMessageOptions | 否 | None | 进阶消息选项,例如 `created_at`、`telemetry`、`turn_id`、`message_kind` 和 `source_message_ids` |
> **注意**:HTTP API 支持两种模式:
> 1. **简单模式**:使用 `content` 字符串(向后兼容)
@@ -1117,6 +1117,7 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \
```python
import openviking as ov
+from openviking_sdk import ContextPart, TextPart
client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")
await client.initialize()
@@ -1207,7 +1208,7 @@ ov session add-message a1b2c3d4 --role user --content "How do I authenticate use
|------|------|------|--------|------|
| session_id | str | 是 | - | 会话 ID |
| messages | List[AddMessageRequest] | 是 | - | 消息列表,每条消息格式与 `add_message()` 相同,最多 100 条 |
-| telemetry | bool | 否 | False | 是否附加操作遥测数据 |
+| options | BatchAddMessagesOptions | 否 | None | 进阶批量选项,例如 `telemetry`;传入 `options={"telemetry": True}` 可附加操作遥测数据 |
> **注意**:每条消息的格式与 `add_message()` 完全一致,支持 `content`(简单模式)和 `parts`(Parts 模式)。超过 100 条需分批调用。
diff --git a/openviking_cli/client/_http_compat.py b/openviking_cli/client/_http_compat.py
index d9fe260b5..d49d9fc25 100644
--- a/openviking_cli/client/_http_compat.py
+++ b/openviking_cli/client/_http_compat.py
@@ -133,77 +133,13 @@ class AsyncHTTPClient(import_openviking_sdk().AsyncHTTPClient):
if len(args) <= timeout_index and not _timeout_configured_outside_call():
kwargs["timeout"] = 180.0
super().__init__(*args, **kwargs)
-
- async def initialize(self) -> None:
- # The upstream SDK uses httpx defaults (max_connections=100). High-parallel
- # tau2 rollouts can exceed that from one shared client and hit PoolTimeout
- # while waiting for a free connection, so raise the pool ceiling.
- headers: Dict[str, str] = {}
- if getattr(self, "_api_key", None):
- headers["X-API-Key"] = self._api_key
- if getattr(self, "_account", None):
- headers["X-OpenViking-Account"] = self._account
- if getattr(self, "_user_id", None):
- headers["X-OpenViking-User"] = self._user_id
- if getattr(self, "_actor_peer_id", None):
- headers["X-OpenViking-Actor-Peer"] = self._actor_peer_id
- headers.update(getattr(self, "_extra_headers", {}) or {})
-
- max_connections = 512
- max_keepalive = 128
- self._http = httpx.AsyncClient(
- base_url=self._url,
- headers=headers,
- timeout=self._timeout,
- params={"profile": "1"} if self._profile_enabled else None,
- limits=httpx.Limits(
- max_connections=max_connections,
- max_keepalive_connections=max_keepalive,
- ),
- )
- observer_cls = getattr(import_openviking_sdk().client, "_HTTPObserver", None)
- if observer_cls is not None:
- self._observer = observer_cls(self)
+ # High-parallel tau2 rollouts can exceed httpx defaults from one shared
+ # client and hit PoolTimeout while waiting for a free connection.
+ self._http_limits = httpx.Limits(max_connections=512, max_keepalive_connections=128)
def _raise_exception(self, error: Dict[str, Any]) -> None:
_raise_legacy_exception(error)
- async def add_message(
- self,
- session_id: str,
- role: str,
- content: str | None = None,
- parts: list[dict] | None = None,
- created_at: str | None = None,
- peer_id: str | None = None,
- telemetry: Any = False,
- turn_id: str | None = None,
- message_kind: str | None = None,
- source_message_ids: list[str] | None = None,
- ) -> Dict[str, Any]:
- payload: Dict[str, Any] = {"role": role}
- if parts is not None:
- payload["parts"] = parts
- elif content is not None:
- payload["content"] = content
- else:
- raise ValueError("Either content or parts must be provided")
- optional = {
- "created_at": created_at,
- "peer_id": peer_id,
- "turn_id": turn_id,
- "message_kind": message_kind,
- "source_message_ids": source_message_ids,
- }
- payload.update({key: value for key, value in optional.items() if value is not None})
- if telemetry is not False:
- payload["telemetry"] = telemetry
- session_path = self._path_segment(session_id)
- response = await self._request(
- "POST", f"/api/v1/sessions/{session_path}/messages", json=payload
- )
- return self._handle_response_data(response).get("result", {})
-
async def update_session_config(
self,
session_id: str,
@@ -267,34 +203,6 @@ class SyncHTTPClient(import_openviking_sdk().SyncHTTPClient):
super().__init__(*args, **kwargs)
self._async_client = AsyncHTTPClient(*args, **kwargs)
- def add_message(
- self,
- session_id: str,
- role: str,
- content: str | None = None,
- parts: list[dict] | None = None,
- created_at: str | None = None,
- peer_id: str | None = None,
- telemetry: Any = False,
- turn_id: str | None = None,
- message_kind: str | None = None,
- source_message_ids: list[str] | None = None,
- ) -> Dict[str, Any]:
- return run_async(
- self._async_client.add_message(
- session_id,
- role,
- content=content,
- parts=parts,
- created_at=created_at,
- peer_id=peer_id,
- telemetry=telemetry,
- turn_id=turn_id,
- message_kind=message_kind,
- source_message_ids=source_message_ids,
- )
- )
-
def update_session_config(
self,
session_id: str,
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index f16e24a96..497c02055 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -344,6 +344,7 @@ class AsyncHTTPClient:
self._ldap_password = config.ldap_password
self._oidc_token = config.oidc_token
self._event_hooks = {event: list(hooks) for event, hooks in (event_hooks or {}).items()}
+ self._http_limits: Optional[httpx.Limits] = None
self._http: Optional[httpx.AsyncClient] = None
self._observer: Optional[_HTTPObserver] = None
self._snapshot: Optional["AsyncHTTPSnapshotNamespace"] = None
@@ -377,13 +378,16 @@ class AsyncHTTPClient:
headers["Authorization"] = f"Bearer {token}"
headers.update(self._extra_headers)
- self._http = httpx.AsyncClient(
- base_url=self._url,
- headers=headers,
- timeout=self._timeout,
- event_hooks=self._event_hooks,
- params={"profile": "1"} if self._profile_enabled else None,
- )
+ client_kwargs: Dict[str, Any] = {
+ "base_url": self._url,
+ "headers": headers,
+ "timeout": self._timeout,
+ "event_hooks": self._event_hooks,
+ "params": {"profile": "1"} if self._profile_enabled else None,
+ }
+ if self._http_limits is not None:
+ client_kwargs["limits"] = self._http_limits
+ self._http = httpx.AsyncClient(**client_kwargs)
self._observer = _HTTPObserver(self)
@staticmethod
diff --git a/tests/client/test_http_client_config.py b/tests/client/test_http_client_config.py
index ee1c4ed86..095cbae03 100644
--- a/tests/client/test_http_client_config.py
+++ b/tests/client/test_http_client_config.py
@@ -138,7 +138,7 @@ async def test_async_http_client_omits_identity_headers_when_unconfigured(tmp_pa
def __init__(self, **kwargs):
captured.update(kwargs)
- monkeypatch.setattr("openviking_cli.client.http.httpx.AsyncClient", FakeAsyncClient)
+ monkeypatch.setattr("openviking_sdk.client.httpx.AsyncClient", FakeAsyncClient)
client = AsyncHTTPClient(
url="http://explicit-host:1933",
@@ -165,7 +165,7 @@ async def test_async_http_client_sends_configured_identity_headers(tmp_path, mon
def __init__(self, **kwargs):
captured.update(kwargs)
- monkeypatch.setattr("openviking_cli.client.http.httpx.AsyncClient", FakeAsyncClient)
+ monkeypatch.setattr("openviking_sdk.client.httpx.AsyncClient", FakeAsyncClient)
client = AsyncHTTPClient(
url="http://explicit-host:1933",
@@ -213,6 +213,39 @@ async def test_async_http_client_sends_agent_id_as_actor_peer_header(tmp_path, m
assert "X-OpenViking-Agent" not in captured["headers"]
+async def test_async_http_client_uses_sdk_initialize_with_compat_limits(tmp_path, monkeypatch):
+ captured: dict[str, object] = {}
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text("{}")
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
+
+ class FakeAsyncClient:
+ def __init__(self, **kwargs):
+ captured.update(kwargs)
+
+ async def hook(response):
+ return response
+
+ monkeypatch.setattr("openviking_sdk.client.httpx.AsyncClient", FakeAsyncClient)
+
+ client = AsyncHTTPClient(
+ url="http://explicit-host:1933",
+ auth_mode="oidc",
+ oidc_token="header.payload.signature",
+ event_hooks={"response": [hook]},
+ timeout=33.0,
+ extra_headers={},
+ )
+ await client.initialize()
+
+ assert captured["headers"]["Authorization"] == "Bearer header.payload.signature"
+ assert captured["event_hooks"] == {"response": [hook]}
+ limits_repr = repr(captured["limits"])
+ assert "max_connections=512" in limits_repr
+ assert "max_keepalive_connections=128" in limits_repr
+
+
def test_async_http_client_rejects_unknown_ovcli_field(tmp_path, monkeypatch):
config_path = tmp_path / "ovcli.conf"
config_path.write_text(json.dumps({"ur": "http://localhost:1933"}))
diff --git a/tests/client/test_rebuild_clients.py b/tests/client/test_rebuild_clients.py
index 77b76cfaf..b2aa201a8 100644
--- a/tests/client/test_rebuild_clients.py
+++ b/tests/client/test_rebuild_clients.py
@@ -251,7 +251,7 @@ def test_sync_http_client_batch_add_messages_forwards_to_async_client():
assert result == {"session_id": "batch-session", "message_count": 2, "added": 2}
assert mock_run.called
- mock_batch.assert_called_once_with("batch-session", messages)
+ mock_batch.assert_called_once_with("batch-session", messages, None)
def test_run_async_from_foreign_event_loop_uses_shared_background_loop():