datacoder 0.2.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.
datacoder/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """DataCoder — Python SDK for DataCoder AI Data Analyst Platform."""
2
+
3
+ from .client import DataCoderSDK
4
+
5
+ __version__ = "0.2.0"
6
+ __all__ = ["DataCoderSDK"]
datacoder/client.py ADDED
@@ -0,0 +1,231 @@
1
+ """DataCoder SDK client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ import requests
9
+
10
+
11
+ @dataclass
12
+ class RAGResult:
13
+ """Result from a RAG query."""
14
+
15
+ query: str
16
+ folder_id: str
17
+ results: list[dict[str, Any]]
18
+ count: int
19
+
20
+ @property
21
+ def answer(self) -> str:
22
+ """Concatenated content from all results."""
23
+ return "\n\n".join(r.get("content", "") for r in self.results)
24
+
25
+ @property
26
+ def sources(self) -> list[str]:
27
+ """List of source document names."""
28
+ return [r.get("source", "") for r in self.results if r.get("source")]
29
+
30
+ def __repr__(self) -> str:
31
+ return f"RAGResult(count={self.count}, sources={self.sources[:3]})"
32
+
33
+
34
+ @dataclass
35
+ class QuotaInfo:
36
+ """Current quota usage information."""
37
+
38
+ plan: str
39
+ chat_used_today: int
40
+ chat_limit: int
41
+ chat_rate_limit: int
42
+ sdk_used_today: int
43
+ sdk_limit: int
44
+ sdk_rate_limit: int
45
+
46
+ @property
47
+ def sdk_remaining(self) -> int:
48
+ if self.sdk_limit == -1:
49
+ return -1
50
+ return max(0, self.sdk_limit - self.sdk_used_today)
51
+
52
+ def __repr__(self) -> str:
53
+ remaining = "unlimited" if self.sdk_limit == -1 else self.sdk_remaining
54
+ return f"QuotaInfo(plan={self.plan}, sdk_remaining={remaining})"
55
+
56
+
57
+ class DataCoderError(Exception):
58
+ """Base exception for DataCoder SDK errors."""
59
+
60
+ def __init__(self, message: str, status_code: int = 0, response: dict | None = None):
61
+ super().__init__(message)
62
+ self.status_code = status_code
63
+ self.response = response or {}
64
+
65
+
66
+ class AuthenticationError(DataCoderError):
67
+ """Invalid or missing API key."""
68
+
69
+
70
+ class QuotaExceededError(DataCoderError):
71
+ """Daily quota or rate limit exceeded."""
72
+
73
+ def __init__(self, message: str, retry_after: int = 0, **kwargs):
74
+ super().__init__(message, **kwargs)
75
+ self.retry_after = retry_after
76
+
77
+
78
+ class NotFoundError(DataCoderError):
79
+ """Resource not found."""
80
+
81
+
82
+ class ForbiddenError(DataCoderError):
83
+ """Access denied to this resource."""
84
+
85
+
86
+ @dataclass
87
+ class DataCoderSDK:
88
+ """DataCoder SDK — programmatic access to RAG knowledge bases.
89
+
90
+ Usage::
91
+
92
+ from datacoder_sdk import DataCoderSDK
93
+
94
+ sdk = DataCoderSDK(
95
+ api_key="dc_sk_...",
96
+ base_url="https://datacoder.clouditia.com",
97
+ )
98
+
99
+ # Query a knowledge base
100
+ result = sdk.query(folder_id="xxx-xxx", query="What are the risks?")
101
+ print(result.answer)
102
+ print(result.sources)
103
+
104
+ # Check quota
105
+ quota = sdk.quota()
106
+ print(f"Remaining: {quota.sdk_remaining}")
107
+
108
+ # List accessible folders
109
+ folders = sdk.folders()
110
+ """
111
+
112
+ api_key: str
113
+ base_url: str = "https://datacoder.clouditia.com"
114
+ timeout: int = 30
115
+ _session: requests.Session = field(default_factory=requests.Session, repr=False)
116
+
117
+ def __post_init__(self):
118
+ self.base_url = self.base_url.rstrip("/")
119
+ self._session.headers.update({
120
+ "Authorization": f"Bearer {self.api_key}",
121
+ "Content-Type": "application/json",
122
+ "User-Agent": f"datacoder-sdk-python/0.1.0",
123
+ })
124
+
125
+ def _request(self, method: str, path: str, **kwargs) -> dict:
126
+ """Make an authenticated API request."""
127
+ url = f"{self.base_url}/api/v1/auth{path}"
128
+ kwargs.setdefault("timeout", self.timeout)
129
+
130
+ try:
131
+ resp = self._session.request(method, url, **kwargs)
132
+ except requests.ConnectionError as e:
133
+ raise DataCoderError(f"Connection failed: {e}") from e
134
+ except requests.Timeout as e:
135
+ raise DataCoderError(f"Request timed out after {self.timeout}s") from e
136
+
137
+ if resp.status_code == 401:
138
+ raise AuthenticationError(
139
+ "Invalid or expired SDK key",
140
+ status_code=401,
141
+ response=resp.json() if resp.text else {},
142
+ )
143
+ if resp.status_code == 403:
144
+ raise ForbiddenError(
145
+ resp.json().get("error", "Access denied"),
146
+ status_code=403,
147
+ response=resp.json() if resp.text else {},
148
+ )
149
+ if resp.status_code == 404:
150
+ raise NotFoundError(
151
+ resp.json().get("error", "Not found"),
152
+ status_code=404,
153
+ response=resp.json() if resp.text else {},
154
+ )
155
+ if resp.status_code == 429:
156
+ data = resp.json() if resp.text else {}
157
+ raise QuotaExceededError(
158
+ data.get("error", "Rate limit or quota exceeded"),
159
+ status_code=429,
160
+ retry_after=int(resp.headers.get("Retry-After", data.get("retry_after", 0))),
161
+ response=data,
162
+ )
163
+ if resp.status_code >= 400:
164
+ data = resp.json() if resp.text else {}
165
+ raise DataCoderError(
166
+ data.get("error", f"HTTP {resp.status_code}"),
167
+ status_code=resp.status_code,
168
+ response=data,
169
+ )
170
+
171
+ return resp.json()
172
+
173
+ def query(self, folder_id: str, query: str, top_k: int = 10) -> RAGResult:
174
+ """Query a RAG knowledge base.
175
+
176
+ Args:
177
+ folder_id: UUID of the knowledge folder to search.
178
+ query: Natural language question.
179
+ top_k: Maximum number of results (1-20, default 10).
180
+
181
+ Returns:
182
+ RAGResult with matching chunks, sources and scores.
183
+
184
+ Raises:
185
+ AuthenticationError: Invalid SDK key.
186
+ QuotaExceededError: Daily quota or rate limit reached.
187
+ ForbiddenError: SDK key doesn't have access to this folder.
188
+ NotFoundError: Folder not found.
189
+ """
190
+ data = self._request("POST", "/sdk/rag/query/", json={
191
+ "folder_id": str(folder_id),
192
+ "query": query,
193
+ "top_k": min(max(1, top_k), 20),
194
+ })
195
+ return RAGResult(
196
+ query=data.get("query", query),
197
+ folder_id=data.get("folder_id", folder_id),
198
+ results=data.get("results", []),
199
+ count=data.get("count", 0),
200
+ )
201
+
202
+ def quota(self) -> QuotaInfo:
203
+ """Check current quota usage.
204
+
205
+ Returns:
206
+ QuotaInfo with plan, usage counters and limits.
207
+ """
208
+ data = self._request("GET", "/sdk/quota/")
209
+ chat = data.get("chat", {})
210
+ sdk = data.get("sdk", {})
211
+ return QuotaInfo(
212
+ plan=data.get("plan", "free"),
213
+ chat_used_today=chat.get("used_today", 0),
214
+ chat_limit=chat.get("limit", 0),
215
+ chat_rate_limit=chat.get("rate_limit", 0),
216
+ sdk_used_today=sdk.get("used_today", 0),
217
+ sdk_limit=sdk.get("limit", 0),
218
+ sdk_rate_limit=sdk.get("rate_limit", 0),
219
+ )
220
+
221
+ def ping(self) -> bool:
222
+ """Check if the API is reachable and the key is valid.
223
+
224
+ Returns:
225
+ True if authenticated successfully.
226
+ """
227
+ try:
228
+ self.quota()
229
+ return True
230
+ except DataCoderError:
231
+ return False
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.4
2
+ Name: datacoder
3
+ Version: 0.2.0
4
+ Summary: Python SDK for DataCoder — AI Data Analyst Platform (RAG API)
5
+ Author-email: Clouditia <contact@clouditia.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://datacoder.clouditia.com
8
+ Project-URL: Documentation, https://datacoder.clouditia.com/docs
9
+ Project-URL: Repository, https://github.com/clouditia/datacoder
10
+ Keywords: datacoder,rag,sdk,ai,data-analyst
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.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ Requires-Dist: requests>=2.28
23
+
24
+ # DataCoder SDK
25
+
26
+ Python SDK for [DataCoder](https://datacoder.clouditia.com) — AI Data Analyst Platform.
27
+
28
+ Query your RAG knowledge bases programmatically.
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install datacoder
34
+ ```
35
+
36
+ ## Quick Start
37
+
38
+ ```python
39
+ from datacoder import DataCoderSDK
40
+
41
+ # Initialize with your SDK key and server URL
42
+ sdk = DataCoderSDK(
43
+ api_key="dc_sk_your_key_here",
44
+ base_url="https://datacoder.clouditia.com",
45
+ )
46
+
47
+ # Test connectivity
48
+ if sdk.ping():
49
+ print("Connected!")
50
+
51
+ # Query a knowledge base
52
+ result = sdk.query(
53
+ folder_id="your-folder-uuid",
54
+ query="Quels sont les risques de crédit dans Bâle III ?",
55
+ )
56
+
57
+ print(result.answer) # Combined text from all matching chunks
58
+ print(result.sources) # List of source document names
59
+ print(result.count) # Number of results
60
+
61
+ # Check your quota
62
+ quota = sdk.quota()
63
+ print(f"Plan: {quota.plan}")
64
+ print(f"SDK remaining today: {quota.sdk_remaining}")
65
+ ```
66
+
67
+ ## API Reference
68
+
69
+ ### `DataCoderSDK(api_key, base_url, timeout=30)`
70
+
71
+ Initialize the SDK client.
72
+
73
+ | Parameter | Type | Default | Description |
74
+ |-----------|------|---------|-------------|
75
+ | `api_key` | `str` | — | Your SDK key (starts with `dc_sk_`) |
76
+ | `base_url` | `str` | `https://datacoder.clouditia.com` | DataCoder server URL |
77
+ | `timeout` | `int` | `30` | Request timeout in seconds |
78
+
79
+ ### `sdk.query(folder_id, query, top_k=10) → RAGResult`
80
+
81
+ Query a RAG knowledge base.
82
+
83
+ | Parameter | Type | Default | Description |
84
+ |-----------|------|---------|-------------|
85
+ | `folder_id` | `str` | — | UUID of the knowledge folder |
86
+ | `query` | `str` | — | Natural language question |
87
+ | `top_k` | `int` | `10` | Max results (1-20) |
88
+
89
+ **Returns:** `RAGResult`
90
+
91
+ | Property | Type | Description |
92
+ |----------|------|-------------|
93
+ | `result.answer` | `str` | Concatenated content from all matching chunks |
94
+ | `result.sources` | `list[str]` | Source document names |
95
+ | `result.count` | `int` | Number of results |
96
+ | `result.results` | `list[dict]` | Raw results with `content`, `source`, `page`, `score` |
97
+ | `result.query` | `str` | Original query |
98
+ | `result.folder_id` | `str` | Folder queried |
99
+
100
+ ### `sdk.quota() → QuotaInfo`
101
+
102
+ Check current usage and limits.
103
+
104
+ | Property | Type | Description |
105
+ |----------|------|-------------|
106
+ | `quota.plan` | `str` | Current plan (`free`, `pro`, `enterprise`) |
107
+ | `quota.sdk_used_today` | `int` | SDK requests used today |
108
+ | `quota.sdk_limit` | `int` | Daily SDK limit (-1 = unlimited) |
109
+ | `quota.sdk_remaining` | `int` | Remaining SDK requests (-1 = unlimited) |
110
+ | `quota.sdk_rate_limit` | `int` | Max requests per minute |
111
+ | `quota.chat_used_today` | `int` | Chat messages used today |
112
+ | `quota.chat_limit` | `int` | Daily chat limit |
113
+ | `quota.chat_rate_limit` | `int` | Chat rate limit per minute |
114
+
115
+ ### `sdk.ping() → bool`
116
+
117
+ Test if the API is reachable and the key is valid. Returns `True` or `False`.
118
+
119
+ ## Plans & Quotas
120
+
121
+ | | Free | Pro (29€/mo) | Enterprise (99€/mo) |
122
+ |--|------|-------------|---------------------|
123
+ | SDK requests/day | 10 | 1,000 | 100,000 |
124
+ | SDK rate limit | 5/min | 100/min | 1,000/min |
125
+ | Chat messages/day | 20 | 200 | 50,000 |
126
+
127
+ ## Error Handling
128
+
129
+ ```python
130
+ from datacoder import DataCoderSDK
131
+ from datacoder.client import (
132
+ AuthenticationError,
133
+ QuotaExceededError,
134
+ ForbiddenError,
135
+ NotFoundError,
136
+ DataCoderError,
137
+ )
138
+
139
+ sdk = DataCoderSDK(api_key="dc_sk_...", base_url="https://...")
140
+
141
+ try:
142
+ result = sdk.query(folder_id="...", query="...")
143
+ except AuthenticationError:
144
+ print("Invalid or expired API key")
145
+ except QuotaExceededError as e:
146
+ print(f"Quota exceeded. Retry after {e.retry_after}s")
147
+ except ForbiddenError:
148
+ print("No access to this folder with this SDK key")
149
+ except NotFoundError:
150
+ print("Folder not found or not owned by this user")
151
+ except DataCoderError as e:
152
+ print(f"API error: {e} (HTTP {e.status_code})")
153
+ ```
154
+
155
+ ## Get your SDK Key
156
+
157
+ 1. Log in to [DataCoder](https://datacoder.clouditia.com)
158
+ 2. Go to **Settings → SDK**
159
+ 3. Enter a name and click **Generate**
160
+ 4. Copy your key (shown only once)
161
+
162
+ ## On-Premise
163
+
164
+ DataCoder can be deployed on your own infrastructure. Point `base_url` to your self-hosted instance:
165
+
166
+ ```python
167
+ sdk = DataCoderSDK(
168
+ api_key="dc_sk_...",
169
+ base_url="https://datacoder.your-company.com",
170
+ )
171
+ ```
172
+
173
+ ## License
174
+
175
+ MIT — [Clouditia](https://clouditia.com)
@@ -0,0 +1,6 @@
1
+ datacoder/__init__.py,sha256=gsCovq75F7z2glRlvuQ4_uF67M5BuGE27V7YlYkhUhE,155
2
+ datacoder/client.py,sha256=fS4R6k9QNT-NpMUgBx9cnnlxuYHOBiVOVVBA_Ln1utw,7105
3
+ datacoder-0.2.0.dist-info/METADATA,sha256=Bn4O6ILm3A7xuerCpgQ9-zie_oUqyxdNgmkxwUEbGcM,5294
4
+ datacoder-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ datacoder-0.2.0.dist-info/top_level.txt,sha256=1KTmDuB8GVRNTSmq-K2E9h_FGVE9qIcaN2XUcMZ3Lx0,10
6
+ datacoder-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ datacoder