Skip to content

Commit

Permalink
chore: remove redundant workflows code
Browse files Browse the repository at this point in the history
  • Loading branch information
adolphnov committed Nov 16, 2024
1 parent f84cc34 commit 527e709
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 51 deletions.
1 change: 0 additions & 1 deletion doc/cn/CONFIG.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ OPENAI_API_BASE,GOOGLE_API_BASE,MISTRAL_API_BASE,COHERE_API_BASE,ANTHROPIC_API_B
| AI_PROVIDER | AI提供商 | `auto` | 可选值 `auto, openai, azure, workers, google, vertex, mistral, cohere, anthropic` |
| AI_IMAGE_PROVIDER | AI图片提供商 | `auto` | 可选值 `auto, openai, azure, workers` |
| SYSTEM_INIT_MESSAGE | 全局默认初始化消息 | `你是一个得力的助手` | 根据绑定的语言自动选择默认值 |
| SYSTEM_INIT_MESSAGE_ROLE | 全局默认初始化消息角色 | `system` | |

### OpenAI

Expand Down
1 change: 0 additions & 1 deletion doc/en/CONFIG.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ Each user's custom configuration can only be modified by sending a message throu
| AI_PROVIDER | AI provider | `auto` | Options `auto, openai, azure, workers, gemini, mistral, cohere, anthropic` |
| AI_IMAGE_PROVIDER | AI image provider | `auto` | Options `auto, openai, azure, workers` |
| SYSTEM_INIT_MESSAGE | Default initialization message. | `You are a helpful assistant` | Automatically select default values based on the bound language. |
| SYSTEM_INIT_MESSAGE_ROLE | Default initialization message role. | `system` | |

### OpenAI

Expand Down
2 changes: 0 additions & 2 deletions src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,6 @@ export class AgentShareConfig {
AI_IMAGE_PROVIDER = 'openai';
// 全局默认初始化消息
SYSTEM_INIT_MESSAGE: string | null = null;
// 全局默认初始化消息角色
SYSTEM_INIT_MESSAGE_ROLE = 'system';
}

