call-model.ts 15.8 KB
import { HumanMessage } from '@langchain/core/messages';
import { completeChat, getDefaultModelConfig, setDefaultModelConfig, type CompleteChatOptions } from '@coderio/ai-client';
import { logger } from './logger';
import { getDebugConfig, getModelConfig, type ModelConfig } from './config';
import { writeFile } from './file';
import { readFile } from 'node:fs/promises';
import { extname } from 'node:path';
import { workspaceManager } from './workspace';

/**
 * Content part types for multimodal messages
 */
type ContentPart = { type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } };

/**
 * Map file extensions to MIME types for inline base64 images.
 */
const MIME_BY_EXT: Record<string, string> = {
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.webp': 'image/webp',
    '.bmp': 'image/bmp',
    '.svg': 'image/svg+xml',
};

function guessMimeFromUrl(url: string): string {
    const clean = url.split('?')[0].split('#')[0];
    const ext = extname(clean).toLowerCase();
    return MIME_BY_EXT[ext] || 'image/png';
}

/**
 * Decide whether to downscale images before sending them to the model.
 *
 * Only **local models** (loopback / Ollama — almost always small 2B–7B
 * checkpoints) and **explicitly small models** (a `:Nb`-style tag with N ≤ 4)
 * get downscaled. External large models (e.g. qwen3.8-max) keep the
 * full-resolution image so design fidelity is preserved — the product's whole
 * point is high-fidelity restoration, and downscaling only helps when the model
 * itself would otherwise choke on multi-MB base64 payloads.
 */
function shouldDownscaleImages(config: ModelConfig): boolean {
    const baseUrl = (config.baseUrl || '').toLowerCase();
    const model = (config.model || '').toLowerCase();

    // Local install: Ollama listens on :11434, or any loopback OpenAI-compatible
    // server. Local setups almost always run small checkpoints.
    const isLocal = /11434/.test(baseUrl) || /(localhost|127\.0\.0\.1)/.test(baseUrl);

    // Small model by parameter count in the tag, e.g. qwen3-vl:2b, qwen3:0.6b.
    const m = model.match(/[:\-]([0-9]*\.?[0-9]+)b\b/);
    const paramsB = m ? parseFloat(m[1]) : NaN;
    const isSmallModel = Number.isFinite(paramsB) && paramsB <= 4;

    return isLocal || isSmallModel;
}

/**
 * Normalize any image reference into an inline base64 `data:` URI.
 *
 * Why: Ollama's OpenAI-compatible `/v1` endpoint (and several local
 * OpenAI-compatible servers) reject `image_url` with an http(s) URL or a
 * filesystem path — they require the image inlined as
 * `data:<mime>;base64,<payload>`. OpenAI itself accepts both forms, so
 * inlining unconditionally keeps the engine provider-agnostic and is the
 * system-level fix rather than a per-provider patch.
 *
 * `downscale` controls whether the inlined image is also shrunk to fit
 * `COD_R_IMAGE_MAX_EDGE` (default 768px) — see `shouldDownscaleImages`. When
 * false the image is inlined at full resolution (preserves fidelity for large
 * external models).
 *
 * - `data:` URI → returned as-is (or downscaled if requested).
 * - http(s) URL → fetched and inlined.
 * - local path   → read from disk and inlined.
 */
async function normalizeImageToDataUri(
    raw: string,
    downscale: boolean,
    timeoutMs = 30000
): Promise<string> {
    const url = raw.trim();
    if (!url) throw new Error('empty image reference');
    if (url.startsWith('data:')) {
        // Already inline. Downscale only when the target model needs it.
        return downscale ? downscaleDataUri(url) : url;
    }

    let buf: Buffer;
    let mime: string;
    if (/^https?:\/\//i.test(url)) {
        const controller = new AbortController();
        const timer = setTimeout(() => controller.abort(), timeoutMs);
        try {
            const res = await fetch(url, { signal: controller.signal });
            if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
            mime = res.headers.get('content-type') || guessMimeFromUrl(url);
            buf = Buffer.from(await res.arrayBuffer());
        } finally {
            clearTimeout(timer);
        }
    } else {
        // Local filesystem path
        mime = guessMimeFromUrl(url) || 'image/png';
        buf = await readFile(url);
    }
    if (!downscale) {
        // Full resolution — external large models keep design fidelity.
        return `data:${mime};base64,${buf.toString('base64')}`;
    }
    return toDataUri(buf, mime);
}

async function toDataUri(buf: Buffer, mime: string): Promise<string> {
    const scaled = await downscaleToFit(buf, mime);
    return `data:${scaled.mime};base64,${scaled.buf.toString('base64')}`;
}

async function downscaleDataUri(uri: string): Promise<string> {
    const m = /^data:([^;]+);base64,(.*)$/s.exec(uri);
    if (!m) return uri;
    try {
        const buf = Buffer.from(m[2], 'base64');
        const scaled = await downscaleToFit(buf, m[1]);
        return `data:${scaled.mime};base64,${scaled.buf.toString('base64')}`;
    } catch {
        return uri;
    }
}

