|
| 1 | +import axios, { type AxiosResponse } from 'axios' |
| 2 | +import { type Readable } from 'stream' |
| 3 | +import { GrammyError } from 'grammy' |
| 4 | +import { pino } from 'pino' |
| 5 | + |
| 6 | +import config from '../../../config' |
| 7 | +import { type OnCallBackQueryData, type OnMessageContext, type ChatConversation } from '../../types' |
| 8 | +import { type LlmCompletion } from './llmApi' |
| 9 | +import { headersStream } from './helper' |
| 10 | +import { LlmModelsEnum } from '../utils/llmModelsManager' |
| 11 | +import { type ModelParameters } from '../utils/types' |
| 12 | +import { prepareConversation } from './openai' |
| 13 | + |
| 14 | +const logger = pino({ |
| 15 | + name: 'deepSeek - llmsBot', |
| 16 | + transport: { |
| 17 | + target: 'pino-pretty', |
| 18 | + options: { colorize: true } |
| 19 | + } |
| 20 | +}) |
| 21 | + |
| 22 | +const API_ENDPOINT = config.llms.apiEndpoint |
| 23 | + |
| 24 | +export const deepSeekStreamCompletion = async ( |
| 25 | + conversation: ChatConversation[], |
| 26 | + model = LlmModelsEnum.GPT_35_TURBO, |
| 27 | + ctx: OnMessageContext | OnCallBackQueryData, |
| 28 | + msgId: number, |
| 29 | + limitTokens = true, |
| 30 | + parameters?: ModelParameters |
| 31 | +): Promise<LlmCompletion> => { |
| 32 | + logger.info(`Handling ${model} stream completion`) |
| 33 | + parameters = parameters ?? { |
| 34 | + system: ctx.session.currentPrompt, |
| 35 | + max_tokens: +config.openAi.chatGpt.maxTokens |
| 36 | + } |
| 37 | + const data = { |
| 38 | + model, |
| 39 | + stream: true, |
| 40 | + system: parameters.system, |
| 41 | + max_tokens: limitTokens ? parameters.max_tokens : undefined, |
| 42 | + messages: prepareConversation(conversation, model, ctx) // .map(m => { return { content: m.content, role: m.role } }) |
| 43 | + } |
| 44 | + let wordCount = 0 |
| 45 | + let wordCountMinimum = 2 |
| 46 | + const url = `${API_ENDPOINT}/deepseek/completions` |
| 47 | + if (!ctx.chat?.id) { |
| 48 | + throw new Error('Context chat id should not be empty after openAI streaming') |
| 49 | + } |
| 50 | + |
| 51 | + const response: AxiosResponse = await axios.post(url, data, headersStream) |
| 52 | + |
| 53 | + const completionStream: Readable = response.data |
| 54 | + let completion = '' |
| 55 | + let outputTokens = '' |
| 56 | + let inputTokens = '' |
| 57 | + let message = '' |
| 58 | + for await (const chunk of completionStream) { |
| 59 | + const msg = chunk.toString() |
| 60 | + if (msg) { |
| 61 | + if (msg.includes('Input Tokens:')) { |
| 62 | + const tokenMsg = msg.split('Input Tokens: ')[1] |
| 63 | + inputTokens = tokenMsg.split('Output Tokens: ')[0] |
| 64 | + outputTokens = tokenMsg.split('Output Tokens: ')[1] |
| 65 | + completion += msg.split('Input Tokens: ')[0] |
| 66 | + completion = completion.split('Input Tokens: ')[0] |
| 67 | + } else if (msg.includes('Output Tokens: ')) { |
| 68 | + outputTokens = msg.split('Output Tokens: ')[1] |
| 69 | + completion = completion.split('Output Tokens: ')[0] |
| 70 | + } else { |
| 71 | + wordCount++ |
| 72 | + completion += msg |
| 73 | + if (wordCount > wordCountMinimum) { |
| 74 | + if (wordCountMinimum < 64) { |
| 75 | + wordCountMinimum *= 2 |
| 76 | + } |
| 77 | + completion = completion.replaceAll('...', '') |
| 78 | + completion += '...' |
| 79 | + wordCount = 0 |
| 80 | + if (ctx.chat?.id && message !== completion) { |
| 81 | + message = completion |
| 82 | + await ctx.api |
| 83 | + .editMessageText(ctx.chat?.id, msgId, completion) |
| 84 | + .catch(async (e: any) => { |
| 85 | + if (e instanceof GrammyError) { |
| 86 | + if (e.error_code !== 400) { |
| 87 | + throw e |
| 88 | + } else { |
| 89 | + logger.error(e.message) |
| 90 | + } |
| 91 | + } else { |
| 92 | + throw e |
| 93 | + } |
| 94 | + }) |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + completion = completion.replaceAll('...', '') |
| 101 | + await ctx.api |
| 102 | + .editMessageText(ctx.chat?.id, msgId, completion) |
| 103 | + .catch((e: any) => { |
| 104 | + if (e instanceof GrammyError) { |
| 105 | + if (e.error_code !== 400) { |
| 106 | + throw e |
| 107 | + } else { |
| 108 | + logger.error(e) |
| 109 | + } |
| 110 | + } else { |
| 111 | + throw e |
| 112 | + } |
| 113 | + }) |
| 114 | + const totalOutputTokens = outputTokens // response.headers['x-openai-output-tokens'] |
| 115 | + const totalInputTokens = inputTokens // response.headers['x-openai-input-tokens'] |
| 116 | + return { |
| 117 | + completion: { |
| 118 | + content: completion, |
| 119 | + role: 'assistant', |
| 120 | + model, |
| 121 | + timestamp: Date.now() |
| 122 | + }, |
| 123 | + usage: parseInt(totalOutputTokens, 10) + parseInt(totalInputTokens, 10), |
| 124 | + price: 0, |
| 125 | + inputTokens: parseInt(totalInputTokens, 10), |
| 126 | + outputTokens: parseInt(totalOutputTokens, 10) |
| 127 | + } |
| 128 | +} |
0 commit comments