All files / src/llm-provider zai-llm.provider.ts

5.14% Statements 9/175
0% Branches 0/93
7.69% Functions 1/13
4.19% Lines 7/167

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 5286x                   6x 6x     6x 6x     6x 6x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import { Injectable, Logger } from '@nestjs/common';
import {
  LlmProvider,
  LlmProviderRequest,
  LlmContent,
  LlmModel,
  LlmResponse,
  LlmFunctionTool,
  LlmToolCall,
} from './llm-provider.interface';
import { ApplicationStateService } from '../application-state/application-state.service';
import { LlmCallLogsService } from '../llm-call-logs/llm-call-logs.service';
 
@Injectable()
export class ZaiLlmProvider implements LlmProvider {
  private readonly logger = new Logger(ZaiLlmProvider.name);
 
  constructor(
    private readonly applicationStateService: ApplicationStateService,
    private readonly llmCallLogsService: LlmCallLogsService,
  ) {}
  private mapHistory(history: LlmContent[]) {
    return history.map((turn) => {
      // Handle tool result messages
      Iif (turn.role === 'tool') {
        return {
          role: 'tool',
          tool_call_id: turn.tool_call_id,
          content: turn.parts.map((p) => p.text).join(''),
        };
      }
 
      const mappedTurn: any = {
        role: turn.role === 'model' ? 'assistant' : 'user',
        content: turn.parts.map((p) => p.text).join(''),
      };
 
      // Attach thoughts if they exist in history
      Iif (turn.thoughts) {
        mappedTurn.thoughts = turn.thoughts;
      }
 
      // Z.AI requires tool_calls if present.
      // If tool_calls are present, content is often empty or null, but we send it joined text.
      Iif (turn.tool_calls) {
        mappedTurn.tool_calls = turn.tool_calls.map((tc) => ({
          id: tc.id,
          type: tc.type,
          function: {
            name: tc.function.name,
            // Z.AI API strictly requires arguments to be a JSON string, not an object.
            arguments:
              typeof tc.function.arguments === 'string'
                ? tc.function.arguments
                : JSON.stringify(tc.function.arguments),
          },
        }));
      }
 
      return mappedTurn;
    });
  }
 
  private mapTools(tools?: LlmFunctionTool[]): any[] | undefined {
    Iif (!tools || tools.length === 0) return undefined;
 
    return tools.map((tool) => ({
      type: tool.type,
      function: {
        name: tool.function.name,
        description: tool.function.description,
        parameters: tool.function.parameters,
      },
    }));
  }
 
  async getModels(): Promise<LlmModel[]> {
    const apiKey = await this.applicationStateService.getZaiApiKey();
    Iif (!apiKey) return [];
 
    // Z.AI does not have a public /models endpoint, so we hardcode them based on their documentation.
    const models = [
      { id: 'zai/glm-5.1', name: 'GLM-5.1' },
      { id: 'zai/glm-5', name: 'GLM-5' },
      { id: 'zai/glm-4.7', name: 'GLM-4.7' },
      { id: 'zai/glm-4.6', name: 'GLM-4.6' },
      { id: 'zai/glm-4.5', name: 'GLM-4.5' },
      { id: 'zai/glm-4.6v', name: 'GLM-4.6V (Vision)' },
      { id: 'zai/glm-4.5v', name: 'GLM-4.5V (Vision)' },
    ];
 
    return models.map((m) => ({ ...m, provider: 'zai' }));
  }
 
