// Этот код для Worker, который отдает HTML+JS и обрабатывает API export default { async fetch(request, env) { const url = new URL(request.url); // Главная страница - отдаем HTML if (url.pathname === '/' || url.pathname === '/index.html') { return new Response(getHTML(), { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); } // API endpoint для общения с Gemini if (url.pathname === '/api/chat') { return handleChatRequest(request, env); } // Для остальных запросов - 404 return new Response('Not Found', { status: 404 }); } }; // Обработчик API запросов к Gemini async function handleChatRequest(request, env) { if (request.method !== 'POST') { return new Response('Метод не поддерживается', { status: 405 }); } try { const { messages, model = "gemini-2.0-flash-exp" } = await request.json(); // Форматируем сообщения для Gemini API const contents = messages.map(msg => ({ role: msg.role === 'user' ? 'user' : 'model', parts: [{ text: msg.content }] })); const response = await fetch( `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${env.GEMINI_API_KEY}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contents }) } ); if (!response.ok) { throw new Error(`Gemini API error: ${response.status}`); } const data = await response.json(); const text = data?.candidates?.[0]?.content?.parts?.[0]?.text; return new Response(JSON.stringify({ success: true, message: text || 'Пустой ответ от Gemini' }), { headers: { 'Content-Type': 'application/json' } }); } catch (error) { return new Response(JSON.stringify({ success: false, error: error.message }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } } // HTML страница с чатом function getHTML() { return ` Gemini Web Chat

🤖 Gemini Web Chat

Модель:
Привет! Я Gemini AI. Чем могу помочь?
`; }