aiutils-sdk 0.1.2__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aiutils-sdk
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: Python SDK for the AiUtils Developer API — 100+ AI models via one unified API
5
5
  Author-email: AiUtils Team <dev@aiutils.io>
6
6
  License-Expression: MIT
@@ -1,13 +1,15 @@
1
1
  """AiUtils Python SDK — 100+ AI models, one unified API."""
2
2
  from aiutils_sdk.client import AiUtils
3
+ from aiutils_sdk.chat import ChatResponse, ChatStreamChunk
3
4
  from aiutils_sdk.exceptions import (
4
5
  AiUtilsError, AuthenticationError, InsufficientDTError,
5
6
  RateLimitError, APIError, ProviderError,
6
7
  )
7
8
 
8
- __version__ = "0.1.2"
9
+ __version__ = "0.2.0"
9
10
  __all__ = [
10
11
  "AiUtils",
12
+ "ChatResponse", "ChatStreamChunk",
11
13
  "AiUtilsError", "AuthenticationError", "InsufficientDTError",
12
14
  "RateLimitError", "APIError", "ProviderError",
13
15
  ]
@@ -0,0 +1,146 @@
1
+ """Chat completions resource — OpenAI-compatible."""
2
+ from __future__ import annotations
3
+
4
+ import json as _json
5
+ import logging
6
+ from typing import AsyncGenerator, Optional
7
+
8
+ from pydantic import BaseModel
9
+
10
+ from aiutils_sdk.exceptions import APIError
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class ChatMessage(BaseModel):
16
+ role: str
17
+ content: str
18
+
19
+
20
+ class Choice(BaseModel):
21
+ index: int
22
+ message: ChatMessage
23
+ finish_reason: Optional[str] = "stop"
24
+
25
+
26
+ class Usage(BaseModel):
27
+ prompt_tokens: int
28
+ completion_tokens: int
29
+ total_tokens: int
30
+ dt_consumed: int = 0
31
+
32
+
33
+ class ChatResponse(BaseModel):
34
+ id: str
35
+ object: str
36
+ created: int
37
+ model: str
38
+ provider: str = "unknown"
39
+ usage: Usage
40
+ choices: list[Choice]
41
+
42
+
43
+ class ChatStreamChunk(BaseModel):
44
+ """A single chunk from a streaming chat completion."""
45
+ id: str
46
+ object: str
47
+ created: int
48
+ model: str
49
+ choices: list[dict]
50
+
51
+
52
+ class Chat:
53
+ """Chat completions namespace."""
54
+
55
+ def __init__(self, client):
56
+ self._client = client
57
+ self.completions = ChatCompletions(client)
58
+
59
+
60
+ class ChatCompletions:
61
+ """OpenAI-compatible chat completions."""
62
+
63
+ def __init__(self, client):
64
+ self._client = client
65
+
66
+ def create(
67
+ self,
68
+ model: str,
69
+ messages: list[dict],
70
+ temperature: float = 0.7,
71
+ max_tokens: int = 500,
72
+ stream: bool = False,
73
+ top_p: float = 1.0,
74
+ **kwargs,
75
+ ) -> ChatResponse:
76
+ """Create a chat completion."""
77
+ logger.debug(f"Entered into ChatCompletions.create: model={model}")
78
+ body = {
79
+ "model": model,
80
+ "messages": messages,
81
+ "temperature": temperature,
82
+ "max_tokens": max_tokens,
83
+ "stream": stream,
84
+ "top_p": top_p,
85
+ **kwargs,
86
+ }
87
+ data = self._client._request("POST", "/v1/chat/completions", json=body)
88
+ return ChatResponse(**data)
89
+
90
+ async def create_stream(
91
+ self,
92
+ model: str,
93
+ messages: list[dict],
94
+ temperature: float = 0.7,
95
+ max_tokens: int = 500,
96
+ top_p: float = 1.0,
97
+ **kwargs,
98
+ ) -> AsyncGenerator[ChatStreamChunk, None]:
99
+ """Stream a chat completion via SSE (Server-Sent Events).
100
+
101
+ Yields parsed ChatStreamChunk objects as they arrive.
102
+ Uses /v1/chat/completions/stream under the hood.
103
+
104
+ Usage:
105
+ async for chunk in client.chat.completions.create_stream(
106
+ model="openai/gpt-4o",
107
+ messages=[{"role": "user", "content": "Tell me a story"}],
108
+ ):
109
+ content = chunk.choices[0].get("delta", {}).get("content", "")
110
+ print(content, end="", flush=True)
111
+ """
112
+ logger.debug(f"Entered into ChatCompletions.create_stream: model={model}")
113
+ import httpx
114
+ body = {
115
+ "model": model,
116
+ "messages": messages,
117
+ "temperature": temperature,
118
+ "max_tokens": max_tokens,
119
+ "stream": True,
120
+ "top_p": top_p,
121
+ **kwargs,
122
+ }
123
+ headers = dict(self._client._headers)
124
+ headers["Accept"] = "text/event-stream"
125
+ url = f"{self._client.base_url}/v1/chat/completions/stream"
126
+
127
+ async with httpx.AsyncClient(timeout=httpx.Timeout(120.0, connect=10.0)) as http_client:
128
+ async with http_client.stream("POST", url, json=body, headers=headers) as response:
129
+ if response.status_code != 200:
130
+ text = await response.aread()
131
+ self._client._handle_response(response)
132
+ raise APIError(text.decode("utf-8", errors="replace")[:500], status_code=response.status_code)
133
+
134
+ async for line in response.aiter_lines():
135
+ if not line or line.startswith(":"):
136
+ continue
137
+ if line.startswith("data: "):
138
+ data_str = line[6:]
139
+ if data_str == "[DONE]":
140
+ break
141
+ try:
142
+ data = _json.loads(data_str)
143
+ yield ChatStreamChunk(**data)
144
+ except Exception:
145
+ logger.debug(f"Skipping unparseable SSE line: {line[:100]}")
146
+ continue
@@ -28,15 +28,7 @@ class EmbeddingResponse(BaseModel):
28
28
 
