Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Web программирование > JavaScript, Ajax
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 29.11.2023, 09:21   #1
FlashTV
Новичок
Джуниор
 
Регистрация: 29.11.2023
Сообщений: 1
По умолчанию ChatGPT ассистент

Здравствуйте, хотел бы попросить помощи, я создал по туториал у чат для технической поддержки с просто API ChatGPT, но я хочу чтобы не просто ChatGPT работал в чате, а мой ассистент из Playground Assistant, которого я создал, но я без понятия как изменить код так чтобы сама структура не поменялась и не поломалась. Помогите пожалуйста (буду очень благодарен). Вот код:
Код HTML:
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Чат</title>
    <link rel="stylesheet" href="style/style.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
    </head>
<body>
    <button class="chatbot-toggler">
        <span class="material-symbols-outlined">mode_comment</span>
        <span class="material-symbols-outlined">close</span>

    </button>
    <div class="chatbot">
        <header>       
            <h2>COMS Assistant</h2>
            <span class="close-btn material-symbols-outlined">close</span>
        </header>
        <ul class="chatbox">
            <li class="chat incoming">
                <span class="material-symbols-outlined">smart_toy</span>
                <p>Hi there <br>How can I help you today?</p>
            </li>
        </ul>
        <div class="chat-input">
            <textarea placeholder="Enter a message..." required></textarea>
            <span id="send-btn" class="material-symbols-outlined">send</span>
        </div>
    </div>
    <script src="script/script.js" defer></script>
</body>
</html>
[CSS]@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500 ;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Montserrat", sans-serif;
}
body{
background: #E3F2FD;
}
.chatbot-toggler{
position: fixed;
right: 40px;
bottom: 35px;
height: 50px;
width: 50px;
color: #fff;
border: none;
display: flex;
align-items: center;
justify-content: center;
outline: none;
cursor: pointer;
background: #724ae8;
border-radius: 50%;
transition: all 0.2s ease;
}
.show-chatbot .chatbot-toggler{
transform: rotate(90deg);
}
.chatbot-toggler span{
position: absolute;
}
.show-chatbot .chatbot-toggler span:first-child,
.chatbot-toggler span:last-child{
opacity: 0;
}
.show-chatbot .chatbot-toggler span:last-child{
opacity: 1;
}
.chatbot{
position: fixed;
right: 40px;
bottom: 100px;
width: 350px;
transform: scale(0.5);
opacity: 0;
pointer-events: none;
overflow: hidden;
background: #fff;
border-radius: 15px;
transform-origin: bottom right;
box-shadow: 0 0 128px 0 rgba(0, 0, 0, 0.1), 0 32px 64px -48px rgba(0, 0, 0, 0.5);
transition: all 0.1s ease;
}
.show-chatbot .chatbot{
transform: scale(1);
opacity: 1;
pointer-events: auto;
}
.chatbot header{
background: #724ae8;
padding: 16px 0;
text-align: center;
position: relative;
}
.chatbot header h2{
color: #fff;
font-size: 1rem;
font-weight: 700;
}
.chatbot header span{
position: absolute;
right: 20px;
top: 50%;
color: #fff;
cursor: pointer;
display: none;
transform: translateY(-50%);

}
.chatbot .chatbox{
height: 400px;
overflow-y: auto;
padding: 30px 20px 70px;
}
.chatbox .chat{
display: flex;
}
.chatbox .incoming span{
height: 32px;
width: 32px;
color: #fff;
background: #724ae8;
text-align: center;
line-height: 32px;
border-radius: 100%;
margin: auto 10px 0 0;
}
.chatbox .outgoing{
margin: 20px 0;
justify-content: flex-end;
}
.chatbox .chat p{
color: #fff;
max-width: 75%;
white-space: pre-wrap;
font-weight: 600;
font-size: 0.8rem;
padding: 10px 15px;
border-radius: 20px 20px 0 20px;
background: #724ae8;
}
.chatbox .chat p.error{
color: #721c24;
background: #f2f2f2;
}
.chatbox .incoming p{
color: #000;
background: #f2f2f2;
border-radius: 20px 20px 20px 0;
}
.chatbot .chat-input{
position: absolute;
bottom: 0;
width: 100%;
display: flex;
gap: 5px;
background: #fff;
padding: 0 20px;
border-top: 1px solid #ccc;
}
.chat-input textarea{
height: 55px;
width: 100%;
border: none;
outline: none;
max-height: 100px;
font-size: 0.8rem;
resize: none;
padding: 20px 15px 15px 0;
}
.chat-input span{
align-self: flex-end;
height: 55px;
line-height: 55px;
color: #724ae8;
font-size: 1.35rem;
cursor: pointer;
visibility: hidden;
}
.chat-input textarea:valid ~ span{
visibility: visible;
}

