or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

execution-runtime.mdfunctional-api.mdgraph-construction.mdhuman-loop-control.mdindex.mdpersistence-checkpoints.mdprebuilt-agents.mdremote-advanced.mdstate-channels.md

remote-advanced.mddocs/

0

# Remote Execution & Advanced Features

1

2

Distributed graph execution, schema integration, and advanced streaming capabilities for complex multi-system workflows and enterprise integrations.

3

4

## Capabilities

5

6

### Remote Graph Execution

7

8

Execute LangGraph workflows on remote services with transparent local interface for distributed computing scenarios.

9

10

```typescript { .api }

11

/**

12

* Graph that executes on a remote LangGraph service

13

*/

14

class RemoteGraph {

15

constructor(params: RemoteGraphParams);

16

17

/** Execute graph on remote service */

18

invoke(

19

input: any,

20

config?: LangGraphRunnableConfig

21

): Promise<any>;

22

23

/** Stream execution from remote service */

24

stream(

25

input: any,

26

config?: LangGraphRunnableConfig

27

): AsyncIterableIterator<any>;

28

29

/** Batch execute on remote service */

30

batch(

31

inputs: any[],

32

config?: LangGraphRunnableConfig | LangGraphRunnableConfig[]

33

): Promise<any[]>;

34

35

/** Get state from remote graph */

36

getState(config: LangGraphRunnableConfig): Promise<StateSnapshot>;

37

38

/** Update state on remote graph */

39

updateState(

40

config: LangGraphRunnableConfig,

41

values: any,

42

asNode?: string

43

): Promise<void>;

44

}

45

46

interface RemoteGraphParams {

47

/** Remote service URL */

48

url: string;

49

50

/** Graph name on remote service */

51

graphName: string;

52

53

/** Authentication configuration */

54

auth?: {

55

type: "apiKey" | "bearer" | "basic";

56

token?: string;

57

username?: string;

58

password?: string;

59

};

60

61

/** Connection timeout */

62

timeout?: number;

63

64

/** Retry configuration */

65

retry?: {

66

attempts: number;

67

backoff: "linear" | "exponential";

68

delay: number;

69

};

70

71

/** Custom headers */

72

headers?: Record<string, string>;

73

}

74

```

75

76

**Usage Example:**

77

78

```typescript

79

import { RemoteGraph } from "@langchain/langgraph/remote";

80

81

const remoteGraph = new RemoteGraph({

82

url: "https://api.langgraph.com",

83

graphName: "document-processor",

84

auth: {

85

type: "apiKey",

86

token: process.env.LANGGRAPH_API_KEY

87

},

88

timeout: 30000,

89

retry: {

90

attempts: 3,

91

backoff: "exponential",

92

delay: 1000

93

}

94

});

95

96

// Use like any local graph

97

const result = await remoteGraph.invoke(

98

{ document: documentData },

99

{ configurable: { thread_id: "remote-session-1" } }

100

);

101

102

// Stream from remote

103

for await (const chunk of remoteGraph.stream(input)) {

104

console.log("Remote chunk:", chunk);

105

}

106

```

107

108

## Schema Integration

109

110

### Zod Schema Extraction

111

112

Extract JSON schemas from compiled graphs for validation, documentation, and API generation.

113

114

```typescript { .api }

115

/**

116

* Extract state type schema from a graph

117

*/

118

function getStateTypeSchema(graph: unknown): JSONSchema | undefined;

119

120

/**

121

* Extract update type schema from a graph

122

*/

123

function getUpdateTypeSchema(graph: unknown): JSONSchema | undefined;

124

125

/**

126

* Extract input type schema from a graph

127

*/

128

function getInputTypeSchema(graph: unknown): JSONSchema | undefined;

129

130

/**

131

* Extract output type schema from a graph

132

*/

133

function getOutputTypeSchema(graph: unknown): JSONSchema | undefined;

134

135

/**

136

* Extract configuration type schema from a graph

137

*/

138

function getConfigTypeSchema(graph: unknown): JSONSchema | undefined;

139

140

interface JSONSchema {

141

type: string;

142

properties?: Record<string, JSONSchema>;

143

required?: string[];

144

items?: JSONSchema;

145

additionalProperties?: boolean | JSONSchema;

146

enum?: any[];

147

[key: string]: any;

148

}

149

```

