Форум программистов, компьютерный форум, киберфорум
JavaScript: API
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/3: Рейтинг темы: голосов - 3, средняя оценка - 5.00
0 / 0 / 0
Регистрация: 11.06.2022
Сообщений: 18

Playground Assistant - внедрение в проект

27.11.2023, 14:03. Показов 837. Ответов 1

Студворк — интернет-сервис помощи студентам
Здравствуйте, хотел бы попросить помощи, я создал по туториал у чат для технической поддержки с просто API ChatGPT, но я хочу чтобы не просто ChatGPT работал в чате, а мой ассистент из Playground Assistant, которого я создал, но я без понятия как изменить код так чтобы сама структура не поменялась и не поломалась. Помогите пожалуйста (буду очень благодарен). Вот код:
JavaScript
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
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").textContent = 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(userMessage, "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("click", () => document.body.classList.remove("show-chatbot"));
chatbotToggler.addEventListener("click", () => document.body.classList.toggle("show-chatbot"));
HTML5
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
<!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
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
163
164
165
166
167
168
169
170
@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;
    }
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
27.11.2023, 14:03
Ответы с готовыми решениями:

Внедрение NUnit-тестов в проект
Добрый день, форумчане. Написал программу, теперь интересует как внедрить в нее NUnit тесты. Прочитал статей, ничего толком не понял. Цель:...

Внедрение dll & asi в проект
Здравствуйте, хотел бы что бы вы помогли мне с таким вот вопросом: Я делаю проект и у меня есть Asi файл(аналог dll) что бы не таскать...

Программист по внедрению 1C внедрение 1С 8.2; УПП (проект, возможно трудоустройство в штат) Москва от 130000 руб
В компании «Simplex» открыта вакансия: Программист по внедрению 1C внедрение 1С 8.2; УПП (проект, возможно трудоустройство в штат) ...

1
0 / 0 / 0
Регистрация: 11.06.2022
Сообщений: 18
02.12.2023, 17:59  [ТС]
Капец, никто не разобрался вообще
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
02.12.2023, 17:59
Помогаю со студенческими работами здесь

playground
Поставил macos 10.15 на vmware, где скачать playground ниже 4 версии потому что macos 10.15 не поддерживает playground 4 и через app...

"Внедрение" файла в проект
Всем привет. Появилась небольшая проблема при написании программы. Есть xml-файл , в нем хранятся некие данные. Проблема состоит в том...

Подключение Playground
Подскажите пожалуйста, как подключить Playground 5.0 SDK к Visual Studio 2008 Заранее спасибо!

Playground SDK
Скачал Playground SDK 4.0. Как приаттачить его к ВизуалСтудио? У меня 2008 стоит. Нужно ставить 2005?

JavaScript playground в RU домене
Приветствую. В связи с последними событиями, смотрю https://jsfiddle.net без VPN уже не пускает с русскими IP. ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
BOINC: 22 года — и всё ещё работает
Programma_Boinc 12.03.2026
BOINC: 22 года — и всё ещё работает Дэвид Андерсон написал ретроспективу. Кратко: в 2001 году он ушёл из United Devices, где был CTO, и за несколько месяцев написал ядро BOINC — клиент, сервер,. . .
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru