pi169 0.1__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.
pi169/__init__.py ADDED
@@ -0,0 +1,63 @@
1
+ """
2
+ Pi169 SDK
3
+ """
4
+
5
+ from .client import Pi169Client
6
+ from .exceptions import (
7
+ Pi169Error,
8
+ AlpieError,
9
+ APIError,
10
+ AuthError,
11
+ RateLimitError,
12
+ TimeoutError,
13
+ ServerError,
14
+ EngineOverloadedError,
15
+ ModelNotFoundError,
16
+ LimitExceededError,
17
+ ContentPolicyViolationError,
18
+ ContextWindowExceededError,
19
+ UnsupportedParamsError,
20
+ )
21
+
22
+ from .alpie_types import (
23
+ ChatMessage,
24
+ ChatCompletionRequest,
25
+ ChatCompletionResponse,
26
+ ChatCompletionChoice,
27
+ StreamChunk,
28
+ Usage,
29
+ )
30
+
31
+ __version__ = "0.1.4"
32
+
33
+ # Backward compatibility
34
+ Alpie = Pi169Client
35
+
36
+ __all__ = [
37
+ # clients
38
+ "Pi169Client",
39
+ "AsyncPi169Client",
40
+
41
+ # errors
42
+ "Pi169Error",
43
+ "AlpieError",
44
+ "APIError",
45
+ "AuthError",
46
+ "RateLimitError",
47
+ "TimeoutError",
48
+ "ServerError",
49
+ "EngineOverloadedError",
50
+ "ModelNotFoundError",
51
+ "LimitExceededError",
52
+ "ContentPolicyViolationError",
53
+ "ContextWindowExceededError",
54
+ "UnsupportedParamsError",
55
+
56
+ # types
57
+ "ChatMessage",
58
+ "ChatCompletionRequest",
59
+ "ChatCompletionResponse",
60
+ "ChatCompletionChoice",
61
+ "StreamChunk",
62
+ "Usage",
63
+ ]
pi169/alpie_types.py ADDED
@@ -0,0 +1,139 @@
1
+ """
2
+ Type definitions for the pi169 SDK.
3
+ """
4
+
5
+ from typing import List, Optional, Dict, Any, Literal
6
+ from dataclasses import dataclass, field
7
+
8
+
9
+ @dataclass
10
+ class ChatMessage:
11
+ """Represents a chat message."""
12
+
13
+ role: Literal["system", "user", "assistant"]
14
+ content: str
15
+
16
+ def to_dict(self) -> Dict[str, str]:
17
+ """Convert to dictionary for API requests."""
18
+ return {"role": self.role, "content": self.content}
19
+
20
+
21
+ @dataclass
22
+ class Usage:
23
+ """Token usage information."""
24
+
25
+ prompt_tokens: int = 0
26
+ completion_tokens: int = 0
27
+ total_tokens: int = 0
28
+
29
+
30
+ @dataclass
31
+ class ChatCompletionChoice:
32
+ """Represents a single completion choice."""
33
+
34
+ index: int
35
+ message: ChatMessage
36
+ finish_reason: Optional[str] = None
37
+
38
+
39
+ @dataclass
40
+ class ChatCompletionResponse:
41
+ """Response from the chat completion API."""
42
+
43
+ id: str
44
+ model: str
45
+ choices: List[ChatCompletionChoice]
46
+ created: int
47
+ usage: Optional[Usage] = None
48
+
49
+ @classmethod
50
+ def from_dict(cls, data: Dict[str, Any]) -> "ChatCompletionResponse":
51
+ """Create a ChatCompletionResponse from API response data."""
52
+ choices = []
53
+ for choice_data in data.get("choices", []):
54
+ message_data = choice_data.get("message", {})
55
+ message = ChatMessage(
56
+ role=message_data.get("role", "assistant"),
57
+ content=message_data.get("content", "")
58
+ )
59
+ choice = ChatCompletionChoice(
60
+ index=choice_data.get("index", 0),
61
+ message=message,
62
+ finish_reason=choice_data.get("finish_reason")
63
+ )
64
+ choices.append(choice)
65
+
66
+ usage_data = data.get("usage", {})
67
+ usage = Usage(
68
+ prompt_tokens=usage_data.get("prompt_tokens", 0),
69
+ completion_tokens=usage_data.get("completion_tokens", 0),
70
+ total_tokens=usage_data.get("total_tokens", 0)
71
+ ) if usage_data else None
72
+
73
+ return cls(
74
+ id=data.get("id", ""),
75
+ model=data.get("model", ""),
76
+ choices=choices,
77
+ created=data.get("created", 0),
78
+ usage=usage
79
+ )
80
+
81
+
82
+ @dataclass
83
+ class StreamChunk:
84
+ """Represents a chunk from a streaming response."""
85
+
86
+ id: str
87
+ model: str
88
+ choices: List[Dict[str, Any]]
89
+ created: int
90
+ delta_content: str = ""
91
+ finish_reason: Optional[str] = None
92
+
93
+ @classmethod
94
+ def from_dict(cls, data: Dict[str, Any]) -> "StreamChunk":
95
+ """Create a StreamChunk from streaming API data."""
96
+ choices = data.get("choices", [])
97
+ delta_content = ""
98
+ finish_reason = None
99
+
100
+ if choices:
101
+ delta = choices[0].get("delta", {})
102
+ delta_content = delta.get("content", "")
103
+ finish_reason = choices[0].get("finish_reason")
104
+
105
+ return cls(
106
+ id=data.get("id", ""),
107
+ model=data.get("model", ""),
108
+ choices=choices,
109
+ created=data.get("created", 0),
110
+ delta_content=delta_content,
111
+ finish_reason=finish_reason
112
+ )
113
+
114
+
115
+ @dataclass
116
+ class ChatCompletionRequest:
117
+ """Request parameters for chat completion."""
118
+
119
+ model: str
120
+ messages: List[ChatMessage]
121
+ max_tokens: int = 16384
122
+ temperature: float = 1.0
123
+ stream: bool = False
124
+ top_p: float = 1.0
125
+ frequency_penalty: float = 0.0
126
+ presence_penalty: float = 0.0
127
+
128
+ def to_dict(self) -> Dict[str, Any]:
129
+ """Convert to dictionary for API requests."""
130
+ return {
131
+ "model": self.model,
132
+ "messages": [msg.to_dict() for msg in self.messages],
133
+ "max_tokens": self.max_tokens,
134
+ "temperature": self.temperature,
135
+ "stream": self.stream,
136
+ "top_p": self.top_p,
137
+ "frequency_penalty": self.frequency_penalty,
138
+ "presence_penalty": self.presence_penalty,
139
+ }
pi169/async_client.py ADDED
@@ -0,0 +1,377 @@
1
+ import json
2
+ from typing import AsyncIterator, Optional, Union, List
3
+ import httpx
4
+
5
+ from pi169.exceptions import (
6
+ APIError,
7
+ AuthError,
8
+ RateLimitError,
9
+ TimeoutError as ApiTimeoutError,
10
+ ServerError,
11
+ EngineOverloadedError,
12
+ ModelNotFoundError,
13
+ LimitExceededError,
14
+ ContentPolicyViolationError,
15
+ ContextWindowExceededError,
16
+ UnsupportedParamsError,
17
+ KeyNotActive
18
+ )
19
+
20
+ from pi169.alpie_types import (
21
+ ChatMessage,
22
+ ChatCompletionRequest,
23
+ ChatCompletionResponse,
24
+ StreamChunk,
25
+ )
26
+
27
+
28
+ class AsyncPi169Client:
29
+ """
30
+ Asynchronous client for interacting with the 169Pi API.
31
+
32
+ This client handles authentication, request formulation, and error handling
33
+ for async chat completions. It is designed to be used within an `asyncio`
34
+ event loop.
35
+
36
+ Args:
37
+ api_key (str): Your 169Pi API key for authentication.
38
+ base_url (str, optional): The base URL for the API.
39
+ Defaults to "https://api.169pi.com/v1".
40
+ timeout (float, optional): Request timeout in seconds. Defaults to 60.0.
41
+ max_retries (int, optional): Number of times to retry failed requests.
42
+ Defaults to 2.
43
+
44
+ Attributes:
45
+ chat (AsyncChatCompletions): Access to chat completion endpoints.
46
+
47
+ Basic usage inside an async function:
48
+
49
+ >>> import asyncio
50
+ >>> from pi169.async_client import AsyncPi169Client
51
+ >>>
52
+ >>> async def main():
53
+ >>> client = AsyncPi169Client(api_key="your_api_key")
54
+ >>>
55
+ >>> # Non-streaming request
56
+ >>> response = await client.chat.completions.create(
57
+ >>> model="alpie-32b",
58
+ >>> messages=[{"role": "user", "content": "Hello!"}]
59
+ >>> )
60
+ >>> print(response.choices[0].message.content)
61
+ >>>
62
+ >>> asyncio.run(main())
63
+
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ api_key: str,
69
+ base_url: str = "https://api.169pi.com/v1", # Updated URL placeholder based on context
70
+ timeout: float = 60.0,
71
+ max_retries: int = 2,
72
+ ):
73
+ if not api_key:
74
+ raise AuthError("API key is required")
75
+
76
+ self.api_key = api_key
77
+ self.base_url = base_url.rstrip("/")
78
+ self.timeout = timeout
79
+ self.max_retries = max_retries
80
+
81
+ self.chat = AsyncChatCompletions(self)
82
+
83
+ def _get_headers(self, stream: bool = False) -> dict:
84
+ headers = {
85
+ "Authorization": f"Bearer {self.api_key}",
86
+ "Content-Type": "application/json",
87
+ }
88
+ if stream:
89
+ headers["Accept"] = "text/event-stream"
90
+ return headers
91
+
92
+ def _handle_error_response(self, response: httpx.Response) -> None:
93
+ """Handle error responses from the API."""
94
+ try:
95
+ error_data = response.json()
96
+ except Exception:
97
+ error_data = {"error": {"message": response.text or "Unknown error"}}
98
+
99
+ error_info = error_data.get("error", {})
100
+
101
+ if isinstance(error_info, dict):
102
+ message = (
103
+ error_info.get("message") or
104
+ error_data.get("detail") or
105
+ error_data.get("error_description") or
106
+ str(error_info) or
107
+ response.text or
108
+ "Unknown error"
109
+ )
110
+ error_type = error_info.get("type", "unknown")
111
+ else:
112
+ message = (
113
+ str(error_info) or
114
+ error_data.get("message") or
115
+ error_data.get("detail") or
116
+ response.text or
117
+ "Unknown error"
118
+ )
119
+ error_type = "unknown"
120
+
121
+ status_code = response.status_code
122
+
123
+ if status_code == 401:
124
+ if message.lower() in ["error", "unauthorized", ""]:
125
+ message = "Invalid API key. Please check your API key and try again."
126
+ raise AuthError(message, status_code, error_data)
127
+
128
+ if status_code == 400:
129
+ if error_type == "content_policy_violation":
130
+ raise ContentPolicyViolationError(message, status_code, error_data)
131
+ elif error_type == "context_window_exceeded":
132
+ raise ContextWindowExceededError(message, status_code, error_data)
133
+ elif error_type == "unsupported_params":
134
+ raise UnsupportedParamsError(message, status_code, error_data)
135
+ else:
136
+ raise APIError(message, status_code, error_data)
137
+
138
+ if status_code == 402:
139
+ if error_type == "limit_exceeded":
140
+ raise LimitExceededError(message, status_code, error_data)
141
+ elif error_type == "key_not_active":
142
+ raise KeyNotActive(message, status_code, error_data)
143
+ else:
144
+ raise APIError(message, status_code, error_data)
145
+
146
+ if status_code == 403:
147
+ raise ContentPolicyViolationError(message, status_code, error_data)
148
+
149
+ if status_code == 404:
150
+ raise ModelNotFoundError(message, status_code, error_data)
151
+
152
+ if status_code == 429:
153
+ raise RateLimitError(message, status_code, error_data)
154
+
155
+ if status_code == 503:
156
+ raise EngineOverloadedError(message, status_code, error_data)
157
+
158
+ if status_code == 504:
159
+ raise ApiTimeoutError(message, status_code, error_data)
160
+
161
+ if 500 <= status_code <= 599:
162
+ raise ServerError(f"Server error {status_code}: {message}", status_code, error_data)
163
+
164
+ raise APIError(f"API error {status_code}: {message}", status_code, error_data)
165
+
166
+
167
+ class AsyncChatCompletions:
168
+ """
169
+ Async handler for chat completion endpoints.
170
+
171
+ This class provides methods to generate model responses asynchronously.
172
+ It supports both standard request-response patterns and streaming responses
173
+ via Server-Sent Events (SSE).
174
+ """
175
+
176
+ def __init__(self, client: AsyncPi169Client):
177
+ self.client = client
178
+ self.completions = self
179
+
180
+ async def create(
181
+ self,
182
+ model: str,
183
+ messages: List[Union[ChatMessage, dict]],
184
+ max_tokens: int = 10000,
185
+ temperature: float = 1.0,
186
+ stream: bool = False,
187
+ top_p: float = 1.0,
188
+ frequency_penalty: float = 0.0,
189
+ presence_penalty: float = 0.0,
190
+ ) -> Union[ChatCompletionResponse, AsyncIterator[StreamChunk]]:
191
+ """
192
+ Asynchronously creates a model response for the given chat conversation.
193
+
194
+ Args:
195
+ model (str): The name of the model to use (e.g., "alpie-32b").
196
+ messages (List[Union[ChatMessage, dict]]): A list of messages comprising
197
+ the conversation so far. Each message should be a dictionary or
198
+ ChatMessage object with 'role' and 'content' keys.
199
+ max_tokens (int, optional): The maximum number of tokens to generate
200
+ in the completion. Defaults to 10000.
201
+ temperature (float, optional): Sampling temperature to use, between 0.0 and 1.0.
202
+ Higher values make output more random, lower values more deterministic.
203
+ Defaults to 1.0.
204
+ stream (bool, optional): If True, partial message deltas will be sent
205
+ as data-only server-sent events as they become available.
206
+ Defaults to False.
207
+ top_p (float, optional): An alternative to sampling with temperature,
208
+ called nucleus sampling. Defaults to 1.0.
209
+ frequency_penalty (float, optional): Number between -2.0 and 2.0.
210
+ Positive values penalize new tokens based on their existing frequency
211
+ in the text so far. Defaults to 0.0.
212
+ presence_penalty (float, optional): Number between -2.0 and 2.0.
213
+ Positive values penalize new tokens based on whether they appear
214
+ in the text so far. Defaults to 0.0.
215
+
216
+ Returns:
217
+ Union[ChatCompletionResponse, AsyncIterator[StreamChunk]]:
218
+ - If `stream` is False, returns a single `ChatCompletionResponse` object
219
+ containing the complete response.
220
+ - If `stream` is True, returns an asynchronous iterator that yields
221
+ `StreamChunk` objects.
222
+
223
+ Raises:
224
+ APIError: If the API returns a non-200 status code or the message type is invalid.
225
+ AuthError: If authentication fails.
226
+ TimeoutError: If the request times out.
227
+
228
+ Example:
229
+ >>> stream = await client.chat.completions.create(
230
+ >>> model="alpie-32b",
231
+ >>> messages=[{"role": "user", "content": "Hello!"}],
232
+ >>> stream=True,
233
+ >>> )
234
+ >>> async for chunk in stream:
235
+ >>> if chunk.choices:
236
+ >>> delta = chunk.choices[0].get("delta", {})
237
+ >>> if delta.get("content"):
238
+ >>> print(delta["content"], end="")
239
+
240
+ """
241
+
242
+ chat_messages = []
243
+ for msg in messages:
244
+ if isinstance(msg, ChatMessage):
245
+ chat_messages.append(msg)
246
+ elif isinstance(msg, dict):
247
+ chat_messages.append(ChatMessage(role=msg["role"], content=msg["content"]))
248
+ else:
249
+ raise APIError(f"Invalid message type: {type(msg)}")
250
+
251
+ request = ChatCompletionRequest(
252
+ model=model,
253
+ messages=chat_messages,
254
+ max_tokens=max_tokens,
255
+ temperature=temperature,
256
+ stream=stream,
257
+ top_p=top_p,
258
+ frequency_penalty=frequency_penalty,
259
+ presence_penalty=presence_penalty,
260
+ )
261
+
262
+ if stream:
263
+ return self._create_streaming(request)
264
+ else:
265
+ return await self._create_non_streaming(request)
266
+
267
+ async def _create_non_streaming(self, request: ChatCompletionRequest) -> ChatCompletionResponse:
268
+ """
269
+ Internal method to handle non-streaming chat completion requests.
270
+
271
+ Sends a POST request to the API and parses the JSON response into a
272
+ ChatCompletionResponse object.
273
+
274
+ Args:
275
+ request (ChatCompletionRequest): The prepared request object containing
276
+ model parameters and messages.
277
+
278
+ Returns:
279
+ ChatCompletionResponse: The structured response from the API.
280
+
281
+ Raises:
282
+ ApiTimeoutError: If the request exceeds the client's timeout setting.
283
+ APIError: For standard HTTP errors or unexpected exceptions.
284
+ AuthError: If the API key is invalid.
285
+ """
286
+ url = f"{self.client.base_url}/chat/completions"
287
+ headers = self.client._get_headers(stream=False)
288
+ payload = request.to_dict()
289
+
290
+ try:
291
+ # Using AsyncClient context manager
292
+ async with httpx.AsyncClient(timeout=self.client.timeout) as client:
293
+ response = await client.post(url, headers=headers, json=payload)
294
+
295
+ if response.status_code != 200:
296
+ self.client._handle_error_response(response)
297
+
298
+ data = response.json()
299
+ return ChatCompletionResponse.from_dict(data)
300
+
301
+ except httpx.TimeoutException as e:
302
+ raise ApiTimeoutError(str(e))
303
+
304
+ except httpx.HTTPError as e:
305
+ raise APIError(f"Network error: {str(e)}")
306
+
307
+ except (AuthError, RateLimitError, APIError, ContentPolicyViolationError,
308
+ ModelNotFoundError, ServerError, LimitExceededError, EngineOverloadedError):
309
+ raise
310
+
311
+ except Exception as e:
312
+ raise APIError(f"Unexpected error: {str(e)}")
313
+
314
+ async def _create_streaming(self, request: ChatCompletionRequest) -> AsyncIterator[StreamChunk]:
315
+ """
316
+ Internal method to handle streaming chat completion requests (SSE).
317
+
318
+ Establishes a persistent connection and yields chunks of data as they
319
+ arrive using Server-Sent Events (SSE) format.
320
+
321
+ Args:
322
+ request (ChatCompletionRequest): The prepared request object.
323
+
324
+ Yields:
325
+ StreamChunk: A parsed chunk of the streaming response.
326
+
327
+ Raises:
328
+ APIError: If the stream is interrupted or contains error data.
329
+ """
330
+ url = f"{self.client.base_url}/chat/completions"
331
+ headers = self.client._get_headers(stream=True)
332
+ payload = request.to_dict()
333
+
334
+ try:
335
+ async with httpx.AsyncClient(timeout=None) as client:
336
+ async with client.stream("POST", url, headers=headers, json=payload) as response:
337
+
338
+ if response.status_code != 200:
339
+ await response.aread() # Read response body asynchronously before handling error
340
+ self.client._handle_error_response(response)
341
+
342
+ async for chunk in response.aiter_text():
343
+ if "data: " in chunk:
344
+ for part in chunk.strip().split("\n\n"):
345
+ part = part.strip()
346
+
347
+ if part == "data: [DONE]":
348
+ return
349
+
350
+ if not part.startswith("data: "):
351
+ continue
352
+
353
+ try:
354
+ data_json = json.loads(part[6:])
355
+
356
+ if "error" in data_json:
357
+ message = data_json["error"].get("message", "Unknown error")
358
+ raise APIError(f"Streaming error: {message}", response_data=data_json)
359
+
360
+ yield StreamChunk.from_dict(data_json)
361
+
362
+ except json.JSONDecodeError:
363
+ continue
364
+
365
+ except httpx.TimeoutException as e:
366
+ raise ApiTimeoutError(str(e))
367
+
368
+ except httpx.HTTPError as e:
369
+ raise APIError(f"Network error: {str(e)}")
370
+
371
+ except (AuthError, RateLimitError, APIError, ContentPolicyViolationError,
372
+ ModelNotFoundError, ServerError, EngineOverloadedError,
373
+ LimitExceededError):
374
+ raise
375
+
376
+ except Exception as e:
377
+ raise APIError(f"Unexpected streaming error: {str(e)}")
pi169/cli.py ADDED
@@ -0,0 +1,36 @@
1
+ import argparse
2
+ import os
3
+ from pi169 import Pi169Client
4
+
5
+ def main():
6
+ parser = argparse.ArgumentParser(description="Pi169 CLI")
7
+ parser.add_argument("prompt", help="Prompt to send to the model")
8
+ parser.add_argument("--model", default="alpie-32b")
9
+ parser.add_argument("--stream", action="store_true")
10
+
11
+ args = parser.parse_args()
12
+
13
+ api_key = os.getenv("ALPIE_API_KEY")
14
+ if not api_key:
15
+ raise RuntimeError("ALPIE_API_KEY not set")
16
+
17
+ client = Pi169Client(api_key=api_key)
18
+
19
+ if args.stream:
20
+ stream = client.chat.completions.create(
21
+ model=args.model,
22
+ messages=[{"role": "user", "content": args.prompt}],
23
+ stream=True,
24
+ )
25
+ for chunk in stream:
26
+ if chunk.choices:
27
+ delta = chunk.choices[0].get("delta", {})
28
+ if delta.get("content"):
29
+ print(delta["content"], end="", flush=True)
30
+ print()
31
+ else:
32
+ response = client.chat.completions.create(
33
+ model=args.model,
34
+ messages=[{"role": "user", "content": args.prompt}],
35
+ )
36
+ print(response.choices[0].message.content)