@ibti-tech/chatbot
v0.6.5
Published
Chatbot developed for IBTI products
Readme
@ibti-tech/chatbot
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.
📋 Features
- 🎨 Customizable themes: Support for light and dark themes
- 🌍 Internationalization: Support for Brazilian Portuguese (pt-BR) and English (en)
- 💬 Modern interface: Responsive and intuitive design
- ⚡ Optimized performance: Built with ESBuild for maximum performance
- 🔌 Easy integration: Simple React component to use
- 📱 Responsive: Works perfectly on desktop and mobile
- 📍 Flexible positioning: Precise horizontal positioning with predefined values or custom CSS units (px, %, rem, calc, etc.)
📦 Installation
Install the package using yarn or npm:
# Using yarn
yarn add @ibti-tech/chatbot
# Using npm
npm install @ibti-tech/chatbot🚀 Basic Usage
Import
import { ChatbotProvider, ChatbotBar } from '@ibti-tech/chatbot'Minimal Example
import React from 'react'
import { ChatbotProvider, ChatbotBar } from '@ibti-tech/chatbot'
function App() {
return (
<ChatbotProvider
locale="pt-BR"
apiURL="https://api.example.com"
theme="dark"
>
<ChatbotBar />
</ChatbotProvider>
)
}
export default App📚 Available Components
ChatbotProvider
Context component that provides chatbot configuration and state to child components.
Props
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| locale | 'pt-BR' \| 'en' | ✅ | Chatbot interface language |
| apiURL | string | ✅ | Chatbot backend API URL |
| theme | 'light' \| 'dark' | ✅ | Chatbot visual theme |
| isOpen | boolean | ❌ | Controls if the chatbot is initially open. Default: false |
| texts | ChatbotTypes.Texts | ❌ | Custom texts to override default translations. See Custom Texts section |
| children | ReactNode | ❌ | Child components to be rendered |
ChatbotBar
Main component that displays the chatbot bar with toggle button and conversation interface.
Props
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| verticalPosition | 'top' \| 'bottom' | ❌ | Vertical position of the chatbot. Default: 'bottom' |
| horizontalPosition | 'left' \| 'right' | ❌ | Horizontal position of the chatbot bar container. Default: 'right' |
| 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. |
| 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 |
| 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 |
| aboveHeader | boolean | ❌ | Convenient prop to position the chatbot above header elements. When true, sets z-index to 9999 and allows topOffset configuration. Default: false |
| 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 |
Examples
Positioning above header elements:
// Option 1: Using aboveHeader prop (recommended)
<ChatbotBar
verticalPosition="top"
aboveHeader={true}
topOffset={120} // Adjust based on your header height
/>
// Option 2: Using custom zIndex
<ChatbotBar
verticalPosition="top"
zIndex={9999}
topOffset="120px"
/>
// Option 3: Using CSS units for topOffset
<ChatbotBar
verticalPosition="top"
aboveHeader={true}
topOffset="8rem" // Using rem units for better scalability
/>
// Option 4: Push content down instead of overlaying (only works with verticalPosition="top")
// When pushContentDown is true, the chatbot occupies full width and pushes header content down
<ChatbotBar
verticalPosition="top"
pushContentDown={true}
/>
// ✅ CORRECT - Component at the beginning
function App() {
return (
<ChatbotProvider ...>
<ChatbotBar verticalPosition="top" pushContentDown={true} />
<header>...</header>
<main>...</main>
</ChatbotProvider>
)
}
// ❌ WRONG - Component at the end (will appear at bottom even with pushContentDown)
function App() {
return (
<ChatbotProvider ...>
<header>...</header>
<main>...</main>
<ChatbotBar verticalPosition="top" pushContentDown={true} />
</ChatbotProvider>
)
}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.
⚠️ 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}.
Precise horizontal positioning on desktop:
// Using predefined values
<ChatbotBar
deviceHorizontalPosition="left" // Aligns to left
/>
<ChatbotBar
deviceHorizontalPosition="right" // Aligns to right (default behavior)
/>
<ChatbotBar
deviceHorizontalPosition="center" // Centers the device
/>
// Using custom values with any CSS unit
<ChatbotBar
deviceHorizontalPosition="20px" // 20 pixels from left
/>
<ChatbotBar
deviceHorizontalPosition="10%" // 10% from left edge
/>
<ChatbotBar
deviceHorizontalPosition="2rem" // 2rem from left edge
/>
<ChatbotBar
deviceHorizontalPosition="calc(100% - 200px)" // 200px from right edge
/>
// Combining with other positioning props
<ChatbotBar
verticalPosition="bottom"
horizontalPosition="right" // Bar container alignment
deviceHorizontalPosition="50px" // Device positioned 50px from left
/>Important notes about deviceHorizontalPosition:
- Only affects desktop/tablet view (mobile always uses full width)
- Custom values are applied as the
leftCSS property - Predefined values (
'left','right','center') use margin-based alignment - When using custom values, the device maintains its fixed width to prevent button shrinking
- This prop provides precise control over the ChatbotDevice position, independent of the bar container alignment
ChatbotDevice
Alternative component that can be used to display the chatbot on different devices or layouts.
Props
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| verticalPosition | 'top' \| 'bottom' | ❌ | Vertical position of the chatbot. Default: 'bottom' |
| pushContentDown | boolean | ❌ | When true and verticalPosition is 'top', the chatbot will push content down instead of overlaying it. Default: false |
| 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. |
🎨 Themes
The chatbot supports two themes:
light: Light theme with bright colorsdark: Dark theme with dark colors
<ChatbotProvider theme="dark" ...>
<ChatbotBar />
</ChatbotProvider>🌍 Localization
The chatbot supports the following languages:
pt-BR: Brazilian Portugueseen: English
<ChatbotProvider locale="pt-BR" ...>
<ChatbotBar />
</ChatbotProvider>Custom Texts
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.
<ChatbotProvider
locale="pt-BR"
apiURL="https://api.example.com"
theme="dark"
texts={{
'pt-BR': {
CHATBOT_NAME: 'Meu Assistente',
INPUT_PLACEHOLDER: 'Digite sua mensagem...',
CHATBOT_BAR: {
OPEN: 'Abrir chat',
CLOSE: 'Fechar chat',
},
CHAT_FEEDBACK: {
TITLE: 'Avalie esta resposta',
DESCRIPTION: 'Sua opinião nos ajuda a melhorar',
MESSAGE_FIELD: 'Mensagem (opcional)',
SUBMIT_BUTTON: 'Enviar',
CLOSE_BUTTON: 'Fechar',
RATE: 'Avaliar',
},
SUGGESTED_QUESTIONS: {
TITLE: 'Perguntas sugeridas',
LOADING: 'Carregando...',
},
STATUS: {
ONLINE: 'Online',
LOADING: 'Carregando',
WRITING: 'Digitando...',
UNAVAILABLE: 'Indisponível',
INACTIVE: 'Inativo',
},
ERRORS: {
UNKNOWN: 'Erro desconhecido',
},
MESSAGE_ACTIONS: {
COPY: 'Copiar',
SHARE: 'Compartilhar',
RESEND: 'Reenviar',
},
USER_LABEL: 'Você',
WRITING_MESSAGE: 'Digitando...',
},
'en': {
CHATBOT_NAME: 'My Assistant',
// ... other custom texts
},
}}
>
<ChatbotBar />
</ChatbotProvider>Available text keys:
CHATBOT_NAME: Name displayed in the chatbot headerINPUT_PLACEHOLDER: Placeholder text for the input fieldCHATBOT_BAR.OPEN: Text for opening the chatbotCHATBOT_BAR.CLOSE: Text for closing the chatbotCHAT_FEEDBACK.*: All feedback form textsSUGGESTED_QUESTIONS.*: Suggested questions section textsSTATUS.*: Status indicator textsERRORS.*: Error message textsMESSAGE_ACTIONS.*: Message action button textsUSER_LABEL: Label for user messagesWRITING_MESSAGE: Text shown when the bot is typing
📝 Complete Example
import React from 'react'
import { ChatbotProvider, ChatbotBar } from '@ibti-tech/chatbot'
function MyApp() {
return (
<div className="app">
<h1>My Application</h1>
{/* Other components of your application */}
<ChatbotProvider
locale="pt-BR"
apiURL={process.env.REACT_APP_CHATBOT_API_URL || "http://localhost:6061"}
theme="dark"
isOpen={false}
>
<ChatbotBar
verticalPosition="bottom"
horizontalPosition="right"
deviceHorizontalPosition="right"
/>
</ChatbotProvider>
</div>
)
}
export default MyApp🎛️ Advanced Configuration
Positioning the Chatbot
You can control the position of the chatbot using the ChatbotBar component props:
// Bottom right (default)
<ChatbotBar />
// Top right
<ChatbotBar verticalPosition="top" />
// Bottom left (bar container aligned left)
<ChatbotBar horizontalPosition="left" />
// Top left (bar container aligned left)
<ChatbotBar
verticalPosition="top"
horizontalPosition="left"
/>
// Precise horizontal positioning on desktop
<ChatbotBar
deviceHorizontalPosition="center" // Centers the device
/>
<ChatbotBar
deviceHorizontalPosition="50px" // 50px from left edge
/>
<ChatbotBar
deviceHorizontalPosition="calc(100% - 250px)" // 250px from right edge
/>
// Combining bar container and device positioning
<ChatbotBar
horizontalPosition="right" // Bar container on right
deviceHorizontalPosition="20px" // Device 20px from left (within container)
/>Understanding the positioning props:
horizontalPosition: Controls the alignment of the bar container ('left'or'right')deviceHorizontalPosition: Provides precise control over the ChatbotDevice position on desktop:- Predefined values:
'left','right','center'(use margin-based alignment) - Custom values: Any CSS unit string (e.g.,
'20px','10%','calc(100% - 200px)') applied as theleftproperty - Only affects desktop/tablet view; mobile always uses full width
- Predefined values:
Controlling Initial State
Use the isOpen prop to control whether the chatbot starts open or closed:
<ChatbotProvider
locale="pt-BR"
apiURL="https://api.example.com"
theme="dark"
isOpen={true} // Chatbot starts open
>
<ChatbotBar />
</ChatbotProvider>🔧 Requirements
Peer Dependencies
This package requires the following dependencies that must be installed in your project:
react:^18.2.0react-dom:^18.2.0lodash:^4.17.21nookies:^2.5.2
Make sure these dependencies are installed:
yarn add react react-dom lodash nookies
# or
npm install react react-dom lodash nookies📡 Backend API
The chatbot expects the backend API to be configured and accessible at the provided URL. The API must implement the following endpoints:
Required Endpoints
1. GET /chat/welcome?locale={locale}
Purpose: Retrieves the welcome message and checks API health/availability.
Query Parameters:
locale(required): The locale code ('pt-BR'or'en')
Response:
{
"welcomeMessage": "Hello! How can I help you today?"
}Status Codes:
200 OK: API is available and welcome message is returned4xx/5xx: API is considered unavailable
Notes:
- This endpoint is used for health checks (via
HEADorGETrequests) - The chatbot uses this to determine connection status
- Should return a welcome message appropriate for the specified locale
2. POST /chat/completion?locale={locale}
Purpose: Sends a chat message and receives a streaming response from the AI assistant.
Query Parameters:
locale(required): The locale code ('pt-BR'or'en')
Request Body:
{
"context": [
{
"role": "user",
"content": "What is artificial intelligence?"
},
{
"role": "assistant",
"content": "Artificial intelligence (AI) is..."
},
{
"role": "user",
"content": "Tell me more about machine learning"
}
]
}Request Body Schema:
context(required, array): Array of chat messages representing the conversation history- Each item must have:
role(required, string): Either"user"or"assistant"content(required, string): The message content
- The array must not be empty
- The last message should typically be from the
"user"role
- Each item must have:
Response:
- Content-Type:
text/event-stream - Format: Server-Sent Events (SSE) stream
- Body: Plain text chunks that are concatenated to form the complete response
Response Headers:
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-aliveStatus Codes:
200 OK: Stream started successfully429 Too Many Requests: Rate limit exceeded (should send error message via stream before closing)4xx/5xx: Error occurred
Streaming Behavior:
- The response is sent as a continuous stream of text chunks
- Each chunk is immediately displayed to the user as it arrives
- The stream ends when the complete response is sent
- The chatbot accumulates all chunks to form the final message
Error Handling:
- For
429errors, the API should send a friendly error message via the stream before closing:{"error": "Sorry, too many requests were made. Please try again in a few moments. 😊"} - For other errors, the stream should be closed and an appropriate HTTP status code returned
Example Flow:
- Frontend sends POST request with conversation context
- Backend starts streaming response chunks
- Frontend receives chunks and displays them incrementally
- Stream completes when response is finished
- Frontend saves the complete message to conversation history
3. POST /chat/feedback
Purpose: Submits user feedback about a chatbot response (rating and optional message).
Request Body:
{
"rating_score": 5,
"chat_context": [
{
"role": "user",
"content": "What is AI?"
},
{
"role": "assistant",
"content": "Artificial intelligence is..."
}
],
"locale": "pt-BR",
"message": "Very helpful response!"
}Request Body Schema:
rating_score(required, number): Rating from 1 to 5 (inclusive)- Valid values:
1,2,3,4,5
- Valid values:
chat_context(required, array): The conversation context that was rated- Same structure as in
/chat/completionendpoint - Must not be empty
- Same structure as in
locale(required, string): The locale code ('pt-BR'or'en')message(optional, string): Optional feedback message from the user
Response:
- Status Code:
200 OKor201 Created(implementation dependent) - Body: Typically empty or a success confirmation
Status Codes:
200 OK/201 Created: Feedback submitted successfully400 Bad Request: Invalid request body (invalid rating, missing fields, etc.)4xx/5xx: Other errors
Notes:
- This endpoint is called when a user rates a chatbot response
- The feedback is typically stored for analytics and improvement purposes
- The endpoint should handle the request asynchronously if possible to avoid blocking the UI
API Requirements Summary
| Endpoint | Method | Purpose | Streaming | Required |
|----------|--------|---------|-----------|----------|
| /chat/welcome | GET | Health check & welcome message | ❌ | ✅ |
| /chat/completion | POST | Send message & receive response | ✅ | ✅ |
| /chat/feedback | POST | Submit user feedback | ❌ | ✅ |
Implementation Notes
- CORS: The API must allow cross-origin requests from the frontend domain
- Locale Support: All endpoints should respect the
localeparameter and return appropriate content - Error Handling: Provide clear error messages in the appropriate locale
- Streaming: The
/chat/completionendpoint must support Server-Sent Events (SSE) for real-time response streaming - Rate Limiting: Consider implementing rate limiting and return
429status when exceeded - Content-Type:
- Use
application/jsonfor JSON endpoints - Use
text/event-streamfor streaming endpoints
- Use
Example API Base URL
<ChatbotProvider
apiURL="https://api.example.com" // Base URL without trailing slash
// ...
/>The chatbot will automatically append the endpoint paths (e.g., /chat/welcome, /chat/completion, /chat/feedback) to this base URL.
🐛 Issues and Support
If you encounter any issues or have questions:
- Check the complete documentation
- Open an issue on GitHub
- Contact the IBTI team
📄 License
ISC
👥 Author
IBTI Soluções em TI
For more information about development and contribution, see the DEV_NOTES.md file.
