cencori 0.1.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.
- cencori-0.1.0/.gitignore +44 -0
- cencori-0.1.0/PKG-INFO +95 -0
- cencori-0.1.0/README.md +65 -0
- cencori-0.1.0/examples/basic_usage.py +79 -0
- cencori-0.1.0/pyproject.toml +55 -0
- cencori-0.1.0/src/cencori/__init__.py +34 -0
- cencori-0.1.0/src/cencori/ai.py +142 -0
- cencori-0.1.0/src/cencori/client.py +91 -0
- cencori-0.1.0/src/cencori/errors.py +47 -0
- cencori-0.1.0/src/cencori/types.py +48 -0
cencori-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# Distribution / packaging
|
|
7
|
+
.Python
|
|
8
|
+
build/
|
|
9
|
+
develop-eggs/
|
|
10
|
+
dist/
|
|
11
|
+
downloads/
|
|
12
|
+
eggs/
|
|
13
|
+
.eggs/
|
|
14
|
+
lib/
|
|
15
|
+
lib64/
|
|
16
|
+
parts/
|
|
17
|
+
sdist/
|
|
18
|
+
var/
|
|
19
|
+
wheels/
|
|
20
|
+
*.egg-info/
|
|
21
|
+
.installed.cfg
|
|
22
|
+
*.egg
|
|
23
|
+
|
|
24
|
+
# Virtual environments
|
|
25
|
+
venv/
|
|
26
|
+
ENV/
|
|
27
|
+
env/
|
|
28
|
+
.venv/
|
|
29
|
+
|
|
30
|
+
# IDE
|
|
31
|
+
.idea/
|
|
32
|
+
.vscode/
|
|
33
|
+
*.swp
|
|
34
|
+
*.swo
|
|
35
|
+
|
|
36
|
+
# Testing
|
|
37
|
+
.pytest_cache/
|
|
38
|
+
.coverage
|
|
39
|
+
htmlcov/
|
|
40
|
+
.tox/
|
|
41
|
+
.nox/
|
|
42
|
+
|
|
43
|
+
# Type checking
|
|
44
|
+
.mypy_cache/
|
cencori-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cencori
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for Cencori - AI Infrastructure for Production
|
|
5
|
+
Project-URL: Homepage, https://cencori.com
|
|
6
|
+
Project-URL: Documentation, https://cencori.com/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/cencori/cencori-python
|
|
8
|
+
Author-email: FohnAI <support@cencori.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
Keywords: ai,anthropic,api,gateway,gemini,infrastructure,llm,openai
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Requires-Python: >=3.8
|
|
23
|
+
Requires-Dist: httpx>=0.24.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: mypy>=1.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: ruff>=0.1; extra == 'dev'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# Cencori Python SDK
|
|
32
|
+
|
|
33
|
+
Official Python SDK for Cencori - AI Infrastructure for Production.
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install cencori
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Quick Start
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from cencori import Cencori
|
|
45
|
+
|
|
46
|
+
cencori = Cencori(api_key="your-api-key")
|
|
47
|
+
|
|
48
|
+
response = cencori.ai.chat(
|
|
49
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
print(response.content)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Streaming
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
for chunk in cencori.ai.chat_stream(
|
|
59
|
+
messages=[{"role": "user", "content": "Tell me a story"}],
|
|
60
|
+
model="gpt-4o"
|
|
61
|
+
):
|
|
62
|
+
print(chunk.delta, end="", flush=True)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Error Handling
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from cencori import (
|
|
69
|
+
Cencori,
|
|
70
|
+
AuthenticationError,
|
|
71
|
+
RateLimitError,
|
|
72
|
+
SafetyError
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
response = cencori.ai.chat(messages=[...])
|
|
77
|
+
except AuthenticationError:
|
|
78
|
+
print("Invalid API key")
|
|
79
|
+
except RateLimitError:
|
|
80
|
+
print("Too many requests")
|
|
81
|
+
except SafetyError as e:
|
|
82
|
+
print(f"Content blocked: {e.reasons}")
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Supported Models
|
|
86
|
+
|
|
87
|
+
| Provider | Models |
|
|
88
|
+
|----------|--------|
|
|
89
|
+
| OpenAI | `gpt-4o`, `gpt-4-turbo`, `gpt-3.5-turbo` |
|
|
90
|
+
| Anthropic | `claude-3-opus`, `claude-3-sonnet`, `claude-3-haiku` |
|
|
91
|
+
| Google | `gemini-2.5-flash`, `gemini-2.0-flash` |
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT © FohnAI
|
cencori-0.1.0/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Cencori Python SDK
|
|
2
|
+
|
|
3
|
+
Official Python SDK for Cencori - AI Infrastructure for Production.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install cencori
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from cencori import Cencori
|
|
15
|
+
|
|
16
|
+
cencori = Cencori(api_key="your-api-key")
|
|
17
|
+
|
|
18
|
+
response = cencori.ai.chat(
|
|
19
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
print(response.content)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Streaming
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
for chunk in cencori.ai.chat_stream(
|
|
29
|
+
messages=[{"role": "user", "content": "Tell me a story"}],
|
|
30
|
+
model="gpt-4o"
|
|
31
|
+
):
|
|
32
|
+
print(chunk.delta, end="", flush=True)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Error Handling
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from cencori import (
|
|
39
|
+
Cencori,
|
|
40
|
+
AuthenticationError,
|
|
41
|
+
RateLimitError,
|
|
42
|
+
SafetyError
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
response = cencori.ai.chat(messages=[...])
|
|
47
|
+
except AuthenticationError:
|
|
48
|
+
print("Invalid API key")
|
|
49
|
+
except RateLimitError:
|
|
50
|
+
print("Too many requests")
|
|
51
|
+
except SafetyError as e:
|
|
52
|
+
print(f"Content blocked: {e.reasons}")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Supported Models
|
|
56
|
+
|
|
57
|
+
| Provider | Models |
|
|
58
|
+
|----------|--------|
|
|
59
|
+
| OpenAI | `gpt-4o`, `gpt-4-turbo`, `gpt-3.5-turbo` |
|
|
60
|
+
| Anthropic | `claude-3-opus`, `claude-3-sonnet`, `claude-3-haiku` |
|
|
61
|
+
| Google | `gemini-2.5-flash`, `gemini-2.0-flash` |
|
|
62
|
+
|
|
63
|
+
## License
|
|
64
|
+
|
|
65
|
+
MIT © FohnAI
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Example usage of Cencori Python SDK."""
|
|
2
|
+
|
|
3
|
+
from cencori import Cencori, AuthenticationError, RateLimitError, SafetyError
|
|
4
|
+
|
|
5
|
+
# Initialize client
|
|
6
|
+
cencori = Cencori(api_key="your-api-key")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# Example 1: Basic chat
|
|
10
|
+
def basic_chat():
|
|
11
|
+
response = cencori.ai.chat(
|
|
12
|
+
messages=[{"role": "user", "content": "What is the capital of France?"}],
|
|
13
|
+
model="gpt-4o",
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
print(f"Response: {response.content}")
|
|
17
|
+
print(f"Model: {response.model}")
|
|
18
|
+
print(f"Cost: ${response.cost_usd:.6f}")
|
|
19
|
+
print(f"Tokens: {response.usage.total_tokens}")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# Example 2: Streaming
|
|
23
|
+
def streaming_chat():
|
|
24
|
+
print("Streaming response: ", end="")
|
|
25
|
+
|
|
26
|
+
for chunk in cencori.ai.chat_stream(
|
|
27
|
+
messages=[{"role": "user", "content": "Tell me a short story about a robot."}],
|
|
28
|
+
model="gpt-4o",
|
|
29
|
+
):
|
|
30
|
+
print(chunk.delta, end="", flush=True)
|
|
31
|
+
|
|
32
|
+
print() # New line at the end
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# Example 3: Error handling
|
|
36
|
+
def error_handling():
|
|
37
|
+
try:
|
|
38
|
+
response = cencori.ai.chat(
|
|
39
|
+
messages=[{"role": "user", "content": "Hello!"}],
|
|
40
|
+
)
|
|
41
|
+
print(response.content)
|
|
42
|
+
except AuthenticationError:
|
|
43
|
+
print("Error: Invalid API key")
|
|
44
|
+
except RateLimitError:
|
|
45
|
+
print("Error: Rate limit exceeded, please slow down")
|
|
46
|
+
except SafetyError as e:
|
|
47
|
+
print(f"Error: Content blocked - {e.reasons}")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# Example 4: Multi-turn conversation
|
|
51
|
+
def conversation():
|
|
52
|
+
messages = [
|
|
53
|
+
{"role": "system", "content": "You are a helpful assistant."},
|
|
54
|
+
{"role": "user", "content": "My name is Alice."},
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
response1 = cencori.ai.chat(messages=messages, model="gpt-4o")
|
|
58
|
+
print(f"Assistant: {response1.content}")
|
|
59
|
+
|
|
60
|
+
# Add assistant response and user follow-up
|
|
61
|
+
messages.append({"role": "assistant", "content": response1.content})
|
|
62
|
+
messages.append({"role": "user", "content": "What's my name?"})
|
|
63
|
+
|
|
64
|
+
response2 = cencori.ai.chat(messages=messages, model="gpt-4o")
|
|
65
|
+
print(f"Assistant: {response2.content}")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
if __name__ == "__main__":
|
|
69
|
+
print("=== Basic Chat ===")
|
|
70
|
+
basic_chat()
|
|
71
|
+
|
|
72
|
+
print("\n=== Streaming ===")
|
|
73
|
+
streaming_chat()
|
|
74
|
+
|
|
75
|
+
print("\n=== Error Handling ===")
|
|
76
|
+
error_handling()
|
|
77
|
+
|
|
78
|
+
print("\n=== Conversation ===")
|
|
79
|
+
conversation()
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cencori"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official Python SDK for Cencori - AI Infrastructure for Production"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
authors = [
|
|
12
|
+
{ name = "FohnAI", email = "support@cencori.com" }
|
|
13
|
+
]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.8",
|
|
20
|
+
"Programming Language :: Python :: 3.9",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
25
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
26
|
+
]
|
|
27
|
+
keywords = ["ai", "llm", "openai", "anthropic", "gemini", "api", "gateway", "infrastructure"]
|
|
28
|
+
requires-python = ">=3.8"
|
|
29
|
+
dependencies = [
|
|
30
|
+
"httpx>=0.24.0",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
dev = [
|
|
35
|
+
"pytest>=7.0",
|
|
36
|
+
"pytest-asyncio>=0.21",
|
|
37
|
+
"ruff>=0.1",
|
|
38
|
+
"mypy>=1.0",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://cencori.com"
|
|
43
|
+
Documentation = "https://cencori.com/docs"
|
|
44
|
+
Repository = "https://github.com/cencori/cencori-python"
|
|
45
|
+
|
|
46
|
+
[tool.hatch.build.targets.wheel]
|
|
47
|
+
packages = ["src/cencori"]
|
|
48
|
+
|
|
49
|
+
[tool.ruff]
|
|
50
|
+
line-length = 100
|
|
51
|
+
target-version = "py38"
|
|
52
|
+
|
|
53
|
+
[tool.mypy]
|
|
54
|
+
python_version = "3.8"
|
|
55
|
+
strict = true
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Cencori Python SDK
|
|
3
|
+
|
|
4
|
+
Official Python SDK for Cencori - AI Infrastructure for Production.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .client import Cencori
|
|
8
|
+
from .errors import (
|
|
9
|
+
CencoriError,
|
|
10
|
+
AuthenticationError,
|
|
11
|
+
RateLimitError,
|
|
12
|
+
SafetyError,
|
|
13
|
+
)
|
|
14
|
+
from .types import (
|
|
15
|
+
Message,
|
|
16
|
+
ChatParams,
|
|
17
|
+
ChatResponse,
|
|
18
|
+
StreamChunk,
|
|
19
|
+
Usage,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
__all__ = [
|
|
24
|
+
"Cencori",
|
|
25
|
+
"CencoriError",
|
|
26
|
+
"AuthenticationError",
|
|
27
|
+
"RateLimitError",
|
|
28
|
+
"SafetyError",
|
|
29
|
+
"Message",
|
|
30
|
+
"ChatParams",
|
|
31
|
+
"ChatResponse",
|
|
32
|
+
"StreamChunk",
|
|
33
|
+
"Usage",
|
|
34
|
+
]
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""AI module for chat completions."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any, Dict, Iterator, List, Optional, Union
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
from .errors import AuthenticationError, CencoriError, RateLimitError, SafetyError
|
|
9
|
+
from .types import ChatResponse, StreamChunk, Usage
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AIModule:
|
|
13
|
+
"""AI module for chat completions."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, client: "Cencori") -> None: # type: ignore[name-defined]
|
|
16
|
+
self._client = client
|
|
17
|
+
|
|
18
|
+
def chat(
|
|
19
|
+
self,
|
|
20
|
+
messages: List[Dict[str, str]],
|
|
21
|
+
model: str = "gemini-2.5-flash",
|
|
22
|
+
temperature: Optional[float] = None,
|
|
23
|
+
max_tokens: Optional[int] = None,
|
|
24
|
+
user_id: Optional[str] = None,
|
|
25
|
+
) -> ChatResponse:
|
|
26
|
+
"""
|
|
27
|
+
Send a chat completion request (non-streaming).
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
messages: List of message dicts with 'role' and 'content'
|
|
31
|
+
model: AI model to use (default: gemini-2.5-flash)
|
|
32
|
+
temperature: Sampling temperature (0-1)
|
|
33
|
+
max_tokens: Maximum tokens in response
|
|
34
|
+
user_id: Optional user ID for rate limiting
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
ChatResponse with content, usage, and cost
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
AuthenticationError: Invalid API key
|
|
41
|
+
RateLimitError: Rate limit exceeded
|
|
42
|
+
SafetyError: Content blocked by safety filters
|
|
43
|
+
"""
|
|
44
|
+
payload: Dict[str, Any] = {
|
|
45
|
+
"messages": messages,
|
|
46
|
+
"model": model,
|
|
47
|
+
"stream": False,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if temperature is not None:
|
|
51
|
+
payload["temperature"] = temperature
|
|
52
|
+
if max_tokens is not None:
|
|
53
|
+
payload["maxTokens"] = max_tokens
|
|
54
|
+
if user_id is not None:
|
|
55
|
+
payload["userId"] = user_id
|
|
56
|
+
|
|
57
|
+
data = self._client._request("POST", "/api/ai/chat", json=payload)
|
|
58
|
+
|
|
59
|
+
return ChatResponse(
|
|
60
|
+
content=data["content"],
|
|
61
|
+
model=data["model"],
|
|
62
|
+
provider=data["provider"],
|
|
63
|
+
usage=Usage(
|
|
64
|
+
prompt_tokens=data["usage"]["prompt_tokens"],
|
|
65
|
+
completion_tokens=data["usage"]["completion_tokens"],
|
|
66
|
+
total_tokens=data["usage"]["total_tokens"],
|
|
67
|
+
),
|
|
68
|
+
cost_usd=data["cost_usd"],
|
|
69
|
+
finish_reason=data["finish_reason"],
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
def chat_stream(
|
|
73
|
+
self,
|
|
74
|
+
messages: List[Dict[str, str]],
|
|
75
|
+
model: str = "gemini-2.5-flash",
|
|
76
|
+
temperature: Optional[float] = None,
|
|
77
|
+
max_tokens: Optional[int] = None,
|
|
78
|
+
user_id: Optional[str] = None,
|
|
79
|
+
) -> Iterator[StreamChunk]:
|
|
80
|
+
"""
|
|
81
|
+
Send a chat completion request with streaming.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
messages: List of message dicts with 'role' and 'content'
|
|
85
|
+
model: AI model to use (default: gemini-2.5-flash)
|
|
86
|
+
temperature: Sampling temperature (0-1)
|
|
87
|
+
max_tokens: Maximum tokens in response
|
|
88
|
+
user_id: Optional user ID for rate limiting
|
|
89
|
+
|
|
90
|
+
Yields:
|
|
91
|
+
StreamChunk objects with delta text
|
|
92
|
+
|
|
93
|
+
Raises:
|
|
94
|
+
AuthenticationError: Invalid API key
|
|
95
|
+
RateLimitError: Rate limit exceeded
|
|
96
|
+
SafetyError: Content blocked by safety filters
|
|
97
|
+
"""
|
|
98
|
+
payload: Dict[str, Any] = {
|
|
99
|
+
"messages": messages,
|
|
100
|
+
"model": model,
|
|
101
|
+
"stream": True,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if temperature is not None:
|
|
105
|
+
payload["temperature"] = temperature
|
|
106
|
+
if max_tokens is not None:
|
|
107
|
+
payload["maxTokens"] = max_tokens
|
|
108
|
+
if user_id is not None:
|
|
109
|
+
payload["userId"] = user_id
|
|
110
|
+
|
|
111
|
+
url = f"{self._client._base_url}/api/ai/chat"
|
|
112
|
+
headers = {
|
|
113
|
+
"Content-Type": "application/json",
|
|
114
|
+
"CENCORI_API_KEY": self._client._api_key,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
with httpx.Client(timeout=60.0) as http_client:
|
|
118
|
+
with http_client.stream("POST", url, json=payload, headers=headers) as response:
|
|
119
|
+
if response.status_code == 401:
|
|
120
|
+
raise AuthenticationError()
|
|
121
|
+
if response.status_code == 429:
|
|
122
|
+
raise RateLimitError()
|
|
123
|
+
if not response.is_success:
|
|
124
|
+
raise CencoriError(f"Request failed with status {response.status_code}")
|
|
125
|
+
|
|
126
|
+
for line in response.iter_lines():
|
|
127
|
+
if not line or not line.startswith("data: "):
|
|
128
|
+
continue
|
|
129
|
+
|
|
130
|
+
data_str = line[6:] # Remove "data: " prefix
|
|
131
|
+
|
|
132
|
+
if data_str == "[DONE]":
|
|
133
|
+
return
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
data = json.loads(data_str)
|
|
137
|
+
yield StreamChunk(
|
|
138
|
+
delta=data.get("delta", ""),
|
|
139
|
+
finish_reason=data.get("finish_reason"),
|
|
140
|
+
)
|
|
141
|
+
except json.JSONDecodeError:
|
|
142
|
+
continue
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Cencori SDK client."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, Optional
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from .ai import AIModule
|
|
8
|
+
from .errors import AuthenticationError, CencoriError, RateLimitError, SafetyError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Cencori:
|
|
12
|
+
"""
|
|
13
|
+
Cencori SDK client.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
api_key: Your Cencori API key
|
|
17
|
+
base_url: API base URL (default: https://cencori.com)
|
|
18
|
+
timeout: Request timeout in seconds (default: 30)
|
|
19
|
+
|
|
20
|
+
Example:
|
|
21
|
+
>>> from cencori import Cencori
|
|
22
|
+
>>> cencori = Cencori(api_key="your-api-key")
|
|
23
|
+
>>> response = cencori.ai.chat(
|
|
24
|
+
... messages=[{"role": "user", "content": "Hello!"}]
|
|
25
|
+
... )
|
|
26
|
+
>>> print(response.content)
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
api_key: str,
|
|
32
|
+
base_url: str = "https://cencori.com",
|
|
33
|
+
timeout: float = 30.0,
|
|
34
|
+
) -> None:
|
|
35
|
+
if not api_key:
|
|
36
|
+
raise ValueError("API key is required")
|
|
37
|
+
|
|
38
|
+
self._api_key = api_key
|
|
39
|
+
self._base_url = base_url.rstrip("/")
|
|
40
|
+
self._timeout = timeout
|
|
41
|
+
|
|
42
|
+
# Initialize modules
|
|
43
|
+
self.ai = AIModule(self)
|
|
44
|
+
|
|
45
|
+
def _request(
|
|
46
|
+
self,
|
|
47
|
+
method: str,
|
|
48
|
+
endpoint: str,
|
|
49
|
+
json: Optional[Dict[str, Any]] = None,
|
|
50
|
+
headers: Optional[Dict[str, str]] = None,
|
|
51
|
+
) -> Dict[str, Any]:
|
|
52
|
+
"""Make an HTTP request to the Cencori API."""
|
|
53
|
+
url = f"{self._base_url}{endpoint}"
|
|
54
|
+
|
|
55
|
+
request_headers = {
|
|
56
|
+
"Content-Type": "application/json",
|
|
57
|
+
"CENCORI_API_KEY": self._api_key,
|
|
58
|
+
}
|
|
59
|
+
if headers:
|
|
60
|
+
request_headers.update(headers)
|
|
61
|
+
|
|
62
|
+
with httpx.Client(timeout=self._timeout) as client:
|
|
63
|
+
response = client.request(
|
|
64
|
+
method=method,
|
|
65
|
+
url=url,
|
|
66
|
+
json=json,
|
|
67
|
+
headers=request_headers,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# Handle errors
|
|
71
|
+
if response.status_code == 401:
|
|
72
|
+
raise AuthenticationError()
|
|
73
|
+
|
|
74
|
+
if response.status_code == 429:
|
|
75
|
+
raise RateLimitError()
|
|
76
|
+
|
|
77
|
+
data = response.json()
|
|
78
|
+
|
|
79
|
+
if response.status_code == 400 and "reasons" in data:
|
|
80
|
+
raise SafetyError(
|
|
81
|
+
message=data.get("error", "Content safety violation"),
|
|
82
|
+
reasons=data.get("reasons", []),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
if not response.is_success:
|
|
86
|
+
raise CencoriError(
|
|
87
|
+
message=data.get("error", "Request failed"),
|
|
88
|
+
status_code=response.status_code,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
return data
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Custom error classes for Cencori SDK."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional, List
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CencoriError(Exception):
|
|
7
|
+
"""Base exception for Cencori SDK errors."""
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
message: str,
|
|
12
|
+
status_code: Optional[int] = None,
|
|
13
|
+
code: Optional[str] = None,
|
|
14
|
+
):
|
|
15
|
+
super().__init__(message)
|
|
16
|
+
self.message = message
|
|
17
|
+
self.status_code = status_code
|
|
18
|
+
self.code = code
|
|
19
|
+
|
|
20
|
+
def __str__(self) -> str:
|
|
21
|
+
return self.message
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AuthenticationError(CencoriError):
|
|
25
|
+
"""Raised when API key is invalid or missing."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, message: str = "Invalid API key"):
|
|
28
|
+
super().__init__(message, status_code=401, code="INVALID_API_KEY")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class RateLimitError(CencoriError):
|
|
32
|
+
"""Raised when rate limit is exceeded."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, message: str = "Rate limit exceeded"):
|
|
35
|
+
super().__init__(message, status_code=429, code="RATE_LIMIT_EXCEEDED")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SafetyError(CencoriError):
|
|
39
|
+
"""Raised when content violates safety policies."""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
message: str = "Content safety violation",
|
|
44
|
+
reasons: Optional[List[str]] = None,
|
|
45
|
+
):
|
|
46
|
+
super().__init__(message, status_code=400, code="SAFETY_VIOLATION")
|
|
47
|
+
self.reasons = reasons or []
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Type definitions for Cencori SDK."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import List, Literal, Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class Message:
|
|
9
|
+
"""A chat message."""
|
|
10
|
+
role: Literal["system", "user", "assistant"]
|
|
11
|
+
content: str
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class ChatParams:
|
|
16
|
+
"""Parameters for chat completion."""
|
|
17
|
+
messages: List[Message]
|
|
18
|
+
model: str = "gemini-2.5-flash"
|
|
19
|
+
temperature: Optional[float] = None
|
|
20
|
+
max_tokens: Optional[int] = None
|
|
21
|
+
stream: bool = False
|
|
22
|
+
user_id: Optional[str] = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class Usage:
|
|
27
|
+
"""Token usage statistics."""
|
|
28
|
+
prompt_tokens: int
|
|
29
|
+
completion_tokens: int
|
|
30
|
+
total_tokens: int
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class ChatResponse:
|
|
35
|
+
"""Response from chat completion."""
|
|
36
|
+
content: str
|
|
37
|
+
model: str
|
|
38
|
+
provider: str
|
|
39
|
+
usage: Usage
|
|
40
|
+
cost_usd: float
|
|
41
|
+
finish_reason: Literal["stop", "length", "content_filter", "error"]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class StreamChunk:
|
|
46
|
+
"""A chunk from streaming response."""
|
|
47
|
+
delta: str
|
|
48
|
+
finish_reason: Optional[Literal["stop", "length", "content_filter", "error"]] = None
|