@ibti-tech/chatbot 0.6.5 → 0.8.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/README.md CHANGED
@@ -1,616 +1,136 @@
1
1
  # @ibti-tech/chatbot
2
2
 
3
- A modern and customizable React chatbot component developed by IBTI Soluções em TI. This package provides an intelligent conversational interface that can be easily integrated into any React application.
3
+ React chatbot widget by IBTI. Use it in React apps or embed via a single script in any HTML/WordPress/PHP site.
4
4
 
5
- ## 📋 Features
5
+ ## Features
6
6
 
7
- - 🎨 **Customizable themes**: Support for light and dark themes
8
- - 🌍 **Internationalization**: Support for Brazilian Portuguese (pt-BR) and English (en)
9
- - 💬 **Modern interface**: Responsive and intuitive design
10
- - ⚡ **Optimized performance**: Built with ESBuild for maximum performance
11
- - 🔌 **Easy integration**: Simple React component to use
12
- - 📱 **Responsive**: Works perfectly on desktop and mobile
13
- - 📍 **Flexible positioning**: Precise horizontal positioning with predefined values or custom CSS units (px, %, rem, calc, etc.)
7
+ - Light/dark theme, pt-BR and en
8
+ - Responsive, configurable position (top/bottom, left/right, custom CSS)
9
+ - React component or script embed (no React required on the host page)
14
10
 
15
- ## 📦 Installation
16
-
17
- Install the package using yarn or npm:
11
+ ## Installation
18
12
 
19
13
  ```bash
20
- # Using yarn
21
14
  yarn add @ibti-tech/chatbot
22
-
23
- # Using npm
15
+ # or
24
16
  npm install @ibti-tech/chatbot
25
17
  ```
26
18
 
27
- ## 🚀 Basic Usage
28
-
29
- ### Import
30
-
31
- ```jsx
32
- import { ChatbotProvider, ChatbotBar } from '@ibti-tech/chatbot'
33
- ```
19
+ **Peer dependencies:** `react` ^18.2.0, `react-dom` ^18.2.0, `lodash` ^4.17.21, `nookies` ^2.5.2
34
20
 
35
- ### Minimal Example
21
+ ## Usage (React)
36
22
 