let warnedSharpMissing = false;

/**
 * Downscale an image so its longest edge does not exceed `COD_R_IMAGE_MAX_EDGE`
 * (default 768). Local 2B-class vision models (e.g. qwen3-vl:2b) return garbled
 * structure JSON / empty component output when fed multi-megabyte base64
 * payloads; keeping the longest edge at ~768px drops the payload by one or two
 * orders of magnitude and lets the model actually parse the layout.
 *
 * `sharp` is an optional peer dependency (see coderio/package.json). If it is
 * not installed we return the image unchanged and warn once — the engine keeps
 * working, just without downscaling.
 */
async function downscaleToFit(
    buf: Buffer,
    mime: string
): Promise<{ buf: Buffer; mime: string }> {
    const maxEdge = Number(process.env.COD_R_IMAGE_MAX_EDGE ?? 768);
    if (!Number.isFinite(maxEdge) || maxEdge <= 0) return { buf, mime };
    let sharp: any;
    try {
        sharp = (await import('sharp')).default;
    } catch {
        if (!warnedSharpMissing) {
            warnedSharpMissing = true;
            logger.printErrorLog(
                '[image] sharp not installed — images sent to model un-downscaled. ' +
                    'Run `pnpm --filter @coderio/coderio add sharp` to enable image downscaling for local models.'
            );
        }
        return { buf, mime };
    }
    try {
        const img = sharp(buf);
        const meta = await img.metadata();
        if (!meta.width || !meta.height) return { buf, mime };
        if (Math.max(meta.width, meta.height) <= maxEdge) return { buf, mime };
        const resized = await img
            .resize({
                width: meta.width >= meta.height ? maxEdge : undefined,
                height: meta.width >= meta.height ? undefined : maxEdge,
                fit: 'inside',
                withoutEnlargement: true,
            })
            .toBuffer();
        return { buf: resized, mime };
    } catch {
        return { buf, mime };
    }
}

/**
 * Options for calling the model
 */
export interface CallModelOptions {
    question: string;
    imageUrls?: string | string[];
    streaming?: boolean;
    responseFormat?: { type: 'json_object' | 'text' };
    maxTokens?: number;
}

/**
 * Validate model configuration
 * @param config - Model configuration to validate
 * @throws Error if required fields are missing
 */
function validateModelConfig(config: ModelConfig | null | undefined): asserts config is ModelConfig {
    if (!config || !config.provider || !config.model || !config.baseUrl || !config.apiKey) {
        throw new Error(
            `Invalid model configuration. Required fields: provider, model, baseUrl, apiKey. Please check your config.yaml file.`
        );
    }
}

/**
 * Push the engine-resolved model identity into the generic AI client.
 *
 * `@coderio/ai-client` is deliberately business-agnostic: it never reads
 * config.yaml, never touches env vars and knows nothing about the engine. The
 * engine is the only layer that knows where credentials come from
 * (config.yaml / runtime override injected by the backend), so it hands them
 * over here — once per process, and again whenever they actually change.
 */
function syncDefaultModelConfig(config: ModelConfig): void {
    const current = getDefaultModelConfig();
    if (
        !current ||
        current.modelName !== config.model ||
        current.apiKey !== config.apiKey ||
        current.baseUrl !== config.baseUrl
    ) {
        setDefaultModelConfig({
            modelName: config.model,
            apiKey: config.apiKey,
            baseUrl: config.baseUrl,
            temperature: 0.1,
        });
    }
}

/**
 * Call an LLM model with the given options
 * @param options - Configuration options for the model call
 * @returns The model's text response
 */
