everstack 0.1.0__py3-none-any.whl
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.
- everstack/__init__.py +122 -0
- everstack/_client.py +167 -0
- everstack/_errors.py +136 -0
- everstack/_transport.py +254 -0
- everstack/_types.py +305 -0
- everstack/_version.py +1 -0
- everstack/generated/__init__.py +1 -0
- everstack/generated/models.py +2851 -0
- everstack/py.typed +0 -0
- everstack/resources/__init__.py +1 -0
- everstack/resources/agents.py +489 -0
- everstack/resources/audio.py +156 -0
- everstack/resources/chat.py +160 -0
- everstack/resources/datasets.py +114 -0
- everstack/resources/embeddings.py +70 -0
- everstack/resources/evaluations.py +99 -0
- everstack/resources/images.py +120 -0
- everstack/resources/models.py +30 -0
- everstack/resources/moderations.py +53 -0
- everstack/resources/observability.py +105 -0
- everstack/resources/rerank.py +69 -0
- everstack/resources/responses.py +153 -0
- everstack-0.1.0.dist-info/METADATA +52 -0
- everstack-0.1.0.dist-info/RECORD +25 -0
- everstack-0.1.0.dist-info/WHEEL +4 -0
everstack/__init__.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Everstack — The official Python SDK for the Everstack AI platform."""
|
|
2
|
+
|
|
3
|
+
from ._version import __version__
|
|
4
|
+
from ._client import Everstack, AsyncEverstack
|
|
5
|
+
from ._errors import (
|
|
6
|
+
EverstackError,
|
|
7
|
+
APIError,
|
|
8
|
+
AuthenticationError,
|
|
9
|
+
PermissionDeniedError,
|
|
10
|
+
NotFoundError,
|
|
11
|
+
RateLimitError,
|
|
12
|
+
InternalServerError,
|
|
13
|
+
ServiceUnavailableError,
|
|
14
|
+
TimeoutError,
|
|
15
|
+
ConnectionError,
|
|
16
|
+
InvalidModelError,
|
|
17
|
+
)
|
|
18
|
+
from ._types import (
|
|
19
|
+
# Chat
|
|
20
|
+
ChatMessage,
|
|
21
|
+
Usage,
|
|
22
|
+
FallbackInfo,
|
|
23
|
+
ChoiceMessage,
|
|
24
|
+
Choice,
|
|
25
|
+
ChatCompletionResponse,
|
|
26
|
+
DeltaMessage,
|
|
27
|
+
ChunkChoice,
|
|
28
|
+
ChatCompletionChunk,
|
|
29
|
+
# Embeddings
|
|
30
|
+
EmbeddingData,
|
|
31
|
+
EmbeddingsUsage,
|
|
32
|
+
EmbeddingsResponse,
|
|
33
|
+
# Models
|
|
34
|
+
Model,
|
|
35
|
+
ModelsListResponse,
|
|
36
|
+
# Audio
|
|
37
|
+
TranscriptionWord,
|
|
38
|
+
TranscriptionSegment,
|
|
39
|
+
TranscriptionResponse,
|
|
40
|
+
TranslationResponse,
|
|
41
|
+
SpeechResponse,
|
|
42
|
+
# Images
|
|
43
|
+
ImageData,
|
|
44
|
+
ImageUsage,
|
|
45
|
+
ImageResponse,
|
|
46
|
+
# Moderations
|
|
47
|
+
ModerationCategories,
|
|
48
|
+
ModerationCategoryScores,
|
|
49
|
+
ModerationResult,
|
|
50
|
+
ModerationResponse,
|
|
51
|
+
# Rerank
|
|
52
|
+
RerankResult,
|
|
53
|
+
RerankMeta,
|
|
54
|
+
RerankResponse,
|
|
55
|
+
# Responses API
|
|
56
|
+
ResponseOutputItem,
|
|
57
|
+
ResponseUsage,
|
|
58
|
+
ResponseObject,
|
|
59
|
+
DeleteResponseResult,
|
|
60
|
+
ListResponsesResult,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
__all__ = [
|
|
64
|
+
"__version__",
|
|
65
|
+
# Clients
|
|
66
|
+
"Everstack",
|
|
67
|
+
"AsyncEverstack",
|
|
68
|
+
# Errors
|
|
69
|
+
"EverstackError",
|
|
70
|
+
"APIError",
|
|
71
|
+
"AuthenticationError",
|
|
72
|
+
"PermissionDeniedError",
|
|
73
|
+
"NotFoundError",
|
|
74
|
+
"RateLimitError",
|
|
75
|
+
"InternalServerError",
|
|
76
|
+
"ServiceUnavailableError",
|
|
77
|
+
"TimeoutError",
|
|
78
|
+
"ConnectionError",
|
|
79
|
+
"InvalidModelError",
|
|
80
|
+
# Chat types
|
|
81
|
+
"ChatMessage",
|
|
82
|
+
"Usage",
|
|
83
|
+
"FallbackInfo",
|
|
84
|
+
"ChoiceMessage",
|
|
85
|
+
"Choice",
|
|
86
|
+
"ChatCompletionResponse",
|
|
87
|
+
"DeltaMessage",
|
|
88
|
+
"ChunkChoice",
|
|
89
|
+
"ChatCompletionChunk",
|
|
90
|
+
# Embeddings types
|
|
91
|
+
"EmbeddingData",
|
|
92
|
+
"EmbeddingsUsage",
|
|
93
|
+
"EmbeddingsResponse",
|
|
94
|
+
# Models types
|
|
95
|
+
"Model",
|
|
96
|
+
"ModelsListResponse",
|
|
97
|
+
# Audio types
|
|
98
|
+
"TranscriptionWord",
|
|
99
|
+
"TranscriptionSegment",
|
|
100
|
+
"TranscriptionResponse",
|
|
101
|
+
"TranslationResponse",
|
|
102
|
+
"SpeechResponse",
|
|
103
|
+
# Images types
|
|
104
|
+
"ImageData",
|
|
105
|
+
"ImageUsage",
|
|
106
|
+
"ImageResponse",
|
|
107
|
+
# Moderations types
|
|
108
|
+
"ModerationCategories",
|
|
109
|
+
"ModerationCategoryScores",
|
|
110
|
+
"ModerationResult",
|
|
111
|
+
"ModerationResponse",
|
|
112
|
+
# Rerank types
|
|
113
|
+
"RerankResult",
|
|
114
|
+
"RerankMeta",
|
|
115
|
+
"RerankResponse",
|
|
116
|
+
# Responses types
|
|
117
|
+
"ResponseOutputItem",
|
|
118
|
+
"ResponseUsage",
|
|
119
|
+
"ResponseObject",
|
|
120
|
+
"DeleteResponseResult",
|
|
121
|
+
"ListResponsesResult",
|
|
122
|
+
]
|
everstack/_client.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Everstack client — the main entry point for the SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Optional, Dict
|
|
6
|
+
|
|
7
|
+
from ._transport import Transport, AsyncTransport, GATEWAY_URL
|
|
8
|
+
from .resources.chat import Chat, AsyncChat
|
|
9
|
+
from .resources.embeddings import Embeddings, AsyncEmbeddings
|
|
10
|
+
from .resources.models import Models, AsyncModels
|
|
11
|
+
from .resources.audio import Audio, AsyncAudio
|
|
12
|
+
from .resources.images import Images, AsyncImages
|
|
13
|
+
from .resources.moderations import Moderations, AsyncModerations
|
|
14
|
+
from .resources.rerank import Rerank, AsyncRerank
|
|
15
|
+
from .resources.responses import Responses, AsyncResponses
|
|
16
|
+
from .resources.agents import Agents, AsyncAgents
|
|
17
|
+
from .resources.datasets import Datasets, AsyncDatasets
|
|
18
|
+
from .resources.evaluations import Evaluations, AsyncEvaluations
|
|
19
|
+
from .resources.observability import Observability, AsyncObservability
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Everstack:
|
|
23
|
+
"""Synchronous Everstack client.
|
|
24
|
+
|
|
25
|
+
Example::
|
|
26
|
+
|
|
27
|
+
from everstack import Everstack
|
|
28
|
+
|
|
29
|
+
client = Everstack(api_key="pk_...")
|
|
30
|
+
response = client.chat.completions.create(
|
|
31
|
+
model="@openai/gpt-4o",
|
|
32
|
+
messages=[{"role": "user", "content": "Hello!"}],
|
|
33
|
+
)
|
|
34
|
+
print(response.choices[0].message.content)
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
chat: Chat
|
|
38
|
+
embeddings: Embeddings
|
|
39
|
+
models: Models
|
|
40
|
+
audio: Audio
|
|
41
|
+
images: Images
|
|
42
|
+
moderations: Moderations
|
|
43
|
+
rerank: Rerank
|
|
44
|
+
responses: Responses
|
|
45
|
+
agents: Agents
|
|
46
|
+
datasets: Datasets
|
|
47
|
+
evaluations: Evaluations
|
|
48
|
+
observability: Observability
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
api_key: str,
|
|
53
|
+
*,
|
|
54
|
+
base_url: Optional[str] = None,
|
|
55
|
+
provider: Optional[str] = None,
|
|
56
|
+
org_id: Optional[str] = None,
|
|
57
|
+
user_id: Optional[str] = None,
|
|
58
|
+
headers: Optional[Dict[str, str]] = None,
|
|
59
|
+
timeout: float = 60.0,
|
|
60
|
+
) -> None:
|
|
61
|
+
self._transport = Transport(
|
|
62
|
+
base_url=base_url or GATEWAY_URL,
|
|
63
|
+
api_key=api_key,
|
|
64
|
+
provider=provider,
|
|
65
|
+
org_id=org_id,
|
|
66
|
+
user_id=user_id,
|
|
67
|
+
headers=headers,
|
|
68
|
+
timeout=timeout,
|
|
69
|
+
)
|
|
70
|
+
self._api_key = api_key
|
|
71
|
+
|
|
72
|
+
self.chat = Chat(self._transport)
|
|
73
|
+
self.embeddings = Embeddings(self._transport)
|
|
74
|
+
self.models = Models(self._transport)
|
|
75
|
+
self.audio = Audio(self._transport)
|
|
76
|
+
self.images = Images(self._transport)
|
|
77
|
+
self.moderations = Moderations(self._transport)
|
|
78
|
+
self.rerank = Rerank(self._transport)
|
|
79
|
+
self.responses = Responses(self._transport)
|
|
80
|
+
self.agents = Agents(self._transport)
|
|
81
|
+
self.datasets = Datasets(self._transport)
|
|
82
|
+
self.evaluations = Evaluations(self._transport)
|
|
83
|
+
self.observability = Observability(self._transport)
|
|
84
|
+
|
|
85
|
+
def close(self) -> None:
|
|
86
|
+
"""Close the underlying HTTP client."""
|
|
87
|
+
self._transport.close()
|
|
88
|
+
|
|
89
|
+
def __enter__(self) -> "Everstack":
|
|
90
|
+
return self
|
|
91
|
+
|
|
92
|
+
def __exit__(self, *args: object) -> None:
|
|
93
|
+
self.close()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class AsyncEverstack:
|
|
97
|
+
"""Asynchronous Everstack client.
|
|
98
|
+
|
|
99
|
+
Example::
|
|
100
|
+
|
|
101
|
+
from everstack import AsyncEverstack
|
|
102
|
+
|
|
103
|
+
async with AsyncEverstack(api_key="pk_...") as client:
|
|
104
|
+
response = await client.chat.completions.create(
|
|
105
|
+
model="@openai/gpt-4o",
|
|
106
|
+
messages=[{"role": "user", "content": "Hello!"}],
|
|
107
|
+
)
|
|
108
|
+
print(response.choices[0].message.content)
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
chat: AsyncChat
|
|
112
|
+
embeddings: AsyncEmbeddings
|
|
113
|
+
models: AsyncModels
|
|
114
|
+
audio: AsyncAudio
|
|
115
|
+
images: AsyncImages
|
|
116
|
+
moderations: AsyncModerations
|
|
117
|
+
rerank: AsyncRerank
|
|
118
|
+
responses: AsyncResponses
|
|
119
|
+
agents: AsyncAgents
|
|
120
|
+
datasets: AsyncDatasets
|
|
121
|
+
evaluations: AsyncEvaluations
|
|
122
|
+
observability: AsyncObservability
|
|
123
|
+
|
|
124
|
+
def __init__(
|
|
125
|
+
self,
|
|
126
|
+
api_key: str,
|
|
127
|
+
*,
|
|
128
|
+
base_url: Optional[str] = None,
|
|
129
|
+
provider: Optional[str] = None,
|
|
130
|
+
org_id: Optional[str] = None,
|
|
131
|
+
user_id: Optional[str] = None,
|
|
132
|
+
headers: Optional[Dict[str, str]] = None,
|
|
133
|
+
timeout: float = 60.0,
|
|
134
|
+
) -> None:
|
|
135
|
+
self._transport = AsyncTransport(
|
|
136
|
+
base_url=base_url or GATEWAY_URL,
|
|
137
|
+
api_key=api_key,
|
|
138
|
+
provider=provider,
|
|
139
|
+
org_id=org_id,
|
|
140
|
+
user_id=user_id,
|
|
141
|
+
headers=headers,
|
|
142
|
+
timeout=timeout,
|
|
143
|
+
)
|
|
144
|
+
self._api_key = api_key
|
|
145
|
+
|
|
146
|
+
self.chat = AsyncChat(self._transport)
|
|
147
|
+
self.embeddings = AsyncEmbeddings(self._transport)
|
|
148
|
+
self.models = AsyncModels(self._transport)
|
|
149
|
+
self.audio = AsyncAudio(self._transport)
|
|
150
|
+
self.images = AsyncImages(self._transport)
|
|
151
|
+
self.moderations = AsyncModerations(self._transport)
|
|
152
|
+
self.rerank = AsyncRerank(self._transport)
|
|
153
|
+
self.responses = AsyncResponses(self._transport)
|
|
154
|
+
self.agents = AsyncAgents(self._transport)
|
|
155
|
+
self.datasets = AsyncDatasets(self._transport)
|
|
156
|
+
self.evaluations = AsyncEvaluations(self._transport)
|
|
157
|
+
self.observability = AsyncObservability(self._transport)
|
|
158
|
+
|
|
159
|
+
async def close(self) -> None:
|
|
160
|
+
"""Close the underlying HTTP client."""
|
|
161
|
+
await self._transport.close()
|
|
162
|
+
|
|
163
|
+
async def __aenter__(self) -> "AsyncEverstack":
|
|
164
|
+
return self
|
|
165
|
+
|
|
166
|
+
async def __aexit__(self, *args: object) -> None:
|
|
167
|
+
await self.close()
|
everstack/_errors.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Everstack SDK error hierarchy."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Dict, Optional, Type
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class EverstackError(Exception):
|
|
9
|
+
"""Base error for all Everstack SDK errors."""
|
|
10
|
+
|
|
11
|
+
def __init__(self, message: str) -> None:
|
|
12
|
+
super().__init__(message)
|
|
13
|
+
self.message = message
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class APIError(EverstackError):
|
|
17
|
+
"""An error returned by the Everstack API."""
|
|
18
|
+
|
|
19
|
+
status_code: int
|
|
20
|
+
code: Optional[str]
|
|
21
|
+
param: Optional[str]
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
message: str,
|
|
26
|
+
*,
|
|
27
|
+
status_code: int,
|
|
28
|
+
code: Optional[str] = None,
|
|
29
|
+
param: Optional[str] = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
self.status_code = status_code
|
|
33
|
+
self.code = code
|
|
34
|
+
self.param = param
|
|
35
|
+
|
|
36
|
+
def __repr__(self) -> str:
|
|
37
|
+
return f"{self.__class__.__name__}(status_code={self.status_code}, message={self.message!r})"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class AuthenticationError(APIError):
|
|
41
|
+
"""401 — Invalid or missing API key."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, message: str = "Invalid API key") -> None:
|
|
44
|
+
super().__init__(message, status_code=401, code="authentication_error")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class PermissionDeniedError(APIError):
|
|
48
|
+
"""403 — Insufficient permissions."""
|
|
49
|
+
|
|
50
|
+
def __init__(self, message: str = "Permission denied") -> None:
|
|
51
|
+
super().__init__(message, status_code=403, code="permission_denied")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class NotFoundError(APIError):
|
|
55
|
+
"""404 — Resource not found."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, message: str = "Not found") -> None:
|
|
58
|
+
super().__init__(message, status_code=404, code="not_found")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class RateLimitError(APIError):
|
|
62
|
+
"""429 — Rate limit exceeded."""
|
|
63
|
+
|
|
64
|
+
retry_after: Optional[float]
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
message: str = "Rate limit exceeded",
|
|
69
|
+
*,
|
|
70
|
+
retry_after: Optional[float] = None,
|
|
71
|
+
) -> None:
|
|
72
|
+
super().__init__(message, status_code=429, code="rate_limit_exceeded")
|
|
73
|
+
self.retry_after = retry_after
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class InternalServerError(APIError):
|
|
77
|
+
"""500 — Internal server error."""
|
|
78
|
+
|
|
79
|
+
def __init__(self, message: str = "Internal server error") -> None:
|
|
80
|
+
super().__init__(message, status_code=500, code="internal_error")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class ServiceUnavailableError(APIError):
|
|
84
|
+
"""503 — Service temporarily unavailable."""
|
|
85
|
+
|
|
86
|
+
def __init__(self, message: str = "Service unavailable") -> None:
|
|
87
|
+
super().__init__(message, status_code=503, code="service_unavailable")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class TimeoutError(EverstackError):
|
|
91
|
+
"""Request timed out."""
|
|
92
|
+
|
|
93
|
+
pass
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class ConnectionError(EverstackError):
|
|
97
|
+
"""Could not connect to the API."""
|
|
98
|
+
|
|
99
|
+
pass
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class InvalidModelError(EverstackError):
|
|
103
|
+
"""Invalid model identifier."""
|
|
104
|
+
|
|
105
|
+
def __init__(self, model: str) -> None:
|
|
106
|
+
super().__init__(f"Invalid model: {model}")
|
|
107
|
+
self.model = model
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
_STATUS_MAP: Dict[int, Type[APIError]] = {
|
|
111
|
+
401: AuthenticationError,
|
|
112
|
+
403: PermissionDeniedError,
|
|
113
|
+
404: NotFoundError,
|
|
114
|
+
429: RateLimitError,
|
|
115
|
+
500: InternalServerError,
|
|
116
|
+
503: ServiceUnavailableError,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _raise_for_status(status_code: int, body: Dict[str, object]) -> None:
|
|
121
|
+
"""Raise the appropriate error for an API error response."""
|
|
122
|
+
if status_code < 400:
|
|
123
|
+
return
|
|
124
|
+
|
|
125
|
+
message = body.get("message") or body.get("error", {}).get("message", "Unknown error")
|
|
126
|
+
code = body.get("code") or body.get("error", {}).get("code")
|
|
127
|
+
|
|
128
|
+
error_cls = _STATUS_MAP.get(status_code, APIError)
|
|
129
|
+
|
|
130
|
+
if error_cls is RateLimitError:
|
|
131
|
+
raise RateLimitError(message)
|
|
132
|
+
|
|
133
|
+
if error_cls is APIError:
|
|
134
|
+
raise APIError(message, status_code=status_code, code=code)
|
|
135
|
+
|
|
136
|
+
raise error_cls(message)
|
everstack/_transport.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""HTTP transport layer for the Everstack SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, AsyncIterator, Dict, Iterator, Optional
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from ._errors import (
|
|
11
|
+
ConnectionError,
|
|
12
|
+
TimeoutError,
|
|
13
|
+
_raise_for_status,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
GATEWAY_URL = "https://gateway.everstack.ai"
|
|
17
|
+
|
|
18
|
+
# Header names matching the Node SDK transport
|
|
19
|
+
_HEADER_API_KEY = "x-mf-api-key"
|
|
20
|
+
_HEADER_PROVIDER = "x-mf-provider"
|
|
21
|
+
_HEADER_ORG_ID = "x-mf-org-id"
|
|
22
|
+
_HEADER_USER_ID = "x-mf-user-id"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Transport:
|
|
26
|
+
"""Sync HTTP transport backed by httpx."""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
*,
|
|
31
|
+
base_url: str,
|
|
32
|
+
api_key: str,
|
|
33
|
+
provider: Optional[str] = None,
|
|
34
|
+
org_id: Optional[str] = None,
|
|
35
|
+
user_id: Optional[str] = None,
|
|
36
|
+
headers: Optional[Dict[str, str]] = None,
|
|
37
|
+
timeout: float = 60.0,
|
|
38
|
+
) -> None:
|
|
39
|
+
self._base_url = base_url.rstrip("/")
|
|
40
|
+
|
|
41
|
+
default_headers: Dict[str, str] = {
|
|
42
|
+
_HEADER_API_KEY: api_key,
|
|
43
|
+
"Content-Type": "application/json",
|
|
44
|
+
}
|
|
45
|
+
if provider:
|
|
46
|
+
default_headers[_HEADER_PROVIDER] = provider
|
|
47
|
+
if org_id:
|
|
48
|
+
default_headers[_HEADER_ORG_ID] = org_id
|
|
49
|
+
if user_id:
|
|
50
|
+
default_headers[_HEADER_USER_ID] = user_id
|
|
51
|
+
if headers:
|
|
52
|
+
default_headers.update(headers)
|
|
53
|
+
|
|
54
|
+
self._client = httpx.Client(
|
|
55
|
+
base_url=self._base_url,
|
|
56
|
+
headers=default_headers,
|
|
57
|
+
timeout=httpx.Timeout(timeout),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def request(
|
|
61
|
+
self,
|
|
62
|
+
method: str,
|
|
63
|
+
path: str,
|
|
64
|
+
*,
|
|
65
|
+
json_body: Optional[Any] = None,
|
|
66
|
+
params: Optional[Dict[str, Any]] = None,
|
|
67
|
+
) -> Any:
|
|
68
|
+
"""Make a synchronous HTTP request and return the parsed JSON body."""
|
|
69
|
+
try:
|
|
70
|
+
response = self._client.request(
|
|
71
|
+
method,
|
|
72
|
+
path,
|
|
73
|
+
json=json_body,
|
|
74
|
+
params=_clean_params(params),
|
|
75
|
+
)
|
|
76
|
+
except httpx.TimeoutException as exc:
|
|
77
|
+
raise TimeoutError(str(exc)) from exc
|
|
78
|
+
except httpx.ConnectError as exc:
|
|
79
|
+
raise ConnectionError(str(exc)) from exc
|
|
80
|
+
|
|
81
|
+
if response.status_code >= 400:
|
|
82
|
+
try:
|
|
83
|
+
body = response.json()
|
|
84
|
+
except Exception:
|
|
85
|
+
body = {"message": response.text}
|
|
86
|
+
_raise_for_status(response.status_code, body)
|
|
87
|
+
|
|
88
|
+
if response.status_code == 204:
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
return response.json()
|
|
92
|
+
|
|
93
|
+
def stream(
|
|
94
|
+
self,
|
|
95
|
+
method: str,
|
|
96
|
+
path: str,
|
|
97
|
+
*,
|
|
98
|
+
json_body: Optional[Any] = None,
|
|
99
|
+
) -> Iterator[Dict[str, Any]]:
|
|
100
|
+
"""Make a streaming request and yield parsed SSE/JSON-line events."""
|
|
101
|
+
try:
|
|
102
|
+
with self._client.stream(method, path, json=json_body) as response:
|
|
103
|
+
if response.status_code >= 400:
|
|
104
|
+
body_text = response.read().decode()
|
|
105
|
+
try:
|
|
106
|
+
body = json.loads(body_text)
|
|
107
|
+
except Exception:
|
|
108
|
+
body = {"message": body_text}
|
|
109
|
+
_raise_for_status(response.status_code, body)
|
|
110
|
+
|
|
111
|
+
for line in response.iter_lines():
|
|
112
|
+
if not line:
|
|
113
|
+
continue
|
|
114
|
+
# Handle SSE format: "data: {...}"
|
|
115
|
+
if line.startswith("data: "):
|
|
116
|
+
data = line[6:]
|
|
117
|
+
if data == "[DONE]":
|
|
118
|
+
break
|
|
119
|
+
try:
|
|
120
|
+
yield json.loads(data)
|
|
121
|
+
except json.JSONDecodeError:
|
|
122
|
+
continue
|
|
123
|
+
else:
|
|
124
|
+
# Plain JSON lines
|
|
125
|
+
try:
|
|
126
|
+
yield json.loads(line)
|
|
127
|
+
except json.JSONDecodeError:
|
|
128
|
+
continue
|
|
129
|
+
except httpx.TimeoutException as exc:
|
|
130
|
+
raise TimeoutError(str(exc)) from exc
|
|
131
|
+
except httpx.ConnectError as exc:
|
|
132
|
+
raise ConnectionError(str(exc)) from exc
|
|
133
|
+
|
|
134
|
+
def close(self) -> None:
|
|
135
|
+
self._client.close()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class AsyncTransport:
|
|
139
|
+
"""Async HTTP transport backed by httpx."""
|
|
140
|
+
|
|
141
|
+
def __init__(
|
|
142
|
+
self,
|
|
143
|
+
*,
|
|
144
|
+
base_url: str,
|
|
145
|
+
api_key: str,
|
|
146
|
+
provider: Optional[str] = None,
|
|
147
|
+
org_id: Optional[str] = None,
|
|
148
|
+
user_id: Optional[str] = None,
|
|
149
|
+
headers: Optional[Dict[str, str]] = None,
|
|
150
|
+
timeout: float = 60.0,
|
|
151
|
+
) -> None:
|
|
152
|
+
self._base_url = base_url.rstrip("/")
|
|
153
|
+
|
|
154
|
+
default_headers: Dict[str, str] = {
|
|
155
|
+
_HEADER_API_KEY: api_key,
|
|
156
|
+
"Content-Type": "application/json",
|
|
157
|
+
}
|
|
158
|
+
if provider:
|
|
159
|
+
default_headers[_HEADER_PROVIDER] = provider
|
|
160
|
+
if org_id:
|
|
161
|
+
default_headers[_HEADER_ORG_ID] = org_id
|
|
162
|
+
if user_id:
|
|
163
|
+
default_headers[_HEADER_USER_ID] = user_id
|
|
164
|
+
if headers:
|
|
165
|
+
default_headers.update(headers)
|
|
166
|
+
|
|
167
|
+
self._client = httpx.AsyncClient(
|
|
168
|
+
base_url=self._base_url,
|
|
169
|
+
headers=default_headers,
|
|
170
|
+
timeout=httpx.Timeout(timeout),
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
async def request(
|
|
174
|
+
self,
|
|
175
|
+
method: str,
|
|
176
|
+
path: str,
|
|
177
|
+
*,
|
|
178
|
+
json_body: Optional[Any] = None,
|
|
179
|
+
params: Optional[Dict[str, Any]] = None,
|
|
180
|
+
) -> Any:
|
|
181
|
+
"""Make an async HTTP request and return the parsed JSON body."""
|
|
182
|
+
try:
|
|
183
|
+
response = await self._client.request(
|
|
184
|
+
method,
|
|
185
|
+
path,
|
|
186
|
+
json=json_body,
|
|
187
|
+
params=_clean_params(params),
|
|
188
|
+
)
|
|
189
|
+
except httpx.TimeoutException as exc:
|
|
190
|
+
raise TimeoutError(str(exc)) from exc
|
|
191
|
+
except httpx.ConnectError as exc:
|
|
192
|
+
raise ConnectionError(str(exc)) from exc
|
|
193
|
+
|
|
194
|
+
if response.status_code >= 400:
|
|
195
|
+
try:
|
|
196
|
+
body = response.json()
|
|
197
|
+
except Exception:
|
|
198
|
+
body = {"message": response.text}
|
|
199
|
+
_raise_for_status(response.status_code, body)
|
|
200
|
+
|
|
201
|
+
if response.status_code == 204:
|
|
202
|
+
return None
|
|
203
|
+
|
|
204
|
+
return response.json()
|
|
205
|
+
|
|
206
|
+
async def stream(
|
|
207
|
+
self,
|
|
208
|
+
method: str,
|
|
209
|
+
path: str,
|
|
210
|
+
*,
|
|
211
|
+
json_body: Optional[Any] = None,
|
|
212
|
+
) -> AsyncIterator[Dict[str, Any]]:
|
|
213
|
+
"""Make a streaming request and yield parsed SSE/JSON-line events."""
|
|
214
|
+
try:
|
|
215
|
+
async with self._client.stream(method, path, json=json_body) as response:
|
|
216
|
+
if response.status_code >= 400:
|
|
217
|
+
body_bytes = await response.aread()
|
|
218
|
+
body_text = body_bytes.decode()
|
|
219
|
+
try:
|
|
220
|
+
body = json.loads(body_text)
|
|
221
|
+
except Exception:
|
|
222
|
+
body = {"message": body_text}
|
|
223
|
+
_raise_for_status(response.status_code, body)
|
|
224
|
+
|
|
225
|
+
async for line in response.aiter_lines():
|
|
226
|
+
if not line:
|
|
227
|
+
continue
|
|
228
|
+
if line.startswith("data: "):
|
|
229
|
+
data = line[6:]
|
|
230
|
+
if data == "[DONE]":
|
|
231
|
+
break
|
|
232
|
+
try:
|
|
233
|
+
yield json.loads(data)
|
|
234
|
+
except json.JSONDecodeError:
|
|
235
|
+
continue
|
|
236
|
+
else:
|
|
237
|
+
try:
|
|
238
|
+
yield json.loads(line)
|
|
239
|
+
except json.JSONDecodeError:
|
|
240
|
+
continue
|
|
241
|
+
except httpx.TimeoutException as exc:
|
|
242
|
+
raise TimeoutError(str(exc)) from exc
|
|
243
|
+
except httpx.ConnectError as exc:
|
|
244
|
+
raise ConnectionError(str(exc)) from exc
|
|
245
|
+
|
|
246
|
+
async def close(self) -> None:
|
|
247
|
+
await self._client.aclose()
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _clean_params(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, str]]:
|
|
251
|
+
"""Remove None values and convert to strings for query params."""
|
|
252
|
+
if params is None:
|
|
253
|
+
return None
|
|
254
|
+
return {k: str(v) for k, v in params.items() if v is not None}
|