-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChat.js
More file actions
162 lines (143 loc) · 4.74 KB
/
Chat.js
File metadata and controls
162 lines (143 loc) · 4.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"use client";
import React, { useState, useEffect, useRef } from "react";
import { marked } from "marked";
import "./Chat.css";
const Chat = () => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const [loading, setLoading] = useState(false);
const [darkMode, setDarkMode] = useState(false);
const chatWindowRef = useRef(null);
// Replace with your actual server's IP/URL
const apiUrl = "http://192.168.2.235:55441/api/v0/chat/completions";
const model = "phi-4";
useEffect(() => {
if (chatWindowRef.current) {
chatWindowRef.current.scrollTop = chatWindowRef.current.scrollHeight;
}
}, [messages]);
useEffect(() => {
if (darkMode) {
document.body.classList.add("dark-mode");
} else {
document.body.classList.remove("dark-mode");
}
}, [darkMode]);
const toggleDarkMode = () => setDarkMode((prev) => !prev);
const sendMessage = async () => {
if (!input.trim()) return;
const timestamp = new Date().toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
});
// Add user message to chat
const newMessages = [...messages, { role: "user", content: input, timestamp }];
setMessages(newMessages);
setInput("");
setLoading(true);
// Prepare for streaming response
const assistantMessage = {
role: "assistant",
content: "",
timestamp: new Date().toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
}),
};
setMessages([...newMessages, assistantMessage]);
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: model,
messages: newMessages,
temperature: 0.7,
max_tokens: 200,
stream: true,
}),
});
if (!response.ok) throw new Error(`HTTP Error: ${response.status}`);
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let done = false;
while (!done) {
const { value, done: readerDone } = await reader.read();
done = readerDone;
if (value) {
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split("\n").filter((line) => line.startsWith("data: "));
for (const line of lines) {
const json = line.slice(6); // Remove "data: "
if (json.trim() === "[DONE]") {
done = true;
break;
}
const parsed = JSON.parse(json);
const delta = parsed.choices[0]?.delta?.content || "";
assistantMessage.content += delta;
setMessages([...newMessages, { ...assistantMessage }]);
}
}
}
} catch (error) {
console.error("Error:", error);
setMessages([
...newMessages,
{ role: "assistant", content: "Error: Unable to fetch response.", timestamp },
]);
} finally {
setLoading(false);
}
};
return (
<div className={`chat-container ${darkMode ? "dark-mode" : ""}`}>
<div className="chat-header">
<h1>Chat with LMStudio</h1>
<button onClick={toggleDarkMode} className="dark-mode-toggle">
{darkMode ? "Light Mode" : "Dark Mode"}
</button>
</div>
<div id="chat-window" ref={chatWindowRef} className="chat-window">
{messages.map((msg, index) => (
<div
key={index}
className={
msg.role === "user"
? "chat-bubble user-bubble"
: "chat-bubble assistant-bubble"
}
>
<div
dangerouslySetInnerHTML={{
__html:
msg.role === "assistant" ? marked(msg.content) : msg.content,
}}
/>
<div className="chat-bubble-timestamp">{msg.timestamp}</div>
</div>
))}
{loading && (
<div className="chat-bubble assistant-bubble typing-indicator">
<span>.</span>
<span>.</span>
<span>.</span>
</div>
)}
</div>
<div className="chat-input">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type your message..."
onKeyPress={(e) => e.key === "Enter" && sendMessage()}
/>
<button onClick={sendMessage} disabled={loading}>
{loading ? "Sending..." : "Send"}
</button>
</div>
</div>
);
};
export default Chat;