File size: 9,628 Bytes
ff49634
 
df94b74
ff49634
 
 
 
99d1f6e
 
 
 
 
 
 
 
 
 
 
 
 
f90228b
 
 
 
 
 
99d1f6e
f90228b
 
 
99d1f6e
 
 
f90228b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff49634
 
f90228b
 
 
 
 
 
 
 
 
 
ff49634
f90228b
 
ff49634
f90228b
 
 
 
 
 
 
ff49634
 
 
f90228b
 
 
 
ff49634
 
 
f90228b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff49634
 
 
 
 
 
 
 
 
f90228b
 
df94b74
c1e702e
 
 
 
 
 
 
 
 
 
 
 
f2d1fea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99d1f6e
 
 
 
 
 
f90228b
 
 
c1e702e
 
 
 
 
 
 
df94b74
 
 
 
 
f90228b
f2d1fea
 
 
 
 
 
 
 
 
 
 
99d1f6e
f90228b
c1e702e
99d1f6e
 
 
f90228b
99d1f6e
c1e702e
 
 
 
99d1f6e
f90228b
f2d1fea
f90228b
 
 
 
c1e702e
f90228b
 
99d1f6e
 
 
 
 
 
 
62fdec8
f90228b
 
 
 
 
 
99d1f6e
 
 
 
f2d1fea
f90228b
 
 
 
ff49634
f90228b
 
c1e702e
 
 
 
 
 
 
 
 
 
ff49634
f90228b
ff49634
 
f90228b
 
 
 
 
99d1f6e
 
f90228b
 
 
 
 
ff49634
f90228b
 
 
ff49634
 
 
 
f90228b
ff49634
 
f90228b
ff49634
f90228b
 
 
ff49634
 
f90228b
 
 
 
 
 
 
 
df94b74
 
 
 
 
c1e702e
 
 
 
df94b74
c1e702e
 
 
 
df94b74
c1e702e
 
 
f90228b
 
 
 
 
 
99d1f6e
 
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
import {
  extractContentFromCompletionBody,
  isLikelyTruncatedJson,
  looksLikeHtmlErrorPage,
  stripReasoningBlocks,
} from "./parse-response";

export interface ChatMessage {
  role: "system" | "user" | "assistant";
  content: string;
}

export interface ChatCompletionOptions {
  messages: ChatMessage[];
  model: string;
  temperature?: number;
  max_tokens?: number;
  response_format?: { type: "json_object" };
}

export interface StreamCallbacks {
  onToken: (token: string) => void;
}

export interface ChatCompletionResult {
  content: string;
  usage?: {
    prompt_tokens?: number;
    completion_tokens?: number;
    total_tokens?: number;
  };
}

// Simple debug logger that works in both Node and Bun
function log(
  level: "info" | "error" | "warn",
  message: string,
  meta?: Record<string, unknown>,
) {
  const timestamp = new Date().toISOString();
  const metaStr = meta ? ` ${JSON.stringify(meta)}` : "";
  // eslint-disable-next-line no-console
  console[level](`[${timestamp}] [AI-CLIENT] ${level.toUpperCase()}: ${message}${metaStr}`);
}

function parseSSELine(line: string): { content?: string; usage?: ChatCompletionResult["usage"] } | null {
  if (!line.startsWith("data: ")) return null;
  const data = line.slice(6).trim();
  if (data === "[DONE]") return null;
  try {
    const chunk = JSON.parse(data);
    const choice = chunk.choices?.[0];
    const content = choice?.delta?.content ?? choice?.message?.content;
    const usage = chunk.usage;
    return { content: typeof content === "string" ? content : undefined, usage };
  } catch {
    return null;
  }
}

