react-chatbot-test / src /hooks /useChatCompletion.js
ferrywuai's picture
Replace manual token input with Hugging Face OAuth login
a9b2457
import { useState } from "react";
import { simulateTyping } from "../utils/simulateTyping";
// Handle chat completion logic, including settings, UI behavior, and error management
export function useChatCompletion(
client,
chatSettings,
uiSettings,
onMessageComplete
) {
const [isLoading, setIsLoading] = useState(false);
const [typingMessage, setTypingMessage] = useState("");
const [error, setError] = useState(null);
const sendMessage = async (message) => {
if (!client) {
setError({
type: "MISSING_CLIENT",
message: "Please login Hugging Face first.",
});
return;
}
setIsLoading(true);
setError(null);
setTypingMessage("");
let result;
try {
result = await client.chatCompletion({
model: "openai/gpt-oss-20b",
messages: [
{ role: "system", content: chatSettings.system },
{ role: "user", content: message },
],
temperature: chatSettings.temperature,
top_p: chatSettings.top_p,
max_tokens: chatSettings.max_tokens,
});
} catch (err) {
setError({ type: "CHAT_ERROR", message: err.message });
return;
} finally {
setIsLoading(false);
}
const assistantReply = result.choices[0].message.content;
if (uiSettings.typingEnabled) {
simulateTyping(assistantReply, setTypingMessage, () => {
onMessageComplete({ user: message, assistant: assistantReply });
setTypingMessage("");
});
} else {
onMessageComplete({ user: message, assistant: assistantReply });
}
};
return { sendMessage, isLoading, typingMessage, error };
}