150

151

**Usage Example:**

152

153

```typescript

154

import {

155

getStateTypeSchema,

156

getInputTypeSchema,

157

getOutputTypeSchema

158

} from "@langchain/langgraph/zod";

159

160

const graph = new StateGraph(MyAnnotation)

161

.addNode("process", processNode)

162

.compile();

163

164

// Extract schemas

165

const stateSchema = getStateTypeSchema(graph);

166

const inputSchema = getInputTypeSchema(graph);

167

const outputSchema = getOutputTypeSchema(graph);

168

169

// Use schemas for validation

170

function validateInput(input: unknown): boolean {

171

return validateAgainstSchema(input, inputSchema);

172

}

173

174

// Generate API documentation

175

const apiDocs = {

176

endpoints: {

177

"/invoke": {

178

input: inputSchema,

179

output: outputSchema

180

}

181

},

182

stateStructure: stateSchema

183

};

184

```

185

186

### Schema Registry

187

188

Registry system for managing and accessing schema metadata across applications.

189

190

```typescript { .api }

191

/**

192

* Registry for schema metadata

193

*/

194

class SchemaMetaRegistry {

195

/** Register schema metadata */

196

register(key: string, metadata: SchemaMeta): void;

197

198

/** Retrieve schema metadata */

199

get(key: string): SchemaMeta | undefined;

200

201

/** List all registered schemas */

202

list(): string[];

203

204

/** Clear registry */

205

clear(): void;

206

}

207

208

/**

209

* Global schema registry instance

210

*/

211

const schemaMetaRegistry: SchemaMetaRegistry;

212

213

interface SchemaMeta {

214

title?: string;

215

description?: string;

216

version?: string;

217

tags?: string[];

218

examples?: any[];

219

deprecated?: boolean;

220

}

221

```

222

223

**Usage Example:**

224

225

```typescript

226

import { schemaMetaRegistry } from "@langchain/langgraph/zod/schema";

227

228

// Register schema metadata

229

schemaMetaRegistry.register("UserState", {

230

title: "User State Schema",

231

description: "State structure for user management workflows",

232

version: "1.0.0",

233

tags: ["user", "state"],

234

examples: [

235

{ userId: "123", name: "John Doe", active: true }

236

]

237

});

238

239

// Retrieve and use metadata

240

const userStateMeta = schemaMetaRegistry.get("UserState");

241

if (userStateMeta && !userStateMeta.deprecated) {

242

console.log(`Using ${userStateMeta.title} v${userStateMeta.version}`);

243

}

244

```

245

246

## Advanced Streaming

247

248

### Custom Stream Modes

249

250

Implement custom streaming modes for specialized output formats and processing patterns.

251

252

```typescript

253

interface CustomStreamMode {

254

name: string;

255

transformer: (chunk: any) => any;

256

aggregator?: (chunks: any[]) => any;

257

}

258

259

// Custom streaming for metrics

260

const metricsStream: CustomStreamMode = {

261

name: "metrics",

262

transformer: (chunk) => ({

263

timestamp: Date.now(),

264

nodeMetrics: extractMetrics(chunk),

265

performance: calculatePerformance(chunk)

266

}),

267

aggregator: (chunks) => ({

268

totalExecution: chunks.length,

269

averagePerformance: chunks.reduce((sum, c) => sum + c.performance, 0) / chunks.length,

270

timeline: chunks.map(c => ({ time: c.timestamp, metrics: c.nodeMetrics }))

271

})

272

};

273

274

// Usage with custom stream mode

275

for await (const metrics of graph.stream(input, {

276

streamMode: "custom",

277

customMode: metricsStream

278

})) {

279

updateDashboard(metrics);

280

}

281

```

