File size: 7,359 Bytes
c2c8c8d da1152a c2c8c8d da1152a c2c8c8d | 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 | import axios, { AxiosInstance, AxiosError } from 'axios';
import { GLMMessage, GLMResponse, GLMStreamResponse, GLM_DEFAULTS } from '@glmpilot/shared';
import { config } from '../config/env.js';
import { logger } from '../utils/logger.js';
import { stripCodeFences } from '../utils/code-parser.js';
import { countTokens } from '../utils/token-counter.js';
export class GLMClient {
private client: AxiosInstance;
private model: string;
private concurrentRequests = 0;
private maxConcurrent = GLM_DEFAULTS.MAX_CONCURRENT_REQUESTS;
private waitQueue: Array<() => void> = [];
constructor() {
this.model = config.GLM_MODEL || GLM_DEFAULTS.MODEL;
const baseUrl = (config.GLM_BASE_URL || GLM_DEFAULTS.BASE_URL).trim().replace(/\/?$/, '/');
this.client = axios.create({
baseURL: baseUrl,
timeout: GLM_DEFAULTS.TIMEOUT_MS,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${config.GLM_API_KEY}`,
},
});
}
async chat(
messages: GLMMessage[],
options: { temperature?: number; max_tokens?: number; top_p?: number } = {}
): Promise<GLMResponse> {
await this.waitForSlot();
try {
const body = {
model: this.model,
messages,
temperature: options.temperature ?? GLM_DEFAULTS.TEMPERATURE,
max_tokens: options.max_tokens ?? GLM_DEFAULTS.MAX_TOKENS,
top_p: options.top_p ?? GLM_DEFAULTS.TOP_P,
stream: false,
};
const fullUrl = `${this.client.defaults.baseURL}chat/completions`;
logger.info('GLM request starting', {
url: fullUrl,
messageCount: messages.length,
tokenEstimate: countTokens(messages.map(m => m.content).join('')),
});
const result = await this.retryWithBackoff(async () => {
const response = await this.client.post<GLMResponse>('chat/completions', body);
return response.data;
}, GLM_DEFAULTS.MAX_RETRIES);
logger.info('GLM response', { status: 'success', usage: result.usage });
return result;
} finally {
this.releaseSlot();
}
}
async *chatStream(
messages: GLMMessage[],
options: { temperature?: number; max_tokens?: number } = {},
signal?: AbortSignal
): AsyncGenerator<string> {
await this.waitForSlot();
try {
const body = {
model: this.model,
messages,
temperature: options.temperature ?? GLM_DEFAULTS.TEMPERATURE,
max_tokens: options.max_tokens ?? GLM_DEFAULTS.MAX_TOKENS,
top_p: GLM_DEFAULTS.TOP_P,
stream: true,
};
const response = await this.client.post('chat/completions', body, {
responseType: 'stream',
signal,
});
let buffer = '';
for await (const chunk of response.data) {
buffer += chunk.toString();
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || !trimmed.startsWith('data: ')) continue;
const data = trimmed.slice(6);
if (data === '[DONE]') return;
try {
const parsed: GLMStreamResponse = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) yield content;
} catch {
// Skip malformed chunks
}
}
}
} catch (err) {
if (signal?.aborted) return;
const axiosErr = err as import('axios').AxiosError;
if (axiosErr.response) {
// For streaming requests, response.data is a Node.js Readable stream.
// Read it to get the actual GLM API error body.
try {
const chunks: Buffer[] = [];
for await (const chunk of axiosErr.response.data as AsyncIterable<Buffer>) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
const body = Buffer.concat(chunks).toString('utf-8');
throw new Error(`GLM API ${axiosErr.response.status}: ${body}`);
} catch (readErr) {
if ((readErr as Error).message.startsWith('GLM API')) throw readErr;
}
}
throw err;
} finally {
this.releaseSlot();
}
}
async analyzeCode(code: string, instruction: string, systemPrompt: string): Promise<string> {
const messages: GLMMessage[] = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: `${instruction}\n\n\`\`\`\n${code}\n\`\`\`` },
];
const response = await this.chat(messages, {
temperature: 0.2,
max_tokens: GLM_DEFAULTS.MAX_TOKENS,
});
return response.choices[0]?.message?.content || '';
}
async completeCode(
prefix: string,
suffix: string,
language: string,
fileContext?: string
): Promise<string> {
const systemPrompt = `You are an expert ${language} code completion engine. You will be given code with a cursor position marked as <CURSOR>. Output ONLY the code that should be inserted at the cursor position. Do not include any explanation, markdown formatting, or the surrounding code. Output raw code only.`;
const userContent = fileContext
? `${fileContext}\n\n// Current file:\n${prefix}<CURSOR>${suffix}`
: `${prefix}<CURSOR>${suffix}`;
const messages: GLMMessage[] = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userContent },
];
const response = await this.chat(messages, {
temperature: 0.3,
max_tokens: 256,
});
const content = response.choices[0]?.message?.content || '';
return stripCodeFences(content);
}
private async waitForSlot(): Promise<void> {
if (this.concurrentRequests < this.maxConcurrent) {
this.concurrentRequests++;
return;
}
return new Promise((resolve) => {
this.waitQueue.push(() => {
this.concurrentRequests++;
resolve();
});
});
}
private releaseSlot(): void {
this.concurrentRequests--;
const next = this.waitQueue.shift();
if (next) next();
}
private async retryWithBackoff<T>(fn: () => Promise<T>, maxRetries: number): Promise<T> {
const delays = GLM_DEFAULTS.RETRY_DELAYS;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
const axiosErr = error as AxiosError;
const status = axiosErr.response?.status;
if (axiosErr.response) {
logger.error('GLM API Error Response:', {
status: axiosErr.response.status,
data: axiosErr.response.data,
});
}
if (status && status >= 400 && status < 500 && status !== 429) {
throw error;
}
if (attempt === maxRetries) throw error;
let delay = delays[attempt] || 4000;
if (status === 429) {
const retryAfter = axiosErr.response?.headers?.['retry-after'];
if (retryAfter) delay = parseInt(retryAfter, 10) * 1000;
}
logger.warn(`GLM request failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${delay}ms`, {
status,
message: axiosErr.message,
});
await new Promise((r) => setTimeout(r, delay));
}
}
throw new Error('Retry exhausted');
}
}
export const glm = new GLMClient();
|