chat: подключение к бекенду
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
import { useLocation } from '@docusaurus/router';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { useOptions } from '@docuservix/hooks/useOptions';
|
||||
import { IChat, IChatMessage, IChatSource } from '@docuservix/models/chat';
|
||||
|
||||
interface UseChatResult {
|
||||
dialog: IChat;
|
||||
typing: boolean;
|
||||
statusMessage?: string;
|
||||
sendMessage: (text: string) => void;
|
||||
}
|
||||
|
||||
function useQuery(): string {
|
||||
const location = useLocation();
|
||||
const params = new URLSearchParams(location.search);
|
||||
|
||||
return params.get('q') ?? '';
|
||||
}
|
||||
|
||||
export function useChat(): UseChatResult {
|
||||
const chatEndpoint = useOptions().api + '/v1/chat';
|
||||
const urlQuery = useQuery();
|
||||
|
||||
const [messages, setMessages] = useState<IChatMessage[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const initialSentRef = useRef(false);
|
||||
const messagesEndRef = useRef(messages);
|
||||
|
||||
messagesEndRef.current = messages;
|
||||
|
||||
const sendMessage = useCallback(
|
||||
async (text: string) => {
|
||||
const content = text.trim();
|
||||
|
||||
if (!content) {
|
||||
return;
|
||||
}
|
||||
|
||||
const userMessage: IChatMessage = { role: 'user', content };
|
||||
const newHistory = [...messagesEndRef.current, userMessage];
|
||||
|
||||
setMessages(newHistory);
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const res = await fetch(chatEndpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ messages: newHistory }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const data: { answer: string; sources?: IChatSource[] } = await res.json();
|
||||
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ role: 'assistant', content: data.answer, sources: data.sources },
|
||||
]);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Ошибка при обращении к серверу');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[chatEndpoint],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (urlQuery && !initialSentRef.current) {
|
||||
initialSentRef.current = true;
|
||||
sendMessage(urlQuery);
|
||||
}
|
||||
}, [urlQuery, sendMessage]);
|
||||
|
||||
return {
|
||||
dialog: { messages },
|
||||
typing: loading,
|
||||
statusMessage: error ?? undefined,
|
||||
sendMessage,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { usePluginData } from '@docusaurus/useGlobalData';
|
||||
|
||||
import { DocuservixOptions } from '@docuservix/models/docuservix';
|
||||
|
||||
export function useOptions(): DocuservixOptions {
|
||||
return usePluginData('docuservix') as DocuservixOptions;
|
||||
}
|
||||
@@ -2,7 +2,11 @@ import path from 'path';
|
||||
|
||||
import type { LoadContext, Plugin } from '@docusaurus/types';
|
||||
|
||||
export default function docuservix() {
|
||||
import { DocuservixOptions } from '@docuservix/models/docuservix';
|
||||
|
||||
export default function docuservix(options: Partial<DocuservixOptions> = {}) {
|
||||
const api = process.env.DOCUSERVIX_API || options.api || '/api';
|
||||
|
||||
return function pluginDocuservix(_context: LoadContext): Plugin {
|
||||
return {
|
||||
name: 'docuservix',
|
||||
@@ -18,7 +22,11 @@ export default function docuservix() {
|
||||
},
|
||||
|
||||
async contentLoaded({ actions }) {
|
||||
const { addRoute } = actions;
|
||||
const { addRoute, setGlobalData } = actions;
|
||||
|
||||
setGlobalData({
|
||||
api,
|
||||
});
|
||||
|
||||
addRoute({
|
||||
path: '/chat',
|
||||
|
||||
@@ -2,7 +2,36 @@ export interface IChat {
|
||||
messages: IChatMessage[];
|
||||
}
|
||||
|
||||
export interface IChatSource {
|
||||
file: string;
|
||||
heading: string;
|
||||
anchor: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export interface IChatMessage {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
sources?: IChatSource[];
|
||||
}
|
||||
|
||||
function stripNumericPrefixes(p: string): string {
|
||||
return p
|
||||
.split('/')
|
||||
.map((seg) => seg.replace(/^\d+-/, ''))
|
||||
.join('/');
|
||||
}
|
||||
|
||||
export function sourceToUrl(file: string, anchor: string): string {
|
||||
let p = file.replace(/^docs\//, '').replace(/\.md$/, '');
|
||||
|
||||
p = stripNumericPrefixes(p);
|
||||
|
||||
return `/docs/${p}${anchor ? `#${anchor}` : ''}`;
|
||||
}
|
||||
|
||||
export function sourceToPath(file: string): string {
|
||||
const p = file.replace(/^docs\//, '').replace(/\.md$/, '');
|
||||
|
||||
return stripNumericPrefixes(p);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface DocuservixOptions {
|
||||
api?: string;
|
||||
}
|
||||
@@ -1,30 +1,20 @@
|
||||
import Layout from '@theme/Layout';
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
import { IChat } from '@docuservix/models/chat';
|
||||
import { useChat } from '@docuservix/hooks/useChat';
|
||||
import { Chat } from '@docuservix/widgets/chat';
|
||||
|
||||
const dialog: IChat = {
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: 'Can you show me some CSS animations? It can be simple tools like chatbots...',
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: "Hello! I'm your **AI assistant**. How can I help you today?",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export function ChatPage(): ReactNode {
|
||||
const { dialog, typing, statusMessage, sendMessage } = useChat();
|
||||
|
||||
return (
|
||||
<Layout title="Чат">
|
||||
<main className="container margin-vert--lg">
|
||||
<Chat
|
||||
dialog={dialog}
|
||||
statusMessage="Unable to connect to the server"
|
||||
typing
|
||||
typing={typing}
|
||||
statusMessage={statusMessage}
|
||||
onSend={sendMessage}
|
||||
/>
|
||||
</main>
|
||||
</Layout>
|
||||
|
||||
Reference in New Issue
Block a user