@ragbits/api-client 0.0.2 → 1.3.0

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/README.md CHANGED
@@ -1,38 +1,54 @@
1
- # Ragbits API Client
1
+ # @ragbits/api-client
2
2
 
3
- A TypeScript client for communicating with the Ragbits API. This client provides methods for both regular HTTP requests and server-sent events (streaming) functionality.
3
+ A TypeScript client for communicating with the Ragbits API. This client provides type-safe methods for both regular HTTP requests and server-sent events (streaming) functionality.
4
+
5
+ ## Features
6
+
7
+ - **Type-safe API calls** - Full TypeScript support with predefined endpoints
8
+ - **Streaming support** - Real-time server-sent events with proper error handling
9
+ - **Modern JavaScript** - ES modules and CommonJS support
10
+ - **Abortable requests** - Cancel ongoing requests and streams
11
+ - **Error handling** - Comprehensive error handling with detailed error messages
12
+ - **Zero dependencies** - Lightweight with no runtime dependencies
4
13
 
5
14
  ## Installation
6
15
 
7
16
  ```bash
8
- npm install ragbits-api-client
17
+ npm install @ragbits/api-client
9
18
  ```
10
19
 
11
- ## Usage
20
+ ## Quick Start
12
21
 
13
22
  ```typescript
14
- import { RagbitsClient, type ChatResponse } from 'ragbits-api-client'
23
+ import { RagbitsClient } from '@ragbits/api-client'
15
24
 
16
25
  // Initialize the client
17
26
  const client = new RagbitsClient({
18
27
  baseUrl: 'http://127.0.0.1:8000', // Optional, defaults to http://127.0.0.1:8000
28
+ auth: {
29
+ getToken: () => 'token',
30
+ onUnauthorized: () => {
31
+ console.warn('⚠️ Unauthorized')
32
+ },
33
+ }, // Optional, used to provide auth details
19
34
  })
20
35
 
21
36
  // Get API configuration
22
- const config = await client.getConfig()
37
+ const config = await client.makeRequest('/api/config')
23
38
 
24
39
  // Send a chat message with streaming response
25
- const cleanup = client.sendChatMessage(
40
+ const cleanup = client.makeStreamRequest(
41
+ '/api/chat',
26
42
  {
27
43
  message: 'Hello!',
28
44
  history: [],
29
45
  context: {}, // Optional
30
46
  },
31
47
  {
32
- onMessage: (data: ChatResponse) => {
48
+ onMessage: (data) => {
33
49
  console.log('Received message:', data)
34
50
  },
35
- onError: (error: string) => {
51
+ onError: (error) => {
36
52
  console.error('Error:', error)
37
53
  },
38
54
  onClose: () => {
@@ -45,10 +61,13 @@ const cleanup = client.sendChatMessage(
45
61
  cleanup()
46
62
 
47
63
  // Send feedback
48
- await client.sendFeedback({
49
- message_id: 'message-123',
50
- feedback: 'like',
51
- payload: { reason: 'helpful' },
64
+ await client.makeRequest('/api/feedback', {
65
+ method: 'POST',
66
+ body: {
67
+ message_id: 'message-123',
68
+ feedback: 'like',
69
+ payload: { reason: 'helpful' },
70
+ },
52
71
  })
53
72
  ```
54
73
 
@@ -61,86 +80,211 @@ The main client class for interacting with the Ragbits API.
61
80
  #### Constructor
62
81
 
63
82
  ```typescript
64
- new RagbitsClient(config?: { baseUrl?: string })
83
+ new RagbitsClient(config?: ClientConfig)
65
84
  ```
66
85
 
86
+ **Parameters:**
87
+
67
88
  - `config.baseUrl` (optional): Base URL for the API. Defaults to 'http://127.0.0.1:8000'
89
+ - `config.auth` (optional): An object containing authentication details. Provide `getToken` to automatically attach `Authorization: Bearer <token>` to every request. `onUnauthorized` is called if the library encounters a 401 status code.
90
+
91
+ **Throws:** `Error` if the base URL is invalid
68
92
 
69
93
  #### Methods
70
94
 
71
- ##### `getConfig()`
95
+ ##### `getBaseUrl(): string`
72
96
 
73
- Get the API configuration.
97
+ Get the base URL used by this client.
74
98
 
75
- - Returns: `Promise<Record<string, unknown>>` - API configuration object
99
+ **Returns:** The configured base URL
76
100
 
77
- ##### `sendChatMessage(chatRequest, callbacks)`
101
+ ##### `async makeRequest<Endpoints, URL>(endpoint, options?): Promise<Result>`
78
102
 