282

283

### Stream Filtering and Transformation

284

285

Advanced stream processing for filtering and transforming streaming output.

286

287

```typescript

288

// Stream with filtering

289

async function* filteredStream(

290

graph: CompiledGraph,

291

input: any,

292

filter: (chunk: any) => boolean

293

) {

294

for await (const chunk of graph.stream(input)) {

295

if (filter(chunk)) {

296

yield chunk;

297

}

298

}

299

}

300

301

// Stream with transformation

302

async function* transformedStream(

303

graph: CompiledGraph,

304

input: any,

305

transformer: (chunk: any) => any

306

) {

307

for await (const chunk of graph.stream(input)) {

308

yield transformer(chunk);

309

}

310

}

311

312

// Buffered streaming

313

async function* bufferedStream(

314

graph: CompiledGraph,

315

input: any,

316

bufferSize: number

317

) {

318

const buffer = [];

319

320

for await (const chunk of graph.stream(input)) {

321

buffer.push(chunk);

322

323

if (buffer.length >= bufferSize) {

324

yield buffer.splice(0, bufferSize);

325

}

326

}

327

328

if (buffer.length > 0) {

329

yield buffer;

330

}

331

}

332

```

333

334

## Performance Optimization

335

336

### Caching and Memoization

337

338

Built-in caching mechanisms for improving performance of repeated operations.

339

340

```typescript

341

interface CacheConfig {

342

/** Cache key generation strategy */

343

keyStrategy: "input" | "state" | "custom";

344

345

/** Custom key generator */

346

keyGenerator?: (input: any) => string;

347

348

/** Cache TTL in milliseconds */

349

ttl?: number;

350

351

/** Maximum cache size */

352

maxSize?: number;

353

354

/** Cache storage backend */

355

storage?: "memory" | "disk" | "redis";

356

}

357

358

// Node with caching

359

const cachedNode = withCache(

360

{

361

keyStrategy: "input",

362

ttl: 300000, // 5 minutes

363

maxSize: 1000

364

},

365

async (state) => {

366

// Expensive operation

367

return await processExpensiveOperation(state);

368

}

369

);

370

```

371

372

### Parallel Execution Optimization

373

374

Optimize parallel execution patterns for maximum performance.

375

376

```typescript

377

// Parallel node execution with concurrency control

378

const parallelProcessor = async (state: State) => {

379

const tasks = state.items.map(item => processItem(item));

380

381

// Control concurrency

382

const results = await Promise.allSettled(

383

limitConcurrency(tasks, 5) // Max 5 concurrent operations

384

);

385

386

return {

387

results: results.map(r => r.status === "fulfilled" ? r.value : null),

388

errors: results.filter(r => r.status === "rejected").map(r => r.reason)

389

};

390

};

391

392

// Dynamic resource allocation

393

const adaptiveProcessor = async (state: State) => {

394

const systemLoad = await getSystemLoad();

395

const concurrency = systemLoad < 0.7 ? 10 : 3;

396

397

return await processWithConcurrency(state.data, concurrency);

398

};

399

```

400

401

### Memory Management

402

403

Advanced memory management for large-scale graph execution.

404

405

```typescript

406

interface MemoryConfig {

407

/** Maximum memory per execution */

408

maxMemoryPerExecution?: number;

409

410

/** Garbage collection strategy */

411

gcStrategy?: "aggressive" | "conservative" | "adaptive";

412

413

/** Memory monitoring */

414

monitoring?: {

415

enabled: boolean;

416

thresholds: {

417

warning: number;

418

critical: number;

419

};

420

};

421

}

422

423

// Memory-aware graph compilation

424

const memoryOptimizedGraph = graph.compile({

425

memoryConfig: {

426

maxMemoryPerExecution: 512 * 1024 * 1024, // 512MB

427

gcStrategy: "adaptive",

428

monitoring: {

429

enabled: true,

430

thresholds: {

431

warning: 0.8,

432

critical: 0.95

433

}

434

}

435

}

436

});

437

```