async function readSSEStream(
  reader: any,
  callbacks: StreamCallbacks,
): Promise<{ content: string; usage?: ChatCompletionResult["usage"]; rawBody: string }> {
  const decoder = new TextDecoder();
  let buffer = "";
  let rawBody = "";
  let fullContent = "";
  let lastUsage: ChatCompletionResult["usage"] | undefined;

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunkText = decoder.decode(value, { stream: true });
    rawBody += chunkText;
    buffer += chunkText;
    const lines = buffer.split("\n");
    buffer = lines.pop() ?? "";

    for (const line of lines) {
      const trimmedLine = line.trim();
      if (!trimmedLine || trimmedLine.startsWith(":")) continue;
      const parsed = parseSSELine(trimmedLine);
      if (!parsed) continue;
      if (parsed.content) {
        fullContent += parsed.content;
        callbacks.onToken(parsed.content);
      }
      if (parsed.usage) {
        lastUsage = parsed.usage;
      }
    }
  }

  // Process any remaining buffer
  if (buffer.trim()) {
    const parsed = parseSSELine(buffer.trim());
    if (parsed) {
      if (parsed.content) {
        fullContent += parsed.content;
        callbacks.onToken(parsed.content);
      }
      if (parsed.usage) {
        lastUsage = parsed.usage;
      }
    }
  }

  if (!fullContent) {
    const nonStreamContent = extractContentFromCompletionBody(rawBody);
    if (nonStreamContent) {
      fullContent = nonStreamContent;
      callbacks.onToken(nonStreamContent);
    }
  }

  return { content: fullContent, usage: lastUsage, rawBody };
}

const MAX_TRUNCATION_RETRIES = 2;

function isResponseFormatError(status: number, text: string): boolean {
  if (status !== 400 && status !== 422) return false;
  const lower = text.toLowerCase();
  return (
    lower.includes("response_format") ||
    lower.includes("json mode") ||
    lower.includes("json_object") ||
    lower.includes("unsupported parameter")
  );
}

const METADATA_HOSTS = new Set([
  "169.254.169.254",              // AWS / GCP / Azure metadata
  "metadata.google.internal",     // GCP metadata
  "metadata",                     // some cloud providers
  "100.100.100.200",              // Alibaba Cloud metadata
]);

const RFC1918_PATTERN = /^(?:10\.\d+\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[01])\.\d+\.\d+|192\.168\.\d+\.\d+)$/;

function isMetadataOrPrivateHost(hostname: string): boolean {
  const lower = hostname.toLowerCase();
  if (METADATA_HOSTS.has(lower)) return true;
  // Allow loopback (localhost/127.0.0.1/::1) for local model backends
  // Block RFC1918 only in production — dev may have LAN model servers
  if (RFC1918_PATTERN.test(hostname) && process.env.NODE_ENV === "production") return true;
  return false;
}

