import { Telegraf, session } from 'telegraf'; import { message } from…
- User
import { Telegraf, session } from 'telegraf'; import { message } from 'telegraf/filters'; import { code } from 'telegraf/format'; import config from 'config'; import { ogg } from './src/ogg.js'; import { openaiGPT } from './src/openai.js'; import { Client } from '@gradio/client';
const INITIAL_SESSION = { messages: [], };
const BOT_TOKEN = config.get('TELEGRAM_TOKEN'); const bot = new Telegraf(BOT_TOKEN);
async function initGradioClient() { try { const gradioClient = await Client.connect('yuntian-deng/ChatGPT4'); const app_info = await gradioClient.view_api(); console.log('Доступные эндпоинты API:', app_info); return gradioClient; } catch (error) { console.error('Ошибка подключения клиента Gradio:', error); throw error; } }
async function getPrediction(app, inputText, apiEndpoint) { try { console.log(
Проверка эндпоинта: ${apiEndpoint} с запросом:, inputText);const predictionResult = await app.predict(apiEndpoint, [inputText]); if (predictionResult && predictionResult.data) { const responseMessage = predictionResult.data[0]; console.log(`Ответ от ${apiEndpoint}:`, responseMessage); return responseMessage; } console.warn('Получены неожиданные данные формата.'); return 'Получены неожиданные данные.';} catch (error) { console.error(
Ошибка при запросе ${apiEndpoint}:, error); return 'Извините, произошла ошибка при обработке вашего запроса.'; } }initGradioClient() .then(async (client) => { gradioClient = client; console.log('Gradio клиент инициализирован'); // Пробуем получить ответ, чтобы диагностировать проблемы const responsePredict = await getPrediction(client, 'ты тут ?', '/predict'); console.log('Ответ от /predict:', responsePredict); }) .catch((error) => { console.error('Не удалось инициализировать Gradio клиент:', error); });
bot.use(session());
bot.command('new', async (ctx) => { ctx.session = INITIAL_SESSION; await ctx.reply('Жду вашего голосового или текстового сообщения'); });
bot.command('start', async (ctx) => { ctx.session = INITIAL_SESSION; await ctx.reply('Жду вашего голосового или текстового сообщения'); });
bot.on(message('voice'), async (ctx) => { ctx.session ??= INITIAL_SESSION; try { const link = await ctx.telegram.getFileLink(ctx.message.voice.file_id); const userId = String(ctx.message.from.id); const oggPath = await ogg.create(link.href, userId); const mp3Path = await ogg.toMp3(oggPath, userId); const name = ctx.from.first_name; const text = await openaiGPT.transcription(mp3Path);
if (text.includes('Кеша') && gradioClient) { const textAsked = text.slice(5); await ctx.reply(code(`${name} Ваш запрос: ${textAsked}`)); const responseMessage = await getPrediction(gradioClient, textAsked, '/predict'); await ctx.reply(responseMessage); }} catch (error) { console.log('Ошибка при обработке голосового сообщения:', error.message); } });
- Assistant
- User
сделал как ты написал, теперь ошибка $ node index.js Доступные эндпоинты API: { named_endpoints: { '/enable_inputs': { parameters: [], returns: [], type: [Object] }, '/reset_textbox': { parameters: [], returns: [Array], type: [Object] }, '/predict': { parameters: [Array], returns: [Array], type: [Object] }, '/reset_textbox_1': { parameters: [], returns: [Array], type: [Object] }, '/predict_1': { parameters: [Array], returns: [Array], type: [Object] } }, unnamed_endpoints: { '0': { parameters: [Array], returns: [Array], type: [Obje ct] } } } Gradio клиент инициализирован Проверка эндпоинта: /predict с запросом: ты тут ? Ошибка при запросе /predict: { type: 'status', endpoint: '/predict', fn_index: 3, time: 2024-10-18T16:12:47.817Z, original_msg: undefined, queue: true, title: undefined, message: null, visible: undefined, duration: undefined, stage: 'error', code: undefined, success: false } Ответ от /predict: Извините, произошла ошибка при обработке вашего запроса. Проверка эндпоинта: /predict с запросом: ты тут ? Ошибка при запросе /predict: { type: 'status', endpoint: '/predict', fn_index: 3, time: 2024-10-18T16:13:04.012Z, original_msg: undefined, queue: true, title: undefined, message: null, visible: undefined, duration: undefined, stage: 'error', code: undefined, success: false }
- Assistant
- User
$ node index.js Доступные эндпоинты API: { named_endpoints: { '/enable_inputs': { parameters: [], returns: [], type: [Object] }, '/reset_textbox': { parameters: [], returns: [Array], type: [Object] }, '/predict': { parameters: [Array], returns: [Array], type: [Object] }, '/reset_textbox_1': { parameters: [], returns: [Array], type: [Object] }, '/predict_1': { parameters: [Array], returns: [Array], type: [Object] } }, unnamed_endpoints: { '0': { parameters: [Array], returns: [Array], type: [Obje ct] } } } Gradio client initialized Attempting endpoint: /predict request: Are you there? Error during /predict request, attempt 1: { type: 'status', endpoint: '/predict', fn_index: 3, time: 2024-10-18T16:15:06.498Z, original_msg: undefined, queue: true, title: undefined, message: null, visible: undefined, duration: undefined, stage: 'error', code: undefined, success: false } Attempting endpoint: /predict request: Are you there? Error during /predict request, attempt 2: { type: 'status', endpoint: '/predict', fn_index: 3, time: 2024-10-18T16:15:09.606Z, original_msg: undefined, queue: true, title: undefined, message: null, visible: undefined, duration: undefined, stage: 'error', code: undefined, success: false } Attempting endpoint: /predict request: Are you there? Error during /predict request, attempt 3: { type: 'status', endpoint: '/predict', fn_index: 3, time: 2024-10-18T16:15:12.067Z, original_msg: undefined, queue: true, title: undefined, message: null, visible: undefined, duration: undefined, stage: 'error', code: undefined, success: false } Response from /predict: Sorry, there was an error processing your request after multiple attempts.
- Assistant
- User
$ node index.js Доступные эндпоинты API: { named_endpoints: { '/enable_inputs': { parameters: [], returns: [], type: [Object] }, '/reset_textbox': { parameters: [], returns: [Array], type: [Object] }, '/predict': { parameters: [Array], returns: [Array], type: [Object] }, '/reset_textbox_1': { parameters: [], returns: [Array], type: [Object] }, '/predict_1': { parameters: [Array], returns: [Array], type: [Object] } }, unnamed_endpoints: { '0': { parameters: [Array], returns: [Array], type: [Obje ct] } } } Gradio client initialized Error testing different endpoint: { type: 'status', endpoint: '/predict_1', fn_index: 5, time: 2024-10-18T16:16:39.068Z, original_msg: undefined, queue: true, title: undefined, message: null, visible: undefined, duration: undefined, stage: 'error', code: undefined, success: false }
- Assistant
- User
напиши все тоже самое только на русском
- Assistant