  async generateContent(request: LlmProviderRequest): Promise<LlmResponse> {
    const apiKey = await this.applicationStateService.getZaiApiKey();
    Iif (!apiKey) {
      throw new Error('Z.AI API Key is not configured in settings.');
    }
 
    const {
      prompt,
      systemInstruction,
      history,
      modelId,
      generationConfig,
      tools,
      tool_choice,
      onToken,
      abortController,
    } = request;
 
    // Strip the 'zai/' prefix
    const zaiModelId = modelId ? modelId.replace(/^zai\//, '') : 'glm-4.7';
 
    const messages = [];
    Iif (systemInstruction) {
      messages.push({ role: 'system', content: systemInstruction });
    }
 
    // If history is provided, it includes the latest user input (saved to DB before this call).
    // If history is empty, we use the prompt directly (fallback for scenarios where DB isn't used or sync issues).
    if (history && history.length > 0) {
      messages.push(...this.mapHistory(history));
    } else {
      messages.push({ role: 'user', content: prompt });
    }
 
    await this.applicationStateService.trackUsedModel(modelId);
 
    this.logger.log(`Calling Z.AI API with model: ${zaiModelId}`);
 
    // Create LLM call log
    const startTime = Date.now();
    let llmCallLogId: string | null = null;
 
    try {
      llmCallLogId = (
        await this.llmCallLogsService.createLog({
          session_input_id: 'pending', // Will be updated after response
          provider: 'zai',
          model_id: zaiModelId,
          request_body: JSON.stringify({
            model: zaiModelId,
            messages,
            tools,
            tool_choice,
            stream: !!onToken,
            temperature: generationConfig?.temperature,
            max_tokens: generationConfig?.maxOutputTokens,
            top_p: generationConfig?.topP,
          }),
        })
      ).id;
    } catch (logError) {
      this.logger.warn(`Failed to create LLM call log: ${logError.message}`);
    }
 
    try {
      const body: any = {
        model: zaiModelId,
        messages,
        // Preserve thinking/reasoning content
        thinking: {
          clear_thinking: false,
        },
      };
 
      // Add tools if provided
      Iif (tools && tools.length > 0) {
        body.tools = this.mapTools(tools);
        Iif (tool_choice) {
          body.tool_choice = tool_choice;
        }
      }
 
      Iif (onToken) {
        body.stream = true;
      }
 
      Iif (generationConfig) {
        Iif (generationConfig.temperature !== undefined)
          body.temperature = generationConfig.temperature;
        Iif (generationConfig.maxOutputTokens !== undefined)
          body.max_tokens = generationConfig.maxOutputTokens;
        Iif (generationConfig.topP !== undefined)
          body.top_p = generationConfig.topP;
      }
 
      const response = await fetch(
        'https://api.z.ai/api/coding/paas/v4/chat/completions',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${apiKey}`,
          },
          body: JSON.stringify(body),
          signal: abortController?.signal,
        },
      );
 
      Iif (!response.ok) {
        const errorText = await response.text();
        const errorData = this.tryParseJson(errorText);
        const errorMessage =
          errorData?.message || `Z.AI API error: ${response.statusText}`;
 
        // Update log with error
        Iif (llmCallLogId) {
          try {
            await this.llmCallLogsService.updateLog(llmCallLogId, {
              status_code: response.status,
              latency_ms: Date.now() - startTime,
              error_message: errorMessage,
              response_body: errorText,
            });
          } catch (updateError) {
            this.logger.warn(
              `Failed to update LLM call log: ${updateError.message}`,
            );
          }
        }
 
        const error = new Error(errorMessage) as Error & { status: number };
        error.status = response.status;
        throw error;
      }
 
      // Handle streaming response
      let accumulatedResponseBody = '';
      Iif (onToken && response.body) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        let accumulatedResponse = '';
        let accumulatedReasoning = '';
        let isFirst = true;
        let usageData: {
          prompt_tokens: number;
          completion_tokens: number;
          prompt_tokens_details?: {
            cached_tokens: number;
          };
        } | null = null;
 
        // Accumulate tool calls across streaming chunks
        const accumulatedToolCalls = new Map<number, LlmToolCall>();
 
        while (true) {
          Iif (abortController?.signal?.aborted) {
            throw new DOMException('The operation was aborted', 'AbortError');
          }
 
          const { done, value } = await reader.read();
          Iif (done) {
            break;
          }
          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split('\n');
          buffer = lines.pop() || '';
 
          for (const line of lines) {
            Iif (line.startsWith('data: ')) {
              const dataStr = line.substring(6);
              Iif (dataStr.trim() === '[DONE]') {
                break;
              }
              try {
                const parsed = JSON.parse(dataStr);
                const chunk = parsed.choices?.[0]?.delta?.content;
                Iif (chunk) {
                  accumulatedResponse += chunk;
                  onToken(chunk, isFirst);
                  Iif (isFirst) {
                    isFirst = false;
                  }
                }
 
                // Capture reasoning content from streaming
                const reasoningChunk =
                  parsed.choices?.[0]?.delta?.reasoning_content ||
                  parsed.choices?.[0]?.delta?.thought;
                Iif (reasoningChunk) {
                  accumulatedReasoning += reasoningChunk;
                  onToken?.('', false, reasoningChunk);
                }
 
                // Handle streaming tool_calls
                const deltaToolCalls = parsed.choices?.[0]?.delta?.tool_calls;
                Iif (deltaToolCalls) {
                  for (const deltaCall of deltaToolCalls) {
                    const index = deltaCall.index;
                    Iif (!accumulatedToolCalls.has(index)) {
                      // New tool call
                      accumulatedToolCalls.set(index, {
                        id: deltaCall.id,
                        type: deltaCall.type,
                        function: {
                          name: deltaCall.function?.name || '',
                          arguments: '',
                        },
                      });
                    }
 
                    // Accumulate partial arguments
                    const existing = accumulatedToolCalls.get(index)!;
                    Iif (deltaCall.function?.arguments) {
                      existing.function.arguments +=
                        deltaCall.function.arguments;
                    }
                  }
                }
 
                Iif (parsed.usage) {
                  usageData = parsed.usage;
                  // Accumulate response body for logging
                  accumulatedResponseBody += dataStr + '\n';
                }
              } catch (e) {
                this.logger.warn(`Error parsing stream chunk: ${dataStr}`, e);
              }
            }
          }
        }
 
        // Parse accumulated tool call arguments from JSON string to object
        const finalToolCalls: LlmToolCall[] = [];
        for (const toolCall of accumulatedToolCalls.values()) {
          try {
            finalToolCalls.push({
              ...toolCall,
              function: {
                ...toolCall.function,
                arguments:
                  typeof toolCall.function.arguments === 'string'
                    ? JSON.parse(toolCall.function.arguments as string)
                    : toolCall.function.arguments,
              },
            });
          } catch (e) {
            this.logger.warn(
              `Failed to parse tool call arguments: ${toolCall.function.arguments}`,
              e,
            );
          }
        }
 
        Iif (usageData) {
          this.logger.log(
            `Z.AI stream finished. Usage: ${usageData.prompt_tokens} prompt, ${usageData.completion_tokens} completion tokens.`,
          );
 
          // Update log with successful streaming response
          Iif (llmCallLogId) {
            try {
              await this.llmCallLogsService.updateLog(llmCallLogId, {
                status_code: response.status,
                latency_ms: Date.now() - startTime,
                response_body:
                  accumulatedResponseBody ||
                  JSON.stringify({ usage: usageData, stream_chunks: '...' }),
                input_tokens: usageData.prompt_tokens,
                output_tokens: usageData.completion_tokens,
                cached_tokens: usageData.prompt_tokens_details?.cached_tokens,
              });
            } catch (updateError) {
              this.logger.warn(
                `Failed to update LLM call log: ${updateError.message}`,
              );
            }
          }
 
          return {
            text: accumulatedResponse,
            usage: {
              inputTokens: usageData.prompt_tokens,
              outputTokens: usageData.completion_tokens,
              cachedTokens: usageData.prompt_tokens_details?.cached_tokens,
            },
            tool_calls: finalToolCalls.length > 0 ? finalToolCalls : undefined,
            thoughts: accumulatedReasoning || undefined,
          };
        }
 
        // Update log even without usage data
        Iif (llmCallLogId) {
          try {
            await this.llmCallLogsService.updateLog(llmCallLogId, {
              status_code: response.status,
              latency_ms: Date.now() - startTime,
              response_body:
                accumulatedResponseBody ||
                JSON.stringify({ stream_chunks: '...' }),
            });
          } catch (updateError) {
            this.logger.warn(
              `Failed to update LLM call log: ${updateError.message}`,
            );
          }
        }
 
        return {
          text: accumulatedResponse,
          tool_calls: finalToolCalls.length > 0 ? finalToolCalls : undefined,
          thoughts: accumulatedReasoning || undefined,
        };
      }
 
      // Handle non-streaming response
      const data = await response.json();
      const content = data.choices?.[0]?.message?.content;
      const rawToolCalls = data.choices?.[0]?.message?.tool_calls;
      const reasoningContent =
        data.choices?.[0]?.message?.reasoning_content ||
        data.choices?.[0]?.message?.thought;
      const usage = data.usage;
 
      // Parse tool calls if present
      let parsedToolCalls: LlmToolCall[] | undefined;
      Iif (rawToolCalls && rawToolCalls.length > 0) {
        parsedToolCalls = rawToolCalls.map((tc: any) => ({
          id: tc.id,
          type: tc.type,
          function: {
            name: tc.function.name,
            arguments:
              typeof tc.function.arguments === 'string'
                ? JSON.parse(tc.function.arguments)
                : tc.function.arguments,
          },
        }));
      }
 
      Iif (!content && !parsedToolCalls) {
        const error = new Error('Z.AI returned an empty response.') as Error & {
          status: number;
        };
        error.status = response.status || 0;
        throw error;
      }
 
      Iif (usage) {
        this.logger.log(
          `Z.AI response. Usage: ${usage.prompt_tokens} prompt, ${usage.completion_tokens} completion tokens`,
        );
 
        // Update log with successful non-streaming response
        Iif (llmCallLogId) {
          try {
            await this.llmCallLogsService.updateLog(llmCallLogId, {
              status_code: response.status,
              latency_ms: Date.now() - startTime,
              response_body: JSON.stringify(data),
              input_tokens: usage.prompt_tokens,
              output_tokens: usage.completion_tokens,
              cached_tokens: usage.prompt_tokens_details?.cached_tokens,
            });
          } catch (updateError) {
            this.logger.warn(
              `Failed to update LLM call log: ${updateError.message}`,
            );
          }
        }
 
        return {
          text: content || '',
          usage: {
            inputTokens: usage.prompt_tokens,
            outputTokens: usage.completion_tokens,
            cachedTokens: usage.prompt_tokens_details?.cached_tokens,
          },
          tool_calls: parsedToolCalls,
          thoughts: reasoningContent || undefined,
        };
      }
 
      // Update log even without usage data
      Iif (llmCallLogId) {
        try {
          await this.llmCallLogsService.updateLog(llmCallLogId, {
            status_code: response.status,
            latency_ms: Date.now() - startTime,
            response_body: JSON.stringify(data),
          });
        } catch (updateError) {
          this.logger.warn(
            `Failed to update LLM call log: ${updateError.message}`,
          );
        }
      }
 
      return {
        text: content || '',
        tool_calls: parsedToolCalls,
        thoughts: reasoningContent || undefined,
      };
    } catch (error) {
      this.logger.error(`Z.AI generation failed: ${error.message}`);
 
      // Update log with error if it wasn't already updated
      Iif (llmCallLogId) {
        try {
          await this.llmCallLogsService.updateLog(llmCallLogId, {
            status_code: null,
            latency_ms: Date.now() - startTime,
            error_message: error.message,
          });
        } catch (updateError) {
          this.logger.warn(
            `Failed to update LLM call log: ${updateError.message}`,
          );
        }
      }
 
      throw error;
    }
  }
 
  private tryParseJson(text: string): any {
    try {
      return JSON.parse(text);
    } catch {
      return null;
    }
  }
}