29
29
 
30
30
  class Embeddings:
31
- """Embeddings namespace."""
32
-
33
- def __init__(self, client):
34
- self._client = client
35
- self.create = EmbeddingCreate(client)
36
-
37
-
38
- class EmbeddingCreate:
39
- """Create embeddings from text."""
31
+ """Embeddings namespace — vector embeddings."""
40
32
 
41
33
  def __init__(self, client):
42
34
  self._client = client
@@ -48,8 +40,11 @@ class EmbeddingCreate:
48
40
  encoding_format: str = "float",
49
41
  **kwargs,
50
42
  ) -> EmbeddingResponse:
51
- """Create an embedding vector for the given input."""
52
- logger.debug(f"Entered into EmbeddingCreate.create: model={model}")
43
+ """Create an embedding vector for the given input.
44
+
45
+ Usage: client.embeddings.create(model="text-embedding-3-small", input="Hello")
46
+ """
47
+ logger.debug(f"Entered into Embeddings.create: model={model}")
53
48
  body = {
54
49
  "model": model,
55
50
  "input": input,
@@ -1,9 +1,10 @@
1
1
  """Universal generation resource — image, video, audio, 3D models."""
2
2
  from __future__ import annotations
3
3
 
4
+ import json as _json
4
5
  import logging
5
6
  import time
6
- from typing import Optional
7
+ from typing import AsyncGenerator, Optional
7
8
 
8
9
  from pydantic import BaseModel
9
10
 
@@ -79,3 +80,44 @@ class Generations:
79
80
  logger.debug(f"Entered into Generations.get: id={generation_id}")
80
81
  data = self._client._request("GET", f"/v1/generations/{generation_id}")
81
82
  return GenerationResponse(**data)
83
+
84
+ async def stream(self, generation_id: str) -> AsyncGenerator[dict, None]:
85
+ """Stream generation progress via SSE. No polling needed.
86
+
87
+ Yields parsed status dicts as they arrive. The server pushes
88
+ progress updates every 3 seconds until the generation completes,
89
+ fails, or times out (5 min max).
90
+
91
+ Status values: 'processing', 'completed', 'failed', 'timeout', 'error'.
92
+
93
+ Usage:
94
+ async for event in client.generations.stream(gen_id):
95
+ print(event['status'], event.get('elapsed_s'))
96
+ if event['status'] != 'processing':
97
+ break
98
+ """
99
+ logger.debug(f"Entered into Generations.stream: id={generation_id}")
100
+ import httpx
101
+ headers = dict(self._client._headers)
102
+ headers["Accept"] = "text/event-stream"
103
+ url = f"{self._client.base_url}/v1/generations/{generation_id}/stream"
104
+
105
+ async with httpx.AsyncClient(timeout=httpx.Timeout(310.0, connect=10.0)) as http_client:
106
+ async with http_client.stream("GET", url, headers=headers) as response:
107
+ if response.status_code != 200:
108
+ text = await response.aread()
109
+ self._client._handle_response(response)
110
+ from aiutils_sdk.exceptions import APIError
111
+ raise APIError(text.decode("utf-8", errors="replace")[:500], status_code=response.status_code)
112
+
113
+ async for line in response.aiter_lines():
114
+ if not line or line.startswith(":"):
115
+ continue
116
+ if line.startswith("data: "):
117
+ data_str = line[6:]
118
+ if data_str == "[DONE]":
119
+ return
120
+ try:
121
+ yield _json.loads(data_str)
122
+ except Exception:
123
+ continue
@@ -19,15 +19,7 @@ class ImageResponse(BaseModel):
19
19
 
20
20
 
21
21
  class Images:
22
- """Images namespace."""
23
-
24
- def __init__(self, client):
25
- self._client = client
26
- self.generate = ImageGenerate(client)
27
-
28
-
29
- class ImageGenerate:
30
- """Image generation endpoint."""
22
+ """Images namespace — image generation."""
31
23
 
32
24
  def __init__(self, client):
33
25
  self._client = client
@@ -40,8 +32,11 @@ class ImageGenerate:
40
32
  size: str = "1024x1024",
41
33
  **kwargs,
42
34
  ) -> ImageResponse:
