( chatMessages: OpenAI.ChatCompletionMessageParam[], functions: OpenAI.ChatCompletionTool[], chatState: ChatStateType, model: string, chatURL: string, stream: false | true | null | undefined = false, contentCallBack: (chunk?: OpenAI.Chat.Completions.ChatCompletionChunk) => void )
| 362 | |
| 363 | // calls openRouter OR OpenAI chatmodels |
| 364 | export async function callLLM( |
| 365 | chatMessages: OpenAI.ChatCompletionMessageParam[], |
| 366 | functions: OpenAI.ChatCompletionTool[], |
| 367 | chatState: ChatStateType, |
| 368 | model: string, |
| 369 | chatURL: string, |
| 370 | stream: false | true | null | undefined = false, |
| 371 | contentCallBack: (chunk?: OpenAI.Chat.Completions.ChatCompletionChunk) => void |
| 372 | ): Promise<OpenAI.ChatCompletion | undefined> { |
| 373 | const headers: Record<string, string> = generateHeaders(chatState); |
| 374 | let chatCompletion: OpenAI.ChatCompletion | undefined = undefined; |
| 375 | const openai = getOpenai(chatState.openAIApiKey, chatState.baseURL, headers); |
| 376 | |
| 377 | const payload: OpenAI.ChatCompletionCreateParams = { |
| 378 | model, |
| 379 | messages: chatMessages, |
| 380 | user: 'taskyon', |
| 381 | temperature: 0.0, |
| 382 | stream, |
| 383 | n: 1, |
| 384 | }; |
| 385 | |
| 386 | if (functions.length > 0) { |
| 387 | payload.tool_choice = 'auto'; |
| 388 | payload.tools = functions; |
| 389 | } |
| 390 | |
| 391 | if (payload.stream) { |
| 392 | let cancelStreaming = false; |
| 393 | function cancelStreamListener() { |
| 394 | cancelStreaming = true; |
| 395 | } |
| 396 | document.addEventListener( |
| 397 | CURRENT_TASK_CANCELLATION_EVENT, |
| 398 | cancelStreamListener |
| 399 | ); |
| 400 | try { |
| 401 | const completion = await openai.chat.completions.create(payload); |
| 402 | |
| 403 | const chunks = []; |
| 404 | for await (const chunk of completion) { |
| 405 | if (cancelStreaming) { |
| 406 | return; |
| 407 | } |
| 408 | chunks.push(chunk); |
| 409 | if (chunk) { |
| 410 | contentCallBack(chunk); |
| 411 | } |
| 412 | } |
| 413 | chatCompletion = accumulateChatCompletion(chunks); |
| 414 | } catch (error) { |
| 415 | console.error('Error during streaming:', error); |
| 416 | } |
| 417 | document.removeEventListener( |
| 418 | CURRENT_TASK_CANCELLATION_EVENT, |
| 419 | cancelStreamListener |
| 420 | ); |
| 421 | } else { |
no test coverage detected