438

439

## Enterprise Integration

440

441

### Authentication and Authorization

442

443

Enterprise-grade authentication and authorization for graph execution.

444

445

```typescript

446

interface AuthConfig {

447

/** Authentication provider */

448

provider: "oauth2" | "saml" | "ldap" | "custom";

449

450

/** Provider configuration */

451

config: Record<string, any>;

452

453

/** Role-based access control */

454

rbac?: {

455

roles: string[];

456

permissions: Record<string, string[]>;

457

};

458

459

/** Audit logging */

460

audit?: {

461

enabled: boolean;

462

logLevel: "minimal" | "detailed";

463

};

464

}

465

466

// Authenticated graph execution

467

const authenticatedGraph = graph.compile({

468

auth: {

469

provider: "oauth2",

470

config: {

471

clientId: process.env.OAUTH_CLIENT_ID,

472

clientSecret: process.env.OAUTH_CLIENT_SECRET,

473

tokenEndpoint: "https://auth.company.com/token"

474

},

475

rbac: {

476

roles: ["admin", "user", "viewer"],

477

permissions: {

478

admin: ["read", "write", "execute"],

479

user: ["read", "execute"],

480

viewer: ["read"]

481

}

482

}

483

}

484

});

485

```

486

487

### Monitoring and Observability

488

489

Comprehensive monitoring and observability for production deployments.

490

491

```typescript

492

interface ObservabilityConfig {

493

/** Metrics collection */

494

metrics?: {

495

enabled: boolean;

496

provider: "prometheus" | "datadog" | "custom";

497

labels?: Record<string, string>;

498

};

499

500

/** Distributed tracing */

501

tracing?: {

502

enabled: boolean;

503

provider: "jaeger" | "zipkin" | "opentelemetry";

504

samplingRate?: number;

505

};

506

507

/** Logging configuration */

508

logging?: {

509

level: "debug" | "info" | "warn" | "error";

510

structured: boolean;

511

destination?: "console" | "file" | "remote";

512

};

513

}

514

515

// Observable graph

516

const observableGraph = graph.compile({

517

observability: {

518

metrics: {

519

enabled: true,

520

provider: "prometheus",

521

labels: { service: "document-processor", version: "1.0.0" }

522

},

523

tracing: {

524

enabled: true,

525

provider: "jaeger",

526

samplingRate: 0.1

527

},

528

logging: {

529

level: "info",

530

structured: true,

531

destination: "remote"

532

}

533

}

534

});

535

```

536

537

### Multi-Tenant Support

538

539

Support for multi-tenant deployments with isolation and resource management.

540

541

```typescript

542

interface MultiTenantConfig {

543

/** Tenant isolation strategy */

544

isolation: "namespace" | "database" | "instance";

545

546

/** Resource limits per tenant */

547

limits?: {

548

maxConcurrentExecutions?: number;

549

maxMemoryPerTenant?: number;

550

maxExecutionTime?: number;

551

};

552

553

/** Tenant authentication */

554

tenantAuth?: {

555

enabled: boolean;

556

strategy: "header" | "subdomain" | "path";

557

validation: (tenantId: string) => Promise<boolean>;

558

};

559

}

560

561

// Multi-tenant graph

562

const multiTenantGraph = graph.compile({

563

multiTenant: {

564

isolation: "namespace",

565

limits: {

566

maxConcurrentExecutions: 10,

567

maxMemoryPerTenant: 1024 * 1024 * 1024, // 1GB

568

maxExecutionTime: 300000 // 5 minutes

569

},

570

tenantAuth: {

571

enabled: true,

572

strategy: "header",

573

validation: async (tenantId) => {

574

return await validateTenant(tenantId);

575

}

576

}

577

}

578

});

579

```