43
- """Generate images from a prompt."""
44
- logger.debug(f"Entered into ImageGenerate.generate: model={model}")
35
+ """Generate images from a prompt.
36
+
37
+ Usage: client.images.generate(model="dall-e-3", prompt="...")
38
+ """
39
+ logger.debug(f"Entered into Images.generate: model={model}")
45
40
  body = {"model": model, "prompt": prompt, "n": n, "size": size, **kwargs}
46
41
  data = self._client._request("POST", "/v1/images/generations", json=body)
47
42
  return ImageResponse(**data)
@@ -84,3 +84,13 @@ class Models:
84
84
  """Get detailed information about a specific model."""
85
85
  logger.debug(f"Entered into Models.get: id={model_id}")
86
86
  return self._client._request("GET", f"/v1/models/{model_id}")
87
+
88
+ def pricing(
89
+ self,
90
+ model_id: str,
91
+ parameters: Optional[dict] = None,
92
+ ) -> dict:
93
+ """Estimate DT cost for a model request before running it."""
94
+ logger.debug(f"Entered into Models.pricing: model_id={model_id}")
95
+ body = {"model": model_id, "parameters": parameters or {}}
96
+ return self._client._request("POST", "/v1/pricing/estimate", json=body)
@@ -58,17 +58,40 @@ class Wallet:
58
58
  self,
59
59
  limit: int = 20,
60
60
  after: Optional[str] = None,
61
+ auto_paginate: bool = False,
61
62
  ) -> TransactionList:
62
- """Get transaction history (paginated via cursor)."""
63
- logger.debug(f"Entered into Wallet.transactions: limit={limit}")
64
- params: dict = {"limit": limit}
65
- if after:
66
- params["after"] = after
67
- data = self._client._request("GET", "/v1/wallet/transactions", params=params)
68
- return TransactionList(
69
- transactions=[Transaction(**t) for t in data.get("transactions", [])],
70
- has_more=data.get("has_more", False),
71
- )
63
+ """Get transaction history (paginated via cursor).
64
+
65
+ Args:
66
+ limit: Max items per page (default 20, max 100).
67
+ after: Cursor for keyset pagination (ISO8601 created_at of last item).
68
+ auto_paginate: If True, automatically fetch all pages and return
69
+ the complete list. Uses the cursor from each page.
70
+ """
71
+ logger.debug(f"Entered into Wallet.transactions: limit={limit}, auto_paginate={auto_paginate}")
72
+ if not auto_paginate:
73
+ params: dict = {"limit": limit}
74
+ if after:
75
+ params["after"] = after
76
+ data = self._client._request("GET", "/v1/wallet/transactions", params=params)
77
+ return TransactionList(
78
+ transactions=[Transaction(**t) for t in data.get("transactions", [])],
79
+ has_more=data.get("has_more", False),
80
+ )
81
+
82
+ all_txns: list[Transaction] = []
83
+ cursor: Optional[str] = after
84
+ while True:
85
+ params: dict = {"limit": min(limit, 100)}
86
+ if cursor:
87
+ params["after"] = cursor
88
+ data = self._client._request("GET", "/v1/wallet/transactions", params=params)
89
+ page = [Transaction(**t) for t in data.get("transactions", [])]
90
+ all_txns.extend(page)
91
+ if not data.get("has_more", False) or not page:
92
+ break
93
+ cursor = page[-1].created_at
94
+ return TransactionList(transactions=all_txns, has_more=False)
72
95
 
