call-model.ts
7.92 KB
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
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 { workspaceManager } from './workspace';
/**
* Content part types for multimodal messages
*/
type ContentPart = { type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } };
/**
* 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(`Configuration error: ${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
if (imageUrls) {
const urls = Array.isArray(imageUrls) ? imageUrls : [imageUrls];
for (const url of urls) {
if (url && typeof url === 'string' && url.trim()) {
contentParts.push({ type: 'image_url', image_url: { url: url.trim() } });
}
}
}
// 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) {
const debugContent = [
'------------config------------',
JSON.stringify(
{
model: config.model,
baseUrl: config.baseUrl,
maxTokens,
timeout: requestTimeoutMs,
maxRetries,
responseFormat,
enableThinking,
},
null,
2
),
'------------request------------',
JSON.stringify(contentParts, 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'}`);
}
}