-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathOpenCodeChatModel.ts
More file actions
379 lines (334 loc) · 10.5 KB
/
Copy pathOpenCodeChatModel.ts
File metadata and controls
379 lines (334 loc) · 10.5 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
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import {
BaseChatModel,
type BaseChatModelParams,
type BindToolsInput,
} from "@langchain/core/language_models/chat_models";
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import { BaseMessage, AIMessage } from "@langchain/core/messages";
import { ChatResult } from "@langchain/core/outputs";
import type { Runnable } from "@langchain/core/runnables";
import { getOpenCodeAuthHeaders } from "./auth";
export interface OpenCodeChatModelInput extends BaseChatModelParams {
baseUrl?: string;
authType?: string;
apiKey?: string;
username?: string;
password?: string;
agent?: string;
providerID?: string;
modelID?: string;
temperature?: number;
maxTokens?: number;
}
interface OpenCodeSession {
id: string;
createdAt: string;
}
interface OpenCodeMessagePart {
type: "text" | "file" | "tool" | "reasoning";
text?: string;
content?: string;
url?: string;
filename?: string;
mime?: string;
}
interface OpenCodeMessageResponse {
parts: OpenCodeMessagePart[];
}
export class OpenCodeChatModel extends BaseChatModel {
baseUrl = "http://127.0.0.1:4096";
authType = "none";
apiKey?: string;
username?: string;
password?: string;
agent = "build";
providerID = "anthropic";
modelID = "claude-3-5-sonnet-20241022";
temperature?: number;
maxTokens?: number;
private requestTimeout = 30000; // 30 second timeout for API requests
constructor(fields: OpenCodeChatModelInput) {
super(fields);
// Validate and set baseUrl
const baseUrl = fields.baseUrl ?? this.baseUrl;
try {
new URL(baseUrl);
this.baseUrl = baseUrl;
} catch {
throw new Error(`Invalid baseUrl: ${baseUrl}. Must be a valid URL.`);
}
// Validate required fields
const providerID = fields.providerID ?? this.providerID;
const modelID = fields.modelID ?? this.modelID;
if (!providerID || providerID.trim() === "") {
throw new Error("providerID is required and cannot be empty");
}
if (!modelID || modelID.trim() === "") {
throw new Error("modelID is required and cannot be empty");
}
this.authType = fields.authType ?? this.authType;
this.apiKey = fields.apiKey;
this.username = fields.username;
this.password = fields.password;
this.agent = fields.agent ?? this.agent;
this.providerID = providerID;
this.modelID = modelID;
this.temperature = fields.temperature;
this.maxTokens = fields.maxTokens;
}
_llmType(): string {
return "opencode";
}
// Declare that this model supports tool calling
// This is required for n8n AI Agent to recognize tool support
get supportsToolCalling(): boolean {
return true;
}
// Implement bindTools to enable tool calling functionality
// This method is called by LangChain when tools are bound to the model
bindTools(
_tools: BindToolsInput[],
_kwargs?: Partial<this["ParsedCallOptions"]>,
): Runnable {
// Return a runnable that includes the bound tools
// OpenCode handles tools internally, so we just return this model instance
return this as unknown as Runnable;
}
async _generate(
messages: BaseMessage[],
_options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun,
): Promise<ChatResult> {
let sessionId: string | undefined;
try {
// Create fresh session for this execution
sessionId = await this.createSession();
// Convert messages to OpenCode prompt format
const promptParts = this.convertMessagesToPromptParts(messages);
// Send prompt to OpenCode and get response directly
const responseText = await this.sendPrompt(sessionId, promptParts);
// Notify callback manager if provided
if (runManager) {
await runManager.handleLLMNewToken(responseText);
}
return {
generations: [
{
text: responseText,
message: new AIMessage(responseText),
},
],
};
} finally {
// Clean up session after execution if one was created
if (sessionId) {
await this.deleteSession(sessionId);
}
}
}
// Streaming is not implemented - OpenCode API returns complete responses
// LangChain will automatically fall back to using _generate for streaming calls
private async createSession(): Promise<string> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
...getOpenCodeAuthHeaders({
authType: this.authType,
apiKey: this.apiKey,
username: this.username,
password: this.password,
}),
};
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.requestTimeout);
try {
const response = await fetch(`${this.baseUrl}/session`, {
method: "POST",
headers,
body: JSON.stringify({
agent: this.agent,
model: {
providerID: this.providerID,
modelID: this.modelID,
},
}),
signal: controller.signal,
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(
`Failed to create OpenCode session (${response.status}): ${errorBody}`,
);
}
// Validate response structure
const data: any = await response.json();
if (typeof data?.id !== "string") {
throw new Error(
'Failed to create session: API response is missing or has an invalid "id" field',
);
}
const session = data as OpenCodeSession;
return session.id;
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
throw new Error(
`Request to create session timed out after ${this.requestTimeout / 1000} seconds`,
);
}
throw error;
} finally {
clearTimeout(timeoutId);
}
}
private convertMessagesToPromptParts(
messages: BaseMessage[],
): OpenCodeMessagePart[] {
const parts: OpenCodeMessagePart[] = [];
for (const message of messages) {
const content = message.content;
if (typeof content === "string") {
parts.push({
type: "text",
text: content,
});
} else if (Array.isArray(content)) {
for (const item of content) {
if (typeof item === "string") {
parts.push({
type: "text",
text: item,
});
} else if (item.type === "text") {
parts.push({
type: "text",
text: item.text,
});
}
// Could add support for image_url and other types here
}
}
}
return parts;
}
private async sendPrompt(
sessionId: string,
parts: OpenCodeMessagePart[],
): Promise<string> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
...getOpenCodeAuthHeaders({
authType: this.authType,
apiKey: this.apiKey,
username: this.username,
password: this.password,
}),
};
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.requestTimeout);
try {
// Build request body with optional parameters
const body: Record<string, any> = {
parts,
model: {
providerID: this.providerID,
modelID: this.modelID,
},
agent: this.agent,
};
// Add optional model parameters if specified
if (this.temperature !== undefined) {
body.temperature = this.temperature;
}
if (this.maxTokens !== undefined) {
body.max_tokens = this.maxTokens;
}
const response = await fetch(
`${this.baseUrl}/session/${sessionId}/message`,
{
method: "POST",
headers,
body: JSON.stringify(body),
signal: controller.signal,
},
);
if (!response.ok) {
const errorBody = await response.text();
throw new Error(
`Failed to send prompt to OpenCode (${response.status}): ${errorBody}`,
);
}
// Parse the response and validate structure
const data: any = await response.json();
if (!data || !Array.isArray(data.parts)) {
throw new Error(
'Invalid response from OpenCode: missing or invalid "parts" field',
);
}
const responseData = data as OpenCodeMessageResponse;
const textParts: string[] = [];
for (const part of responseData.parts) {
if (part.type === "text" && part.text) {
textParts.push(part.text);
}
}
// Ensure we got some text content back
if (textParts.length === 0) {
throw new Error(
"OpenCode API returned a response with no text content",
);
}
return textParts.join("");
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
throw new Error(
`Request to send prompt timed out after ${this.requestTimeout / 1000} seconds`,
);
}
throw error;
} finally {
clearTimeout(timeoutId);
}
}
private async deleteSession(sessionId: string): Promise<void> {
try {
const headers = getOpenCodeAuthHeaders({
authType: this.authType,
apiKey: this.apiKey,
username: this.username,
password: this.password,
});
const controller = new AbortController();
const timeoutId = setTimeout(
() => controller.abort(),
this.requestTimeout,
);
try {
await fetch(`${this.baseUrl}/session/${sessionId}`, {
method: "DELETE",
headers,
signal: controller.signal,
});
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
console.warn(
`Session deletion timed out after ${this.requestTimeout / 1000} seconds for session ${sessionId}`,
);
} else {
// Log cleanup errors for monitoring but don't throw
console.warn(
`Failed to clean up OpenCode session ${sessionId}:`,
error,
);
}
} finally {
clearTimeout(timeoutId);
}
} catch (error) {
// Log any outer errors but don't throw
console.warn(`Error during session cleanup for ${sessionId}:`, error);
}
}
// Deprecated: Kept for backward compatibility, but no longer needed
async cleanup(): Promise<void> {
// Sessions are now cleaned up automatically per-execution
}
}