73
96
  def estimate_cost(
74
97
  self,
@@ -72,14 +72,41 @@ class Webhooks:
72
72
  logger.debug("Entered into Webhooks.delete_config")
73
73
  return self._client._request("DELETE", "/v1/webhooks/config")
74
74
 
75
- def list_deliveries(self, limit: int = 20, after: Optional[str] = None) -> WebhookDeliveryList:
76
- """List recent webhook delivery attempts (for debugging)."""
77
- logger.debug(f"Entered into Webhooks.list_deliveries: limit={limit}")
78
- params: dict = {"limit": limit}
79
- if after:
80
- params["after"] = after
81
- data = self._client._request("GET", "/v1/webhooks/deliveries", params=params)
82
- return WebhookDeliveryList(
83
- deliveries=[WebhookDelivery(**d) for d in data.get("deliveries", [])],
84
- has_more=data.get("has_more", False),
85
- )
75
+ def list_deliveries(
76
+ self,
77
+ limit: int = 20,
78
+ after: Optional[str] = None,
79
+ auto_paginate: bool = False,
80
+ ) -> WebhookDeliveryList:
81
+ """List recent webhook delivery attempts (for debugging).
82
+
83
+ Args:
84
+ limit: Max items per page (default 20, max 100).
85
+ after: Cursor for keyset pagination (ISO8601 created_at of last item).
86
+ auto_paginate: If True, automatically fetch all pages and return
87
+ the complete list.
88
+ """
89
+ logger.debug(f"Entered into Webhooks.list_deliveries: limit={limit}, auto_paginate={auto_paginate}")
90
+ if not auto_paginate:
91
+ params: dict = {"limit": limit}
92
+ if after:
93
+ params["after"] = after
94
+ data = self._client._request("GET", "/v1/webhooks/deliveries", params=params)
95
+ return WebhookDeliveryList(
96
+ deliveries=[WebhookDelivery(**d) for d in data.get("deliveries", [])],
97
+ has_more=data.get("has_more", False),
98
+ )
99
+
100
+ all_deliveries: list[WebhookDelivery] = []
101
+ cursor: Optional[str] = after
102
+ while True:
103
+ params: dict = {"limit": min(limit, 100)}
104
+ if cursor:
105
+ params["after"] = cursor
106
+ data = self._client._request("GET", "/v1/webhooks/deliveries", params=params)
107
+ page = [WebhookDelivery(**d) for d in data.get("deliveries", [])]
108
+ all_deliveries.extend(page)
109
+ if not data.get("has_more", False) or not page:
110
+ break
111
+ cursor = page[-1].created_at
112
+ return WebhookDeliveryList(deliveries=all_deliveries, has_more=False)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aiutils-sdk
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: Python SDK for the AiUtils Developer API — 100+ AI models via one unified API
5
5
  Author-email: AiUtils Team <dev@aiutils.io>
6
6
  License-Expression: MIT
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aiutils-sdk"
3
- version = "0.1.2"
3
+ version = "0.2.0"
4
4
  description = "Python SDK for the AiUtils Developer API — 100+ AI models via one unified API"
5
5
  requires-python = ">=3.9"
6
6
  dependencies = [
@@ -1,76 +0,0 @@
1
- """Chat completions resource — OpenAI-compatible."""
2
- from __future__ import annotations
3
-
4
- import logging
5
- from typing import Optional
6
-
7
- from pydantic import BaseModel
8
-
9
- logger = logging.getLogger(__name__)
10
-
11
-
12
- class ChatMessage(BaseModel):
13
- role: str
14
- content: str
15
-
16
-
17
- class Choice(BaseModel):
18
- index: int
19
- message: ChatMessage
20
- finish_reason: Optional[str] = "stop"
21
-
22
-
23
- class Usage(BaseModel):
24
- prompt_tokens: int
25
- completion_tokens: int
26
- total_tokens: int
27
- dt_consumed: int = 0
28
-
29
-
30
- class ChatResponse(BaseModel):
31
- id: str
32
- object: str
33
- created: int
34
- model: str
35
- provider: str = "unknown"
36
- usage: Usage
37
- choices: list[Choice]
38
-
39
-
40
- class Chat:
41
- """Chat completions namespace."""
42
-
43
- def __init__(self, client):
44
- self._client = client
45
- self.completions = ChatCompletions(client)
46
-
47
-
48
- class ChatCompletions:
49
- """OpenAI-compatible chat completions."""
50
-
51
- def __init__(self, client):
52
- self._client = client
53
-
54
- def create(
55
- self,
56
- model: str,
57
- messages: list[dict],
58
- temperature: float = 0.7,
59
- max_tokens: int = 500,
60
- stream: bool = False,
61
- top_p: float = 1.0,
62
- **kwargs,
63
- ) -> ChatResponse:
64
- """Create a chat completion."""
65
- logger.debug(f"Entered into ChatCompletions.create: model={model}")
66
- body = {
67
- "model": model,
68
- "messages": messages,
69
- "temperature": temperature,
70
- "max_tokens": max_tokens,
71
- "stream": stream,
72
- "top_p": top_p,
73
- **kwargs,
74
- }
75
- data = self._client._request("POST", "/v1/chat/completions", json=body)
76
- return ChatResponse(**data)
File without changes
File without changes