file md
Инструкция по использованию Сверхлёгкого AI-клиента
1. Настройка
Перед запуском впишите свой API-ключ Gemini в файл .env:
GEMINI_API_KEY=ваш_ключ
2. Запуск сервера
Если сервер еще не запущен, выполните:
python main.py
3. Клиентские подключения
3.1. Browser Console (F12)
Скопируйте и вставьте в консоль любого сайта:
fetch("https://web-production-a422c.up.railway.app/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "Привет, как дела?" })
})
.then(res => res.json())
.then(data => console.log("AI:", data.response));
3.2. Windows Command Prompt (CMD)
curl -s -X POST https://web-production-a422c.up.railway.app/chat -H "Content-Type: application/json" -d "{\"message\":\"Привет через CMD\"}"
3.3. Windows PowerShell
$body = @{ message = "Привет из PowerShell" } | ConvertTo-Json
$response = Invoke-RestMethod -Uri "https://web-production-a422c.up.railway.app/chat" -Method Post -ContentType "application/json" -Body $body
$response.response
3.4. Интерактивный CLI (PowerShell) - САМАЯ СТАБИЛЬНАЯ ВЕРСИЯ
Если предыдущие версии выдавали каракули, используйте эту:
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
while ($true) {
$input = Read-Host "Вы"
if ($input -eq "exit") { break }
$body = @{ message = $input } | ConvertTo-Json -Compress
# Добавлен charset=utf-8 в ContentType
$res = Invoke-RestMethod -Uri "https://web-production-a422c.up.railway.app/chat" -Method Post -ContentType "application/json; charset=utf-8" -Body $body
Write-Host "AI: $($res.response)" -ForegroundColor Green
}
3.4. Интерактивный CLI (WindowsPowerShell) - САМАЯ СТАБИЛЬНАЯ ВЕРСИЯ
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
while ($true) {
$input_text = Read-Host "Вы"
if ($input_text -eq "exit") { break }
# Формируем JSON-строку
$json_string = @{ message = $input_text } | ConvertTo-Json -Compress
# Превращаем текст в UTF-8 байты для правильной отправки (чтобы бот нас понял)
$utf8_bytes = [System.Text.Encoding]::UTF8.GetBytes($json_string)
try {
$res = Invoke-RestMethod -Uri "https://web-production-a422c.up.railway.app/chat" `
-Method Post `
-ContentType "application/json" `
-Body $utf8_bytes
# Лекарство от кракозябр в ответе:
# 1. Берем испорченный текст ответа
$bad_text = $res.response
# 2. Превращаем его в байты в той кодировке, в которой PowerShell ошибочно его прочитал (ISO-8859-1)
$bytes = [System.Text.Encoding]::GetEncoding("iso-8859-1").GetBytes($bad_text)
# 3. Декодируем эти байты обратно как нормальный UTF-8
$good_text = [System.Text.Encoding]::UTF8.GetString($bytes)
Write-Host "AI: $good_text" -ForegroundColor Green
}
catch {
Write-Host "Ошибка: $_" -ForegroundColor Red
}
}
3.6. Интерактивный CLI Browser Console (F12)
async function chat(text) {
console.log(`%cВы:%c ${text}`, 'color: #0084ff; font-weight: bold; font-size: 14px;', 'color: unset; font-size: 14px;');
try {
let res = await fetch("https://web-production-a422c.up.railway.app/chat", {
method: "POST", headers: {"Content-Type": "application/json"},
body: JSON.stringify({message: text})
});
let data = await res.json();
console.log(`%cAI:%c ${data.response}`, 'color: #4CAF50; font-weight: bold; font-size: 14px;', 'color: unset; font-size: 14px;');
} catch(e) { console.error("Ошибка сервера:", e); }
}
console.log("%c✅ Функция чата загружена! Напишите: chat('ваш текст')", "color: green; font-weight: bold;");
3.7. Всплывающее окно (Визуальный чат) Browser Console (F12)
(function() {
// Создаем окно чата
const chatBox = document.createElement('div');
chatBox.style.cssText = `position:fixed; bottom:20px; right:20px; width:350px; height:450px; background:white; border:1px solid #ccc; border-radius:10px; z-index:999999;
display:flex; flex-direction:column; box-shadow:0 4px 15px rgba(0,0,0,0.2); font-family:sans-serif;`;
// Заголовок
const header = document.createElement('div');
header.style.cssText = 'padding:12px; background:#4CAF50; color:white; border-radius:10px 10px 0 0; text-align:center; font-weight:bold; cursor:pointer;';
header.innerText = ' Локальный AI Чат (Закрыть)';
header.onclick = () => document.body.removeChild(chatBox);
// Область сообщений
const messages = document.createElement('div');
messages.style.cssText = 'flex:1; padding:15px; overflow-y:auto; display:flex; flex-direction:column; gap:10px; background:#f0f2f5;';
// Ввод
const inputArea = document.createElement('div');
inputArea.style.cssText = 'display:flex; padding:10px; border-top:1px solid #eee; background:white; border-radius:0 0 10px 10px;';
const input = document.createElement('input');
input.type = 'text';
input.placeholder = 'Введите сообщение...';
input.style.cssText = 'flex:1; padding:10px; border:1px solid #ccc; border-radius:20px; outline:none; font-size:14px;';
const btn = document.createElement('button');
btn.innerText = '➤';
btn.style.cssText = `margin-left:10px; width:40px; height:40px; background:#4CAF50; color:white; border:none; border-radius:50%; cursor:pointer; font-size:18px; display:flex;
align-items:center; justify-content:center;`;
function addMsg(text, isUser) {
const msg = document.createElement('div');
msg.style.cssText = `max-width:85%; padding:10px 15px; border-radius:15px; font-size:14px; line-height:1.4; word-wrap:break-word; ${isUser ? `align-self:flex-end;
background:#0084ff; color:white;` : 'align-self:flex-start; background:white; color:black; box-shadow:0 1px 2px rgba(0,0,0,0.1);'}`;
msg.innerText = text;
messages.appendChild(msg);
messages.scrollTop = messages.scrollHeight;
}
async function send() {
const text = input.value.trim();
if(!text) return;
addMsg(text, true);
input.value = '';
input.disabled = btn.disabled = true;
try {
const res = await fetch("https://web-production-a422c.up.railway.app/chat", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: text })
});
const data = await res.json();
addMsg(data.response, false);
} catch (e) {
addMsg("❌ Ошибка соединения!", false);
}
input.disabled = btn.disabled = false;
input.focus();
}
btn.onclick = send;
input.onkeypress = (e) => { if(e.key === 'Enter') send(); };
// Сборка
inputArea.append(input, btn);
chatBox.append(header, messages, inputArea);
document.body.appendChild(chatBox);
addMsg("Привет! Я готов отвечать на твои вопросы.", false);
})();
4. Развертывание на Railway (Pro / Free)
Проект полностью готов к деплою на Railway.
Шаги для развертывания:
- Зарегистрируйтесь на Railway.app.
- Создайте новый проект (New Project) -> Deploy from GitHub repo.
- Выберите ваш репозиторий с этим проектом.
- Перейдите в настройки созданного сервиса (Variables) и добавьте переменную окружения:
GEMINI_API_KEY=ваш_ключ
- Railway автоматически найдет файл
requirements.txtи установит зависимости, а затем запустит проект благодаря файлуProcfile.
Примечание: После успешного деплоя, Railway выдаст вам публичный URL (например, https://web-production-a422c.up.railway.app/chat). Замените http://localhost:8000/chat в клиентских скриптах на ваш новый публичный URL.