sference-sdk 0.3.0__tar.gz → 0.3.2__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.5
2
2
  Name: sference-sdk
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: Python SDK for the sference batch API
5
5
  Project-URL: Homepage, https://sference.com
6
6
  Project-URL: Repository, https://github.com/s-ference/sference
@@ -129,6 +129,40 @@ row = client.get_response(created.id)
129
129
 
130
130
  For a stream, add `stream_id` inside `metadata` next to `completion_window`.
131
131
 
132
+ ### Decisions (realtime classification)
133
+
134
+ `POST /v1/decisions` answers up to 64 questions about one `state` (text or any JSON value) in a single call. Pick a model with `modality == "decisions"` from `list_models()`. Question types: `choice` (pick one label), `score` (ordinal scale, index 0 = lowest) and `noul` (probability of true). Billed on input tokens only, including image tokens.
135
+
136
+ Both clients accept `images=["data:image/png;base64,..."]` or
137
+ `images=[{"content_type": "image/jpeg", "base64": "..."}]` (also available as
138
+ `sference_sdk.DecisionImage`). Images precede the state in array order and travel
139
+ inline without separate uploads. Clef accepts up to 4 PNG/JPEG/WebP images,
140
+ 4 MiB and 16 megapixels each, 8 MiB total decoded bytes, with a 13 MiB request
141
+ body limit. Remote URLs are not accepted. Accepted images are EXIF-oriented and
142
+ downscaled to at most 2,097,152 pixels before inference; usage counts the resulting
143
+ image tokens. The 16-megapixel limit applies to the original uploaded image.
144
+
145
+ ```python
146
+ from sference_sdk import ChoiceQuestion, NoulQuestion, ScoreQuestion, SferenceClient
147
+
148
+ client = SferenceClient(api_key="sk_...")
149
+
150
+ decision = client.create_decision(
151
+ model="Cloudflare/clef",
152
+ state="I was charged twice this month, please refund me.",
153
+ questions={
154
+ "route": ChoiceQuestion(criteria={"billing": "Payments and invoices", "support": "Everything else"}),
155
+ "urgency": ScoreQuestion(criteria=["Low", "Medium", "High"]),
156
+ "refund": NoulQuestion(instructions="Does the customer ask for a refund?"),
157
+ },
158
+ )
159
+ decision.answers["route"].choice # "billing"
160
+ decision.answers["urgency"].score # 0..2, expected value over the scale
161
+ decision.answers["refund"].noul # probability of true
162
+ ```
163
+
164
+ Questions may also be plain dicts (`{"type": "noul"}`). `429` means no decision capacity right now and is safe to retry; `504` means the deadline passed and nothing was charged.
165
+
132
166
  ### OpenAI Python SDK (`openai` package)
133
167
 
134
168
  If you already use the official OpenAI client, point it at sference’s **`/v1`** endpoint and the same API key (with `responses:read` and `responses:write`).
@@ -102,6 +102,40 @@ row = client.get_response(created.id)
102
102
 
103
103
  For a stream, add `stream_id` inside `metadata` next to `completion_window`.
104
104
 
105
+ ### Decisions (realtime classification)
106
+
107
+ `POST /v1/decisions` answers up to 64 questions about one `state` (text or any JSON value) in a single call. Pick a model with `modality == "decisions"` from `list_models()`. Question types: `choice` (pick one label), `score` (ordinal scale, index 0 = lowest) and `noul` (probability of true). Billed on input tokens only, including image tokens.
108
+
109
+ Both clients accept `images=["data:image/png;base64,..."]` or
110
+ `images=[{"content_type": "image/jpeg", "base64": "..."}]` (also available as
111
+ `sference_sdk.DecisionImage`). Images precede the state in array order and travel
112
+ inline without separate uploads. Clef accepts up to 4 PNG/JPEG/WebP images,
113
+ 4 MiB and 16 megapixels each, 8 MiB total decoded bytes, with a 13 MiB request
114
+ body limit. Remote URLs are not accepted. Accepted images are EXIF-oriented and
115
+ downscaled to at most 2,097,152 pixels before inference; usage counts the resulting
116
+ image tokens. The 16-megapixel limit applies to the original uploaded image.
117
+
118
+ ```python
119
+ from sference_sdk import ChoiceQuestion, NoulQuestion, ScoreQuestion, SferenceClient
120
+
121
+ client = SferenceClient(api_key="sk_...")
122
+
123
+ decision = client.create_decision(
124
+ model="Cloudflare/clef",
125
+ state="I was charged twice this month, please refund me.",
126
+ questions={
127
+ "route": ChoiceQuestion(criteria={"billing": "Payments and invoices", "support": "Everything else"}),
128
+ "urgency": ScoreQuestion(criteria=["Low", "Medium", "High"]),
129
+ "refund": NoulQuestion(instructions="Does the customer ask for a refund?"),
130
+ },
131
+ )
132
+ decision.answers["route"].choice # "billing"
133
+ decision.answers["urgency"].score # 0..2, expected value over the scale
134
+ decision.answers["refund"].noul # probability of true
135
+ ```
136
+
137
+ Questions may also be plain dicts (`{"type": "noul"}`). `429` means no decision capacity right now and is safe to retry; `504` means the deadline passed and nothing was charged.
138
+
105
139
  ### OpenAI Python SDK (`openai` package)
106
140
 
107
141
  If you already use the official OpenAI client, point it at sference’s **`/v1`** endpoint and the same API key (with `responses:read` and `responses:write`).
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sference-sdk"
3
- version = "0.3.0"
3
+ version = "0.3.2"
4
4
  description = "Python SDK for the sference batch API"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -20,9 +20,17 @@ from .models import (
20
20
  BatchList,
21
21
  BatchResultRow,
22
22
  BatchResults,
23
+ ChoiceAnswer,
24
+ ChoiceQuestion,
23
25
  CompletionWindow,
26
+ DecisionImage,
27
+ DecisionResponse,
24
28
  InferenceRequest,
25
29
  LoginResponse,
30
+ NoulAnswer,
31
+ NoulQuestion,
32
+ ScoreAnswer,
33
+ ScoreQuestion,
26
34
  Stream,
27
35
  StreamInferenceCompletionEvent,
28
36
  StreamEventList,
@@ -38,10 +46,18 @@ __all__ = [
38
46
  "BatchList",
39
47
  "BatchResultRow",
40
48
  "BatchResults",
49
+ "ChoiceAnswer",
50
+ "ChoiceQuestion",
51
+ "DecisionResponse",
52
+ "DecisionImage",
41
53
  "COMPLETION_WINDOWS",
42
54
  "CompletionWindow",
43
55
  "LoginResponse",
44
56
  "InferenceRequest",
57
+ "NoulAnswer",
58
+ "NoulQuestion",
59
+ "ScoreAnswer",
60
+ "ScoreQuestion",
45
61
  "Stream",
46
62
  "StreamInferenceCompletionEvent",
47
63
  "StreamEventList",
@@ -6,7 +6,7 @@ import os
6
6
  import time
7
7
  import warnings
8
8
  from pathlib import Path
9
- from collections.abc import Mapping
9
+ from collections.abc import Mapping, Sequence
10
10
  from typing import Any, AsyncIterator, BinaryIO
11
11
 
12
12
  import httpx
@@ -20,7 +20,11 @@ from .models import (
20
20
  BatchList,
21
21
  BatchResultRow,
22
22
  BatchResults,
23
+ CreateDecisionPayload,
23
24
  CreateEmbeddingPayload,
25
+ DecisionQuestion,
26
+ DecisionImage,
27
+ DecisionResponse,
24
28
  EmbeddingInput,
25
29
  EmbeddingEncodingFormat,
26
30
  EmbeddingResponse,
@@ -129,6 +133,27 @@ class AsyncSferenceClient:
129
133
  response = await self._request("POST", "/v1/embeddings", payload.model_dump(exclude_none=True))
130
134
  return EmbeddingResponse.model_validate(response)
131
135
 
136
+ async def create_decision(
137
+ self,
138
+ *,
139
+ model: str,
140
+ state: Any,
141
+ questions: Mapping[str, DecisionQuestion | Mapping[str, Any]],
142
+ images: Sequence[str | DecisionImage | Mapping[str, Any]] | None = None,
143
+ ) -> DecisionResponse:
144
+ """Answer up to 64 questions about ``state`` in one realtime call (POST /v1/decisions).
145
+
146
+ ``state`` is any JSON value (text or an object). Questions may be model
147
+ instances or plain dicts with a ``type`` of ``choice``, ``score`` or ``noul``.
148
+ ``images`` accepts up to four PNG/JPEG/WebP data URLs or objects with
149
+ ``content_type`` and ``base64``. Limits: 4 MiB/16 MP each, 8 MiB total.
150
+ """
151
+ payload = CreateDecisionPayload.model_validate(
152
+ {"model": model, "state": state, "questions": dict(questions), "images": list(images) if images is not None else []}
153
+ )
154
+ response = await self._request("POST", "/v1/decisions", payload.model_dump(mode="json", exclude={"images"} if images is None else set()))
155
+ return DecisionResponse.model_validate(response)
156
+
132
157
  async def submit_batch(
133
158
  self,
134
159
  *,
@@ -6,7 +6,7 @@ import os
6
6
  import time
7
7
  import warnings
8
8
  from contextlib import contextmanager
9
- from collections.abc import Iterator, Mapping
9
+ from collections.abc import Iterator, Mapping, Sequence
10
10
  from pathlib import Path
11
11
  from typing import Any, BinaryIO
12
12
 
@@ -20,7 +20,11 @@ from .models import (
20
20
  BatchList,
21
21
  BatchResultRow,
22
22
  BatchResults,
23
+ CreateDecisionPayload,
23
24
  CreateEmbeddingPayload,
25
+ DecisionQuestion,
26
+ DecisionImage,
27
+ DecisionResponse,
24
28
  EmbeddingInput,
25
29
  EmbeddingEncodingFormat,
26
30
  EmbeddingResponse,
@@ -185,6 +189,27 @@ class SferenceClient:
185
189
  response = self._request("POST", "/v1/embeddings", payload.model_dump(exclude_none=True))
186
190
  return EmbeddingResponse.model_validate(response)
187
191
 
192
+ def create_decision(
193
+ self,
194
+ *,
195
+ model: str,
196
+ state: Any,
197
+ questions: Mapping[str, DecisionQuestion | Mapping[str, Any]],
198
+ images: Sequence[str | DecisionImage | Mapping[str, Any]] | None = None,
199
+ ) -> DecisionResponse:
200
+ """Answer up to 64 questions about ``state`` in one realtime call (POST /v1/decisions).
201
+
202
+ ``state`` is any JSON value (text or an object). Questions may be model
203
+ instances or plain dicts with a ``type`` of ``choice``, ``score`` or ``noul``.
204
+ ``images`` accepts up to four PNG/JPEG/WebP data URLs or objects with
205
+ ``content_type`` and ``base64``. Limits: 4 MiB/16 MP each, 8 MiB total.
206
+ """
207
+ payload = CreateDecisionPayload.model_validate(
208
+ {"model": model, "state": state, "questions": dict(questions), "images": list(images) if images is not None else []}
209
+ )
210
+ response = self._request("POST", "/v1/decisions", payload.model_dump(mode="json", exclude={"images"} if images is None else set()))
211
+ return DecisionResponse.model_validate(response)
212
+
188
213
  def submit_batch(
189
214
  self,
190
215
  *,
@@ -352,3 +352,89 @@ class CreateEmbeddingPayload(BaseModel):
352
352
  encoding_format: EmbeddingEncodingFormat = "float"
353
353
  dimensions: int | None = None
354
354
  user: str | None = None
355
+
356
+
357
+ # Decisions (POST /v1/decisions): classify one ``state`` against up to 64 questions.
358
+ class ChoiceQuestion(BaseModel):
359
+ """Pick one of ``criteria`` (label -> description)."""
360
+
361
+ model_config = ConfigDict(extra="forbid")
362
+
363
+ type: Literal["choice"] = "choice"
364
+ instructions: Any = ""
365
+ criteria: dict[str, Any]
366
+
367
+
368
+ class ScoreQuestion(BaseModel):
369
+ """Rate on the ordinal scale ``criteria`` (index 0 = lowest)."""
370
+
371
+ model_config = ConfigDict(extra="forbid")
372
+
373
+ type: Literal["score"] = "score"
374
+ instructions: Any = ""
375
+ criteria: list[Any]
376
+
377
+
378
+ class NoulQuestion(BaseModel):
379
+ """Yes/no probability; ``criteria`` may describe the ``"true"``/``"false"`` cases."""
380
+
381
+ model_config = ConfigDict(extra="forbid")
382
+
383
+ type: Literal["noul"] = "noul"
384
+ instructions: Any = ""
385
+ criteria: dict[Literal["true", "false"], Any] | None = None
386
+
387
+
388
+ DecisionQuestion = Annotated[ChoiceQuestion | ScoreQuestion | NoulQuestion, Field(discriminator="type")]
389
+
390
+
391
+ class DecisionImage(BaseModel):
392
+ """Embedded PNG, JPEG, or WebP. Image bytes are base64-encoded, never uploaded separately."""
393
+
394
+ model_config = ConfigDict(extra="forbid")
395
+
396
+ content_type: Literal["image/png", "image/jpeg", "image/webp"]
397
+ base64: str
398
+
399
+
400
+ class CreateDecisionPayload(BaseModel):
401
+ model_config = ConfigDict(extra="forbid")
402
+
403
+ model: str
404
+ state: Any
405
+ questions: dict[str, DecisionQuestion]
406
+ images: list[str | DecisionImage] = Field(default_factory=list, max_length=4)
407
+
408
+
409
+ class ChoiceAnswer(BaseModel):
410
+ type: Literal["choice"] = "choice"
411
+ choice: str
412
+ confidence: float
413
+ probabilities: dict[str, float]
414
+
415
+
416
+ class ScoreAnswer(BaseModel):
417
+ type: Literal["score"] = "score"
418
+ score: float
419
+ confidence: float
420
+ legend: dict[str, Any]
421
+ probabilities: dict[str, float]
422
+
423
+
424
+ class NoulAnswer(BaseModel):
425
+ type: Literal["noul"] = "noul"
426
+ noul: float
427
+
428
+
429
+ DecisionAnswer = Annotated[ChoiceAnswer | ScoreAnswer | NoulAnswer, Field(discriminator="type")]
430
+
431
+
432
+ class DecisionUsage(BaseModel):
433
+ input_tokens: int
434
+ output_tokens: int = 0
435
+
436
+
437
+ class DecisionResponse(BaseModel):
438
+ model: str
439
+ answers: dict[str, DecisionAnswer]
440
+ usage: DecisionUsage
File without changes
File without changes