export async function callModel(options: CallModelOptions): Promise<string> {
    const { question, imageUrls, streaming = false, responseFormat, maxTokens } = options;

    // Validate input
    if (!question || !question.trim()) {
        throw new Error('Question must be a non-empty string');
    }

    // Per-request timeout for the LLM endpoint. Without this, a slow or stalled
    // OpenAI-compatible endpoint (e.g. a remote MAAS deployment) hangs the whole
    // generation forever — the user just sees "stuck at generating" with no error.
    // Overridable via env for environments that need more headroom.
    // Default budget is 10 minutes. The configured model (qwen3.8-max) is a
    // *reasoning* model (it emits `reasoning_content` and "thinks" before
    // answering), so a single structure-generation call on a complex design can
    // legitimately take several minutes. 180s was far too short and killed good
    // calls. Overridable via COD_R_MODEL_TIMEOUT_MS for slower/faster setups.
    const requestTimeoutMs = Number(process.env.COD_R_MODEL_TIMEOUT_MS ?? 600000);
    // Retry only makes sense for a *short* timeout (a quick transient blip).
    // For a long budget, an auto-retry would double the worst-case wait
    // (2 x timeout), so we skip it and give the single call the full budget.
    const maxRetries = Number.isFinite(requestTimeoutMs) && requestTimeoutMs > 0 && requestTimeoutMs <= 60000 ? 1 : 0;

    // Qwen3 / qwen3.8-max are *reasoning* models: they emit `reasoning_content`
    // and "think" before answering. On a complex Figma design the thinking phase
    // alone can exceed the upstream gateway's ~300s server-side timeout (the
    // endpoint then returns "Request timed out"), which is exactly the failure
    // we saw. Disabling thinking (`enable_thinking: false`) keeps the same model
    // but cuts latency from several minutes to tens of seconds — plenty for the
    // structured extraction tasks here. Re-enable reasoning with
    // COD_R_ENABLE_THINKING=1 if a future task genuinely needs it.
    const enableThinking = process.env.COD_R_ENABLE_THINKING === '1';

    // Get and validate config separately
    let config: ModelConfig;
    try {
        config = getModelConfig();
        validateModelConfig(config);
    } catch (error) {
        if (error instanceof Error) {
            logger.printErrorLog(`配置错误:${error.message}`);
        }
        throw error;
    }

    syncDefaultModelConfig(config);

    try {
        // Build multimodal content parts: text + image_url
        const contentParts: ContentPart[] = [];
        contentParts.push({ type: 'text', text: question });

        // Add images if provided. Normalize every reference to an inline
        // base64 data: URI so local OpenAI-compatible servers (Ollama etc.)
        // accept them — they reject http(s)/filesystem URLs.
        if (imageUrls) {
            // Downscale only for local / small models; external large models
            // keep full resolution for maximum design fidelity.
            const downscale = shouldDownscaleImages(config);
            const raws = Array.isArray(imageUrls) ? imageUrls : [imageUrls];
            const normalized = await Promise.all(
                raws
                    .filter((u): u is string => typeof u === 'string' && !!u.trim())
                    .map(async (u) => {
                        try {
                            return await normalizeImageToDataUri(u, downscale);
                        } catch (e) {
                            logger.printErrorLog(
                                `Skipping image (could not inline for model): ${u} — ${e instanceof Error ? e.message : String(e)}`
                            );
                            return null;
                        }
                    })
            );
            for (const du of normalized) {
                if (du) contentParts.push({ type: 'image_url', image_url: { url: du } });
            }
        }

        // Create user message - use array if multimodal, string if text-only
        const userMessage = new HumanMessage({
            content: contentParts.length > 1 ? contentParts : question,
        });

        const aiOpts: CompleteChatOptions = {
            maxTokens,
            timeout: requestTimeoutMs,
            maxRetries,
            streaming,
        };

        // Qwen3 reasoning toggle. We always forward response_format (needed for
        // json_object mode) and additionally disable thinking
        // (enable_thinking: false) unless COD_R_ENABLE_THINKING=1. See the
        // enableThinking note above. The AI client pipes these through without
        // interpreting them.
        const modelKwargs: Record<string, unknown> = {};
        if (responseFormat) {
            modelKwargs.response_format = responseFormat;
        }
        if (!enableThinking) {
            modelKwargs.enable_thinking = false;
        }
        if (Object.keys(modelKwargs).length > 0) {
            aiOpts.modelKwargs = modelKwargs;
        }

        const text = await completeChat([userMessage], aiOpts);

        if (!text) {
            throw new Error('Model returned empty response');
        }

        const debugConfig = getDebugConfig();
        const isDebugEnabled = debugConfig.enabled;
        if (isDebugEnabled) {
            // Redact base64 payloads so the debug file stays readable/small.
            const redactedParts = contentParts.map((p) =>
                p.type === 'image_url'
                    ? {
                          type: 'image_url' as const,
                          image_url: {
                              url: p.image_url.url.startsWith('data:')
                                  ? `[base64 data URI, ${p.image_url.url.length} chars]`
                                  : p.image_url.url,
                          },
                      }
                    : p
            );
            const debugContent = [
                '------------config------------',
                JSON.stringify(
                    {
                        model: config.model,
                        baseUrl: config.baseUrl,
                        maxTokens,
                        timeout: requestTimeoutMs,
                        maxRetries,
                        responseFormat,
                        enableThinking,
                    },
                    null,
                    2
                ),
                '------------request------------',
                JSON.stringify(redactedParts, null, 2),
                '------------response------------',
                JSON.stringify(text, null, 2),
            ].join('\n');
            writeFile(workspaceManager.path?.debug ?? '', `model_${new Date().toISOString().replace(/:/g, '-')}.md`, debugContent);
        }

        return text;
    } catch (error) {
        if (error instanceof Error) {
            logger.printErrorLog(`[${config.model}] Error details: ${error.message}`);
            if (error.stack) {
                logger.printTestLog(`[${config.model}] Stack trace: ${error.stack}`);
            }
        }
        throw new Error(`${config.model} model request failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
}