AI Chat API
The API layer provides a way to programmatically interact with the chatbot. It enables operations such as sending messages, getting the chat history, and more.
- React JS ⚛️
- JavaScript 🟨
Usage
- react-js
- javascript
The useAiChatApi()
hook is used to create an instance of the AiChatApi
object. This object is used to interact with
the chatbot UI, such as sending messages, getting the chat history, and more.
const api = useAiChatApi();
Once created, the api
object can be passed to the AiChat
component as a prop, and its methods can be called to
interact with the AiChat UI.
<AiChat api={api} adapter={adapter} />
As for now, The API
features are only supported for the React JS version of NLUX
.
If you're using the plain JavaScript
and would like to use the API
features, please contact us on
Discord or created a feature request on GitHub.
The NLUX
team also offers prioritised feature requests implementation for
Enterprise users.
Feel free to reach out to us for more information.
API Calls
- react-js
- javascript
You can call api.<yourApiMethod>()
inside your component.
Since API calls are considered side effects, you should ensure that they are properly called (e.g. inside a useEffect
hook) to avoid unnecessary re-renders, and to ensure they do not interfere with the React rendering cycle.
import {AiChat, useAiChatApi} from 'nlux';
export default function App() {
// Create an instance of the AiChatApi using the useAiChatApi hook
const api = useAiChatApi();
// Call `api.composer.send(...)` to send a message to the chatbot
const onClick = useCallback(() => {
api.composer.send('Hello, World!');
}, [api]);
// When creating the AiChat component, pass the `api` object as a prop
return (
<div>
<AiChat api={api} adapter={adapter} />
<button onClick={onClick}>Send Message Programmatically</button>
</div>
);
}
( React-only feature — Ref note on top of this page )
Lifecycle
- react-js
- javascript
The AiChatApi
object has a lifecycle that is tied to the AiChat
component. When the AiChat
component is
unmounted, the AiChatApi
object will be destroyed and any subsequent calls to its methods will result in an exception
being thrown.
In order to prevent this, it is recommended to create the AiChatApi
object inside the same component that renders the
AiChat
component, and to not store the AiChatApi
object in a state variable or a context.
( React-only feature — Ref note on top of this page )
Methods
Please visit the API Methods Reference Page for a complete list of methods available.