function sanitizeForLog(text: string, maxLen = 300): string {
  return text
    .replace(/Bearer\s+[^\s"']+/gi, "Bearer [REDACTED]")
    .replace(/sk-[a-zA-Z0-9_-]{20,}/g, "[REDACTED_API_KEY]")
    .slice(0, maxLen);
}

export class OpenAICompatibleClient {
  constructor(
    private baseUrl: string,
    private apiKey: string,
  ) {}

  async chatCompletion(
    opts: ChatCompletionOptions,
    callbacks?: StreamCallbacks,
  ): Promise<ChatCompletionResult> {
    return this._doChatCompletion(opts, callbacks, { attempt: 1 });
  }

  private async _doChatCompletion(
    opts: ChatCompletionOptions,
    callbacks: StreamCallbacks | undefined,
    ctx: {
      attempt: number;
      truncationRetries?: number;
      retriedForResponseFormat?: boolean;
    },
  ): Promise<ChatCompletionResult> {
    let hostname: string;
    try {
      hostname = new URL(this.baseUrl).hostname;
    } catch {
      throw new Error(`Invalid base URL: ${this.baseUrl}`);
    }

    if (isMetadataOrPrivateHost(hostname)) {
      throw new Error(`Requests to metadata/private network addresses are not allowed`);
    }

    const url = `${this.baseUrl.replace(/\/$/, "")}/chat/completions`;
    const stream = true;
    const body: Record<string, unknown> = {
      model: opts.model,
      messages: opts.messages,
      temperature: opts.temperature ?? 0.7,
      stream,
    };
    if (opts.max_tokens) body.max_tokens = opts.max_tokens;
    if (opts.response_format && !ctx.retriedForResponseFormat) {
      body.response_format = opts.response_format;
    }

    log("info", "Sending chat completion request", {
      url: sanitizeForLog(url, 200),
      model: opts.model,
      messageCount: opts.messages.length,
      maxTokens: opts.max_tokens,
      stream,
      attempt: ctx.attempt,
    });

    const res = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${this.apiKey}`,
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(180_000),
    });

    log("info", "Received response", {
      status: res.status,
      statusText: res.statusText,
      contentType: res.headers.get("content-type"),
    });

    if (!res.ok) {
      const text = await res.text();
      const preview = sanitizeForLog(text, 500);
      log("error", "API request failed", {
        status: res.status,
        statusText: res.statusText,
        preview,
        isHtml: looksLikeHtmlErrorPage(preview),
      });

      // Retry without response_format if provider doesn't support it
      if (!ctx.retriedForResponseFormat && isResponseFormatError(res.status, preview)) {
        log("warn", "Provider rejected response_format, retrying without it");
        return this._doChatCompletion(opts, callbacks, {
          ...ctx,
          attempt: ctx.attempt + 1,
          retriedForResponseFormat: true,
        });
      }

      if (looksLikeHtmlErrorPage(preview)) {
        throw new Error(
          `Upstream returned an HTML error page (status ${res.status}), not AI JSON. ` +
            `Check base URL, proxy, or gateway configuration. ` +
            `Preview: ${preview.slice(0, 200)}`,
        );
      }

      throw new Error(`OpenAI-compatible API error ${res.status}: ${preview}`);
    }

    if (!res.body) {
      throw new Error("Empty response body from API");
    }

    const reader = res.body.getReader() as any;
    const streamResult = await readSSEStream(
      reader,
      callbacks ?? { onToken: () => {} },
    );
    const result = {
      ...streamResult,
      content: stripReasoningBlocks(streamResult.content),
    };

    // Defense: reject actual HTML error pages, not model thinking tags like <think>
    if (looksLikeHtmlErrorPage(result.content)) {
      const preview = result.content.slice(0, 500);
      log("error", "Stream returned HTML error page instead of AI content", {
        preview: preview.slice(0, 200),
      });
      throw new Error(
        `Upstream returned an HTML error page in the stream, not AI JSON. ` +
          `Check base URL, proxy, or gateway configuration. ` +
          `Preview: ${preview.slice(0, 200)}`,
      );
    }

    if (!result.content) {
      throw new Error("Empty response from AI");
    }

    // Truncation detection + retry (incomplete JSON mid-stream)
    const truncationRetries = ctx.truncationRetries ?? 0;
    if (truncationRetries < MAX_TRUNCATION_RETRIES && isLikelyTruncatedJson(result.content)) {
      const baseTokens = opts.max_tokens && opts.max_tokens > 0 ? opts.max_tokens : 8_192;
      const newMaxTokens = Math.min(Math.round(baseTokens * 1.75), 128_000);
      log("warn", "Response looks truncated, retrying with more tokens", {
        originalLength: result.content.length,
        originalMaxTokens: opts.max_tokens,
        newMaxTokens,
        truncationRetry: truncationRetries + 1,
      });
      return this._doChatCompletion(
        { ...opts, max_tokens: newMaxTokens },
        callbacks,
        { ...ctx, attempt: ctx.attempt + 1, truncationRetries: truncationRetries + 1 },
      );
    }

    log("info", "Chat completion successful", {
      contentLength: result.content.length,
      usage: result.usage,
    });

    return result;
  }
}