@codetunezstudios/token-kit 0.1.0-beta.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 Codetunez Studios
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,258 @@
1
+ # @codetunezstudios/token-kit
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@codetunezstudios/token-kit.svg)](https://www.npmjs.com/package/@codetunezstudios/token-kit)
4
+ [![license](https://img.shields.io/npm/l/@codetunezstudios/token-kit.svg)](https://github.com/codetunez-studios/token-kit/blob/main/LICENSE)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0%2B-blue)](https://www.typescriptlang.org/)
6
+ [![Node.js](https://img.shields.io/badge/Node.js-%3E%3D18-green)](https://nodejs.org/)
7
+
8
+ > **Beta** — This SDK is under active development. APIs may change before 1.0.
9
+
10
+ Official TypeScript/JavaScript SDK for [token-kit](https://token-kit.com) — the AI token infrastructure platform for developers.
11
+
12
+ token-kit enables developers to integrate LLM features into their applications using an end-user-funded token model. Users purchase tokens, developers consume them for AI operations.
13
+
14
+ ## Features
15
+
16
+ - **Simple API** — Intuitive methods for chat completions
17
+ - **TypeScript First** — Full type safety and IntelliSense support
18
+ - **Multiple Models** — Support for GPT-3.5, GPT-4, GPT-4 Turbo (more coming)
19
+ - **Token Management** — Built-in balance checking and validation
20
+ - **Error Handling** — Comprehensive typed error classes
21
+ - **Lightweight** — Single runtime dependency (axios)
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install @codetunezstudios/token-kit
27
+ ```
28
+
29
+ ```bash
30
+ yarn add @codetunezstudios/token-kit
31
+ ```
32
+
33
+ ```bash
34
+ pnpm add @codetunezstudios/token-kit
35
+ ```
36
+
37
+ ## Quick Start
38
+
39
+ ```typescript
40
+ import TokenKit from '@codetunezstudios/token-kit';
41
+
42
+ // Initialize with your developer API key
43
+ const tk = new TokenKit({
44
+ apiKey: process.env.TOKENKIT_API_KEY!,
45
+ });
46
+
47
+ // Make a chat request
48
+ const res = await tk.chat('user_token_here', [
49
+ TokenKit.user('What is token-kit?'),
50
+ ]);
51
+
52
+ console.log(res.message.content);
53
+ console.log('Tokens used:', res.tokensDeducted);
54
+ console.log('Balance:', res.userBalance);
55
+ ```
56
+
57
+ ## API Reference
58
+
59
+ ### Constructor
60
+
61
+ ```typescript
62
+ const tk = new TokenKit(config);
63
+ ```
64
+
65
+ | Option | Type | Required | Default | Description |
66
+ |--------|------|----------|---------|-------------|
67
+ | `apiKey` | `string` | Yes | — | Developer API key |
68
+ | `baseUrl` | `string` | No | `https://api.token-kit.com/api/v1` | API base URL |
69
+ | `timeout` | `number` | No | `60000` | Request timeout (ms) |
70
+
71
+ ### Methods
72
+
73
+ #### `tk.chat(userToken, messages, options?)`
74
+
75
+ Send a chat completion request.
76
+
77
+ ```typescript
78
+ const res = await tk.chat('user_token', [
79
+ TokenKit.system('You are a helpful assistant.'),
80
+ TokenKit.user('Explain quantum computing simply.'),
81
+ ], {
82
+ model: 'gpt-4',
83
+ maxTokens: 200,
84
+ temperature: 0.8,
85
+ });
86
+ ```
87
+
88
+ **Options:**
89
+
90
+ | Option | Type | Default | Description |
91
+ |--------|------|---------|-------------|
92
+ | `model` | `string` | `gpt-3.5-turbo` | LLM model to use |
93
+ | `maxTokens` | `number` | `500` | Max tokens in response |
94
+ | `temperature` | `number` | `0.7` | Randomness (0–2) |
95
+
96
+ **Returns** `ChatResponse`:
97
+
98
+ ```typescript
99
+ {
100
+ id: string;
101
+ model: string;
102
+ message: { role: 'assistant'; content: string };
103
+ tokensUsed: { prompt: number; completion: number; total: number };
104
+ tokensDeducted: number;
105
+ finishReason: string;
106
+ userBalance?: number;
107
+ latency?: number;
108
+ }
109
+ ```
110
+
111
+ #### `tk.setUserToken(userToken)`
112
+
113
+ Set the user token for subsequent requests so you don't have to pass it each time.
114
+
115
+ ```typescript
116
+ tk.setUserToken('user_token');
117
+
118
+ // Now you can omit the userToken parameter
119
+ const res = await tk.chat([TokenKit.user('Hello!')]);
120
+ ```
121
+
122
+ #### `tk.validateToken(userToken?)`
123
+
124
+ Validate a user token and check balance/limits.
125
+
126
+ ```typescript
127
+ const info = await tk.validateToken('user_token');
128
+ if (info.valid) {
129
+ console.log('Balance:', info.balance);
130
+ }
131
+ ```
132
+
133
+ #### `tk.getBalance(userToken?)`
134
+
135
+ Get the current token balance.
136
+
137
+ ```typescript
138
+ const balance = await tk.getBalance('user_token');
139
+ ```
140
+
141
+ #### `tk.getModels()`
142
+
143
+ List available LLM models.
144
+
145
+ ```typescript
146
+ const models = await tk.getModels();
147
+ // ['gpt-3.5-turbo', 'gpt-4', 'gpt-4-turbo']
148
+ ```
149
+
150
+ ### Helper Methods
151
+
152
+ ```typescript
153
+ TokenKit.user('message') // { role: 'user', content: 'message' }
154
+ TokenKit.system('message') // { role: 'system', content: 'message' }
155
+ TokenKit.assistant('message') // { role: 'assistant', content: 'message' }
156
+ ```
157
+
158
+ ## Error Handling
159
+
160
+ ```typescript
161
+ import TokenKit, { TokenKitAPIError } from '@codetunezstudios/token-kit';
162
+
163
+ try {
164
+ const res = await tk.chat(userToken, messages);
165
+ } catch (err) {
166
+ if (err instanceof TokenKitAPIError) {
167
+ console.error(err.code); // 'INSUFFICIENT_BALANCE'
168
+ console.error(err.statusCode); // 402
169
+ console.error(err.message); // 'Insufficient token balance'
170
+ }
171
+ }
172
+ ```
173
+
174
+ **Error codes:**
175
+
176
+ | Code | Status | Description |
177
+ |------|--------|-------------|
178
+ | `INVALID_API_KEY` | 401 | Developer API key is invalid |
179
+ | `INVALID_TOKEN` | 401 | User token is invalid or expired |
180
+ | `INSUFFICIENT_BALANCE` | 402 | Not enough tokens |
181
+ | `RATE_LIMIT_EXCEEDED` | 429 | Too many requests |
182
+ | `DAILY_LIMIT_EXCEEDED` | 429 | Daily spending limit reached |
183
+ | `MONTHLY_LIMIT_EXCEEDED` | 429 | Monthly spending limit reached |
184
+ | `MODEL_NOT_SUPPORTED` | 400 | Requested model is not available |
185
+ | `TIMEOUT` | 504 | Request timed out |
186
+ | `NETWORK_ERROR` | 503 | Cannot reach token-kit API |
187
+
188
+ ## Express Integration Example
189
+
190
+ ```typescript
191
+ import express from 'express';
192
+ import TokenKit from '@codetunezstudios/token-kit';
193
+
194
+ const app = express();
195
+ const tk = new TokenKit({ apiKey: process.env.TOKENKIT_API_KEY! });
196
+
197
+ app.post('/api/chat', async (req, res) => {
198
+ try {
199
+ const { userToken, message } = req.body;
200
+ const result = await tk.chat(userToken, [TokenKit.user(message)]);
201
+ res.json({ reply: result.message.content, balance: result.userBalance });
202
+ } catch (err) {
203
+ res.status(500).json({ error: 'Chat failed' });
204
+ }
205
+ });
206
+ ```
207
+
208
+ > **Security:** Never expose your developer API key in client-side code. Always proxy requests through your backend.
209
+
210
+ ## Token Pricing
211
+
212
+ Different models consume tokens at different rates:
213
+
214
+ | Model | Rate | 1,000 TK tokens = |
215
+ |-------|------|-------------------|
216
+ | GPT-3.5 Turbo | 1.0x | 1,000 LLM tokens |
217
+ | GPT-4 Turbo | 2.0x | 500 LLM tokens |
218
+ | GPT-4 | 3.0x | 333 LLM tokens |
219
+
220
+ See [token-kit.com](https://token-kit.com) for current package pricing and details.
221
+
222
+ ## Requirements
223
+
224
+ - Node.js >= 18
225
+ - TypeScript >= 5.0 (recommended)
226
+
227
+ ## Development
228
+
229
+ ```bash
230
+ git clone https://github.com/codetunez-studios/token-kit.git
231
+ cd token-kit
232
+ npm install # Install dependencies
233
+ npm run build # Build (CJS + ESM + types)
234
+ npm test # Run tests
235
+ npm run typecheck # Type checking
236
+ ```
237
+
238
+ ## Contributing
239
+
240
+ Contributions are welcome! Please open an issue or submit a pull request.
241
+
242
+ 1. Fork the repository
243
+ 2. Create your feature branch (`git checkout -b feature/my-feature`)
244
+ 3. Commit your changes (`git commit -m 'Add my feature'`)
245
+ 4. Push to the branch (`git push origin feature/my-feature`)
246
+ 5. Open a Pull Request
247
+
248
+ ## License
249
+
250
+ [MIT](LICENSE) © [Codetunez Studios](https://github.com/codetunez-studios)
251
+
252
+ ## Links
253
+
254
+ - [token-kit Platform](https://token-kit.com)
255
+ - [User Token Portal](https://ai-tokens.me)
256
+ - [Documentation](https://token-kit.com/sdk)
257
+ - [npm Package](https://www.npmjs.com/package/@codetunezstudios/token-kit)
258
+ - [GitHub Issues](https://github.com/codetunez-studios/token-kit/issues)
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Token-Kit SDK - Type Definitions
3
+ * TypeScript types for the Token-Kit SDK
4
+ */
5
+ type MessageRole = 'system' | 'user' | 'assistant';
6
+ interface Message {
7
+ role: MessageRole;
8
+ content: string;
9
+ }
10
+ interface ChatOptions {
11
+ /** LLM model to use (default: 'gpt-3.5-turbo') */
12
+ model?: string;
13
+ /** Maximum tokens in response (default: 500) */
14
+ maxTokens?: number;
15
+ /** Temperature for response randomness 0-2 (default: 0.7) */
16
+ temperature?: number;
17
+ }
18
+ interface ChatResponse {
19
+ /** Unique chat completion ID */
20
+ id: string;
21
+ /** Model used for completion */
22
+ model: string;
23
+ /** Assistant's response message */
24
+ message: Message;
25
+ /** Token usage statistics */
26
+ tokensUsed: {
27
+ prompt: number;
28
+ completion: number;
29
+ total: number;
30
+ };
31
+ /** Number of tokens deducted from user balance */
32
+ tokensDeducted: number;
33
+ /** Reason completion finished */
34
+ finishReason: string;
35
+ /** User's remaining token balance */
36
+ userBalance?: number;
37
+ /** Response latency in milliseconds */
38
+ latency?: number;
39
+ }
40
+ interface TokenValidationResponse {
41
+ /** Whether the token is valid */
42
+ valid: boolean;
43
+ /** User information */
44
+ user?: {
45
+ id: string;
46
+ email: string;
47
+ };
48
+ /** Current token balance */
49
+ balance?: number;
50
+ /** Daily spending so far */
51
+ dailySpending?: number;
52
+ /** Monthly spending so far */
53
+ monthlySpending?: number;
54
+ /** Spending limits */
55
+ limits?: {
56
+ dailyLimit: number;
57
+ monthlyLimit: number;
58
+ perRequestLimit: number;
59
+ };
60
+ }
61
+ interface ModelInfo {
62
+ /** Model identifier */
63
+ name: string;
64
+ /** Human-readable model name */
65
+ displayName: string;
66
+ /** Token rate multiplier */
67
+ tokenRate: number;
68
+ /** Default max tokens */
69
+ defaultMaxTokens: number;
70
+ }
71
+ interface ModelsResponse {
72
+ models: string[];
73
+ count: number;
74
+ }
75
+ interface TokenKitError extends Error {
76
+ /** Error code */
77
+ code: string;
78
+ /** HTTP status code */
79
+ statusCode?: number;
80
+ /** Additional error details */
81
+ details?: unknown;
82
+ }
83
+ declare class TokenKitAPIError extends Error implements TokenKitError {
84
+ code: string;
85
+ statusCode?: number;
86
+ details?: unknown;
87
+ constructor(message: string, code: string, statusCode?: number, details?: unknown);
88
+ }
89
+ interface TokenKitConfig {
90
+ /** Developer API key */
91
+ apiKey: string;
92
+ /** API Gateway base URL (default: https://api.token-kit.com) */
93
+ baseUrl?: string;
94
+ /** Request timeout in milliseconds (default: 60000) */
95
+ timeout?: number;
96
+ }
97
+
98
+ /**
99
+ * Token-Kit SDK - Main Entry Point
100
+ * Official TypeScript SDK for Token-Kit platform
101
+ */
102
+
103
+ /**
104
+ * TokenKit - Main SDK class
105
+ *
106
+ * Example usage:
107
+ * ```typescript
108
+ * const tokenKit = new TokenKit({ apiKey: 'your-api-key' });
109
+ *
110
+ * const response = await tokenKit.chat('user-token', [
111
+ * { role: 'user', content: 'Hello!' }
112
+ * ]);
113
+ *
114
+ * console.log(response.message.content);
115
+ * ```
116
+ */
117
+ declare class TokenKit {
118
+ private client;
119
+ private userToken;
120
+ /**
121
+ * Create a new TokenKit instance
122
+ *
123
+ * @param config - Configuration options
124
+ * @param config.apiKey - Your developer API key
125
+ * @param config.baseUrl - API base URL (optional, defaults to production)
126
+ * @param config.timeout - Request timeout in ms (optional, defaults to 60000)
127
+ */
128
+ constructor(config: TokenKitConfig);
129
+ /**
130
+ * Set the user token for subsequent requests
131
+ * This allows you to omit the userToken parameter in other methods
132
+ *
133
+ * @param userToken - The user's token
134
+ */
135
+ setUserToken(userToken: string): void;
136
+ /**
137
+ * Send a chat completion request
138
+ *
139
+ * @param userTokenOrMessages - User token string OR array of messages (if user token was set)
140
+ * @param messagesOrOptions - Array of messages OR chat options (if first param is user token)
141
+ * @param options - Chat options (only if first two params are provided)
142
+ * @returns Chat completion response
143
+ *
144
+ * @example
145
+ * ```typescript
146
+ * // With explicit user token
147
+ * const response = await tokenKit.chat('user-token', [
148
+ * { role: 'user', content: 'What is Token-Kit?' }
149
+ * ]);
150
+ *
151
+ * // With pre-set user token
152
+ * tokenKit.setUserToken('user-token');
153
+ * const response = await tokenKit.chat([
154
+ * { role: 'user', content: 'What is Token-Kit?' }
155
+ * ]);
156
+ *
157
+ * // With options
158
+ * const response = await tokenKit.chat('user-token', [
159
+ * { role: 'system', content: 'You are a helpful assistant.' },
160
+ * { role: 'user', content: 'Hello!' }
161
+ * ], {
162
+ * model: 'gpt-4',
163
+ * maxTokens: 200,
164
+ * temperature: 0.8
165
+ * });
166
+ * ```
167
+ */
168
+ chat(userTokenOrMessages: string | Message[], messagesOrOptions?: Message[] | ChatOptions, options?: ChatOptions): Promise<ChatResponse>;
169
+ /**
170
+ * Validate a user token and check balance
171
+ *
172
+ * @param userToken - User token to validate (optional if already set)
173
+ * @returns Token validation response with balance and limits
174
+ *
175
+ * @example
176
+ * ```typescript
177
+ * const validation = await tokenKit.validateToken('user-token');
178
+ * console.log('Balance:', validation.balance);
179
+ * console.log('Daily spending:', validation.dailySpending);
180
+ * ```
181
+ */
182
+ validateToken(userToken?: string): Promise<TokenValidationResponse>;
183
+ /**
184
+ * Get balance for the current user token
185
+ *
186
+ * @param userToken - User token (optional if already set)
187
+ * @returns Current token balance
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * const balance = await tokenKit.getBalance('user-token');
192
+ * console.log(`You have ${balance} tokens remaining`);
193
+ * ```
194
+ */
195
+ getBalance(userToken?: string): Promise<number>;
196
+ /**
197
+ * Get list of available LLM models
198
+ *
199
+ * @returns Array of model names
200
+ *
201
+ * @example
202
+ * ```typescript
203
+ * const models = await tokenKit.getModels();
204
+ * console.log('Available models:', models);
205
+ * // ['gpt-3.5-turbo', 'gpt-4', 'gpt-4-turbo']
206
+ * ```
207
+ */
208
+ getModels(): Promise<string[]>;
209
+ /**
210
+ * Helper method to create a simple user message
211
+ *
212
+ * @param content - Message content
213
+ * @returns Message object
214
+ */
215
+ static user(content: string): Message;
216
+ /**
217
+ * Helper method to create a system message
218
+ *
219
+ * @param content - Message content
220
+ * @returns Message object
221
+ */
222
+ static system(content: string): Message;
223
+ /**
224
+ * Helper method to create an assistant message
225
+ *
226
+ * @param content - Message content
227
+ * @returns Message object
228
+ */
229
+ static assistant(content: string): Message;
230
+ }
231
+
232
+ export { type ChatOptions, type ChatResponse, type Message, type MessageRole, type ModelInfo, type ModelsResponse, TokenKit, TokenKitAPIError, type TokenKitConfig, type TokenValidationResponse, TokenKit as default };