// -- Open AI 配置 --
Expand Down
62 changes: 17 additions & 45 deletions src/telegram/handler/chat.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable unused-imports/no-unused-vars */
import type { FilePart, ToolResultPart } from 'ai';
import type * as Telegram from 'telegram-bot-api-types';
import type { ChatStreamTextHandler, HistoryModifier, ImageResult, LLMChatRequestParams } from '../../agent/types';
Expand All @@ -8,7 +9,7 @@ import type { MessageHandler } from './types';
import { loadAudioLLM, loadChatLLM, loadImageGen } from '../../agent';
import { loadHistory, requestCompletionsFromLLM } from '../../agent/chat';
import { ENV } from '../../config/env';
import { clearLog, getLog, logSingleton } from '../../log/logDecortor';
import { getLog, logSingleton } from '../../log/logDecortor';
import { log } from '../../log/logger';
import { sendToolResult } from '../../tools';
import { imageToBase64String, renderBase64DataURI } from '../../utils/image';
Expand All @@ -21,9 +22,9 @@ async function messageInitialize(sender: MessageSender, streamSender: ChatStream
if (!sender.context.message_id) {
try {
setTimeout(() => sendAction(sender.api.token, sender.context.chat_id, 'typing'), 0);
if (!ENV.SEND_INIT_MESSAGE) {
return;
}
// if (!ENV.SEND_INIT_MESSAGE) {
// return;
// }
log.info(`send init message`);
streamSender.send('...', 'chat');
} catch (e) {
Expand All @@ -37,7 +38,7 @@ export async function chatWithLLM(
params: LLMChatRequestParams | null,
context: WorkerContext,
modifier: HistoryModifier | null,
): Promise<UnionData | Response> {
): Promise<Response> {
const sender = MessageSender.from(context.SHARE_CONTEXT.botToken, message);
const streamSender = OnStreamHander(sender, context, message.text || '');
messageInitialize(sender, streamSender);
Expand Down Expand Up @@ -93,7 +94,7 @@ export class ChatHandler implements MessageHandler<WorkerContext> {
// 处理原始消息
const params = await this.processOriginalMessage(message, context);
// 执行工作流
await workflow(context, flowDetail?.workflow || [{}], message, params);
await workflow(context, message, params);
return null;
} catch (e) {
console.error('Error:', e);
Expand Down Expand Up @@ -260,17 +261,12 @@ async function sendTelegraph(context: WorkerContext, sender: MessageSender | Cho
return resp;
}

function clearMessageContext(context: WorkerContext) {
clearLog(context.USER_CONFIG);
context.MIDDEL_CONTEXT.sender = null;
}

type WorkflowHandler = (
eMsg: any,
message: Telegram.Message,
params: LLMChatRequestParams,
context: WorkerContext
) => Promise<UnionData | Response | void>;
) => Promise<Response | void>;

const workflowHandlers: Record<string, WorkflowHandler> = {
'text:text': handleTextToText,
Expand All @@ -282,43 +278,21 @@ const workflowHandlers: Record<string, WorkflowHandler> = {

async function workflow(
context: WorkerContext,
flows: Record<string, any>[],
message: Telegram.Message,
params: LLMChatRequestParams,
): Promise<Response | void> {
const MiddleResult = context.MIDDEL_CONTEXT.middleResult;

for (let i = 0; i < flows.length; i++) {
const eMsg = i === 0 ? context.MIDDEL_CONTEXT.originalMessage : MiddleResult[i - 1];

const handlerKey = `${eMsg?.type || 'text'}:${flows[i]?.type || 'text'}`;
const handler = workflowHandlers[handlerKey];

if (!handler) {
throw new Error(`Unsupported type: ${handlerKey}`);
}

const result = await handler(eMsg, message, params, context) as UnionData | Response;

if (result instanceof Response) {
return result;
}

if (i < flows.length - 1 && ['image', 'text'].includes(result?.type)) {
injectHistory(context, result, flows[i + 1].type);
}

MiddleResult.push(result);
clearMessageContext(context);
}
const eMsg = context.MIDDEL_CONTEXT.originalMessage;
const handlerKey = `${eMsg?.type || 'text'}:text`;
const handler = workflowHandlers[handlerKey];
return handler(eMsg, message, params, context);
}

async function handleTextToText(
eMsg: any,
message: Telegram.Message,
params: LLMChatRequestParams,
context: WorkerContext,
): Promise<UnionData | Response> {
): Promise<Response> {
return chatWithLLM(message, params, context, null);
}

Expand All @@ -327,7 +301,7 @@ async function handleTextToImage(
message: Telegram.Message,
params: LLMChatRequestParams,
context: WorkerContext,
): Promise<UnionData | Response> {
): Promise<Response> {
const agent = loadImageGen(context.USER_CONFIG);
const sender = MessageSender.from(context.SHARE_CONTEXT.botToken, message);
if (!agent) {
Expand All @@ -339,16 +313,15 @@ async function handleTextToImage(
log.info('imageresult', JSON.stringify(result));
await sendImages(result, ENV.SEND_IMAGE_AS_FILE, sender, context.USER_CONFIG);
const api = createTelegramBotAPI(context.SHARE_CONTEXT.botToken);
await api.deleteMessage({ chat_id: sender.context.chat_id, message_id: sender.context.message_id! });
return result as UnionData;
return api.deleteMessage({ chat_id: sender.context.chat_id, message_id: sender.context.message_id! });
}

async function handleAudioToText(
eMsg: any,
message: Telegram.Message,
params: LLMChatRequestParams,
context: WorkerContext,
): Promise<UnionData | Response> {
): Promise<Response> {
const agent = loadAudioLLM(context.USER_CONFIG);
const sender = MessageSender.from(context.SHARE_CONTEXT.botToken, message);
if (!agent) {
Expand All @@ -358,8 +331,7 @@ async function handleAudioToText(
const audio = await fetch(url).then(b => b.blob());
const result = await agent.request(audio, context.USER_CONFIG);
context.MIDDEL_CONTEXT.history.push({ role: 'user', content: result.text || '' });
await sender.sendRichText(`${getLog(context.USER_CONFIG)}\n> \`${result.text}\``, 'MarkdownV2', 'chat');
return result;
return sender.sendRichText(`${getLog(context.USER_CONFIG)}\n> \`${result.text}\``, 'MarkdownV2', 'chat');
}

export async function sendImages(img: ImageResult, SEND_IMAGE_AS_FILE: boolean, sender: MessageSender, config: AgentUserConfig) {
Expand Down
2 changes: 0 additions & 2 deletions wrangler-example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,6 @@ AI_PROVIDER = 'auto'
AI_IMAGE_PROVIDER = 'auto'
## 全局默认初始化消息
#SYSTEM_INIT_MESSAGE = 'You are a useful assistant.'
## 全局默认初始化消息角色
#SYSTEM_INIT_MESSAGE_ROLE = 'system'

## -- Open AI 配置 --
##
Expand Down

0 comments on commit 527e709

Please sign in to comment.