Using llmonitor with React

1

Import

Install the package and import the necessary functions from our React export:

import monitor, { useChatMonitor } from 'llmonitor/react';
2

Initialize llmonitor

Initialize the SDK with your application's tracking ID:

monitor.init({
appId: "YOUR APP ID",
})
3

Use the `useChatMonitor` hook

The useChatMonitor hook exposes the following functions:

const {
restart,
trackFeedback,
trackUserMessage,
trackBotMessage
} = useChatMonitor();

Here's an example of how you would it into your Chat component.

import { useState, useEffect } from "react";
const App = () => {
const [input, setInput] = useState("");
const [messages, setMessages] = useState([]);
const { restart: restartMonitor, trackFeedback, trackUserMessage, trackBotMessage } = useChatMonitor();
// Step 4: Use Effects for Initialization
useEffect(() => {
restartMonitor();
}, []);
// Step 5: Define Your Message Handlers
const askBot = async (query) => {
// Track the user message and keep the message ID in reference
const messageId = trackUserMessage(query);
setMessages([...messages, { id: messageId, role: "user", text: query }]);
const answer = await fetchBotResponse(query, messages); // Split out fetch operation
setMessages([...messages, { id: messageId, role: "bot", text: answer }]);
// Track the bot answer with the same message ID
trackBotMessage(messageId, answer);
}
// Your message logic
const fetchBotResponse = async (query, messages) => {
const response = await fetch("https://...", {
method: "POST",
body: JSON.stringify({ messages }),
});
return await response.text();
};
const restartChat = () => {
setMessages([]);
restartMonitor();
}
// Step 6: Render UI
return (
<>
<div>
{messages.map((message) => (
<div key={message.id}>
<div>{message.role}</div>
<div>{message.text}</div>
</div>
))}
</div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
askBot(input);
setInput("");
}
}}
/>
</>
);
}
4

Reconcile calls on your backend

Make sure to pass the message IDs to your backend to reconcile with the backend calls and agents.

Questions? We're here to help.