MCPcopy Create free account
hub / github.com/DTStack/dt-react-component / useChat

Function useChat

src/chat/useChat.ts:29–281  ·  view source on GitHub ↗
(props?: IUseChatProps<C, P, M>)

Source from the content-addressed store, hash-verified

27const updateReducer = (num: number): number => (num + 1) % 1_000_000;
28
29export default function useChat<
30 // eslint-disable-next-line space-before-function-paren
31 C extends { new (...params: ConstructorParameters<typeof Conversation>): Conversation },
32 P extends { new (...params: ConstructorParameters<typeof Prompt>): Prompt },
33 M extends { new (...params: ConstructorParameters<typeof Message>): Message }
34>(props?: IUseChatProps<C, P, M>) {
35 const [, update] = useReducer(updateReducer, 0);
36
37 const state = useRef<Conversation | undefined>(undefined);
38 const typing = useTyping({
39 onTyping(post) {
40 _updateMessage(typingIds.current.promptId, typingIds.current.messageId, {
41 content: post,
42 });
43 },
44 });
45 const typingIds = useRef<{ promptId: Id; messageId: Id }>({
46 promptId: '',
47 messageId: '',
48 });
49 const closing = useRef<boolean>(false);
50
51 // ================================== Typing ==================================
52 function _start(promptId: Id, messageId: Id) {
53 typing.start();
54 _updateMessage(promptId, messageId, { status: MessageStatus.PENDING });
55 typingIds.current = { promptId, messageId };
56 }
57
58 function _push(promptId: Id, messageId: Id, str: string) {
59 if (promptId === typingIds.current.promptId && messageId === typingIds.current.messageId) {
60 typing.push(str);
61 if (_getMessage(promptId, messageId)?.status !== MessageStatus.GENERATING) {
62 _updateMessage(promptId, messageId, { status: MessageStatus.GENERATING });
63 }
64 }
65 }
66
67 function _close(promptId: Id, messageId: Id) {
68 closing.current = true;
69 typing.close().then(() => {
70 closing.current = false;
71 _updateMessage(promptId, messageId, { status: MessageStatus.DONE });
72 });
73 }
74
75 // ================================== Conversation ==================================
76 function _createConversation(data: ConversationProperties) {
77 const ConversationCtor = props?.ctor?.Conversation || BaseConversation;
78 state.current = new ConversationCtor(data);
79 update();
80 }
81
82 function _removeConversation() {
83 state.current = undefined;
84 update();
85 }
86

Callers 1

useChat.test.tsFile · 0.85

Calls 1

useTypingFunction · 0.85

Tested by

no test coverage detected