@websolutespa/payload-plugin-bowl-llm
Version:
LLM plugin for Bowl PayloadCms plugin
108 lines (107 loc) • 3.9 kB
JavaScript
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useConfig, useLocale } from '@payloadcms/ui';
import { getRouteResolver } from '@websolutespa/payload-utils';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { MessageService } from '../../api/message.service';
import { LlmChunk } from './LlmChunk';
export const LlmChatCompletion = ({ apiKey, appKey, completion, test = false, threadId, onMessage, onEnd, onError })=>{
const ref = useRef(null);
const { config } = useConfig();
const [loading, setLoading] = useState(false);
const [response, setResponse] = useState();
const locale = useLocale();
const routeResolver = getRouteResolver(config);
const messageService = useMemo(()=>{
const url = routeResolver.api(`/llm/message?locale=${locale}`);
return new MessageService({
url
});
}, [
locale
]);
useEffect(()=>{
const fetchData = async (messages, test = false)=>{
try {
setLoading(true);
const sendMessagePayload = {
apiKey,
appKey,
messages,
test,
threadId
};
await messageService.sendMessage(sendMessagePayload, // onMessage
(response)=>{
const meaningChunks = response.chunks.filter((x)=>typeof x === 'string' || ![
'header',
'info',
'log',
'end'
].includes(x.type));
// console.log('meaningChunks', meaningChunks);
if (meaningChunks.length > 0) {
setResponse(response);
if (typeof onMessage === 'function') {
onMessage(response);
}
/*
if (ref.current) {
ref.current.scrollIntoView();
}
*/ }
}, // onEnd
(response)=>{
// console.log('LlmChatCompletion.response', response);
setLoading(false);
if (typeof onEnd === 'function') {
onEnd(response);
}
}, // onChunk
(chunks)=>{
// console.log('onChunk', chunks);
});
} catch (error) {
console.log(`LlmChatCompletion.onSubmit.error ${error.message}.`);
setLoading(false);
if (typeof onError === 'function') {
onError(error);
}
}
};
if (completion) {
fetchData(completion, test);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
apiKey,
appKey,
completion,
messageService,
onEnd,
onError,
// onMessage,
test,
threadId
]);
return /*#__PURE__*/ _jsxs("div", {
className: "llm__chatCompletion",
children: [
response && /*#__PURE__*/ _jsx("div", {
ref: ref,
className: "llm__thread assistant",
children: /*#__PURE__*/ _jsx("div", {
className: "llm__message",
children: response.chunks.map((x, i)=>/*#__PURE__*/ _jsx(LlmChunk, {
item: x
}, i))
})
}),
loading && /*#__PURE__*/ _jsx("div", {
className: "llm__busyIndicator",
children: /*#__PURE__*/ _jsx("span", {})
})
]
});
};
//# sourceMappingURL=LlmChatCompletion.js.map