From 07fe1dced402bb675d7da73783341bc72785eb57 Mon Sep 17 00:00:00 2001 From: foleydang Date: Tue, 17 Nov 2026 10:07:44 +0800 Subject: [PATCH] feat(agentstudio): add usage APIs and reuse SDK transport --- dashscope/applications/agentstudio/client.py | 6 + .../agentstudio/resources/usage.py | 66 ++ .../applications/agentstudio/transport.py | 763 ++++------------ tests/test_agentstudio_usage.py | 852 ++++++++++++++++++ 4 files changed, 1095 insertions(+), 592 deletions(-) create mode 100644 dashscope/applications/agentstudio/resources/usage.py create mode 100644 tests/test_agentstudio_usage.py diff --git a/dashscope/applications/agentstudio/client.py b/dashscope/applications/agentstudio/client.py index b90b7771..90dd9b32 100644 --- a/dashscope/applications/agentstudio/client.py +++ b/dashscope/applications/agentstudio/client.py @@ -16,6 +16,10 @@ validate_region, validate_workspace_id, ) +from dashscope.applications.agentstudio.resources.usage import ( + Usage, + AsyncUsage, +) from dashscope.applications.agentstudio.resources.agents import ( Agents, AsyncAgents, @@ -213,6 +217,7 @@ def __init__( self.memory_stores = MemoryStores(self) self.webhook_endpoints = WebhookEndpoints(self) self.security = Security(self) + self.usage = Usage(self) def close(self) -> None: self.transport.close() @@ -295,6 +300,7 @@ def __init__( self.memory_stores = AsyncMemoryStores(self) self.webhook_endpoints = AsyncWebhookEndpoints(self) self.security = AsyncSecurity(self) + self.usage = AsyncUsage(self) async def aclose(self) -> None: await self.transport.aclose() diff --git a/dashscope/applications/agentstudio/resources/usage.py b/dashscope/applications/agentstudio/resources/usage.py new file mode 100644 index 00000000..9b4312bf --- /dev/null +++ b/dashscope/applications/agentstudio/resources/usage.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Usage summary and trend queries for Managed Agents.""" + +from __future__ import annotations + +from typing import Any, Dict + +_PATH_USAGE_SUMMARY = "/usage/summary" +_PATH_USAGE_TREND = "/usage/trend" + + +class Usage: + """Read workspace, agent, and session usage.""" + + def __init__(self, client) -> None: + self._client = client + + def summary(self, **params: Any) -> Dict[str, Any]: + """Query usage totals and model/tool breakdowns (``POST /usage/summary``). + + Pass the API's snake_case body fields as keyword arguments. The + service validates dimension-specific parameter combinations. + """ + resp = self._client.transport.request( + "POST", + _PATH_USAGE_SUMMARY, + json=dict(params), + ) + return resp.data + + def trend(self, **params: Any) -> Dict[str, Any]: + """Query paginated usage buckets (``POST /usage/trend``). + + Pass the API's snake_case body fields as keyword arguments. To fetch + another page, pass the returned ``next_page_token`` as ``page_token``. + """ + resp = self._client.transport.request( + "POST", + _PATH_USAGE_TREND, + json=dict(params), + ) + return resp.data + + +class AsyncUsage: + """Async usage summary and trend queries.""" + + def __init__(self, client) -> None: + self._client = client + + async def summary(self, **params: Any) -> Dict[str, Any]: + resp = await self._client.transport.request( + "POST", + _PATH_USAGE_SUMMARY, + json=dict(params), + ) + return resp.data + + async def trend(self, **params: Any) -> Dict[str, Any]: + resp = await self._client.transport.request( + "POST", + _PATH_USAGE_TREND, + json=dict(params), + ) + return resp.data diff --git a/dashscope/applications/agentstudio/transport.py b/dashscope/applications/agentstudio/transport.py index 01323f5a..a20f027e 100644 --- a/dashscope/applications/agentstudio/transport.py +++ b/dashscope/applications/agentstudio/transport.py @@ -1,32 +1,18 @@ # -*- coding: utf-8 -*- # Copyright (c) Alibaba, Inc. and its affiliates. -"""HTTP transport for the AgentStudio SDK. - -This module wraps ``httpx.Client`` (sync) and ``httpx.AsyncClient`` -(async) so the rest of the SDK can speak in plain Python data structures. -The transport layer is responsible for: - -* injecting auth / workspace / uid headers, -* JSON encoding / decoding the request and response bodies, -* converting non-2xx responses into :class:`AgentStudioError`, -* retry-on-network-error with bounded exponential backoff. - -It deliberately does *not* implement model marshalling – that lives in -the resource modules so each endpoint can hydrate its own typed shapes. -""" +"""AgentStudio request/response adapters over the SDK 2.0 HTTP transport.""" from __future__ import annotations -import asyncio -import logging -import random -import socket -import time +from contextlib import contextmanager from dataclasses import dataclass -from typing import Any, Dict, IO, Mapping, Optional, Tuple, Union +from typing import Any, Dict, IO, Optional, Tuple, Union +from urllib.parse import urlsplit import httpx +from dashscope.transport import SyncTransport as SDKSyncTransport +from dashscope.transport import AsyncTransport as SDKAsyncTransport from dashscope._shared._sdk_ident import get_sdk_headers from dashscope.applications.agentstudio import ( exceptions as _default_exceptions, @@ -36,22 +22,9 @@ AGENTSTUDIO_MAX_RETRIES, ) -logger = logging.getLogger("dashscope.applications.agentstudio") - -# --------------------------------------------------------------------------- -# Base data classes (merged from _base.py) -# --------------------------------------------------------------------------- - @dataclass class RequestOptions: - """Typed HTTP request options. - - Encapsulates all parameters needed to issue an HTTP request through - the transport layer, replacing bare keyword arguments for better - type safety and testability. - """ - method: str path: str json: Optional[Dict[str, Any]] = None @@ -66,77 +39,62 @@ class RequestOptions: @dataclass class APIResponse: - """Typed API response. - - Wraps the parsed response data together with metadata (request_id, - status_code) so callers no longer need to unpack anonymous tuples. - """ - data: Dict[str, Any] request_id: Optional[str] = None status_code: int = 200 - -# --------------------------------------------------------------------------- -# Constants (merged from _constants.py) -# --------------------------------------------------------------------------- - -HEADER_AUTHORIZATION = "Authorization" -HEADER_REQUEST_ID = "x-request-id" -HEADER_UID = "x-dashscope-uid" -HEADER_USER_AGENT = "User-Agent" - -# --------------------------------------------------------------------------- -# Response normalization helpers (merged from _response.py) -# --------------------------------------------------------------------------- + @classmethod + def from_http_response(cls, response, exceptions_module): + content_type = response.headers.get("Content-Type", "") + if response.status_code < 400 and not content_type.startswith( + "application/json", + ): + payload = { + "_binary": response.content, + "_content_type": content_type, + } + else: + try: + payload = response.json() + except ValueError: + payload = {"raw": response.text} + if response.status_code >= 400 or is_error_payload(payload): + raise exceptions_module.from_response( + status_code=response.status_code, + body=payload, + headers=response.headers, + ) + data, request_id = unwrap(payload) + return cls( + data, + request_id or response.headers.get("x-request-id"), + response.status_code, + ) def unwrap(payload: Any) -> Tuple[Dict[str, Any], Optional[str]]: - """Normalize a JSON response body. - - Returns - ------- - (data, request_id) - ``data`` is the canonical resource payload with ``requestId`` - rewritten to ``request_id``. ``request_id`` is also returned as a - separate value for downstream metadata recording. - """ - - if not isinstance(payload, dict): - return ({"value": payload}, None) - - data = dict(payload) + data = dict(payload) if isinstance(payload, dict) else {"value": payload} request_id = data.pop("requestId", None) - if request_id is not None and "request_id" not in data: - data["request_id"] = request_id - rid = data.get("request_id") - return data, rid if isinstance(rid, str) else None + if request_id is not None: + data.setdefault("request_id", request_id) + request_id = data.get("request_id") + return data, request_id if isinstance(request_id, str) else None def is_error_payload(payload: Any) -> bool: - """Identify error bodies for both documented and pre-release shapes.""" - if not isinstance(payload, dict): return False - if payload.get("type") == "error": - return True - err = payload.get("error") - if isinstance(err, dict): - return any( - k in err - for k in ( - "code", - "message", - "error_code", - "error_message", - ) + error = payload.get("error") + return payload.get("type") == "error" or ( + isinstance(error, dict) + and any( + key in error + for key in ("code", "message", "error_code", "error_message") ) - return False + ) -def _resolve_timeout( - timeout: Union[float, httpx.Timeout, Tuple[float, float], None], -) -> httpx.Timeout: +def _resolve_timeout(timeout): if timeout is None: return AGENTSTUDIO_DEFAULT_TIMEOUT if isinstance(timeout, httpx.Timeout): @@ -149,562 +107,183 @@ def _resolve_timeout( ) -def _backoff(attempt: int) -> float: - """Capped jittered exponential backoff.""" - - base = min(2**attempt, 8.0) - return base + random.random() * 0.25 - - -def _get_retry_after(headers: Mapping[str, str]) -> Optional[float]: - """Parse retry delay from response headers. - - Checks ``retry-after-ms`` (milliseconds), then ``retry-after`` (seconds). - Returns seconds or None. - """ - try: - ms = headers.get("retry-after-ms") - if ms is not None: - return float(ms) / 1000 - except (TypeError, ValueError): - pass - try: - sec = headers.get("retry-after") - if sec is not None: - return float(sec) - except (TypeError, ValueError): - pass - return None - - -def _should_retry(status_code: int, headers: Mapping[str, str]) -> bool: - """Decide whether an HTTP response should be retried.""" - should_retry_header = headers.get("x-should-retry") - if should_retry_header == "true": - return True - if should_retry_header == "false": - return False - return status_code in (408, 409, 429) or status_code >= 500 - - -def _should_retry_exception( - err: BaseException, - exceptions_module: Any = _default_exceptions, -) -> Tuple[bool, Optional[Any]]: - """Walk the ``__cause__`` chain to decide if an exception is retryable. - - Returns ``(should_retry, response_or_none)``. - """ - seen: set[int] = set() - current: Optional[BaseException] = err - while current is not None and id(current) not in seen: - seen.add(id(current)) - if isinstance(current, exceptions_module.AgentStudioError): - return False, None - if isinstance(current, httpx.TimeoutException): - return True, None - if isinstance(current, httpx.NetworkError): - return True, None - current = current.__cause__ - return False, None - - -# --------------------------------------------------------------------------- -# Header builder (shared by sync + async transports) -# --------------------------------------------------------------------------- - - def build_headers( *, - api_key: Optional[str], - uid: Optional[str], - user_agent: str, - extra: Optional[Mapping[str, str]] = None, - json_body: bool = True, - _exceptions_module: Any = _default_exceptions, -) -> Dict[str, str]: - """Compose the canonical AgentStudio request headers.""" - + api_key, + uid, + user_agent, + extra=None, + json_body=True, + _exceptions_module=_default_exceptions, +): if not api_key: raise _exceptions_module.AuthenticationError( "api_key is required. Pass it via Client(api_key=...) or " "the DASHSCOPE_API_KEY environment variable.", code="authentication_error", ) - - headers: Dict[str, str] = { - HEADER_AUTHORIZATION: f"Bearer {api_key}", - HEADER_USER_AGENT: user_agent, - } + headers = {"Authorization": f"Bearer {api_key}", "User-Agent": user_agent} headers.update(get_sdk_headers(module="agentstudio")) if json_body: - headers["Content-Type"] = "application/json" - headers["Accept"] = "application/json" + headers.update( + {"Content-Type": "application/json", "Accept": "application/json"}, + ) if uid: - headers[HEADER_UID] = uid - if extra: - for k, v in extra.items(): - if v is not None: - headers[k] = v + headers["x-dashscope-uid"] = uid + headers.update( + { + key: value + for key, value in (extra or {}).items() + if value is not None + }, + ) return headers -# --------------------------------------------------------------------------- -# Sync transport (httpx) -# --------------------------------------------------------------------------- - - -class SyncTransport: - """Thin ``httpx.Client`` wrapper used by the sync client.""" +class _Transport: + """Share AgentStudio protocol conversion; HTTP mechanics belong to SDK 2.0.""" def __init__( self, *, - base_url: str, - api_key: Optional[str], - workspace: Optional[str], - uid: Optional[str], - user_agent: str, - timeout: Union[float, httpx.Timeout, Tuple[float, float], None], - max_retries: int = AGENTSTUDIO_MAX_RETRIES, - http_client: Optional[httpx.Client] = None, - exceptions_module: Any = _default_exceptions, - ) -> None: + base_url, + api_key, + workspace, + uid, + user_agent, + timeout, + max_retries=AGENTSTUDIO_MAX_RETRIES, + http_client=None, + exceptions_module=_default_exceptions, + ): self.base_url = base_url.rstrip("/") - self.api_key = api_key - self.workspace = workspace - self.uid = uid - self.user_agent = user_agent - self.timeout = timeout - self.max_retries = max_retries - self.exceptions = exceptions_module - self._owns_client = http_client is None - if http_client is not None: - self._client = http_client - else: - socket_options = [ - (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), - ] - if hasattr(socket, "TCP_KEEPINTVL"): - socket_options.append( - (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 60), - ) - if hasattr(socket, "TCP_KEEPIDLE"): - socket_options.append( - (socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60), - ) - if hasattr(socket, "TCP_KEEPCNT"): - socket_options.append( - (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5), - ) - transport = httpx.HTTPTransport( - socket_options=socket_options, - ) - self._client = httpx.Client( - timeout=_resolve_timeout(timeout), - limits=httpx.Limits( - max_connections=1000, - max_keepalive_connections=100, - ), - transport=transport, - ) - - def _absolute_url(self, path: str) -> str: - if path.startswith(("http://", "https://")): - return path - if not path.startswith("/"): - path = "/" + path - return self.base_url + path + self.api_key, self.workspace, self.uid = api_key, workspace, uid + self.user_agent, self.timeout = user_agent, timeout + self.max_retries, self.exceptions = max_retries, exceptions_module + self._transport = self._transport_type( + base_url=self.base_url, + api_key=api_key, + workspace=workspace, + user_agent=user_agent, + timeout=_resolve_timeout(timeout), + max_retries=max_retries, + http_client=http_client, + ) + self._client = self._transport.http_client - def request( # pylint: disable=too-many-branches + def _prepare( self, - method: str, - path: str, + method, + path, *, - params: Optional[Mapping[str, Any]] = None, - json: Any = None, - data: Any = None, - files: Any = None, - extra_headers: Optional[Mapping[str, str]] = None, - timeout: Union[float, httpx.Timeout, Tuple[float, float], None] = None, - stream: bool = False, - ) -> Any: - """Issue an HTTP request and return an :class:`APIResponse`. - - For ``stream=True`` returns the raw :class:`httpx.Response` so - the streaming module can iterate over it. - """ - + params=None, + json=None, + data=None, + files=None, + extra_headers=None, + timeout=None, + stream=False, + ): headers = build_headers( api_key=self.api_key, uid=self.uid, user_agent=self.user_agent, extra=extra_headers, - json_body=( - files is None - and method.upper() not in ("GET", "HEAD", "DELETE") - ), + json_body=files is None + and method.upper() not in ("GET", "HEAD", "DELETE"), _exceptions_module=self.exceptions, ) if files is not None: headers.pop("Content-Type", None) - - url = self._absolute_url(path) - req_timeout = _resolve_timeout( - timeout if timeout is not None else self.timeout, - ) - - attempt = 0 - last_exc: Optional[Exception] = None - while attempt <= self.max_retries: - try: - req = self._client.build_request( - method=method.upper(), - url=url, - params=params, - json=json, - content=data, - files=files, - headers=headers, - timeout=req_timeout, - ) - resp = self._client.send(req, stream=stream) - except httpx.TimeoutException as exc: - last_exc = exc - if attempt >= self.max_retries: - raise self.exceptions.APITimeoutError(str(exc)) from exc - except Exception as exc: - if isinstance(exc, self.exceptions.AgentStudioError): - raise - should_retry, _ = _should_retry_exception(exc, self.exceptions) - last_exc = exc - if attempt >= self.max_retries or not should_retry: - raise self.exceptions.APIConnectionError(str(exc)) from exc - else: - if stream: - if resp.status_code >= 400: - resp.read() - else: - return resp - if _should_retry( - resp.status_code, - resp.headers, - ): - last_exc = self.exceptions.APIStatusError( - f"HTTP {resp.status_code}", - status_code=resp.status_code, - ) - if attempt < self.max_retries: - wait = _get_retry_after(resp.headers) or _backoff( - attempt, - ) - resp.close() - time.sleep(wait) - attempt += 1 - continue - try: - return self._parse(resp) - finally: - resp.close() - time.sleep(_backoff(attempt)) - attempt += 1 - raise self.exceptions.APIConnectionError( - str(last_exc) if last_exc else "unknown", + kwargs = { + "params": params, + "json": json, + "headers": headers, + "sdk_module": "agentstudio", + "timeout": _resolve_timeout( + timeout if timeout is not None else self.timeout, + ), + } + if path.startswith(("http://", "https://")): + url = urlsplit(path) + kwargs["base_url"] = f"{url.scheme}://{url.netloc}" + path = (url.path or "/") + ("?" + url.query if url.query else "") + if not stream: + kwargs.update(content=data, files=files) + send = ( + self._transport.open_stream if stream else self._transport.request ) + return send, path, kwargs - def _parse(self, resp: httpx.Response) -> APIResponse: - header_rid = resp.headers.get("x-request-id") - ctype = resp.headers.get("Content-Type", "") - - if not ctype.startswith("application/json") and resp.status_code < 400: - payload: Any = {"_binary": resp.content, "_content_type": ctype} - data, rid = unwrap(payload) - return APIResponse( - data=data, - request_id=rid or header_rid, - status_code=resp.status_code, - ) - + @contextmanager + def _errors(self): try: - payload = resp.json() - except ValueError: - payload = {"raw": resp.text} - - if resp.status_code >= 400 or is_error_payload(payload): - logger.warning( - "AgentStudio request failed: status=%s request_id=%s body=%s", - resp.status_code, - header_rid, - str(payload)[:500], - ) - raise self.exceptions.from_response( - status_code=resp.status_code, - body=payload, - headers=resp.headers, + yield + except _default_exceptions.AgentStudioError as exc: + if exc.status_code is not None: + raise self.exceptions.from_response( + status_code=exc.status_code, + body=exc.body, + headers=exc.headers, + ) from exc + error_class = ( + self.exceptions.APITimeoutError + if isinstance(exc, _default_exceptions.APITimeoutError) + else self.exceptions.APIConnectionError ) - - data, rid = unwrap(payload) - return APIResponse( - data=data, - request_id=rid or header_rid, - status_code=resp.status_code, - ) - - def close(self) -> None: - if self._owns_client: - self._client.close() + raise error_class(str(exc), request_id=exc.request_id) from exc @property - def is_closed(self) -> bool: + def is_closed(self): return self._client.is_closed - def __enter__(self) -> "SyncTransport": - return self - def __exit__( - self, - exc_type: Optional[type], - exc: Optional[BaseException], - exc_tb: Any, - ) -> None: - self.close() +class SyncTransport(_Transport): + _transport_type = SDKSyncTransport - def __del__(self) -> None: + def request(self, method, path, **kwargs): + send, path, options = self._prepare(method, path, **kwargs) + with self._errors(): + response = send(method, path, **options) + if kwargs.get("stream"): + return response try: - if self.is_closed: - return - self.close() - except Exception: - pass - - -# --------------------------------------------------------------------------- -# Async transport (httpx) -# --------------------------------------------------------------------------- - + return APIResponse.from_http_response(response, self.exceptions) + finally: + response.close() -class AsyncTransport: - """``httpx.AsyncClient`` transport with built-in connection pooling.""" + def close(self): + self._transport.close() - def __init__( - self, - *, - base_url: str, - api_key: Optional[str], - workspace: Optional[str], - uid: Optional[str], - user_agent: str, - timeout: Union[float, httpx.Timeout, Tuple[float, float], None], - max_retries: int = AGENTSTUDIO_MAX_RETRIES, - http_client: Optional[httpx.AsyncClient] = None, - exceptions_module: Any = _default_exceptions, - ) -> None: - self.base_url = base_url.rstrip("/") - self.api_key = api_key - self.workspace = workspace - self.uid = uid - self.user_agent = user_agent - self.timeout = timeout - self.max_retries = max_retries - self.exceptions = exceptions_module - self._owns_client = http_client is None - if http_client is not None: - self._client = http_client - else: - socket_options = [ - (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), - ] - if hasattr(socket, "TCP_KEEPINTVL"): - socket_options.append( - (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 60), - ) - if hasattr(socket, "TCP_KEEPIDLE"): - socket_options.append( - (socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60), - ) - if hasattr(socket, "TCP_KEEPCNT"): - socket_options.append( - (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5), - ) - transport = httpx.AsyncHTTPTransport( - socket_options=socket_options, - ) - self._client = httpx.AsyncClient( - timeout=_resolve_timeout(timeout), - limits=httpx.Limits( - max_connections=1000, - max_keepalive_connections=100, - ), - transport=transport, - ) - - def _absolute_url(self, path: str) -> str: - if path.startswith(("http://", "https://")): - return path - if not path.startswith("/"): - path = "/" + path - return self.base_url + path - - async def request( # pylint: disable=too-many-branches - self, - method: str, - path: str, - *, - params: Optional[Mapping[str, Any]] = None, - json: Any = None, - data: Any = None, - files: Any = None, - extra_headers: Optional[Mapping[str, str]] = None, - timeout: Union[float, httpx.Timeout, Tuple[float, float], None] = None, - stream: bool = False, - ) -> Any: - """Issue an HTTP request. - - For ``stream=True`` returns raw ``httpx.Response``. - """ + def __enter__(self): + return self - headers = build_headers( - api_key=self.api_key, - uid=self.uid, - user_agent=self.user_agent, - extra=extra_headers, - json_body=( - files is None - and method.upper() not in ("GET", "HEAD", "DELETE") - ), - _exceptions_module=self.exceptions, - ) - if files is not None: - headers.pop("Content-Type", None) - req_timeout = _resolve_timeout( - timeout if timeout is not None else self.timeout, - ) - url = self._absolute_url(path) + def __exit__(self, *args): + self.close() - attempt = 0 - last_exc: Optional[Exception] = None - while attempt <= self.max_retries: - try: - req = self._client.build_request( - method=method.upper(), - url=url, - params=params, - json=json, - content=data, - files=files, - headers=headers, - timeout=req_timeout, - ) - resp = await self._client.send(req, stream=stream) - except httpx.TimeoutException as exc: - last_exc = exc - if attempt >= self.max_retries: - raise self.exceptions.APITimeoutError(str(exc)) from exc - except Exception as exc: - if isinstance(exc, self.exceptions.AgentStudioError): - raise - should_retry, _ = _should_retry_exception(exc, self.exceptions) - last_exc = exc - if attempt >= self.max_retries or not should_retry: - raise self.exceptions.APIConnectionError(str(exc)) from exc - else: - if stream: - if resp.status_code >= 400: - await resp.aread() - else: - return resp - if _should_retry( - resp.status_code, - resp.headers, - ): - last_exc = self.exceptions.APIStatusError( - f"HTTP {resp.status_code}", - status_code=resp.status_code, - ) - if attempt < self.max_retries: - wait = _get_retry_after(resp.headers) or _backoff( - attempt, - ) - await resp.aclose() - await asyncio.sleep(wait) - attempt += 1 - continue - try: - return await self._parse(resp) - finally: - await resp.aclose() - await asyncio.sleep(_backoff(attempt)) - attempt += 1 - raise self.exceptions.APIConnectionError( - str(last_exc) if last_exc else "unknown", - ) - async def _parse(self, resp: httpx.Response) -> APIResponse: - header_rid = resp.headers.get("x-request-id") - ctype = resp.headers.get("Content-Type", "") - - if not ctype.startswith("application/json") and resp.status_code < 400: - content = await resp.aread() - data, rid = unwrap({"_binary": content, "_content_type": ctype}) - return APIResponse( - data=data, - request_id=rid or header_rid, - status_code=resp.status_code, - ) +class AsyncTransport(_Transport): + _transport_type = SDKAsyncTransport + async def request(self, method, path, **kwargs): + send, path, options = self._prepare(method, path, **kwargs) + with self._errors(): + response = await send(method, path, **options) + if kwargs.get("stream"): + return response try: - payload = resp.json() - except ValueError: - payload = {"raw": resp.text} - - if resp.status_code >= 400 or is_error_payload(payload): - logger.warning( - "AgentStudio request failed: status=%s request_id=%s body=%s", - resp.status_code, - header_rid, - str(payload)[:500], - ) - raise self.exceptions.from_response( - status_code=resp.status_code, - body=payload, - headers=resp.headers, - ) - - data, rid = unwrap(payload) - return APIResponse( - data=data, - request_id=rid or header_rid, - status_code=resp.status_code, - ) + return APIResponse.from_http_response(response, self.exceptions) + finally: + await response.aclose() - def close(self) -> None: - """No-op: AsyncClient requires async cleanup via aclose().""" + def close(self): + """Async clients require cleanup through aclose().""" - async def aclose(self) -> None: - if self._owns_client: - await self._client.aclose() + async def aclose(self): + await self._transport.aclose() - @property - def is_closed(self) -> bool: - return self._client.is_closed - - async def __aenter__(self) -> "AsyncTransport": + async def __aenter__(self): return self - async def __aexit__( - self, - exc_type: Optional[type], - exc: Optional[BaseException], - exc_tb: Any, - ) -> None: + async def __aexit__(self, *args): await self.aclose() - - def __del__(self) -> None: - if self.is_closed: - return - try: - asyncio.get_running_loop().create_task(self.aclose()) - except RuntimeError: - self.close() - except Exception: - pass diff --git a/tests/test_agentstudio_usage.py b/tests/test_agentstudio_usage.py new file mode 100644 index 00000000..144fa990 --- /dev/null +++ b/tests/test_agentstudio_usage.py @@ -0,0 +1,852 @@ +# -*- coding: utf-8 -*- +import json +import asyncio +import io +import inspect +import threading +import time +from concurrent.futures import ThreadPoolExecutor +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import httpx +import pytest + +from dashscope import Client, AsyncClient + + +# Every resource goes through the real HTTP adapter, rather than a fake +# transport.request() that would bypass the migration under test. +RESOURCE_CASES = [] + + +def _resource_cases( + resource, + path, + scope=(), + create=None, + update=None, + operations=("create", "retrieve", "update", "list", "archive", "delete"), +): + for operation in operations: + args = scope if operation in ("create", "list") else scope + ("item",) + kwargs = ( + create or {} + if operation == "create" + else update or {} + if operation == "update" + else {} + ) + method = ( + "GET" + if operation in ("retrieve", "list") + else "DELETE" + if operation == "delete" + else "POST" + ) + target = path if operation in ("create", "list") else path + "/item" + if operation == "archive": + target += "/archive" + RESOURCE_CASES.append( + (resource, operation, args, kwargs, method, target), + ) + + +_resource_cases( + "agents", + "/agents", + create={"name": "test", "model": "model"}, + update={"version": 1, "name": "changed"}, + operations=("create", "retrieve", "update", "list", "archive"), +) +_resource_cases( + "environments", + "/environments", + create={"name": "test", "config": {"type": "cloud"}}, + update={"name": "changed"}, +) +_resource_cases( + "sessions", + "/sessions", + create={"agent": "agent-test"}, + update={"title": "changed"}, +) +_resource_cases( + "vaults", + "/vaults", + create={"display_name": "test"}, + update={"display_name": "changed"}, +) +_resource_cases( + "vaults.credentials", + "/vaults/scope/credentials", + ("scope",), + create={"auth": {"type": "api_key", "api_key": "secret"}}, + update={"display_name": "changed"}, +) +_resource_cases( + "memory_stores", + "/memory_stores", + create={"name": "test"}, + update={"name": "changed"}, +) +_resource_cases( + "memory_stores.memories", + "/memory_stores/scope/memories", + ("scope",), + create={"path": "/test.md", "content": "test"}, + update={"content": "changed", "content_sha256": "sha"}, + operations=("create", "retrieve", "update", "list", "delete"), +) +_resource_cases( + "skills", + "/skills", + create={"file_id": "file-test"}, + operations=("create", "retrieve", "list", "delete"), +) +_resource_cases( + "skills.versions", + "/skills/scope/versions", + ("scope",), + create={"file_id": "file-test"}, + operations=("create", "retrieve", "list"), +) +_resource_cases("files", "/files", operations=("retrieve", "list", "delete")) +_resource_cases( + "deployments", + "/deployments", + create={"name": "test", "agent": "agent-test", "initial_events": []}, + update={"name": "changed"}, + operations=("create", "retrieve", "update", "list", "archive"), +) +_resource_cases( + "deployment_runs", + "/deployment_runs", + operations=("retrieve", "list"), +) +_resource_cases( + "sessions.threads", + "/sessions/scope/threads", + ("scope",), + operations=("retrieve", "list", "archive"), +) +_resource_cases( + "memory_stores.memory_versions", + "/memory_stores/scope/memory_versions", + ("scope",), + operations=("retrieve", "list"), +) +_resource_cases( + "webhook_endpoints", + "/webhook_endpoints", + create={"url": "https://example.test/hook", "events": ["session.idle"]}, + update={"description": "changed"}, + operations=("create", "retrieve", "update", "list", "delete"), +) +RESOURCE_CASES = [ + ( + *c[:4], + "PUT" if c[0] == "webhook_endpoints" and c[1] == "update" else c[4], + c[5], + ) + for c in RESOURCE_CASES +] +RESOURCE_CASES += [ + ( + "agents", + "list_versions", + ("scope",), + {}, + "GET", + "/agents/scope/versions", + ), + ( + "sessions.events", + "send", + ( + "scope", + [ + { + "type": "message", + "role": "user", + "content": [{"type": "text", "text": "test"}], + }, + ], + ), + {}, + "POST", + "/sessions/scope/events", + ), + ( + "sessions.events", + "list", + ("scope",), + {}, + "GET", + "/sessions/scope/events", + ), + ( + "sessions.events", + "stream", + ("scope",), + {}, + "GET", + "/sessions/scope/events/stream", + ), + ( + "sessions.threads.events", + "list", + ("scope", "item"), + {}, + "GET", + "/sessions/scope/threads/item/events", + ), + ( + "sessions.resources", + "add", + ("scope",), + {"file_id": "file-test"}, + "POST", + "/sessions/scope/resources", + ), + ( + "sessions.resources", + "retrieve", + ("scope", "item"), + {}, + "GET", + "/sessions/scope/resources/item", + ), + ( + "sessions.resources", + "list", + ("scope",), + {}, + "GET", + "/sessions/scope/resources", + ), + ( + "sessions.resources", + "delete", + ("scope", "item"), + {}, + "DELETE", + "/sessions/scope/resources/item", + ), + ( + "skills.versions", + "download", + ("scope", "item"), + {}, + "GET", + "/skills/scope/versions/item/content", + ), + ("files", "upload", (), {}, "POST", "/files"), + ("files", "download", ("item",), {}, "GET", "/files/item/content"), + ( + "memory_stores.memory_versions", + "redact", + ("scope", "item"), + {}, + "POST", + "/memory_stores/scope/memory_versions/item/redact", + ), + ("deployments", "pause", ("item",), {}, "POST", "/deployments/item/pause"), + ( + "deployments", + "unpause", + ("item",), + {}, + "POST", + "/deployments/item/unpause", + ), + ("deployments", "run", ("item",), {}, "POST", "/deployments/item/run"), + ( + "deployments", + "list_runs", + ("item",), + {}, + "GET", + "/deployments/item/runs", + ), + ("security", "overview", (), {}, "GET", "/security/overview"), + ( + "security", + "list_agent_logs", + (), + {"page_size": 1}, + "GET", + "/security/agent_logs", + ), + ( + "usage", + "summary", + (), + {"dimension": "session", "session_id": "scope"}, + "POST", + "/usage/summary", + ), + ( + "usage", + "trend", + (), + { + "dimension": "workspace", + "time_range": { + "start_time": "2026-11-02T00:00:00Z", + "end_time": "2026-11-03T00:00:00Z", + }, + }, + "POST", + "/usage/trend", + ), +] +for operation in ("enable", "disable", "test", "reset_secret", "list_events"): + suffix = "events" if operation == "list_events" else operation + RESOURCE_CASES.append( + ( + "webhook_endpoints", + operation, + ("item",), + {}, + "GET" if operation == "list_events" else "POST", + "/webhook_endpoints/item/" + suffix, + ), + ) + + +def _resource(client, path): + for part in path.split("."): + client = getattr(client, part) + return client + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("entry", ["mounted", "standalone", "legacy"]) +@pytest.mark.parametrize( + "case", + RESOURCE_CASES, + ids=lambda c: c[0] + "." + c[1], +) +@pytest.mark.asyncio +async def test_all_resource_methods_through_http( + entry, + asynchronous, + case, + tmp_path, +): + from dashscope.applications.agentstudio import ( + Client as Studio, + AsyncClient as AsyncStudio, + ) + from dashscope.agentstudio import ( + Client as Legacy, + AsyncClient as AsyncLegacy, + ) + + resource, operation, args, kwargs, method, path = case + requests = [] + + def handler(request): + requests.append(request) + if path.endswith("/events/stream"): + return httpx.Response( + 200, + headers={"content-type": "text/event-stream"}, + content=( + b'data: {"type":"message","role":"assistant",' + b'"content":[{"type":"text","text":"done"}]}\n\n' + ), + ) + if resource == "files" and operation == "download": + return httpx.Response( + 200, + content=b"download-bytes", + headers={"content-type": "application/octet-stream"}, + ) + return httpx.Response( + 200, + json={ + "id": "item", + "name": "test", + "model": {"id": "model"}, + "version": 1, + "data": [], + "next_page": None, + "request_id": "req-matrix", + }, + ) + + pool = (httpx.AsyncClient if asynchronous else httpx.Client)( + transport=httpx.MockTransport(handler), + ) + classes = { + "mounted": (Client, AsyncClient), + "standalone": (Studio, AsyncStudio), + "legacy": (Legacy, AsyncLegacy), + } + client = classes[entry][asynchronous]( + api_key="sk-matrix", + base_url="https://example.test/api/v1/agentstudio", + http_client=pool, + ) + studio = client.agentstudio if entry == "mounted" else client + options = dict(kwargs) + if resource == "files" and operation == "upload": + options["file"] = ("test.bin", io.BytesIO(b"upload-bytes")) + try: + result = getattr(_resource(studio, resource), operation)( + *args, + **options, + ) + if inspect.isawaitable(result): + result = await result + if operation == "stream": + events = ( + [event async for event in result] + if asynchronous + else list(result) + ) + assert len(events) == 1 and events[0].type == "message" + elif resource == "files" and operation == "download": + assert result == b"download-bytes" + assert ( + result.write_to_file(tmp_path / "download.bin").read_bytes() + == result + ) + else: + decoded = ( + result + if isinstance(result, dict) + else result.to_dict() + if hasattr(result, "to_dict") + else {"request_id": result.request_id} + ) + assert decoded["request_id"] == "req-matrix" + assert len(requests) == 1 + request = requests[0] + assert ( + request.method == method + and request.url.path == "/api/v1/agentstudio" + path + ) + assert request.headers["Authorization"] == "Bearer sk-matrix" + assert request.headers["x-dashscope-sdk-client"].endswith( + "/agentstudio", + ) + if resource == "files" and operation == "upload": + assert request.headers["content-type"].startswith( + "multipart/form-data;", + ) + assert b"upload-bytes" in request.content + elif request.content: + assert isinstance(json.loads(request.content), dict) + finally: + if asynchronous: + await client.aclose() + assert not pool.is_closed + await pool.aclose() + else: + client.close() + assert not pool.is_closed + pool.close() + + +def test_resource_matrix_has_no_missing_public_methods(): + from dashscope.applications.agentstudio import Client as Studio + + with Studio(api_key="test", base_url="https://example.test") as client: + for path in {case[0] for case in RESOURCE_CASES}: + resource = _resource(client, path) + expected = { + name + for name, value in type(resource).__dict__.items() + if not name.startswith("_") + and callable(value) + and name not in ("get", "call") + } + assert expected == { + case[1] for case in RESOURCE_CASES if case[0] == path + }, path + if hasattr(resource, "get"): + assert resource.get.__func__ is resource.retrieve.__func__ + if hasattr(resource, "call"): + assert resource.call.__func__ is resource.create.__func__ + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.asyncio +async def test_real_http_connection_pool_and_concurrent_responses( + asynchronous, +): + state = {"active": 0, "max_active": 0, "ports": set(), "ids": set()} + lock = threading.Lock() + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def do_GET(self): + with lock: + state["active"] += 1 + state["max_active"] = max(state["max_active"], state["active"]) + state["ports"].add(self.client_address[1]) + state["ids"].add(self.headers["x-dashscope-client-request-id"]) + try: + time.sleep(0.01) + payload = json.dumps( + {"id": self.path.rsplit("/", 1)[-1]}, + ).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + self.wfile.flush() + finally: + with lock: + state["active"] -= 1 + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + pool = (httpx.AsyncClient if asynchronous else httpx.Client)( + limits=httpx.Limits(max_connections=2, max_keepalive_connections=2), + ) + client = (AsyncClient if asynchronous else Client)( + api_key="local-test", + base_url=f"http://127.0.0.1:{server.server_port}/api/v1", + http_client=pool, + ) + try: + if asynchronous: + results = await asyncio.gather( + *( + client.agentstudio.agents.retrieve(f"agent-{i}") + for i in range(24) + ), + ) + else: + with ThreadPoolExecutor(max_workers=8) as executor: + results = list( + executor.map( + client.agentstudio.agents.retrieve, + [f"agent-{i}" for i in range(24)], + ), + ) + assert [item.id for item in results] == [ + f"agent-{i}" for i in range(24) + ] + assert len(state["ids"]) == 24 + assert len(state["ports"]) <= 2 + assert 1 < state["max_active"] <= 2 + finally: + if asynchronous: + await client.aclose() + assert not pool.is_closed + await pool.aclose() + else: + client.close() + assert not pool.is_closed + pool.close() + server.shutdown() + server.server_close() + thread.join(timeout=5) + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("source", ["path", "stream", "tuple"]) +@pytest.mark.parametrize("failure", [False, True]) +@pytest.mark.asyncio +async def test_multipart_progress_and_file_ownership( + asynchronous, + source, + failure, + tmp_path, + monkeypatch, +): + from dashscope.applications.agentstudio import ( + Client as Studio, + AsyncClient as AsyncStudio, + ) + from dashscope.applications.agentstudio.resources import files as module + from dashscope.errors import APIStatusError + + content = b"upload-content" * 12000 + path = tmp_path / "upload.bin" + path.write_bytes(content) + borrowed = io.BytesIO(content) + file = ( + path + if source == "path" + else borrowed + if source == "stream" + else ("named.bin", borrowed) + ) + opened = [] + original = module._open_file + + def tracked(value): + result = original(value) + opened.append(result) + return result + + monkeypatch.setattr(module, "_open_file", tracked) + progress = [] + + def handler(request): + assert request.headers["content-type"].startswith( + "multipart/form-data;", + ) + assert b"application/x-test" in request.content + assert content in request.content + if failure: + return httpx.Response( + 400, + json={ + "type": "error", + "error": { + "code": "invalid_request_error", + "message": "bad file", + }, + }, + ) + return httpx.Response(200, json={"id": "file-upload"}) + + pool = (httpx.AsyncClient if asynchronous else httpx.Client)( + transport=httpx.MockTransport(handler), + ) + client = (AsyncStudio if asynchronous else Studio)( + api_key="test", + base_url="https://example.test", + http_client=pool, + ) + try: + + async def upload(): + result = client.files.upload( + file, + mime_type="application/x-test", + progress=lambda sent, total: progress.append((sent, total)), + ) + return await result if asynchronous else result + + if failure: + with pytest.raises(APIStatusError): + await upload() + else: + assert (await upload()).id == "file-upload" + assert progress[-1] == (len(content), len(content)) + assert all(a[0] <= b[0] for a, b in zip(progress, progress[1:])) + assert opened[0][1].closed == (source == "path") + finally: + borrowed.close() + if asynchronous: + await client.aclose() + await pool.aclose() + else: + client.close() + pool.close() + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("first_failure", ["429", "network"]) +@pytest.mark.asyncio +async def test_shared_retry_replays_request_once(asynchronous, first_failure): + from dashscope.applications.agentstudio import ( + Client as Studio, + AsyncClient as AsyncStudio, + ) + + requests = [] + + def handler(request): + requests.append(request) + if len(requests) == 1: + if first_failure == "network": + raise httpx.ReadError("connection reset", request=request) + return httpx.Response( + 429, + headers={"retry-after": "0"}, + json={"error": {"code": "rate_limit", "message": "retry"}}, + ) + return httpx.Response( + 200, + json={"request_id": "req-retry", "data": {"usage": {}}}, + ) + + pool = (httpx.AsyncClient if asynchronous else httpx.Client)( + transport=httpx.MockTransport(handler), + ) + client = (AsyncStudio if asynchronous else Studio)( + api_key="retry-key", + base_url="https://example.test", + http_client=pool, + max_retries=1, + ) + try: + result = client.usage.summary( + dimension="session", + session_id="session-retry", + ) + if asynchronous: + result = await result + assert result["request_id"] == "req-retry" + assert len(requests) == 2 + assert requests[0].content == requests[1].content + assert all( + r.headers["Authorization"] == "Bearer retry-key" for r in requests + ) + assert ( + requests[0].headers["x-dashscope-client-request-id"] + == requests[1].headers["x-dashscope-client-request-id"] + ) + finally: + if asynchronous: + await client.aclose() + await pool.aclose() + else: + client.close() + pool.close() + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.asyncio +async def test_usage_uses_parent_transport_and_preserves_cursor(asynchronous): + requests = [] + + def handler(request): + requests.append(request) + return httpx.Response( + 200, + json={ + "request_id": "req-usage", + "data": { + "points": [], + "next_page_token": "opaque-cursor", + "has_more": True, + }, + }, + ) + + http_class = httpx.AsyncClient if asynchronous else httpx.Client + sdk_class = AsyncClient if asynchronous else Client + pool = http_class(transport=httpx.MockTransport(handler)) + client = sdk_class( + api_key="sk-test", + base_url="https://example.test/api/v1", + http_client=pool, + ) + usage = client.agentstudio.usage + query = { + "dimension": "workspace", + "time_range": { + "start_time": "2026-11-02T10:00:00+08:00", + "end_time": "2026-11-02T12:00:00+08:00", + }, + "page_size": 1, + } + try: + summary = usage.summary(dimension="session", session_id="sesn-test") + if asynchronous: + summary = await summary + assert summary["request_id"] == "req-usage" + page = usage.trend(**query) + if asynchronous: + page = await page + result = usage.trend( + **query, + page_token=page["data"]["next_page_token"], + ) + if asynchronous: + await result + assert requests[0].url.path == "/api/v1/agentstudio/usage/summary" + assert json.loads(requests[0].content) == { + "dimension": "session", + "session_id": "sesn-test", + } + assert requests[2].url.path == "/api/v1/agentstudio/usage/trend" + assert json.loads(requests[2].content) == dict( + query, + page_token="opaque-cursor", + ) + assert client.agentstudio.transport._client is pool + finally: + if asynchronous: + await client.aclose() + assert not pool.is_closed + await pool.aclose() + else: + client.close() + assert not pool.is_closed + pool.close() + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize( + "failure", + [None, httpx.ConnectError, httpx.ReadTimeout], +) +@pytest.mark.asyncio +async def test_transport_preserves_absolute_url_and_error_request_id( + asynchronous, + stream, + failure, +): + from dashscope.applications.agentstudio import Client as StudioClient + from dashscope.applications.agentstudio import ( + AsyncClient as AsyncStudioClient, + ) + from dashscope.errors import APIConnectionError, APITimeoutError + + requests = [] + + def handler(request): + requests.append(request) + if failure: + raise failure("network probe", request=request) + return httpx.Response(200, json={"id": "ok"}) + + http_class = httpx.AsyncClient if asynchronous else httpx.Client + client_class = AsyncStudioClient if asynchronous else StudioClient + pool = http_class(transport=httpx.MockTransport(handler)) + client = client_class( + api_key="sk-test", + base_url="https://example.test/api/v1/agentstudio", + http_client=pool, + max_retries=0, + ) + target = "https://example.test/absolute/path?cursor=a%2Fb" + try: + if failure: + error_class = ( + APITimeoutError + if failure is httpx.ReadTimeout + else APIConnectionError + ) + with pytest.raises(error_class) as caught: + result = client.transport.request("GET", target, stream=stream) + if asynchronous: + await result + assert caught.value.request_id + assert caught.value.request_id == caught.value.__cause__.request_id + else: + result = client.transport.request("GET", target, stream=stream) + if asynchronous: + result = await result + if stream: + if asynchronous: + await result.aclose() + else: + result.close() + else: + assert result.data == {"id": "ok"} + assert str(requests[0].url) == target + finally: + if asynchronous: + await client.aclose() + await pool.aclose() + else: + client.close() + pool.close()