79
- Send a chat message and receive streaming responses.
103
+ Make a type-safe API request to any endpoint. `endpoint` must be one of the key of `Endpoints` type
104
+ that define schema of the available endpoints. All default Ragbits routes are supported out of the box.
80
105
 
81
- - Parameters:
82
- - `chatRequest`: ChatRequest
83
- - `message`: string - User message
84
- - `history`: Array<{ role: string; content: string; id?: string }> - Chat history
85
- - `context`: Record<string, unknown> (optional) - Additional context
86
- - `callbacks`: StreamCallbacks
87
- - `onMessage`: (data: ChatResponse) => void | Promise<void> - Called when a message chunk is received
88
- - `onError`: (error: string) => void | Promise<void> - Called when an error occurs
89
- - `onClose`: () => void | Promise<void> (optional) - Called when the stream closes
90
- - Returns: `() => void` - Cleanup function to cancel the stream
106
+ **Parameters:**
91
107
 
92
- ##### `sendFeedback(feedbackData)`
108
+ - `endpoint`: API endpoint path (e.g., '/api/config', '/api/feedback')
109
+ - `options` (optional): Request options
110
+ - `method`: HTTP method (defaults to endpoint's predefined method)
111
+ - `body`: Request body (typed based on endpoint)
112
+ - `headers`: Additional headers
113
+ - `signal`: AbortSignal for cancelling the request
93
114
 
94
- Send feedback for a message.
115
+ **Returns:** Promise with the typed response
95
116
 
96
- - Parameters:
97
- - `feedbackData`: FeedbackRequest
98
- - `message_id`: string - ID of the message to provide feedback for
99
- - `feedback`: string - Type of feedback
100
- - `payload`: Record<string, unknown> | null - Additional feedback data
101
- - Returns: `Promise<Record<string, unknown>>` - Feedback submission response
117
+ **Example:**
102
118
 
103
- ## Types
119
+ ```typescript
120
+ // GET request
121
+ const config = await client.makeRequest('/api/config')
122
+
123
+ // POST request
124
+ const feedback = await client.makeRequest('/api/feedback', {
125
+ method: 'POST',
126
+ body: {
127
+ message_id: 'msg-123',
128
+ feedback: 'like',
129
+ payload: { rating: 5 },
130
+ },
131
+ })
104
132
 
105
- ### ChatResponse
133
+ // Custom endpoints
134
+ type MyEndpoints = {
135
+ '/api/my-endpoint': {
136
+ method: 'GET'
137
+ request: never
138
+ response: string
139
+ }
140
+ }
106
141
 
107
- ```typescript
108
- {
109
- type: 'message' | 'reference' | 'state_update' | 'text' | 'message_id'
110
- content: any
142
+ // or
143
+ type ExtendedEndpoints = BaseApiEndpoints & {
144
+ '/api/my-endpoint': {
145
+ method: 'GET'
146
+ request: never
147
+ response: string
148
+ }
111
149
  }
150
+
151
+ // In case of usage of custom Endpoints, we have to specify the URL as generic parameter
152
+ const myResponse = await client.makeRequest<MyEndpoints, '/api/my-endpoint'>(
153
+ '/api/my-endpoint'
154
+ )
112
155
  ```
113
156
 
114
- ### ChatRequest
157
+ ##### `makeStreamRequest<Endpoints, URL>(endpoint, data, callbacks, signal?): () => void`
158
+
159
+ Make a type-safe streaming request to any streaming endpoints. `endpoint` must be one of the key of `Endpoints` type
160
+ that define schema of the available endpoints. All default Ragbits routes are supported out of the box.
161
+
162
+ **Parameters:**
163
+
164
+ - `endpoint`: Streaming endpoint path (e.g., '/api/chat')
165
+ - `data`: Request data (typed based on endpoint)
166
+ - `callbacks`: Stream callbacks
167
+ - `onMessage`: Called when a message chunk is received
168
+ - `onError`: Called when an error occurs
169
+ - `onClose`: Called when the stream closes (optional)
170
+ - `signal` (optional): AbortSignal for cancelling the stream
171
+
172
+ **Returns:** Cleanup function to cancel the stream
173
+
174
+ **Example:**
115
175
 
116
176
  ```typescript
117
- {
118
- message: string;
119
- history: Array<{
120
- role: string;
121
- content: string;
122
- id?: string;
123
- }>;
124
- context?: Record<string, unknown>;
177
+ const cleanup = client.makeStreamRequest(
178
+ '/api/chat',
179
+ {
180
+ message: 'Tell me about AI',
181
+ history: [
182
+ { role: 'user', content: 'Hello' },
183
+ { role: 'assistant', content: 'Hi there!' },
184
+ ],
185
+ context: { user_id: 'user-123' },
186
+ },
187
+ {
188
+ onMessage: (data) => {
189
+ switch (data.type) {
190
+ case 'text':
191
+ console.log('Text:', data.content)
192
+ break
193
+ case 'reference':
194
+ console.log('Reference:', data.content.title)
195
+ break
196
+ case 'message_id':
197
+ console.log('Message ID:', data.content)
198
+ break
199
+ }
200
+ },
201
+ onError: (error) => {
202
+ console.error('Stream error:', error)
203
+ },
204
+ onClose: () => {
205
+ console.log('Stream completed')
206
+ },
207
+ }
208
+ )
209
+
210
+ // Cancel stream
211
+ cleanup()
212
+
213
+ // Custom endpoints
214
+ type MyEndpoints = {
215
+ '/api/my-endpoint': {
216
+ method: 'GET'
217
+ request: never
218
+ response: string
219
+ }
125
220
  }
221
+
222
+ // In case of usage of custom Endpoints, we have to specify the URL as generic parameter
223
+ const cleanup = client.makeStreamRequest<MyEndpoints, '/api/my-endpoint'>(
224
+ '/api/my-endpoint',
225
+ ...
226
+ )
126
227
  ```
127
228
 
128
- ### FeedbackRequest
229
+ ## Error Handling
230
+
231
+ The client provides comprehensive error handling:
129
232
 
130
233
  ```typescript
131
- {
132
- message_id: string
133
- feedback: string
134
- payload: Record<string, unknown> | null
234
+ try {
235
+ const config = await client.makeRequest('/api/config')
236
+ } catch (error) {
237
+ if (error instanceof Error) {
238
+ console.error('API Error:', error.message)
239
+ }
135
240
  }
136
241
  ```
137
242
 
138
- ### StreamCallbacks
243
+ Common error scenarios:
244
+
245
+ - **Network errors** - Connection failures, timeouts
246
+ - **HTTP errors** - 4xx/5xx status codes
247
+ - **Invalid URLs** - Malformed base URL
248
+ - **Stream errors** - Connection drops, parsing errors
249
+
250
+ ## Aborting Requests
251
+
252
+ Both regular requests and streams can be aborted:
139
253
 
140
254
  ```typescript
141
- {
142
- onMessage: (data: ChatResponse) => void | Promise<void>;
143
- onError: (error: string) => void | Promise<void>;
144
- onClose?: () => void | Promise<void>;
145
- }
255
+ // Abort regular request
256
+ const controller = new AbortController()
257
+ const request = client.makeRequest('/api/config', {
258
+ signal: controller.signal,
259
+ })
260
+ controller.abort() // Cancels the request
261
+
262
+ // Abort stream
263
+ const cleanup = client.makeStreamRequest(
264
+ '/api/chat',
265
+ data,
266
+ callbacks,
267
+ controller.signal
268
+ )
269
+ controller.abort() // Cancels the stream
270
+ cleanup() // Also cancels the stream
146
271
  ```
272
+
273
+ ## Browser Support
274
+
275
+ This package supports all modern browsers with fetch API support:
276
+
277
+ - Chrome 42+
278
+ - Firefox 39+
279
+ - Safari 10.1+
280
+ - Edge 14+
281
+
282
+ ## Node.js Support
283
+
284
+ For Node.js environments, you'll need:
285
+
286
+ - Node.js 18+
287
+
288
+ ## License
289
+
290
+ MIT
@@ -1,4 +1,4 @@
1
- import type { ConfigResponse } from '../types'
1
+ import type { ConfigResponse } from '../src'
2
2
 
3
3
  // Shared config response for tests
4
4
  export const defaultConfigResponse: ConfigResponse = {
@@ -25,4 +25,21 @@ export const defaultConfigResponse: ConfigResponse = {
25
25
  },
26
26
  },
27
27
  customization: null,
28
+ user_settings: {
29
+ form: {
30
+ title: 'Chat Form',
31
+ type: 'object',
32
+ required: ['language'],
33
+ properties: {
34
+ language: {
35
+ title: 'Language',
36
+ description: 'Please select the language',
37
+ type: 'string',
38
+ enum: ['English', 'Polish'],
39
+ },
40
+ },
41
+ },
42
+ },
43
+ debug_mode: false,
44
+ conversation_history: false,
28
45
  }