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 | 7x 15x 15x 15x 15x 15x 15x 1x 1x 15x 15x 10x 15x 5x 3x 1x 15x 15x 7x 7x 7x 7x 2x 2x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 2x 2x 2x 6x 1x 1x 1x 1x 1x 1x 4x 2x 2x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 2x 2x 2x 1x 1x 4x 4x 3x 3x 3x 3x 17x 17x 4x 4x 3x 3x 3x 7x 6x 6x 4x 5x 3x 3x 3x 3x 3x 3x 1x 2x 11x 11x 9x 2x 7x 6x 2x 2x 2x | import { z } from "zod";
import { tutorDifficultySchema, tutorAnswerRatingSchema, tutorResponseStyleSchema, type TutorContentResult } from "@shared/tutor";
import { config } from "../../config";
import { Logger } from "@shared/logger";
import {
TutorProviderError,
type LLMProvider,
type LLMProviderRequest,
type ProviderQuestionResult,
type ProviderStructuredResult,
type StructuredLLMProvider,
type StructuredLLMProviderRequest,
} from "./llm-provider";
import { rankTutorModels } from "./model-preference";
export const TUTOR_TEMPERATURE = 0.2;
function isAbortError(error: unknown): boolean {
return error instanceof Error && error.name === "AbortError";
}
async function withProviderTimeout<T>(
requestSignal: AbortSignal | undefined,
operation: (signal: AbortSignal) => Promise<T>,
): Promise<T> {
requestSignal?.throwIfAborted();
const controller = new AbortController();
let timedOut = false;
const abortFromRequest = () => controller.abort(requestSignal?.reason);
requestSignal?.addEventListener("abort", abortFromRequest, { once: true });
const timeout = globalThis.setTimeout(() => {
timedOut = true;
controller.abort();
}, config.tutor.timeoutMs);
try {
const result = await operation(controller.signal);
requestSignal?.throwIfAborted();
return result;
} catch (error) {
if (requestSignal?.aborted) throw requestSignal.reason ?? error;
if (error instanceof TutorProviderError) throw error;
Eif (timedOut || isAbortError(error)) throw new TutorProviderError("provider-timeout");
throw new TutorProviderError("provider-unavailable");
} finally {
globalThis.clearTimeout(timeout);
requestSignal?.removeEventListener("abort", abortFromRequest);
}
}
const completionChoicesSchema = z.array(z.object({
message: z.object({
content: z.unknown(),
}),
})).min(1);
const completionSchema = z.object({
model: z.string().min(1).optional(),
choices: completionChoicesSchema,
});
const structuredCompletionSchema = z.object({
model: z.string().min(1).optional(),
choices: completionChoicesSchema,
});
const modelsSchema = z.object({
data: z.array(z.object({ id: z.string().min(1).max(128) })),
});
interface ChatCompletionRequestBody {
readonly model: string;
readonly temperature: number;
readonly messages: readonly [
{ readonly role: "system"; readonly content: string },
{ readonly role: "user"; readonly content: string },
];
readonly response_format?: { readonly type: "json_object" };
}
function parseRetryAfter(value: string | null): number | undefined {
Eif (!value) return undefined;
const seconds = Number.parseInt(value, 10);
if (Number.isFinite(seconds) && seconds > 0) return seconds;
const date = Date.parse(value);
if (Number.isFinite(date)) return Math.max(1, Math.ceil((date - Date.now()) / 1_000));
return undefined;
}
function providerErrorForStatus(status: number, retryAfter: number | undefined): TutorProviderError {
Eif (status === 401 || status === 403) return new TutorProviderError("credential-invalid");
if (status === 404) return new TutorProviderError("model-unavailable");
if (status === 429) return new TutorProviderError("rate-limited", retryAfter);
if (status >= 500) return new TutorProviderError("provider-unavailable");
return new TutorProviderError("invalid-response");
}
function extractJsonContent(content: string): unknown {
const trimmed = content.trim();
const openingFence = trimmed.indexOf("```");
const openingLineEnd = openingFence >= 0 ? trimmed.indexOf("\n", openingFence + 3) : -1;
let openingLanguage = "";
if (openingFence >= 0) {
const openingEnd = openingLineEnd >= 0 ? openingLineEnd : trimmed.length;
openingLanguage = trimmed.slice(openingFence + 3, openingEnd).trim();
}
let contentStart = openingFence + 3 + openingLanguage.length;
if (openingLineEnd >= 0) contentStart = openingLineEnd + 1;
const closingFence = openingFence >= 0 ? trimmed.indexOf("```", contentStart) : -1;
const withoutFence = openingLanguage.toLowerCase() === "json" && closingFence >= 0
? trimmed.slice(contentStart, closingFence).trim()
: trimmed;
try {
return JSON.parse(withoutFence);
} catch {
const start = withoutFence.indexOf("{");
const end = withoutFence.lastIndexOf("}");
Eif (start < 0 || end <= start) return withoutFence;
try {
return JSON.parse(withoutFence.slice(start, end + 1));
} catch {
return withoutFence;
}
}
}
function textContentFromMessage(content: unknown): string | undefined {
if (typeof content === "string") return content;
Iif (!Array.isArray(content)) return undefined;
const text = content.map((part) => {
Iif (typeof part === "string") return part;
Eif (typeof part === "object" && part !== null && "text" in part && typeof part.text === "string") {
return part.text;
}
return "";
}).join("").trim();
return text || undefined;
}
function parseOptionalText(value: unknown, maxLength: number): string | undefined {
if (typeof value !== "string") return undefined;
const text = value.trim();
return text.length > 0 && text.length <= maxLength ? text : undefined;
}
function candidateValue(candidate: Record<string, unknown>, key: string): unknown {
return candidate[key];
}
function parseOptionalDifficulty(value: unknown): TutorContentResult["difficulty"] {
const numericValue = typeof value === "string" ? Number(value.trim()) : value;
return tutorDifficultySchema.safeParse(numericValue).success ? numericValue as number : undefined;
}
function parseOptionalAnswerRating(value: unknown): TutorContentResult["answerRating"] {
const numericValue = typeof value === "string" ? Number(value.trim()) : value;
return tutorAnswerRatingSchema.safeParse(numericValue).success ? numericValue as number : undefined;
}
function parseOptionalResponseStyle(value: unknown): TutorContentResult["responseStyle"] | undefined {
return tutorResponseStyleSchema.safeParse(value).success ? value as TutorContentResult["responseStyle"] : undefined;
}
function parseTutorContentObject(candidate: Record<string, unknown>): TutorContentResult {
const question = parseOptionalText(candidateValue(candidate, "question"), 2_000);
Iif (!question) throw new TutorProviderError("invalid-response");
const feedback = parseOptionalText(candidateValue(candidate, "feedback"), 1_000);
const topic = parseOptionalText(candidateValue(candidate, "topic"), 120);
const mermaid = parseOptionalText(candidateValue(candidate, "mermaid"), 12_000);
const difficulty = parseOptionalDifficulty(candidateValue(candidate, "difficulty"));
const answerRating = parseOptionalAnswerRating(candidateValue(candidate, "answerRating"));
const responseStyle = parseOptionalResponseStyle(candidateValue(candidate, "responseStyle"));
Iif (responseStyle === "philosophical" && answerRating !== undefined) {
throw new TutorProviderError("invalid-response");
}
const commonResult = {
question,
...(feedback ? { feedback } : {}),
...(topic ? { topic } : {}),
...(difficulty ? { difficulty } : {}),
...(mermaid ? { mermaid } : {}),
};
Iif (responseStyle === "philosophical") {
return { ...commonResult, responseStyle: "philosophical" };
}
return {
...commonResult,
responseStyle: "normal",
...(answerRating === undefined ? {} : { answerRating }),
};
}
function parseTutorContent(content: string): TutorContentResult {
const candidate = extractJsonContent(content);
if (typeof candidate === "string") {
const question = candidate.trim();
Iif (!question || question.length > 2_000) throw new TutorProviderError("invalid-response");
return { question, responseStyle: "normal" };
}
Iif (typeof candidate !== "object" || candidate === null || !("question" in candidate)) {
throw new TutorProviderError("invalid-response");
}
return parseTutorContentObject(candidate);
}
function parseProviderQuestion(body: unknown, logger: Logger): ProviderQuestionResult {
const parsed = completionSchema.safeParse(body);
if (!parsed.success || !parsed.data.model) throw new TutorProviderError("invalid-response");
const content = textContentFromMessage(parsed.data.choices[0].message.content);
Iif (!content) throw new TutorProviderError("invalid-response");
try {
return { model: parsed.data.model, result: parseTutorContent(content) };
} catch (error) {
if (error instanceof TutorProviderError && error.kind === "invalid-response" && config.nodeEnv === "development") {
logger.debug(`KI:connect model content (diagnostic, no credentials): ${content.slice(0, 12_000)}`);
}
throw error;
}
}
export class KiconnectProvider implements LLMProvider, StructuredLLMProvider {
private readonly baseUrl = config.tutor.baseUrl;
private readonly logger = new Logger("KiconnectProvider");
async listModels(credential: string, signal?: AbortSignal): Promise<readonly string[]> {
return withProviderTimeout(signal, async (providerSignal) => {
const response = await fetch(`${this.baseUrl}/models`, {
headers: { Authorization: `Bearer ${credential}` },
signal: providerSignal,
});
Iif (!response.ok) {
throw providerErrorForStatus(response.status, parseRetryAfter(response.headers.get("retry-after")));
}
const parsed = modelsSchema.safeParse(await response.json().catch(() => null));
Iif (!parsed.success || parsed.data.data.length === 0) {
throw new TutorProviderError("model-unavailable");
}
return [...new Set(parsed.data.data.map(({ id }) => id))];
});
}
async generateLearningQuestion(
request: LLMProviderRequest,
credential: string,
signal?: AbortSignal,
): Promise<ProviderQuestionResult> {
const model = await this.resolveModel(request.model, credential, signal);
const body = await this.requestChatCompletion({
model,
temperature: TUTOR_TEMPERATURE,
messages: [
{ role: "system", content: request.systemPrompt },
{ role: "user", content: request.userPrompt },
],
}, credential, signal);
return parseProviderQuestion(body, this.logger);
}
async generateStructuredResponse(
request: StructuredLLMProviderRequest,
credential: string,
signal?: AbortSignal,
): Promise<ProviderStructuredResult> {
const body = await this.requestChatCompletion({
model: request.model,
temperature: request.temperature,
messages: [
{ role: "system", content: request.systemPrompt },
{ role: "user", content: request.userPrompt },
],
response_format: { type: "json_object" },
}, credential, signal);
const parsed = structuredCompletionSchema.safeParse(body);
Iif (!parsed.success) throw new TutorProviderError("invalid-response");
const content = textContentFromMessage(parsed.data.choices[0].message.content);
Iif (!content) throw new TutorProviderError("invalid-response");
let result: unknown;
try {
result = JSON.parse(content);
} catch {
throw new TutorProviderError("invalid-response");
}
return { model: parsed.data.model, result };
}
private async requestChatCompletion(
requestBody: ChatCompletionRequestBody,
credential: string,
signal?: AbortSignal,
): Promise<unknown> {
return withProviderTimeout(signal, async (providerSignal) => {
const response = await fetch(`${this.baseUrl}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${credential}`,
},
body: JSON.stringify(requestBody),
signal: providerSignal,
});
if (!response.ok) {
throw providerErrorForStatus(response.status, parseRetryAfter(response.headers.get("retry-after")));
}
return await response.json().catch(() => null);
});
}
private async resolveModel(model: string, credential: string, signal?: AbortSignal): Promise<string> {
if (model !== "auto") return model;
const modelId = rankTutorModels(await this.listModels(credential, signal))[0];
Iif (!modelId) throw new TutorProviderError("model-unavailable");
return modelId;
}
}
|