37
23
  ```jsx
38
- import React from 'react'
39
- import { ChatbotProvider, ChatbotBar } from '@ibti-tech/chatbot'
24
+ import { ChatbotProvider, ChatbotBar, useChatbot } from '@ibti-tech/chatbot'
40
25
 
41
26
  function App() {
42
27
  return (
43
28
  <ChatbotProvider
44
29
  locale="pt-BR"
45
30
  apiURL="https://api.example.com"
31
+ publicHash="YOUR_PUBLIC_HASH"
46
32
  theme="dark"
47
33
  >
48
34
  <ChatbotBar />
49
35
  </ChatbotProvider>
50
36
  )
51
37
  }
52
-
53
- export default App
54
- ```
55
-
56
- ## 📚 Available Components
57
-
58
- ### `ChatbotProvider`
59
-
60
- Context component that provides chatbot configuration and state to child components.
61
-
62
- #### Props
63
-
64
- | Prop | Type | Required | Description |
65
- |------|------|----------|-------------|
66
- | `locale` | `'pt-BR' \| 'en'` | ✅ | Chatbot interface language |
67
- | `apiURL` | `string` | ✅ | Chatbot backend API URL |
68
- | `theme` | `'light' \| 'dark'` | ✅ | Chatbot visual theme |
69
- | `isOpen` | `boolean` | ❌ | Controls if the chatbot is initially open. Default: `false` |
70
- | `texts` | `ChatbotTypes.Texts` | ❌ | Custom texts to override default translations. See [Custom Texts](#custom-texts) section |
71
- | `children` | `ReactNode` | ❌ | Child components to be rendered |
72
-
73
- ### `ChatbotBar`
74
-
75
- Main component that displays the chatbot bar with toggle button and conversation interface.
76
-
77
- #### Props
78
-
79
- | Prop | Type | Required | Description |
80
- |------|------|----------|-------------|
81
- | `verticalPosition` | `'top' \| 'bottom'` | ❌ | Vertical position of the chatbot. Default: `'bottom'` |
82
- | `horizontalPosition` | `'left' \| 'right'` | ❌ | Horizontal position of the chatbot bar container. Default: `'right'` |
83
- | `deviceHorizontalPosition` | `'left' \| 'right' \| 'center' \| string` | ❌ | Horizontal position of the ChatbotDevice on desktop. Can be a predefined value ('left', 'right', 'center') or a custom value with any CSS unit (e.g., '20px', '10%', '2rem', 'calc(100% - 200px)'). When using a custom value, it will be applied as the 'left' property. If not provided, the device will use the parent container's positioning. Only affects desktop view. |
84
- | `zIndex` | `number` | ❌ | Custom z-index value. If not provided, uses theme.zIndex.modals. Useful when you need the chatbot to appear above specific elements like headers |
85
- | `topOffset` | `string \| number` | ❌ | Offset from the top when verticalPosition is 'top'. Can be a number (in pixels) or a string (e.g., '100px', '10rem'). Useful to position the chatbot below a fixed header |
86
- | `aboveHeader` | `boolean` | ❌ | Convenient prop to position the chatbot above header elements. When true, sets z-index to 9999 and allows topOffset configuration. Default: `false` |
87
- | `pushContentDown` | `boolean` | ❌ | When true and verticalPosition is 'top', the chatbot will push content down instead of overlaying it. The chatbot will occupy space in the document flow. When false, the chatbot will be fixed and overlay the content. Default: `false` |
88
-
89
- #### Examples
90
-
91
- **Positioning above header elements:**
92
-
93
- ```jsx
94
- // Option 1: Using aboveHeader prop (recommended)
95
- <ChatbotBar
96
- verticalPosition="top"
97
- aboveHeader={true}
98
- topOffset={120} // Adjust based on your header height
99
- />
100
-
101
- // Option 2: Using custom zIndex
102
- <ChatbotBar
103
- verticalPosition="top"
104
- zIndex={9999}
105
- topOffset="120px"
106
- />
107
-
108
- // Option 3: Using CSS units for topOffset
109
- <ChatbotBar
110
- verticalPosition="top"
111
- aboveHeader={true}
112
- topOffset="8rem" // Using rem units for better scalability
113
- />
114
-
115
- // Option 4: Push content down instead of overlaying (only works with verticalPosition="top")
116
- // When pushContentDown is true, the chatbot occupies full width and pushes header content down
117
- <ChatbotBar
118
- verticalPosition="top"
119
- pushContentDown={true}
120
- />
121
-
122
- // ✅ CORRECT - Component at the beginning
123
- function App() {
124
- return (
125
- <ChatbotProvider ...>
126
- <ChatbotBar verticalPosition="top" pushContentDown={true} />
127
- <header>...</header>
128
- <main>...</main>
129
- </ChatbotProvider>
130
- )
131
- }
132
-
133
- // ❌ WRONG - Component at the end (will appear at bottom even with pushContentDown)
134
- function App() {
135
- return (
136
- <ChatbotProvider ...>
137
- <header>...</header>
138
- <main>...</main>
139
- <ChatbotBar verticalPosition="top" pushContentDown={true} />
140
- </ChatbotProvider>
141
- )
142
- }
143
- ```
144
-
145
- **Note:** The component maintains full responsiveness even with custom positioning. The `topOffset` prop accepts both numbers (pixels) and strings (any valid CSS unit). The `pushContentDown` prop only works when `verticalPosition` is `'top'` and makes the chatbot reserve space in the document flow instead of overlaying content. When `pushContentDown` is enabled, the chatbot will occupy the full width of the page (aligned with the host site's container) and push all content below it down, making it perfect for top-of-page integration.
146
-
147
- **⚠️ CRITICAL:** When using `pushContentDown={true}`, you **MUST** render the `ChatbotBar` component at the **beginning** of your DOM structure (before your header and other content) for it to appear at the top of the page. This is because `pushContentDown` uses `position: relative`, which means the component appears where it is in the DOM flow. If you render it at the end of the DOM, it will appear at the bottom of the page even with `pushContentDown={true}`.
148
-
149
- **Precise horizontal positioning on desktop:**
150
-
151
- ```jsx
152
- // Using predefined values
153
- <ChatbotBar
154
- deviceHorizontalPosition="left" // Aligns to left
155
- />
156
- <ChatbotBar
157
- deviceHorizontalPosition="right" // Aligns to right (default behavior)
158
- />
159
- <ChatbotBar
160
- deviceHorizontalPosition="center" // Centers the device
161
- />
162
-
163
- // Using custom values with any CSS unit
164
- <ChatbotBar
165
- deviceHorizontalPosition="20px" // 20 pixels from left
166
- />
167
- <ChatbotBar
168
- deviceHorizontalPosition="10%" // 10% from left edge
169
- />
170
- <ChatbotBar
171
- deviceHorizontalPosition="2rem" // 2rem from left edge
172
- />
173
- <ChatbotBar
174
- deviceHorizontalPosition="calc(100% - 200px)" // 200px from right edge
175
- />
176
-
177
- // Combining with other positioning props
178
- <ChatbotBar
179
- verticalPosition="bottom"
180
- horizontalPosition="right" // Bar container alignment
181
- deviceHorizontalPosition="50px" // Device positioned 50px from left
182
- />
183
- ```
184
-
185
- **Important notes about `deviceHorizontalPosition`:**
186
- - Only affects desktop/tablet view (mobile always uses full width)
187
- - Custom values are applied as the `left` CSS property
188
- - Predefined values (`'left'`, `'right'`, `'center'`) use margin-based alignment
189
- - When using custom values, the device maintains its fixed width to prevent button shrinking
190
- - This prop provides precise control over the ChatbotDevice position, independent of the bar container alignment
191
-
192
- ### `ChatbotDevice`
193
-
194
- Alternative component that can be used to display the chatbot on different devices or layouts.
195
-
196
- #### Props
197
-
198
- | Prop | Type | Required | Description |
199
- |------|------|----------|-------------|
200
- | `verticalPosition` | `'top' \| 'bottom'` | ❌ | Vertical position of the chatbot. Default: `'bottom'` |
201
- | `pushContentDown` | `boolean` | ❌ | When true and verticalPosition is 'top', the chatbot will push content down instead of overlaying it. Default: `false` |
202
- | `horizontalPosition` | `'left' \| 'right' \| 'center' \| string` | ❌ | Horizontal position on desktop. Can be a predefined value ('left', 'right', 'center') or a custom value with any CSS unit (e.g., '20px', '10%', '2rem', 'calc(100% - 200px)'). When using a custom value, it will be applied as the 'left' property. Default: `undefined` (uses parent container positioning). Only affects desktop view. |
203
-
204
- ## 🎨 Themes
205
-
206
- The chatbot supports two themes:
207
-
208
- - **`light`**: Light theme with bright colors
209
- - **`dark`**: Dark theme with dark colors
210
-
211
- ```jsx
212
- <ChatbotProvider theme="dark" ...>
213
- <ChatbotBar />
214
- </ChatbotProvider>
215
- ```
216
-
217
- ## 🌍 Localization
218
-
219
- The chatbot supports the following languages:
220
-
221
- - **`pt-BR`**: Brazilian Portuguese
222
- - **`en`**: English
223
-
224
- ```jsx
225
- <ChatbotProvider locale="pt-BR" ...>
226
- <ChatbotBar />
227
- </ChatbotProvider>
228
- ```
229
-
230
- ### Custom Texts
231
-
232
- You can customize all texts in the chatbot interface by passing a `texts` prop to `ChatbotProvider`. This allows you to override default translations for any locale.
233
-
234
- ```jsx
235
- <ChatbotProvider
236
- locale="pt-BR"
237
- apiURL="https://api.example.com"
238
- theme="dark"
239
- texts={{
240
- 'pt-BR': {
241
- CHATBOT_NAME: 'Meu Assistente',
242
- INPUT_PLACEHOLDER: 'Digite sua mensagem...',
243
- CHATBOT_BAR: {
244
- OPEN: 'Abrir chat',
245
- CLOSE: 'Fechar chat',
246
- },
247
- CHAT_FEEDBACK: {
248
- TITLE: 'Avalie esta resposta',
249
- DESCRIPTION: 'Sua opinião nos ajuda a melhorar',
250
- MESSAGE_FIELD: 'Mensagem (opcional)',
251
- SUBMIT_BUTTON: 'Enviar',
252
- CLOSE_BUTTON: 'Fechar',
253
- RATE: 'Avaliar',
254
- },
255
- SUGGESTED_QUESTIONS: {
256
- TITLE: 'Perguntas sugeridas',
257
- LOADING: 'Carregando...',
258
- },
259
- STATUS: {
260
- ONLINE: 'Online',
261
- LOADING: 'Carregando',
262
- WRITING: 'Digitando...',
263
- UNAVAILABLE: 'Indisponível',
264
- INACTIVE: 'Inativo',
265
- },
266
- ERRORS: {
267
- UNKNOWN: 'Erro desconhecido',
268
- },
269
- MESSAGE_ACTIONS: {
270
- COPY: 'Copiar',
271
- SHARE: 'Compartilhar',
272
- RESEND: 'Reenviar',
273
- },
274
- USER_LABEL: 'Você',
275
- WRITING_MESSAGE: 'Digitando...',
276
- },
277
- 'en': {
278
- CHATBOT_NAME: 'My Assistant',
279
- // ... other custom texts
280
- },
281
- }}
282
- >
283
- <ChatbotBar />
284
- </ChatbotProvider>
285
- ```
286
-
287
- **Available text keys:**
288
- - `CHATBOT_NAME`: Name displayed in the chatbot header
289
- - `INPUT_PLACEHOLDER`: Placeholder text for the input field
290
- - `CHATBOT_BAR.OPEN`: Text for opening the chatbot
291
- - `CHATBOT_BAR.CLOSE`: Text for closing the chatbot
292
- - `CHAT_FEEDBACK.*`: All feedback form texts
293
- - `SUGGESTED_QUESTIONS.*`: Suggested questions section texts
294
- - `STATUS.*`: Status indicator texts
295
- - `ERRORS.*`: Error message texts
296
- - `MESSAGE_ACTIONS.*`: Message action button texts
297
- - `USER_LABEL`: Label for user messages
298
- - `WRITING_MESSAGE`: Text shown when the bot is typing
299
-
300
- ## 📝 Complete Example
301
-
302
- ```jsx
303
- import React from 'react'
304
- import { ChatbotProvider, ChatbotBar } from '@ibti-tech/chatbot'
305
-
306
- function MyApp() {
307
- return (
308
- <div className="app">
309
- <h1>My Application</h1>
310
-
311
- {/* Other components of your application */}
312
-
313
- <ChatbotProvider
314
- locale="pt-BR"
315
- apiURL={process.env.REACT_APP_CHATBOT_API_URL || "http://localhost:6061"}
316
- theme="dark"
317
- isOpen={false}
318
- >
319
- <ChatbotBar
320
- verticalPosition="bottom"
321
- horizontalPosition="right"
322
- deviceHorizontalPosition="right"
323
- />
324
- </ChatbotProvider>
325
- </div>
326
- )
327
- }
328
-
329
- export default MyApp
330
- ```
331
-
332
- ## 🎛️ Advanced Configuration
333
-
334
- ### Positioning the Chatbot
335
-
336
- You can control the position of the chatbot using the `ChatbotBar` component props:
337
-
338
- ```jsx
339
- // Bottom right (default)
340
- <ChatbotBar />
341
-
342
- // Top right
343
- <ChatbotBar verticalPosition="top" />
344
-
345
- // Bottom left (bar container aligned left)
346
- <ChatbotBar horizontalPosition="left" />
347
-
348
- // Top left (bar container aligned left)
349
- <ChatbotBar
350
- verticalPosition="top"
351
- horizontalPosition="left"
352
- />
353
-
354
- // Precise horizontal positioning on desktop
355
- <ChatbotBar
356
- deviceHorizontalPosition="center" // Centers the device
357
- />
358
-
359
- <ChatbotBar
360
- deviceHorizontalPosition="50px" // 50px from left edge
361
- />
362
-
363
- <ChatbotBar
364
- deviceHorizontalPosition="calc(100% - 250px)" // 250px from right edge
365
- />
366
-
367
- // Combining bar container and device positioning
368
- <ChatbotBar
369
- horizontalPosition="right" // Bar container on right
370
- deviceHorizontalPosition="20px" // Device 20px from left (within container)
371
- />
372
- ```
373
-
374
- **Understanding the positioning props:**
375
- - `horizontalPosition`: Controls the alignment of the bar container (`'left'` or `'right'`)
376
- - `deviceHorizontalPosition`: Provides precise control over the ChatbotDevice position on desktop:
377
- - Predefined values: `'left'`, `'right'`, `'center'` (use margin-based alignment)
378
- - Custom values: Any CSS unit string (e.g., `'20px'`, `'10%'`, `'calc(100% - 200px)'`) applied as the `left` property
379
- - Only affects desktop/tablet view; mobile always uses full width
380
-
381
- ### Controlling Initial State
382
-
383
- Use the `isOpen` prop to control whether the chatbot starts open or closed:
384
-
385
- ```jsx
386
- <ChatbotProvider
387
- locale="pt-BR"
388
- apiURL="https://api.example.com"
389
- theme="dark"
390
- isOpen={true} // Chatbot starts open
391
- >
392
- <ChatbotBar />
393
- </ChatbotProvider>
394
38
  ```
395
39
 
396
- ## 🔧 Requirements
40
+ All public types (e.g. `ChatbotTypes`, `ChatbotBarProps`) and parameters are documented with JSDoc in English in the source—your IDE will show parameter names, types, and descriptions on hover.
397
41
 
398
- ### Peer Dependencies
42
+ ### Main props
399
43
 
400
- This package requires the following dependencies that must be installed in your project:
44
+ **ChatbotProvider**
401
45
 
402
- - `react`: `^18.2.0`
403
- - `react-dom`: `^18.2.0`
404
- - `lodash`: `^4.17.21`
405
- - `nookies`: `^2.5.2`
46
+ | Prop | Type | Required | Description |
47
+ |-----------|----------|----------|--------------------------------|
48
+ | `locale` | `'pt-BR' \| 'en'` | ✅ | Interface language |
49
+ | `apiURL` | `string` | ✅ | Backend API base URL |
50
+ | `publicHash` | `string` | ✅ | Chatbot public hash (from admin) |
51
+ | `theme` | `'light' \| 'dark'` | ✅ | Theme |
52
+ | `isOpen` | `boolean` | ❌ | Initial open state. Default: `false` |
53
+ | `texts` | `object` | ❌ | Override labels per locale |
406
54
 
407
- Make sure these dependencies are installed:
55
+ **ChatbotBar**
408
56
 
409
- ```bash
410
- yarn add react react-dom lodash nookies
411
- # or
412
- npm install react react-dom lodash nookies
413
- ```
57
+ | Prop | Type | Default | Description |
58
+ |---------------------------|----------|----------------|--------------------------------------|
59
+ | `verticalPosition` | `'top' \| 'bottom'` | `'bottom'` | Vertical placement |
60
+ | `horizontalPosition` | `'left' \| 'right'` | `'right'` | Bar alignment |
61
+ | `deviceHorizontalPosition`| `'left' \| 'right' \| 'center' \| string` | — | Device position on desktop (or e.g. `'20px'`, `'calc(100% - 200px)'`) |
62
+ | `pushContentDown` | `boolean` | `false` | If `true` and `verticalPosition="top"`, widget pushes content down instead of overlaying |
63
+ | `zIndex`, `topOffset`, `aboveHeader` | — | — | Optional layout/stacking |
414
64
 
415
- ## 📡 Backend API
65
+ When using `pushContentDown={true}` with `verticalPosition="top"`, render `ChatbotBar` **before** your header/main content so it appears at the top.
416
66
 
417
- The chatbot expects the backend API to be configured and accessible at the provided URL. The API must implement the following endpoints:
67
+ ### Types (`ChatbotTypes`)
418
68
 
419
- ### Required Endpoints
69
+ Import: `import type { ChatbotTypes } from '@ibti-tech/chatbot'`
420
70
 
421
- #### 1. `GET /chat/welcome?locale={locale}`
71
+ | Type | Description |
72
+ |------|-------------|
73
+ | `Theme` | `'light' \| 'dark'` |
74
+ | `Locale` | `'pt-BR' \| 'en'` |
75
+ | `CustomColors` | `{ primaryColor?, headerBackground?, userBalloonColor? }` (hex or rgb) |
76
+ | `ChatMessage` | `{ id, timestamp, role, content, error? }` — one message in the thread |
77
+ | `ChatContextItem` | `{ role, content }` — minimal shape for API context |
78
+ | `Status` | `'writing' \| 'loading' \| 'online' \| 'unavailable'` |
79
+ | `InitializationStatus` | `'loading' \| 'domain_not_allowed' \| 'error' \| 'ready'` |
80
+ | `ChatbotPublicResponse` | Response of GET `/chatbots/public/:hash` (id, name, domain, etc.) |
81
+ | `CustomTexts` / `Texts` | Override UI strings per locale (see JSDoc in `types/index.ts`) |
422
82
 
423
- **Purpose**: Retrieves the welcome message and checks API health/availability.
83
+ ## Embed (no React)
424
84
 
425
- **Query Parameters**:
426
- - `locale` (required): The locale code (`'pt-BR'` or `'en'`)
427
-
428
- **Response**:
429
- ```json
430
- {
431
- "welcomeMessage": "Hello! How can I help you today?"
432
- }
433
- ```
85
+ For static HTML, WordPress, PHP, or any site without React, load the script from the CDN:
434
86
 
435
- **Status Codes**:
436
- - `200 OK`: API is available and welcome message is returned
437
- - `4xx/5xx`: API is considered unavailable
438
-
439
- **Notes**:
440
- - This endpoint is used for health checks (via `HEAD` or `GET` requests)
441
- - The chatbot uses this to determine connection status
442
- - Should return a welcome message appropriate for the specified locale
443
-
444
- ---
445
-
446
- #### 2. `POST /chat/completion?locale={locale}`
447
-
448
- **Purpose**: Sends a chat message and receives a streaming response from the AI assistant.
449
-
450
- **Query Parameters**:
451
- - `locale` (required): The locale code (`'pt-BR'` or `'en'`)
452
-
453
- **Request Body**:
454
- ```json
455
- {
456
- "context": [
457
- {
458
- "role": "user",
459
- "content": "What is artificial intelligence?"
460
- },
461
- {
462
- "role": "assistant",
463
- "content": "Artificial intelligence (AI) is..."
464
- },
465
- {
466
- "role": "user",
467
- "content": "Tell me more about machine learning"
468
- }
469
- ]
470
- }
87
+ ```html
88
+ <script>
89
+ window.IBTIChatbotConfig = {
90
+ apiURL: 'https://api-chatbot.ibti.tech',
91
+ publicHash: 'YOUR_PUBLIC_HASH',
92
+ locale: 'pt-BR', // optional: 'pt-BR' | 'en'
93
+ theme: 'light', // optional: 'light' | 'dark'
94
+ position: 'bottom-right' // optional: bottom-right | bottom-left | top-right | top-left
95
+ };
96
+ </script>
97
+ <script src="https://cdn.ibti.tech/ibti-chatbot-embed.js" async></script>
471
98
  ```
472
99
 
473
- **Request Body Schema**:
474
- - `context` (required, array): Array of chat messages representing the conversation history
475
- - Each item must have:
476
- - `role` (required, string): Either `"user"` or `"assistant"`
477
- - `content` (required, string): The message content
478
- - The array must not be empty
479
- - The last message should typically be from the `"user"` role
480
-
481
- **Response**:
482
- - **Content-Type**: `text/event-stream`
483
- - **Format**: Server-Sent Events (SSE) stream
484
- - **Body**: Plain text chunks that are concatenated to form the complete response
100
+ Or configure via data attributes on the script tag:
485
101
 
486
- **Response Headers**:
102
+ ```html
103
+ <script
104
+ src="https://cdn.ibti.tech/ibti-chatbot-embed.js"
105
+ data-api-url="https://api-chatbot.ibti.tech"
106
+ data-public-hash="YOUR_PUBLIC_HASH"
107
+ data-locale="pt-BR"
108
+ data-theme="light"
109
+ data-position="bottom-right"
110
+ async
111
+ ></script>
487
112
  ```
488
- Content-Type: text/event-stream
489
- Cache-Control: no-cache
490
- Connection: keep-alive
491
- ```
492
-
493
- **Status Codes**:
494
- - `200 OK`: Stream started successfully
495
- - `429 Too Many Requests`: Rate limit exceeded (should send error message via stream before closing)
496
- - `4xx/5xx`: Error occurred
497
-
498
- **Streaming Behavior**:
499
- - The response is sent as a continuous stream of text chunks
500
- - Each chunk is immediately displayed to the user as it arrives
501
- - The stream ends when the complete response is sent
502
- - The chatbot accumulates all chunks to form the final message
503
-
504
- **Error Handling**:
505
- - For `429` errors, the API should send a friendly error message via the stream before closing:
506
- ```json
507
- {"error": "Sorry, too many requests were made. Please try again in a few moments. 😊"}
508
- ```
509
- - For other errors, the stream should be closed and an appropriate HTTP status code returned
510
-
511
- **Example Flow**:
512
- 1. Frontend sends POST request with conversation context
513
- 2. Backend starts streaming response chunks
514
- 3. Frontend receives chunks and displays them incrementally
515
- 4. Stream completes when response is finished
516
- 5. Frontend saves the complete message to conversation history
517
-
518
- ---
519
-
520
- #### 3. `POST /chat/feedback`
521
-
522
- **Purpose**: Submits user feedback about a chatbot response (rating and optional message).
523
-
524
- **Request Body**:
525
- ```json
526
- {
527
- "rating_score": 5,
528
- "chat_context": [
529
- {
530
- "role": "user",
531
- "content": "What is AI?"
532
- },
533
- {
534
- "role": "assistant",
535
- "content": "Artificial intelligence is..."
536
- }
537
- ],
538
- "locale": "pt-BR",
539
- "message": "Very helpful response!"
540
- }
541
- ```
542
-
543
- **Request Body Schema**:
544
- - `rating_score` (required, number): Rating from 1 to 5 (inclusive)
545
- - Valid values: `1`, `2`, `3`, `4`, `5`
546
- - `chat_context` (required, array): The conversation context that was rated
547
- - Same structure as in `/chat/completion` endpoint
548
- - Must not be empty
549
- - `locale` (required, string): The locale code (`'pt-BR'` or `'en'`)
550
- - `message` (optional, string): Optional feedback message from the user
551
-
552
- **Response**:
553
- - **Status Code**: `200 OK` or `201 Created` (implementation dependent)
554
- - **Body**: Typically empty or a success confirmation
555
-
556
- **Status Codes**:
557
- - `200 OK` / `201 Created`: Feedback submitted successfully
558
- - `400 Bad Request`: Invalid request body (invalid rating, missing fields, etc.)
559
- - `4xx/5xx`: Other errors
560
-
561
- **Notes**:
562
- - This endpoint is called when a user rates a chatbot response
563
- - The feedback is typically stored for analytics and improvement purposes
564
- - The endpoint should handle the request asynchronously if possible to avoid blocking the UI
565
-
566
- ---
567
-
568
- ### API Requirements Summary
569
-
570
- | Endpoint | Method | Purpose | Streaming | Required |
571
- |----------|--------|---------|-----------|----------|
572
- | `/chat/welcome` | `GET` | Health check & welcome message | ❌ | ✅ |
573
- | `/chat/completion` | `POST` | Send message & receive response | ✅ | ✅ |
574
- | `/chat/feedback` | `POST` | Submit user feedback | ❌ | ✅ |
575
-
576
- ### Implementation Notes
577
-
578
- 1. **CORS**: The API must allow cross-origin requests from the frontend domain
579
- 2. **Locale Support**: All endpoints should respect the `locale` parameter and return appropriate content
580
- 3. **Error Handling**: Provide clear error messages in the appropriate locale
581
- 4. **Streaming**: The `/chat/completion` endpoint must support Server-Sent Events (SSE) for real-time response streaming
582
- 5. **Rate Limiting**: Consider implementing rate limiting and return `429` status when exceeded
583
- 6. **Content-Type**:
584
- - Use `application/json` for JSON endpoints
585
- - Use `text/event-stream` for streaming endpoints
586
-
587
- ### Example API Base URL
588
-
589
- ```jsx
590
- <ChatbotProvider
591
- apiURL="https://api.example.com" // Base URL without trailing slash
592
- // ...
593
- />
594
- ```
595
-
596
- The chatbot will automatically append the endpoint paths (e.g., `/chat/welcome`, `/chat/completion`, `/chat/feedback`) to this base URL.
597
113
 
598
- ## 🐛 Issues and Support
114
+ ## Backend API
599
115
 
600
- If you encounter any issues or have questions:
116
+ The API base URL (e.g. `https://api.example.com`) must expose:
601
117
 
602
- 1. Check the [complete documentation](https://github.com/ibti-solutions/ibti-chatbot)
603
- 2. Open an [issue on GitHub](https://github.com/ibti-solutions/ibti-chatbot/issues)
604
- 3. Contact the IBTI team
118
+ | Endpoint | Method | Purpose | Streaming |
119
+ |--------------------|--------|----------------------------|-----------|
120
+ | `/chatbots/public/:hash` | GET | Get chatbot config (domain, etc.) | No |
121
+ | `/chat/welcome` | GET | Welcome message / health | No |
122
+ | `/chat/completion` | POST | Send message, stream reply | Yes (SSE) |
123
+ | `/chat/feedback` | POST | Submit rating + optional message | No |
605
124
 
606
- ## 📄 License
125
+ Query params used: `locale`, `hash`, `visitorId`. The API should validate `Origin`/`Referer` against the chatbot’s configured domain. CORS must allow the frontend origin.
607
126
 
608
- ISC
127
+ ## Support
609
128
 
610
- ## 👥 Author
129
+ - [Documentation](https://github.com/ibti-solutions/ibti-chatbot)
130
+ - [Issues](https://github.com/ibti-solutions/ibti-chatbot/issues)
611
131
 
612
- IBTI Soluções em TI
132
+ Development and contribution: see [DEV_NOTES.md](./DEV_NOTES.md).
613
133
 
614
- ---
134
+ ## License
615
135
 
616
- For more information about development and contribution, see the [DEV_NOTES.md](./DEV_NOTES.md) file.
136
+ ISC · IBTI Soluções em TI