@media(max-width: 490px){
.chatbot{
right: 0;
bottom: 0;
width: 100%;
height: 100%;
border-radius: 0;
}
.chatbot .chatbox{
height: 90%;
}
.chatbot header span{
display: block;
}
}[/CSS]
[JavaScript]const chatInput = document.querySelector(".chat-input textarea");
const sendChatBtn = document.querySelector(".chat-input span");
const chatbox = document.querySelector(".chatbox");
const chatbotToggler = document.querySelector(".chatbot-toggler");
const chatbotCloseBtn = document.querySelector(".close-btn");



let userMessage;
const API_KEY = "Your_api_key";
const inputInitHeight = chatInput.scrollHeight;

const createChatLi = (message, className) => {
const chatLi = document.createElement("li");
chatLi.classList.add("chat", className);
let chatContent = className === "outgoing" ? <p></p> : <span class="material-symbols-outlined">smart_toy</span><p></p>;
chatLi.innerHTML = chatContent;
chatLi.querySelector("p").textConte nt = message;
return chatLi;
};

const generateResponse = (incomingChatLi) => {
const API_URL = "https://api.openai.com/v1/chat/completions";
const messageElement = incomingChatLi.querySelector("p");

const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": Bearer ${API_KEY}
},
body: JSON.stringify({
model:"gpt-3.5-turbo-16k",
messages: [{role: "user", content: userMessage}]
})
}
fetch(API_URL, requestOptions).then(res => res.json()).then(data => {
messageElement.textContent = data.choices[0].message.content;
}).catch((error) => {
messageElement.classList.add("error ");
messageElement.textContent = "Oops! Somethig went wrong. Please try align.";
}).finally(() => chatbox.scrollTo(0, chatbox.scrollHeight));
}

const handleChat = () => {
userMessage = chatInput.value.trim();
if (!userMessage) return;
chatInput.value = "";
chatInput.style.height = ${inputInitHeight}px;

chatbox.appendChild(createChatLi(us erMessage, "outgoing"));
chatbox.scrollTo(0, chatbox.scrollHeight);

setTimeout(() => {
const incomingChatLi = createChatLi("...", "incoming")
chatbox.appendChild(incomingChatLi) ;
chatbox.scrollTo(0, chatbox.scrollHeight);
generateResponse(incomingChatLi);
}, 600);
}

chatInput.addEventListener("input", () => {
chatInput.style.height = ${inputInitHeight}px;
chatInput.style.height = ${chatInput.scrollHeight}px;
});

chatInput.addEventListener("keydown ", (e) => {
if(e.key === "Enter" && !e.shiftKey && window.innerWidth > 800){
e.preventDefault();
handleChat();
}
});

sendChatBtn.addEventListener("click ", handleChat);
chatbotCloseBtn.addEventListener("c lick", () => document.body.classList.remove("sho w-chatbot"));
chatbotToggler.addEventListener("cl ick", () => document.body.classList.toggle("sho w-chatbot"));[/JavaScript]
FlashTV вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
ChatGPT ? mirudom Общие вопросы по программированию, компьютерный форум 8 20.09.2023 13:43
Возможности ChatGPT в программировании Drouge Свободное общение 5 11.08.2023 16:49
Виртуальный ассистент Осипов Артем Свободное общение 10 01.06.2017 11:21