-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathlanggraph-client.ts
More file actions
374 lines (328 loc) · 10.3 KB
/
langgraph-client.ts
File metadata and controls
374 lines (328 loc) · 10.3 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
/**
* LangGraph-aware ATP Client
*
* This client integrates ATP execution with LangGraph's interrupt-based
* human-in-the-loop (HITL) system. When ATP code calls atp.approval.request(),
* it triggers a LangGraph interrupt for production-ready async approval flows.
*
* Features:
* - LangGraph interrupt integration for approvals
* - LLM sampling via LangChain models
* - Checkpoint-aware state management
* - Production-ready async approval workflows
*/
import { AgentToolProtocolClient, ClientCallbackError } from '@mondaydotcomorg/atp-client';
import type { ClientHooks } from '@mondaydotcomorg/atp-client';
import type { ExecutionResult, ExecutionConfig, ClientTool } from '@mondaydotcomorg/atp-protocol';
import { log } from '@mondaydotcomorg/atp-runtime';
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
import type { BaseMessage } from '@langchain/core/messages';
import { HumanMessage, SystemMessage, AIMessage } from '@langchain/core/messages';
import type { Embeddings } from '@langchain/core/embeddings';
import { AgentToolProtocolServer } from '@mondaydotcomorg/atp-server';
/**
* Approval request that needs human decision
*/
export interface ApprovalRequest {
message: string;
context?: Record<string, unknown>;
executionId: string;
timestamp: number;
}
/**
* Approval response from human
*/
export interface ApprovalResponse {
approved: boolean;
reason?: string;
timestamp: number;
}
/**
* Options for creating the LangGraph ATP client
*/
export interface LangGraphATPClientOptions {
/** ATP server instance */
server?: AgentToolProtocolServer;
/** Base URL of ATP server used for http server (not inProcess) */
serverUrl?: string;
/** Custom headers for authentication (e.g., { Authorization: 'Bearer token' }) */
headers?: Record<string, string>;
/** LangChain LLM for atp.llm.call() sampling */
llm: BaseChatModel;
/**
* LangChain embeddings model for atp.embedding.embed() and atp.embedding.search()
* Optional - if not provided, embedding calls will fail
*/
embeddings?: Embeddings;
/**
* Client-provided tools that execute locally (e.g., file operations, browser automation)
* These tools are registered with the server and can be called from server code execution
*/
tools?: ClientTool[];
/**
* Whether to use LangGraph interrupts for approvals (production mode).
* If false, will use a direct callback handler.
* Default: true
*/
useLangGraphInterrupts?: boolean;
/**
* Direct approval handler (only used if useLangGraphInterrupts = false)
*/
approvalHandler?: (message: string, context?: Record<string, unknown>) => Promise<boolean>;
/**
* Hooks for intercepting and modifying client behavior
*/
hooks?: ClientHooks;
}
/**
* Result of ATP execution that may need approval
*/
export interface ATPExecutionResult {
/** Standard execution result */
result: ExecutionResult;
/** If true, execution is waiting for approval via LangGraph interrupt */
needsApproval: boolean;
/** Approval request details (if needsApproval = true) */
approvalRequest?: ApprovalRequest;
}
/**
* Exception thrown when approval is needed - this triggers LangGraph interrupt
*/
export class ApprovalRequiredException extends ClientCallbackError {
constructor(public readonly approvalRequest: ApprovalRequest) {
super(`Approval required: ${approvalRequest.message}`);
this.name = 'ApprovalRequiredException';
}
}
/**
* LangGraph-aware ATP Client
*
* Integrates ATP with LangGraph's production-ready interrupt system:
* - atp.llm.call() → Routes to LangChain LLM (no interrupt)
* - atp.approval.request() → Throws ApprovalRequiredException (triggers LangGraph interrupt)
* - Supports checkpoint-based state persistence
* - Enables async approval workflows
*/
export class LangGraphATPClient {
private client: AgentToolProtocolClient;
private llm: BaseChatModel;
private embeddings?: Embeddings;
private useLangGraphInterrupts: boolean;
private directApprovalHandler?: (
message: string,
context?: Record<string, unknown>
) => Promise<boolean>;
private pendingApprovals = new Map<string, ApprovalRequest>();
constructor(options: LangGraphATPClientOptions) {
const {
server,
serverUrl,
headers,
llm,
embeddings,
tools,
useLangGraphInterrupts = true,
approvalHandler,
hooks,
} = options;
this.client = new AgentToolProtocolClient({
server,
baseUrl: serverUrl,
headers,
hooks,
serviceProviders: tools ? { tools } : undefined,
});
this.llm = llm;
this.embeddings = embeddings;
this.useLangGraphInterrupts = useLangGraphInterrupts;
this.directApprovalHandler = approvalHandler;
this.client.provideLLM({
call: async (prompt: string, options?: any) => {
return await this.handleLLMCall(prompt, options);
},
extract: async (prompt: string, schema: any, options?: any) => {
return await this.handleLLMExtract(prompt, schema, options);
},
classify: async (text: string, categories: string[], options?: any) => {
return await this.handleLLMClassify(text, categories, options);
},
});
if (this.embeddings) {
this.client.provideEmbedding({
embed: async (text: string) => {
return await this.handleEmbedding(text);
},
});
}
this.client.provideApproval({
request: async (message: string, context?: Record<string, unknown>) => {
return await this.handleApprovalRequest(message, context);
},
});
}
/**
* Initialize the client connection
*/
async connect(): Promise<void> {
await this.client.init({ name: 'langgraph-atp-client', version: '1.0.0' });
await this.client.connect();
}
/**
* Get TypeScript API definitions
*/
getTypeDefinitions(): string {
return this.client.getTypeDefinitions();
}
/**
* Execute ATP code with LangGraph interrupt support
*
* When approval is needed:
* - If useLangGraphInterrupts=true: Throws ApprovalRequiredException
* - If useLangGraphInterrupts=false: Uses direct approval handler
*
* @throws ApprovalRequiredException when approval is needed (interrupt mode)
*/
async execute(code: string, config?: Partial<ExecutionConfig>): Promise<ATPExecutionResult> {
const result = await this.client.execute(code, config);
return {
result,
needsApproval: false,
};
}
/**
* Resume execution after approval decision
*
* Call this after LangGraph resumes from interrupt with approval decision.
*/
async resumeWithApproval(
executionId: string,
approved: boolean,
reason?: string
): Promise<ExecutionResult> {
const approvalResponse: ApprovalResponse = {
approved,
reason,
timestamp: Date.now(),
};
this.pendingApprovals.delete(executionId);
return await this.client.resume(executionId, approvalResponse);
}
/**
* Get pending approval request for an execution
*/
getPendingApproval(executionId: string): ApprovalRequest | undefined {
return this.pendingApprovals.get(executionId);
}
/**
* Handle LLM call - route to LangChain LLM
*/
private async handleLLMCall(prompt: string, options?: any): Promise<string> {
const messages: BaseMessage[] = [];
if (options?.systemPrompt) {
messages.push(new SystemMessage(options.systemPrompt));
}
messages.push(new HumanMessage(prompt));
const response = await this.llm.invoke(messages);
return typeof response.content === 'string'
? response.content
: JSON.stringify(response.content);
}
/**
* Handle LLM extract - route to LangChain LLM with structured output
*/
private async handleLLMExtract(prompt: string, schema: any, options?: any): Promise<any> {
const structuredLLM = this.llm.withStructuredOutput(schema);
const messages: BaseMessage[] = [];
if (options?.systemPrompt) {
messages.push(new SystemMessage(options.systemPrompt));
}
messages.push(new HumanMessage(prompt));
const result = await structuredLLM.invoke(messages);
return result;
}
/**
* Handle LLM classify - route to LangChain LLM
*/
private async handleLLMClassify(
text: string,
categories: string[],
options?: any
): Promise<string> {
const prompt = `Classify the following text into one of these categories: ${categories.join(', ')}\n\nText: ${text}\n\nCategory:`;
const messages: BaseMessage[] = [];
if (options?.systemPrompt) {
messages.push(new SystemMessage(options.systemPrompt));
}
messages.push(new HumanMessage(prompt));
const response = await this.llm.invoke(messages);
const result =
typeof response.content === 'string'
? response.content.trim()
: JSON.stringify(response.content).trim();
if (!categories.includes(result)) {
for (const category of categories) {
if (result.toLowerCase().includes(category.toLowerCase())) {
return category;
}
}
const fallback = categories[0];
if (!fallback) {
throw new Error('No categories provided for classification');
}
return fallback;
}
return result;
}
/**
* Handle embedding - route to LangChain embeddings model
*/
private async handleEmbedding(text: string): Promise<number[]> {
if (!this.embeddings) {
throw new Error(
'Embeddings model not provided. Pass embeddings option when creating LangGraphATPClient.'
);
}
return await this.embeddings.embedQuery(text);
}
/**
* Get the underlying ATP client for advanced usage
*/
getUnderlyingClient(): AgentToolProtocolClient {
return this.client;
}
private async handleApprovalRequest(
message: string,
context?: Record<string, unknown>
): Promise<{ approved: boolean; reason?: string; timestamp: number }> {
const executionId = (context as any)?.executionId;
const cleanContext = context ? { ...context } : undefined;
if (cleanContext) {
delete (cleanContext as any).executionId;
}
if (this.useLangGraphInterrupts) {
if (typeof executionId !== 'string' || !executionId) {
throw new Error('executionId is missing in approval request context');
}
const approvalRequest: ApprovalRequest = {
message,
context: cleanContext,
executionId,
timestamp: Date.now(),
};
this.pendingApprovals.set(executionId, approvalRequest);
throw new ApprovalRequiredException(approvalRequest);
}
if (this.directApprovalHandler) {
const approved = await this.directApprovalHandler(message, cleanContext);
return {
approved,
timestamp: Date.now(),
};
}
log.warn(`Approval request rejected (no handler): ${message}`);
return {
approved: false,
timestamp: Date.now(),
};
}
}