Internationalizes error messages and console logs.
This commit is contained in:
1 parent
fa126651de
commit
c7735cc6f9
4 files changed
+50
-57
No files matched your search
+32
-35
@@ -41,7 +41,7 @@ export class TelegramBot {
|
||||
const message =
|
||||
status === 'started'
|
||||
? `<b>${stepName}</b> ${emoji}`
|
||||
: `<b>${stepName}</b> ${emoji}\n\n<pre>${result?.substring(0, 3000) || 'Готово'}</pre>`;
|
||||
: `<b>${stepName}</b> ${emoji}\n\n<pre>${result?.substring(0, 3000) || 'Done'}</pre>`;
|
||||
|
||||
await this.sendMessage(chatId, message);
|
||||
};
|
||||
@@ -50,7 +50,7 @@ export class TelegramBot {
|
||||
private setupHandlers(): void {
|
||||
this.bot.start((ctx) => {
|
||||
ctx.reply(
|
||||
'Привет! Я бот для работы с AI пайплайнами. Просто отправь мне сообщение, и я обработаю его через пайплайн.',
|
||||
'Hello! I am a bot for working with AI pipelines. Just send me a message and I will process it through the pipeline.',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -61,50 +61,49 @@ export class TelegramBot {
|
||||
|
||||
try {
|
||||
const userPipeline: Pipeline = {
|
||||
description: 'Криптокошелёк анализатор для Liquidswap',
|
||||
systemPrompt: `Вы — профессиональный криптоаналитик и портфельный менеджер.
|
||||
Анализируйте криптовалютный рынок, используя актуальные веб-данные.
|
||||
Проведите анализ портфеля пользователя, адаптируясь к широкому (рыночные тренды, новости) или ограниченному (только портфель) набору данных.
|
||||
Если данные портфеля отсутствуют, запросите их. Охватите по возможности:
|
||||
- Технический анализ (тренды, волатильность, индикаторы).
|
||||
- Фундаментальный анализ (новости, проекты).
|
||||
- Риски (корреляции, ликвидность, регуляторные факторы).
|
||||
- Диверсификацию и оптимизацию.
|
||||
Предоставьте рекомендации по улучшению портфеля.
|
||||
Формат ответа: отчет с разделами "Текущая ситуация на рынке", "Анализ портфеля", "Риски", "Рекомендации".
|
||||
Тон профессиональный, без сложного жаргона.
|
||||
Если данных недостаточно, задайте уточняющие вопросы.
|
||||
Обеспечьте точность ≥ 95%, избегая неподтвержденных предположений.`,
|
||||
description: 'Crypto wallet analyzer for Liquidswap',
|
||||
systemPrompt: `You are a professional crypto analyst and portfolio manager.
|
||||
Analyze the cryptocurrency market using up-to-date web data.
|
||||
Conduct a portfolio analysis, adapting to either a broad (market trends, news) or limited (portfolio only) dataset.
|
||||
If portfolio data is missing, request it. Cover the following aspects if possible:
|
||||
- Technical analysis (trends, volatility, indicators).
|
||||
- Fundamental analysis (news, projects).
|
||||
- Risks (correlations, liquidity, regulatory factors).
|
||||
- Diversification and optimization.
|
||||
Provide recommendations for portfolio improvement.
|
||||
Response format: a report with sections "Current Market Situation", "Portfolio Analysis", "Risks", "Recommendations".
|
||||
Maintain a professional tone without complex jargon.
|
||||
If data is insufficient, ask clarifying questions.
|
||||
Ensure accuracy ≥ 95%, avoiding unsubstantiated assumptions.`,
|
||||
steps: [
|
||||
{
|
||||
name: 'Обработка запроса',
|
||||
name: 'Request Processing',
|
||||
prompt: userMessage,
|
||||
},
|
||||
{
|
||||
name: 'Анализ',
|
||||
prompt: `Я хочу грамотно распределить свой криптовалютный портфель, используя данные DeFi-протокола Liquidswap.
|
||||
Пожалуйста, предоставьте рекомендации по распределению активов,
|
||||
основываясь на данных от инструментов:
|
||||
name: 'Analysis',
|
||||
prompt: `I want to properly allocate my cryptocurrency portfolio using data from the Liquidswap DeFi protocol.
|
||||
Please provide asset allocation recommendations based on data from the following tools:
|
||||
\`get_tokens\`,
|
||||
\`get_pools\`,
|
||||
\`get_pools_historical_aprs\` (за 5 дней),
|
||||
\`get_pools_historical_tvls\` (за 5 дней),
|
||||
\`get_balances_by_address\` (мой адрес Aptos, если потребуется, запросите его) и \`multi_tool_use.parallel\`.
|
||||
Затем напиши доступную информацию об указанном адресе.`,
|
||||
\`get_pools_historical_aprs\` (last 5 days),
|
||||
\`get_pools_historical_tvls\` (last 5 days),
|
||||
\`get_balances_by_address\` (my Aptos address, request it if needed) and \`multi_tool_use.parallel\`.
|
||||
Then provide the available information about the specified address.`,
|
||||
},
|
||||
{
|
||||
name: 'Форматирование ответа',
|
||||
prompt: `Отлично, теперь используя эмодзи давай сделаем из этих данных telegram пост.
|
||||
Сначала кратко напиши простыми словами что следовало бы сделать пользователю,
|
||||
затем напиши подробную детальную информацию.
|
||||
В конце поста должен быть текст: "${process.env.PROMO_TEXT}"`,
|
||||
name: 'Response Formatting',
|
||||
prompt: `Great, now let's create a Telegram post from this data using emojis.
|
||||
First, briefly explain in simple terms what the user should do,
|
||||
then provide detailed information.
|
||||
The post should end with the text: "${process.env.PROMO_TEXT}"`,
|
||||
},
|
||||
],
|
||||
};
|
||||
this.activePipelines.set(chatId, { pipeline: userPipeline, chatId });
|
||||
|
||||
await ctx.sendChatAction('typing');
|
||||
await ctx.reply('🚀 Запускаю анализ...');
|
||||
await ctx.reply('🚀 Starting analysis...');
|
||||
|
||||
const results = await this.pipelineExecutor.executeChain({
|
||||
pipeline: userPipeline,
|
||||
@@ -131,13 +130,11 @@ export class TelegramBot {
|
||||
console.log(`Sending response to chat ${chatId}:`, trimmedResult);
|
||||
await ctx.replyWithHTML(trimmedResult);
|
||||
} else {
|
||||
await ctx.reply(
|
||||
'Не удалось обработать запрос. Пожалуйста, попробуйте еще раз.',
|
||||
);
|
||||
await ctx.reply('Failed to process the request. Please try again.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error processing message:', error);
|
||||
await ctx.reply('Произошла ошибка при обработке вашего запроса.');
|
||||
await ctx.reply('An error occurred while processing your request.');
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user