### Clone QuikChatJS Express.js Example Repository
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/README.md
Clones the QuikChatJS repository and navigates into the specific Express.js example directory to begin setup.
```bash
git clone https://github.com/yourusername/quikchatjs.git
cd quikchatjs/examples/express-chat-widget
```
--------------------------------
### Install Node.js Project Dependencies
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/index.html
Command to install all required Node.js packages listed in `package.json` using npm.
```Bash
npm install
```
--------------------------------
### Install Python Dependencies for FastAPI Quikchat
Source: https://github.com/deftio/quikchat/blob/main/examples/fastapi_llm/index.html
This command installs all necessary Python packages required to run the FastAPI Quikchat application, as specified in the `requirements.txt` file.
```shell
pip install -r requirements.txt
```
--------------------------------
### Install Python Dependencies for FastAPI Quikchat
Source: https://github.com/deftio/quikchat/blob/main/examples/fastapi_llm/README.md
Instructions to install the required Python packages for the FastAPI Quikchat project using pip from the `requirements.txt` file.
```bash
pip install -r requirements.txt
```
--------------------------------
### Start Express.js Application Server
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/index.html
Command to launch the main Express.js server, making the chat application accessible locally.
```Bash
node server.js
```
--------------------------------
### Install Node.js Project Dependencies
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/README.md
Installs all required Node.js packages listed in the `package.json` file using npm.
```bash
npm install
```
--------------------------------
### Initialize Node.js Project and Install Dependencies
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/NPM_Express_js.md
Initializes a new Node.js project and installs the 'quikchat' and 'expressjs' npm packages required for the demo. This step prepares the project environment.
```bash
npm init
npm install quikchat expressjs
```
--------------------------------
### Clone QuikChatJS Repository
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/index.html
Instructions to clone the QuikChatJS repository and navigate to the Express chat widget example directory.
```Bash
git clone https://github.com/yourusername/quikchatjs.git
cd quikchatjs/examples/express-chat-widget
```
--------------------------------
### CSS Styling for QuikChat React Example
Source: https://github.com/deftio/quikchat/blob/main/examples/quikchat-react.html
This CSS defines the basic layout for the QuikChat React example page, including body, root container, and styling for interactive system buttons.
```CSS
body { margin: 0; padding: 5%; height: 100%; width: 100%; font-family: 'Open Sans', sans-serif; font-weight: 300; } #root { height: 50vh; width: 100%; margin: 0 auto; } .system-btn { padding: 8px 8px; background-color: #918434; color: white; border: none; border-radius: 4px; cursor: pointer; white-space: nowrap; margin-right: 10px; }
```
--------------------------------
### Run FastAPI Quikchat Server
Source: https://github.com/deftio/quikchat/blob/main/examples/fastapi_llm/README.md
Command to start the FastAPI web server, making the application accessible locally. The server will typically run on `http://127.0.0.1:8000`.
```bash
python main.py
```
--------------------------------
### Run the FastAPI Quikchat Application
Source: https://github.com/deftio/quikchat/blob/main/examples/fastapi_llm/index.html
Execute this command to start the FastAPI web server. Once running, the application will be accessible in your browser at the specified local address.
```shell
python main.py
```
--------------------------------
### Start Express.js Server
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/README.md
Launches the Node.js Express.js server, making the application accessible via a web browser.
```bash
node server.js
```
--------------------------------
### Configure OpenAI API Environment Variables
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/index.html
Example `.env` file content for setting up OpenAI API base URL and API key, crucial for the chat functionality.
```Shell
OPENAI_BASE_URL=https://api.openai.com/v1
OPENAI_API_KEY=your-api-key
```
--------------------------------
### Integrating QuikChat with Local LMStudio LLM for Conversational Memory
Source: https://github.com/deftio/quikchat/blob/main/examples/lmstudio_with_memory.html
This JavaScript example demonstrates how to set up `quikchat` to interact with a local LMStudio LLM, enabling conversational memory. It initializes the chat interface and defines a streaming callback function that sends user input along with the entire chat history to the LMStudio API, then processes the streamed responses to update the chat in real-time. This setup requires LMStudio to be running locally on port 1234 with a compatible model like `llama3.1`.
```JavaScript
// set up chat instance
const streamingChat = new quikchat('#chat-container',localLLMStreamingCallback, {
theme: 'quikchat-theme-light',
titleArea: { "title": "Memory Chat", "show": true, "align": "left" }
});
streamingChat.messageAddNew("How can I help? ", "bot", "left", "system");
// this calls the Ollama Streaming API with token streaming.
// note that a very similar function can be used to call OpenAI, Mistral, or, Claude etc.
// this is a pure js implementation that hits the API directly and doesn't use any libraries.
function localLLMStreamingCallback(chatInstance, userInput) {
let startPrompt = {
"content": "You are a skilled assistant. Respond to user input with detailed careful answers. If you do not know the answer respond with 'I don't have any information on that topic'.",
"role": "system"
};
let start = true;
chatInstance.messageAddNew(userInput, "user", "right"); // echos the user input to the chat
return fetch('http://localhost:1234/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: "lmstudio-community/Meta-Llama-3.1-8B-Instruct-GGUF",
messages: [startPrompt, ...chatInstance.historyGet()], // passes the chat history to the model
stream: true
})
}).then(response => {
if (!response.ok) {
throw new Error("HTTP error! Status: " + response.status);
}
return response.body.getReader();
}).then(reader => {
let id;
return reader.read().then(function processResult(result) {
if (result.done) {
return;
}
let y=null,x = new TextDecoder().decode(result.value, { stream: true });
x= x.replace("data: ", ""); // remove the data: prefix.. others do this too aparently
try {
y = JSON.parse(x.trim()); // decode the JSON
} catch(e) {}
//console.log(y);
if (y && y.choices && y.choices[0].delta && y.choices[0].delta.content) {
let content = y.choices[0].delta.content;//.message.content;
if (start) {
id = chatInstance.messageAddNew(content, "bot", "left"); // start a new chat message
start = false;
} else {
chatInstance.messageAppendContent(id, content); // append new content to message
}
return reader.read().then(processResult);
}
});
}).then(() => {
// finally done .. can do something here if needed.
}).catch(error => {
console.error('Fetch error:', error);
});
}
```
--------------------------------
### Accessing QuikChat Interfaces
Source: https://github.com/deftio/quikchat/blob/main/examples/fastapi_llm/index.html
These examples demonstrate how to access the main chat interface and the embeddable widget by navigating to their respective URLs in a web browser. This provides a quick way to test and interact with the application locally.
```Usage
Main Chat Interface: Access the main chat interface by navigating to http://127.0.0.1:8000/ in your browser.
Embeddable Widget: Access the embeddable widget by navigating to http://127.0.0.1:8000/widget.
```
--------------------------------
### Configure OpenAI API Environment Variables
Source: https://github.com/deftio/quikchat/blob/main/examples/fastapi_llm/README.md
Guide to setting up necessary environment variables for OpenAI API access by creating a `.env` file in the project root. This includes the base URL and your API key.
```plaintext
OPENAI_BASE_URL=https://api.openai.com/v1
OPENAI_API_KEY=your_openai_api_key_here
```
--------------------------------
### Run Express.js Server
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/NPM_Express_js.md
Starts the local server using Node.js and Express.js, making the Quikchat widget accessible via a web browser at http://localhost:3000.
```bash
node server.cjs
```
--------------------------------
### Basic CSS Styling for Chat Containers
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/static/index.html
Defines basic styling for the page body and chat container elements, setting margins, padding, font properties, and layout for the chat widgets.
```CSS
body { margin: 0; padding: 5%; height: 100%; width: 100%; font-family: 'Open Sans', sans-serif; font-weight: 300; box-sizing: border-box; } .chatContainer { float: left; height: 45vh; width: 45%; margin: 0 auto; padding-right: 10px; margin-bottom: 20px; }
```
--------------------------------
### Build Quikchat Project with Rollup.js
Source: https://github.com/deftio/quikchat/blob/main/index.html
Provides the command to build the Quikchat project. This process uses Rollup.js and requires all dependencies to be installed via `npm install` prior to execution. The build output is a packed and minified version of the code.
```shell
npm run build
```
--------------------------------
### Initialize and Use QuikChatJS Widget with ESM
Source: https://github.com/deftio/quikchat/blob/main/examples/example_esm.html
Demonstrates how to initialize the QuikChatJS widget using ES Modules, handle user messages by echoing them, generate bot responses with lorem ipsum, and dynamically change the widget's theme. It also shows how to add initial messages to the chat.
```JavaScript
import quikchat from '../dist/quikchat.esm.min.js';
document.addEventListener('DOMContentLoaded', () => {
const parentDiv = document.querySelector('#chatContainerInstance');
window.chatBox = new quikchat(parentDiv, (chat, msg) => {
chat.messageAddNew(msg, 'me', 'right'); // echo the message to the chat area
// example of a bot response using the built-in lorem ipsum generator
const botResponse = quikchat.loremIpsum();
chat.messageAddNew(botResponse, 'bot', 'left');
}, {
// options
theme: 'quikchat-theme-light',
titleArea: {
title: 'QuikChatJS',
align: 'left',
show: true
}
});
chatBox.messageAddNew('Hello, how are you?', 'bot', 'left');
chatBox.messageAddNew('I am fine, thank you.', 'user', 'right');
chatBox.messageAddNew('How can I help you today?', 'bot', 'left');
chatBox.changeTheme("quikchat-theme-light");
console.log("quikchat version: "+quikchat.version().version);
});
//cycle through themes
let cycleThemes = (() => {
let themes = ['quikchat-theme-light', 'quikchat-theme-dark', 'quikchat-theme-debug'];
let themeIndex = 0;
return () => {
themeIndex++;
if (themeIndex >= themes.length) {
themeIndex = 0;
}
chatBox.changeTheme(themes[themeIndex]);
};
})();
document.getElementById('themeBtn').addEventListener('click', cycleThemes);
```
--------------------------------
### Initialize QuikChatJS for Streaming Chat with History
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/static/widget.html
Initializes the QuikChatJS library for a streaming chat interface. It handles user input, sends chat history to a backend API, and processes streaming responses from the server, appending them in real-time to the chat interface.
```JavaScript
const streamingDiv = document.querySelector('#chatContainerStreaming'); // Streaming response chat box const streamingChatBox = new quikchat(streamingDiv, async (chat, msg) => { chat.messageAddNew(msg, 'me', 'right'); const response = await fetch('/api/streaming-completion-history', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ history: chat.historyGet() })
}); const reader = response.body.getReader(); const decoder = new TextDecoder("utf-8"); let data = ""; let msgId = 0; while (true) { const { done, value } = await reader.read(); if (done) break; data += decoder.decode(value, { stream: true }); if (0 == msgId) msgId = chat.messageAddNew(data, 'bot', 'left', 'system'); else chat.messageAppendContent(msgId, data); data = ""; // clear data for next chunk } }, { theme: 'quikchat-theme-light', titleArea: { title: 'Streaming Chat with History', align: 'left', show: true }, }); streamingChatBox.messageAddNew('How can I help you?', 'bot', 'left', 'system');
```
--------------------------------
### QuikChatJS Express API Endpoints Overview
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/index.html
Documentation of the API endpoints exposed by the Express.js server, including methods and their purposes for serving pages and handling OpenAI completions.
```APIDOC
GET /
Serves the main chat page.
GET /widget
Serves the embeddable chat widget.
POST /api/completion
Receives a message and returns a completion response from the OpenAI API.
POST /api/completion-history
Receives a history of messages and returns a completion response considering the conversation context.
POST /api/streaming-completion
Streams a completion response in real-time.
POST /api/streaming-completion-history
Streams a completion response in real-time considering the conversation context.
```
--------------------------------
### QuikChatJS Base CSS Styling
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/static/widget.html
Provides basic CSS rules for the QuikChatJS container and general page layout, ensuring proper sizing and font application.
```CSS
* { margin: 0; padding: 0; box-sizing: border-box; } html,body { height: 100%; width: 100%; font-family: 'Open Sans', sans-serif; } .chatContainer { height: 100%; width: 100%; }
```
--------------------------------
### Initialize Completion AI Chat Widget with JavaScript
Source: https://github.com/deftio/quikchat/blob/main/examples/fastapi_llm/static/index.html
Initializes a chat widget that waits for a complete AI response before displaying it. It sends user messages to `/api/completion` and displays the full response once received.
```javascript
const completionDiv = document.querySelector('#chatContainerCompletion');
const completionChatBox = new quikchat(completionDiv, async (chat, msg) => {
chat.messageAddNew(msg, 'me', 'right');
const response = await fetch('/api/completion', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: msg })
});
const data = await response.json();
if (data.response) {
chat.messageAddNew(data.response, 'bot', 'left', 'system');
} else {
chat.messageAddNew('Error fetching completion.', 'bot', 'left', 'system');
}
}, {
theme: 'quikchat-theme-light',
titleArea: { title: 'Completion Chat', align: 'left', show: true }
});
completionChatBox.messageAddNew('How can I help you?', 'bot', 'left');
```
--------------------------------
### Initialize QuikChatJS Widget and Handle Messages (UMD)
Source: https://github.com/deftio/quikchat/blob/main/examples/example_umd.html
This JavaScript example demonstrates how to initialize the QuikChatJS widget using the UMD build. It sets up a message handler to echo user messages and generate bot responses, configures initial theme and title area options, and adds initial messages to the chat.
```JavaScript
document.addEventListener('DOMContentLoaded', () => {
const parentDiv = document.querySelector('#chatContainerInstance');
window.chatBox = new quikchat(parentDiv, (chat, msg) => {
chat.messageAddNew(msg, 'me', 'right'); // echo the message to the chat area
// now do something with the message
// example of a bot response using the built-in lorem ipsum generator
const botResponse = quikchat.loremIpsum();
chat.messageAddNew(botResponse, 'bot', 'left');
}, {
theme: 'quikchat-theme-light',
titleArea: {
title: 'QuikChatJS',
align: 'left',
show: true
}
});
chatBox.messageAddNew('Hello, how are you?', 'bot', 'left');
chatBox.messageAddNew('I am fine, thank you.', 'user', 'right');
chatBox.messageAddNew('How can I help you today?', 'bot', 'left');
chatBox.changeTheme("quikchat-theme-light");
console.log("quikchat version: "+quikchat.version().version);
});
```
--------------------------------
### Basic CSS Styling for QuikChatJS Container and Buttons
Source: https://github.com/deftio/quikchat/blob/main/examples/example_esm.html
Provides essential CSS rules for the QuikChatJS widget's container and associated system buttons. It sets up basic layout, font styles, and button appearance, ensuring the widget integrates cleanly into a web page.
```CSS
body { margin: 0; padding: 5%; height: 100%; width: 100%; font-family: 'Open Sans', sans-serif; font-weight: 300; box-sizing: border-box; } .chatContainer { height: 45vh; width: 100%; margin: 0 auto; } /* these are not part of the widget, just for the demo test */ /* these are not part of the widget, just for the demo test */ .system-btn { margin-top: 2px; margin-bottom: 2px; padding: 12px 8px; background-color: #443491; color: white; border: none; border-radius: 4px; cursor: pointer; white-space: nowrap; }
```
--------------------------------
### Build QuikChat Project from Source
Source: https://github.com/deftio/quikchat/blob/main/README.md
This snippet provides the commands to build the QuikChat project from source using Rollup.js. It involves installing necessary Node.js dependencies and then executing the build script to compile and minify the code.
```bash
npm install
npm run build
```
--------------------------------
### Initialize QuikChat.js with Message Handling and Options
Source: https://github.com/deftio/quikchat/blob/main/index.html
This example illustrates a complete QuikChat initialization within a DOMContentLoaded listener. It demonstrates how to instantiate the chat widget, provide a parent container, define a callback for user messages (echoing and bot response), and configure initial options like theme and title area.
```JavaScript
document.addEventListener('DOMContentLoaded', () => {
const parentDiv = document.querySelector('#chatContainerInstance');
window.chatBox = new quikchat(parentDiv,
(chat, msg) => {
chat.messageAddNew(msg, 'me', 'right'); // echo the message to the chat area
// example of a bot response using the built-in lorem ipsum generator
const botResponse = quikchat.loremIpsum();
chat.messageAddNew(botResponse, 'bot', 'left');
},
{ // options
theme: 'quikchat-theme-light',
titleArea: { title: 'QuikChatJS', align: 'left', show: true },
});
chatBox.messageAddNew('Hello, how are you?', 'bot', 'left');
chatBox.messageAddNew('I am fine, thank you.', 'user', 'right');
chatBox.messageAddNew('How can I help you today?', 'bot', 'left');
chatBox.changeTheme("quikchat-theme-light");
console.log("quikchat version: "+quikchat.version().version);
});
```
--------------------------------
### Initialize Streaming AI Chat Widget with JavaScript
Source: https://github.com/deftio/quikchat/blob/main/examples/fastapi_llm/static/index.html
Initializes a chat widget that displays AI responses word by word using server-sent events. It sends user messages to `/api/streaming-completion` and appends chunks of the response as they arrive.
```javascript
const streamingDiv = document.querySelector('#chatContainerStreaming');
const streamingChatBox = new quikchat(streamingDiv, async (chat, msg) => {
chat.messageAddNew(msg, 'me', 'right');
const response = await fetch('/api/streaming-completion', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: msg })
});
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let data = "";
let msgId = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
data += decoder.decode(value, { stream: true });
if (0 == msgId) msgId = chat.messageAddNew(data, 'bot', 'left', 'system');
else chat.messageAppendContent(msgId, data);
data = ""; // clear data for next chunk
}
}, {
theme: 'quikchat-theme-light',
titleArea: { title: 'Streaming Chat', align: 'left', show: true }
});
streamingChatBox.messageAddNew('How can I help you?', 'bot', 'left', 'system');
```
--------------------------------
### Initialize QuikChat Streaming Widget with FastAPI Integration
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/static/index.html
Initializes a QuikChat widget for streaming AI responses. It sends user messages to a '/api/streaming-completion' endpoint via POST request and processes the streamed response chunk by chunk, appending content to the chat box as it arrives.
```JavaScript
const streamingDiv = document.querySelector('#chatContainerStreaming');
const completionDiv = document.querySelector('#chatContainerCompletion');
// Streaming response chat box
const streamingChatBox = new quikchat(streamingDiv, async (chat, msg) => {
chat.messageAddNew(msg, 'me', 'right');
const response = await fetch('/api/streaming-completion', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: msg })
});
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let data = "";
let msgId = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
data += decoder.decode(value, { stream: true });
if (0 == msgId) msgId = chat.messageAddNew(data, 'bot', 'left', 'system');
else chat.messageAppendContent(msgId, data);
data = ""; // clear data for next chunk
}
}, {
theme: 'quikchat-theme-light',
titleArea: { title: 'Streaming Chat', align: 'left', show: true },
});
streamingChatBox.messageAddNew('How can I help you?', 'bot', 'left', 'system');
```
--------------------------------
### Initialize QuikChat Completion Widget with FastAPI Integration
Source: https://github.com/deftio/quikchat/blob/main/examples/npm_express/static/index.html
Initializes a QuikChat widget for full AI response completions. It sends user messages to a '/api/completion' endpoint via POST request and waits for the complete JSON response before displaying the AI's message in the chat box.
```JavaScript
// Completion response chat box
const completionChatBox = new quikchat(completionDiv, async (chat, msg) => {
chat.messageAddNew(msg, 'me', 'right');
const response = await fetch('/api/completion', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: msg })
});
const data = await response.json();
if (data.response) {
chat.messageAddNew(data.response, 'bot', 'left', 'system');
} else {
chat.messageAddNew('Error fetching completion.', 'bot', 'left', 'system');
}
}, {
theme: 'quikchat-theme-light',
titleArea: { title: 'Completion Chat', align: 'left', show: true },
});
completionChatBox.messageAddNew('How can I help you?', 'bot', 'left');
```
--------------------------------
### QuikChat Lorem Ipsum Generator API (APIDOC)
Source: https://github.com/deftio/quikchat/blob/main/coverage/quikchat.js.html
API documentation for the static `loremIpsum` method, which generates a string of Lorem Ipsum text. It allows specifying character count, starting position, and capitalization.
```APIDOC
quikchat.loremIpsum(numChars, [startSpot=0], [startWithCapitalLetter=true])
numChars: number - The number of characters to generate (random btw 25 and 150 if undefined).
startSpot: number (optional, default=0) - The starting index in the Lorem Ipsum text. If undefined, a random startSpot will be generated.
startWithCapitalLetter: boolean (optional, default=true) - If true, capitalize the first character or inject a capital letter if the first character isn't a capital letter.
Returns: string - A string of Lorem Ipsum text.
```
--------------------------------
### Get QuikChat Library Version and License (JavaScript)
Source: https://github.com/deftio/quikchat/blob/main/coverage/quikchat.js.html
This static method returns an object containing metadata about the QuikChat library, including its version number, license type, and a link to its GitHub repository.
```javascript
static version() {
return { "version": "1.1.12", "license": "BSD-2", "url": "https://github/deftio/quikchat", "fun": true };
}
```
--------------------------------
### Initialize QuikChat with Callback and Manage UI Elements
Source: https://github.com/deftio/quikchat/blob/main/README.md
This example demonstrates initializing QuikChat using a CSS selector for the container and a custom callback function for handling user messages. It also showcases various methods to interact with the chat interface, including adding messages programmatically, retrieving chat history, and dynamically hiding/showing UI elements like the title and input areas, as well as changing themes.
```javascript
chat = new quikchat(
"#chat-container",//a css selector such as "#chat-container" or DOM element
(chat, msg) => { // this callback triggered when user hits the Send
// messages are not automatically echoed.
// this allows filtering of the message before posting.
chat.messageAddNew(msg, 'me', 'right'); // echo msg to chat area
// now call an LLM or do other actions with msg
// ... callLLM(msg) ... do other logic if needed.
// or callLLM(chat.historyGet()); // pass full history (can also filter)
},
{
theme: 'quikchat-theme-light', // set theme, see quikchat.css
titleArea: { title: 'My Chat', align: 'left', show: true }, // internal title area if desired
});
// Add a message at any point not just from callback
chat.messageAddNew('Hello!', 'You', 'left'); // should appear left justified
chat.messageAddNew('Hello!', 'Me', 'right'); // should appear right justified
//... other logic
let messageHistory = chat.historyGet(); // get all the messages (see docs for filters)
console.log(messageHistory); // do something with messages
// show / hide the title area
chat.titleAreaHide(); // hides the title area for a bare chat
// hide the input area
chat.inputAreaHide(); // hides the input area so chat is now just a message stream.
// change themes at any time
chat.changeTheme("quikchat-theme-dark"); // change theme on the fly (see quikchat.css for examples)
```
--------------------------------
### Initialize and Interact with QuikChat Widget in JavaScript
Source: https://github.com/deftio/quikchat/blob/main/dev/debug.html
Demonstrates how to import and initialize the QuikChat widget, attach it to a specified DOM element, and configure its behavior. This snippet includes examples of adding new messages, echoing user input, and utilizing the built-in lorem ipsum generator for testing purposes. It also shows how to set initial theme and title area properties.
```JavaScript
import quikchat from '../src/quikchat.js';
window.quikchat = quikchat; // user can access quikchat from the console
document.addEventListener('DOMContentLoaded', () => {
const chatDiv = document.querySelector('#chatContainer');
window.chatBox = new quikchat(chatDiv, (chat, userContent) => {
chat.messageAddNew(userContent, 'me', 'right'); // echo the message to the chat area
// do something with the message
// this just creates a random of messages using the built-in lorem ipsum generator
chat.messageAddNew(quikchat.loremIpsum(), 'bot', 'left');
}, {
theme: 'quikchat-theme-light',
titleArea: {
title: 'QuikChatJS',
align: 'left',
show: true
}
});
chatBox.messageAddNew('Hello, how are you?', 'bot', 'left');
chatBox.messageAddNew('I am fine, thank you.', 'user', 'right');
chatBox.messageAddNew('How can I help you today?', 'bot', 'left');
chatBox.messageAddNew('I am just trying to test the chat control.', 'user', 'right');
chatBox.messageAddNew('That\'s great!\nlets see how things are working.', 'bot', 'left');
chatBox.messageAddNew('Multi-line content\nAnd some more\nNow look at that\m', 'user', 'right');
chatBox.messageAddNew('That\'s great!\nlets see how things are working.', 'bot', 'left');
chatBox.messageAddNew('Long Message : ' + quikchat.loremIpsum(700,0), 'user', 'right');
chatBox.messageAddNew(quikchat.loremIpsum(70,0), 'user', 'center');
chatBox.messageAddNew('Long Message : ' + quikchat.loremIpsum(700,0), 'user', 'center');
chatBox.messageAddNew(quikchat.loremIpsum(70,0), 'user', 'center');
chatBox.messageAddNew('Long Message : ' + quikchat.loremIpsum(700,0), 'user', 'center');
chatBox.changeTheme("quikchat-theme-light");
let x = chatBox.messageAddNew("Tada","user","right")
window.x = x;
});
```
--------------------------------
### Initialize and Configure Dual QuikChat Instances for Cross-Communication
Source: https://github.com/deftio/quikchat/blob/main/examples/dual-chatrooms.html
This JavaScript code initializes two independent QuikChat instances, '#chat-container1' and '#chat-container2'. It configures their respective titles, applies a dark theme to the second instance, and sets up callback functions to enable real-time message exchange between them. Messages sent in one chat are echoed locally and forwarded to the other instance, demonstrating separate control and inter-chat communication.
```JavaScript
const chat1 = new quikchat('#chat-container1');
chat1.titleAreaSetContents("Sue Smith Chat Window","left"); // optional title area
chat1.titleAreaShow(); // show the title area (default is hidden)
const chat2 = new quikchat('#chat-container2');
chat2.titleAreaSetContents("Pat Park Chat Window","left"); // optional title area
chat2.titleAreaShow(); // show the title area (can hide with chat2.titleAreaHide())
chat2.changeTheme("quikchat-theme-dark"); // change theme of chat2 to show different themes on same page
// callback functions to send messages to each other
cb1 = (chatInstance, content) => {
chatInstance.messageAddNew(content,"Sue Smith","right") // echo input to own message area
chat2.messageAddNew(content,"Sue Smith","left") // post to other chat
}
// set the callback functions
cb2 = (chatInstance, content) => {
chatInstance.messageAddNew(content,"Pat Park","right") // echo input to own message area
chat1.messageAddNew(content,"Pat Park","left") // post to other chat
}
chat1.setCallbackOnSend(cb1);
chat2.setCallbackOnSend(cb2);
// some starter messages for each chat
chat1.messageAddNew("Hello, Pat!","Sue Smith","right"); // writes to chat1
chat1.messageAddNew("Hello, Sue!","Pat Park","left");
chat2.messageAddNew("Hello, Pat!","Sue Smith","left"); // writes to chat2
chat2.messageAddNew("Hello, Sue!","Pat Park","right");
```
--------------------------------
### React Component for QuikChat Integration and Interaction
Source: https://github.com/deftio/quikchat/blob/main/examples/quikchat-react.html
This React component demonstrates how to integrate the QuikChat library, manage chat state with useRef, handle user messages, simulate bot responses, and provide UI controls to toggle the chat title, input area, and cycle through themes.
```JavaScript
const { QuikChat } = window.QuikChatReact;
const App = () => {
const chatRef = React.useRef();
const handleSend = (chat, msg) => {
chat.messageAddNew(msg, 'me', 'right');
// Simulate bot response
setTimeout(() => {
chat.messageAddNew('This is a simulated response.', 'bot', 'left');
}, 1000);
};
const toggleTitle = () => {
chatRef.current.titleAreaToggle();
};
const toggleInput = () => {
chatRef.current.inputAreaToggle();
};
const cycleThemes = (() => {
const themes = ['quikchat-theme-light', 'quikchat-theme-dark', 'quikchat-theme-debug'];
let themeIndex = 0;
return () => {
themeIndex = (themeIndex + 1) % themes.length;
chatRef.current.changeTheme(themes[themeIndex]);
};
})();
return React.createElement(
'div',
null,
React.createElement(QuikChat, {
ref: chatRef,
onSend: handleSend,
options: {
theme: 'quikchat-theme-light',
titleArea: {
title: 'QuikChat React',
align: 'left',
show: true,
},
},
}),
React.createElement(
'div',
{ style: { marginTop: '20px' } },
React.createElement('button', { className: "system-btn", onClick: toggleTitle }, 'Toggle Title'),
React.createElement('button', { className: "system-btn", onClick: toggleInput }, 'Toggle Input'),
React.createElement('button', { className: "system-btn", onClick: cycleThemes }, 'Change Themes')
)
);
};
ReactDOM.render(React.createElement(App), document.getElementById('root'));
```
--------------------------------
### Integrate QuikChat.js via CDN or ES Module
Source: https://github.com/deftio/quikchat/blob/main/index.html
This snippet demonstrates how to include the QuikChat.js library in a web project. It shows both the CDN approach for quick setup by linking script and stylesheet, and the ES module import for modern modular applications.
```HTML
```
```JavaScript
import quikchat from '../dist/quikchat.esm.min.js';
```
--------------------------------
### Initialize QuikChat and Implement Ollama Streaming Callback
Source: https://github.com/deftio/quikchat/blob/main/examples/ollama_with_memory.html
This JavaScript code initializes a QuikChat instance, configuring it with a light theme and a custom title. It then defines `ollamaStreamingCallback`, a pure JavaScript function that interacts directly with the local Ollama API (http://localhost:11434/api/chat) to stream responses. The callback sends user input along with the full chat history to Ollama, enabling conversational memory. It processes the streamed JSON responses, appending new content to the bot's message in real-time. This setup requires a local Ollama instance running on port 11434 with the `llama3.1` model available.
```JavaScript
// set up chat instance
const streamingChat = new quikchat('#chat-container', ollamaStreamingCallback, {
theme: 'quikchat-theme-light',
titleArea: {
title: "Memory Chat",
"show": true,
"align": "left"
}
});
streamingChat.messageAddNew("How can I help? ", "bot", "left", "system");
// this calls the Ollama Streaming API with token streaming.
// note that a very similar function can be used to call OpenAI, Mistral, or, Claude etc.
// this is a pure js implementation that hits the API directly and doesn't use any libraries.
function ollamaStreamingCallback(chatInstance, userInput) {
let startPrompt = {
"content": "You are a skilled assistant. Respond to user input with detailed careful answers. If you do not know the answer respond with 'I don't have any information on that topic'.",
"role": "system"
};
let start = true;
chatInstance.messageAddNew(userInput, "user", "right"); // echos the user input to the chat
return fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: "llama3.1",
messages: [startPrompt, ...chatInstance.historyGet()], // passes the chat history to the model
stream: true
})
}).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.body.getReader();
}).then(reader => {
let id;
return reader.read().then(function processResult(result) {
if (result.done) {
return;
}
let x = new TextDecoder().decode(result.value, {
stream: true
});
let y = JSON.parse(x.trim()); // deocde the JSON
let content = y.message.content; //.message.content;
if (start) {
id = chatInstance.messageAddNew(content, "bot", "left"); // start a new chat message
start = false;
} else {
chatInstance.messageAppendContent(id, content); // append new content to message
}
return reader.read().then(processResult);
});
}).then(() => {
// finally done .. can do something here if needed.
}).catch(error => {
console.error('Fetch error:', error);
});
}
```
--------------------------------
### Generate Lorem Ipsum Text (JavaScript)
Source: https://github.com/deftio/quikchat/blob/main/coverage/quikchat.js.html
This static method generates a string of Lorem Ipsum text. It allows customization of length, starting position, and initial capitalization. If `numChars` is not specified, it generates a random length between 25 and 150 characters.
```javascript
static loremIpsum(numChars, startSpot = undefined, startWithCapitalLetter = true) {
const loremText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ";
if (typeof numChars !== "number") {
numChars = Math.floor(Math.random() * (150)) + 25;
}
if (startSpot === undefined) {
startSpot = Math.floor(Math.random() * loremText.length);
}
startSpot = startSpot % loremText.length;
// Move startSpot to the next non-whitespace and non-punctuation character
while (loremText[startSpot] === ' ' || /[.,:;!?]/.test(loremText[startSpot])) {
startSpot = (startSpot + 1) % loremText.length;
}
let l = loremText.substring(startSpot) + loremText.substring(0, startSpot);
if (typeof numChars !== "number") {
numChars = l.length;
}
let s = "";
while (numChars > 0) {
s += numChars < l.length ? l.substring(0, numChars) : l;
numChars -= l.length;
}
if (s[s.length - 1] === " ") {
s = s.substring(0, s.length - 1) + "."; // always end on non-whitespace. "." was chosen arbitrarily.
}
if (startWithCapitalLetter) {
let c = s[0].toUpperCase();
c = /[A-Z]/.test(c) ? c : "M";
s = c + s.substring(1);
}
return s;
};
// Example usage:
// Returns 200 characters of Lorem Ipsum starting from index 50
loremIpsum(200, 50);
//Returns a 200 Lorem Ipsum characters starting from a random index
loremIpsum(200);
```
--------------------------------
### General CSS Utility and Layout Classes
Source: https://github.com/deftio/quikchat/blob/main/index.html
This extensive CSS block defines a comprehensive set of utility classes for styling web pages. It includes rules for box-sizing, page setup, fonts, text alignment, code formatting, padding, tables (with stripes and sorting indicators), tabbed interfaces, accordions, responsive grid layouts, box styling, sign-in/display helpers, heading sizes, column widths, and color themes (light/dark). Media queries are used for responsive page width adjustments.
```CSS
*{
box-sizing:border-box;
}
.bw-def-page-setup{
height:100%;
width:90%;
margin:0 auto;
padding-left:2%;
padding-right:2%;
left:0;
top:1%;
box-sizing:border-box;
}
.bw-font-serif{
font-family:Times New Roman, Times, serif;
}
.bw-font-sans-serif{
font-family:Arial, Helvetica, sans-serif;
}
.bw-left{
text-align:left;
}
.bw-right{
text-align:right;
}
.bw-center{
text-align:center;
margin:0 auto;
}
.bw-justify{
text-align:justify;
}
.bw-code{
font-family:monospace;
white-space:pre-wrap;
}
.bw-pad1{
padding-left:1%;
padding-right:1%;
}
.bw-table{
border-collapse:collapse;
border-spacing:0;
border:1px solid #444;
}
.bw-table th{
background-color:#bbb;
padding:4px;
border:1px solid #444;
}
.bw-table td{
padding:4px;
border:1px solid #444;
}
.bw-table-stripe tr:nth-child(even){
background-color:#f0f0f0;
}
.bw-table tr td:first-child{
font-weight:700;
}
.bw-table-border-round{
border-radius:2px;
}
.bw-table-sort-upa::after{
content:"\\2191";
}
.bw-table-sort-dna::after{
content:"\\2193";
}
.bw-table-sort-xxa::after{
content:"\\00a0";
}
.bw-tab-item-list{
margin:0;
padding-inline-start:0;
}
.bw-tab-item{
display:inline;
padding-top:0.75em;
padding-left:0.75em;
padding-right:0.75em;
border-top-right-radius:7px;
border-top-left-radius:7px;
}
.bw-tab-active{
font-weight:700;
}
.bw-tab:hover{
cursor:pointer;
font-weight:700;
}
.bw-tab-content-list{
margin:0;
padding-top:0.0em;
}
.bw-tab-content{
display:none;
border-radius:0;
}
.bw-tab-content, .bw-tab-active{
background-color:#ddd;
padding:0.5em;
}
.bw-accordian-container > div{
padding:0.5em;
}
.bw-container{
margin:0 auto;
}
.bw-row{
width:100%;
display:block;
}
.bw-row \[class^="bw-col"\]{
float:left;
}
.bw-row::after{
content:"";
display:table;
clear:both;
}
.bw-box-1{
padding-top:10px;
padding-bottom:10px;
border-radius:8px;
}
.bw-sign{
position:inherit;
display:table;
height:100%;
width:100%;
}
.bw-sign > div{
display:table-cell;
vertical-align:middle;
}
.bw-sign > div > div{
text-align:center;
}
.bw-hide{
display:none;
}
.bw-show{
display:block;
}
.bw-h1{
font-size:2.312rem;
}
.bw-h2{
font-size:1.965rem;
}
.bw-h3{
font-size:1.67rem;
}
.bw-h4{
font-size:1.419rem;
}
.bw-h5{
font-size:1.206rem;
}
.bw-h6{
font-size:1.025rem;
}
.bw-col-1{
width:8.333%;
}
.bw-col-2{
width:16.666%;
}
.bw-col-3{
width:25%;
}
.bw-col-4{
width:33.333%;
}
.bw-col-5{
width:41.666%;
}
.bw-col-6{
width:50%;
}
.bw-col-7{
width:58.333%;
}
.bw-col-8{
width:66.666%;
}
.bw-col-9{
width:75%;
}
.bw-col-10{
width:83.333%;
}
.bw-col-11{
width:91.666%;
}
.bw-col-12{
width:100%;
}
.bw-color-color {
color:#000
}
.bw-color-background-color {
background-color:#ddd
}
.bw-color-active {
active:#222
}
.bw-thm-light {
color: #020202 !important;;
background-color: #e2e2e2 !important;;
}
.bw-thm-dark {
color: #e2e2e2 !important;;
background-color: #020202 !important;;
}
@media only screen and (min-width: 540px) {
.bw-def-page-setup {
width: 96%;
}
}
@media only screen and (min-width: 720px) {
.bw-def-page-setup {
width: 92%;
}
}
@media only screen and (min-width: 960px) {
.bw-def-page-setup {
width: 88%;
}
}
@media only screen and (min-width: 1100px){
.bw-def-page-setup {
width: 86%;
}
}
@media only screen and (min-width: 1600px){
.bw-def-page-setup {
width: 84%;
}
}
.dbat {
padding-left: 10%;
padding-right: 10%;
}
```