@nextsparkjs/plugin-langchain 0.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/.env.example +41 -0
  2. package/api/observability/metrics/route.ts +110 -0
  3. package/api/observability/traces/[traceId]/route.ts +398 -0
  4. package/api/observability/traces/route.ts +205 -0
  5. package/api/sessions/route.ts +332 -0
  6. package/components/observability/CollapsibleJson.tsx +71 -0
  7. package/components/observability/CompactTimeline.tsx +75 -0
  8. package/components/observability/ConversationFlow.tsx +271 -0
  9. package/components/observability/DisabledMessage.tsx +21 -0
  10. package/components/observability/FiltersPanel.tsx +82 -0
  11. package/components/observability/ObservabilityDashboard.tsx +230 -0
  12. package/components/observability/SpansList.tsx +210 -0
  13. package/components/observability/TraceDetail.tsx +335 -0
  14. package/components/observability/TraceStatusBadge.tsx +39 -0
  15. package/components/observability/TracesTable.tsx +97 -0
  16. package/components/observability/index.ts +7 -0
  17. package/docs/01-getting-started/01-overview.md +196 -0
  18. package/docs/01-getting-started/02-installation.md +368 -0
  19. package/docs/01-getting-started/03-configuration.md +794 -0
  20. package/docs/02-core-concepts/01-architecture.md +566 -0
  21. package/docs/02-core-concepts/02-agents.md +597 -0
  22. package/docs/02-core-concepts/03-tools.md +689 -0
  23. package/docs/03-orchestration/01-graph-orchestrator.md +809 -0
  24. package/docs/03-orchestration/02-legacy-react.md +650 -0
  25. package/docs/04-advanced/01-observability.md +645 -0
  26. package/docs/04-advanced/02-token-tracking.md +469 -0
  27. package/docs/04-advanced/03-streaming.md +476 -0
  28. package/docs/04-advanced/04-guardrails.md +597 -0
  29. package/docs/05-reference/01-api-reference.md +1403 -0
  30. package/docs/05-reference/02-customization.md +646 -0
  31. package/docs/05-reference/03-examples.md +881 -0
  32. package/docs/index.md +85 -0
  33. package/hooks/observability/useMetrics.ts +31 -0
  34. package/hooks/observability/useTraceDetail.ts +48 -0
  35. package/hooks/observability/useTraces.ts +59 -0
  36. package/lib/agent-factory.ts +354 -0
  37. package/lib/agent-helpers.ts +201 -0
  38. package/lib/db-memory-store.ts +417 -0
  39. package/lib/graph/index.ts +58 -0
  40. package/lib/graph/nodes/combiner.ts +399 -0
  41. package/lib/graph/nodes/router.ts +440 -0
  42. package/lib/graph/orchestrator-graph.ts +386 -0
  43. package/lib/graph/prompts/combiner.md +131 -0
  44. package/lib/graph/prompts/router.md +193 -0
  45. package/lib/graph/types.ts +365 -0
  46. package/lib/guardrails.ts +230 -0
  47. package/lib/index.ts +44 -0
  48. package/lib/logger.ts +70 -0
  49. package/lib/memory-store.ts +168 -0
  50. package/lib/message-serializer.ts +110 -0
  51. package/lib/prompt-renderer.ts +94 -0
  52. package/lib/providers.ts +226 -0
  53. package/lib/streaming.ts +232 -0
  54. package/lib/token-tracker.ts +298 -0
  55. package/lib/tools-builder.ts +192 -0
  56. package/lib/tracer-callbacks.ts +342 -0
  57. package/lib/tracer.ts +350 -0
  58. package/migrations/001_langchain_memory.sql +83 -0
  59. package/migrations/002_token_usage.sql +127 -0
  60. package/migrations/003_observability.sql +257 -0
  61. package/package.json +28 -0
  62. package/plugin.config.ts +170 -0
  63. package/presets/lib/langchain.config.ts.preset +142 -0
  64. package/presets/templates/sector7/ai-observability/[traceId]/page.tsx +91 -0
  65. package/presets/templates/sector7/ai-observability/page.tsx +54 -0
  66. package/types/langchain.types.ts +274 -0
  67. package/types/observability.types.ts +270 -0
@@ -0,0 +1,794 @@
1
+ # Configuration
2
+
3
+ This guide covers theme-level configuration of the LangChain plugin. All agent definitions, provider settings, and tool factories are configured here.
4
+
5
+ ## Configuration File
6
+
7
+ The central configuration file is located at:
8
+
9
+ ```
10
+ contents/themes/your-theme/lib/langchain/langchain.config.ts
11
+ ```
12
+
13
+ This file is the **single source of truth** for all agent configuration in your theme.
14
+
15
+ ## Basic Structure
16
+
17
+ ```typescript
18
+ import type {
19
+ ThemeLangChainConfig,
20
+ AgentDefinition,
21
+ AgentContext,
22
+ } from '@/contents/plugins/langchain/types/langchain.types'
23
+ // Note: createAgentHelpers must be imported from lib/agent-helpers directly
24
+ // It is NOT exported from the main plugin entry point
25
+ import { createAgentHelpers } from '@/contents/plugins/langchain/lib/agent-helpers'
26
+
27
+ // 1. Import your tool factories
28
+ import { createEntityTools } from './tools/entities'
29
+
30
+ // 2. Define agents
31
+ export const AGENTS: Record<string, AgentDefinition> = {
32
+ 'my-agent': {
33
+ provider: 'ollama',
34
+ temperature: 0.3,
35
+ description: 'What this agent does',
36
+ systemPrompt: 'my-agent', // loads agents/my-agent.md
37
+ createTools: (context: AgentContext) => createEntityTools(context),
38
+ },
39
+ }
40
+
41
+ // 3. Theme configuration
42
+ export const langchainConfig: ThemeLangChainConfig = {
43
+ defaultProvider: 'ollama',
44
+ defaultTemperature: 0.3,
45
+ agents: AGENTS,
46
+ }
47
+
48
+ // 4. Create and export helpers
49
+ const helpers = createAgentHelpers(AGENTS, {
50
+ provider: langchainConfig.defaultProvider,
51
+ temperature: langchainConfig.defaultTemperature,
52
+ })
53
+
54
+ export const {
55
+ getAgentConfig,
56
+ getAgentModelConfig,
57
+ getAgentTools,
58
+ getAgentPromptName,
59
+ getAgentSessionConfig,
60
+ getAgentEnrichContext,
61
+ hasAgent,
62
+ getAgentNames,
63
+ } = helpers
64
+ ```
65
+
66
+ ## Agent Definition
67
+
68
+ Each agent is defined with the following properties:
69
+
70
+ ```typescript
71
+ interface AgentDefinition {
72
+ // LLM Provider
73
+ provider: 'openai' | 'anthropic' | 'ollama'
74
+
75
+ // Optional: Model override (defaults to env config)
76
+ model?: string
77
+
78
+ // Creativity level (0 = deterministic, 1 = creative)
79
+ temperature?: number
80
+
81
+ // Documentation
82
+ description?: string
83
+
84
+ // System prompt filename or inline prompt
85
+ // Supports Handlebars templates: {{user.name}}, {{#if isAdmin}}...{{/if}}
86
+ systemPrompt?: string
87
+
88
+ // Tool factory function
89
+ createTools?: (context: AgentContext) => ToolDefinition[]
90
+
91
+ // Memory customization (TTL, maxMessages)
92
+ sessionConfig?: SessionConfig
93
+
94
+ // Inject runtime data into prompt templates
95
+ enrichContext?: (context: AgentContext) => Promise<AgentContext>
96
+ }
97
+ ```
98
+
99
+ ### Session Configuration
100
+
101
+ Customize memory behavior per agent:
102
+
103
+ ```typescript
104
+ interface SessionConfig {
105
+ // Maximum messages to keep (sliding window)
106
+ maxMessages?: number // Default: 50
107
+
108
+ // TTL in hours (null = no expiration)
109
+ ttlHours?: number | null // Default: null
110
+ }
111
+ ```
112
+
113
+ Example for a sales bot with expiring conversations:
114
+
115
+ ```typescript
116
+ 'sales-assistant': {
117
+ provider: 'openai',
118
+ sessionConfig: {
119
+ ttlHours: 24, // Conversations expire after 24 hours
120
+ maxMessages: 100, // Keep more messages for context
121
+ },
122
+ }
123
+ ```
124
+
125
+ ### Context Enrichment
126
+
127
+ Inject runtime data for dynamic prompt templates:
128
+
129
+ ```typescript
130
+ 'my-agent': {
131
+ provider: 'ollama',
132
+ systemPrompt: 'my-agent', // Template with {{user.name}}, etc.
133
+
134
+ enrichContext: async ({ userId, teamId }) => {
135
+ const user = await UsersService.getById(userId)
136
+ return {
137
+ userId,
138
+ teamId,
139
+ user: { name: user.name, email: user.email },
140
+ }
141
+ },
142
+ }
143
+ ```
144
+
145
+ The enriched context is used to render Handlebars templates in the system prompt.
146
+
147
+ ### Provider Selection
148
+
149
+ Choose the provider based on your use case:
150
+
151
+ | Provider | Best For | Cost |
152
+ |----------|----------|------|
153
+ | `ollama` | Development, local testing | Free |
154
+ | `openai` | Production, high quality | Pay per token |
155
+ | `anthropic` | Alternative production | Pay per token |
156
+
157
+ ### Temperature Settings
158
+
159
+ ```typescript
160
+ // Low temperature: Consistent, factual responses
161
+ { temperature: 0.1 } // Best for: Data retrieval, routing, orchestrators
162
+
163
+ // Medium temperature: Balanced
164
+ { temperature: 0.3 } // Best for: General assistants
165
+
166
+ // High temperature: Creative responses
167
+ { temperature: 0.7 } // Best for: Content generation
168
+ ```
169
+
170
+ > **Plugin Default:** The plugin's default temperature is `0.1` for maximum consistency. Theme configurations typically override this to `0.3` for more conversational agents. Orchestrators should always use `0.1` for reliable routing.
171
+
172
+ ### System Prompt Loading
173
+
174
+ The `systemPrompt` field supports two modes:
175
+
176
+ ```typescript
177
+ // 1. Filename (loads from agents/my-agent.md)
178
+ systemPrompt: 'my-agent'
179
+
180
+ // 2. Inline prompt (contains newlines)
181
+ systemPrompt: `You are a helpful assistant.
182
+ You help users manage their tasks.`
183
+ ```
184
+
185
+ ## Using Presets
186
+
187
+ The plugin provides a configuration preset as a starting point:
188
+
189
+ ```bash
190
+ cp contents/plugins/langchain/presets/lib/langchain.config.ts.preset \
191
+ contents/themes/your-theme/lib/langchain/langchain.config.ts
192
+ ```
193
+
194
+ ### Preset Contents
195
+
196
+ ```typescript
197
+ // From presets/lib/langchain.config.ts.preset
198
+
199
+ export const AGENTS: Record<string, AgentDefinition> = {
200
+ // Single unified agent with all tools
201
+ 'single-agent': {
202
+ provider: 'ollama',
203
+ temperature: 0.3,
204
+ description: 'Unified agent with access to all entity tools',
205
+ systemPrompt: 'single-agent',
206
+ createTools: (context: AgentContext) => [
207
+ ...createEntityATools(context),
208
+ ...createEntityBTools(context),
209
+ ],
210
+ },
211
+
212
+ // Orchestrator for multi-agent routing
213
+ 'orchestrator': {
214
+ provider: 'ollama',
215
+ temperature: 0.1, // Low for consistent routing
216
+ description: 'Routes requests to specialized agents',
217
+ systemPrompt: 'orchestrator',
218
+ createTools: () => createOrchestratorTools(),
219
+ },
220
+
221
+ // Specialized agent for Entity A
222
+ 'entity-a-assistant': {
223
+ provider: 'ollama',
224
+ temperature: 0.3,
225
+ description: 'Specialized agent for Entity A management',
226
+ systemPrompt: 'entity-a-assistant',
227
+ createTools: (context: AgentContext) => createEntityATools(context),
228
+ },
229
+ }
230
+ ```
231
+
232
+ ## Real-World Example
233
+
234
+ Here's a complete configuration from the default theme:
235
+
236
+ ```typescript
237
+ // contents/themes/default/lib/langchain/langchain.config.ts
238
+
239
+ import type {
240
+ ThemeLangChainConfig,
241
+ AgentDefinition,
242
+ AgentContext,
243
+ } from '@/contents/plugins/langchain/types/langchain.types'
244
+ import { createAgentHelpers } from '@/contents/plugins/langchain/lib/agent-helpers'
245
+
246
+ import { createTaskTools } from './tools/tasks'
247
+ import { createCustomerTools } from './tools/customers'
248
+ import { createPageTools } from './tools/pages'
249
+ import { createOrchestratorTools } from './tools/orchestrator'
250
+
251
+ export const AGENTS: Record<string, AgentDefinition> = {
252
+ // Single agent mode: One agent with all tools
253
+ 'single-agent': {
254
+ provider: 'ollama',
255
+ temperature: 0.3,
256
+ description: 'Unified agent with access to all entity tools',
257
+ systemPrompt: 'single-agent',
258
+ createTools: (context: AgentContext) => [
259
+ ...createTaskTools(context),
260
+ ...createCustomerTools(context),
261
+ ...createPageTools(context),
262
+ ],
263
+ },
264
+
265
+ // Orchestrator: Routes to specialized agents
266
+ 'orchestrator': {
267
+ provider: 'ollama',
268
+ temperature: 0.1,
269
+ description: 'Analyzes intent and routes to specialized agents',
270
+ systemPrompt: 'orchestrator',
271
+ createTools: () => createOrchestratorTools(),
272
+ },
273
+
274
+ // Task management specialist
275
+ 'task-assistant': {
276
+ provider: 'ollama',
277
+ temperature: 0.3,
278
+ description: 'Specialized agent for task management',
279
+ systemPrompt: 'task-assistant',
280
+ createTools: (context: AgentContext) => createTaskTools(context),
281
+ },
282
+
283
+ // Customer management specialist
284
+ 'customer-assistant': {
285
+ provider: 'ollama',
286
+ temperature: 0.3,
287
+ description: 'Specialized agent for customer management',
288
+ systemPrompt: 'customer-assistant',
289
+ createTools: (context: AgentContext) => createCustomerTools(context),
290
+ },
291
+
292
+ // Page/content management specialist
293
+ 'page-assistant': {
294
+ provider: 'ollama',
295
+ temperature: 0.3,
296
+ description: 'Specialized agent for page and block management',
297
+ systemPrompt: 'page-assistant',
298
+ createTools: (context: AgentContext) => createPageTools(context),
299
+ },
300
+ }
301
+
302
+ export const langchainConfig: ThemeLangChainConfig = {
303
+ defaultProvider: 'ollama',
304
+ defaultTemperature: 0.3,
305
+ agents: AGENTS,
306
+ }
307
+
308
+ const helpers = createAgentHelpers(AGENTS, {
309
+ provider: langchainConfig.defaultProvider,
310
+ temperature: langchainConfig.defaultTemperature,
311
+ })
312
+
313
+ export const {
314
+ getAgentConfig,
315
+ getAgentModelConfig,
316
+ getAgentTools,
317
+ getAgentPromptName,
318
+ getAgentSessionConfig,
319
+ getAgentEnrichContext,
320
+ hasAgent,
321
+ getAgentNames,
322
+ } = helpers
323
+ ```
324
+
325
+ ## Helper Functions
326
+
327
+ The `createAgentHelpers` factory creates utility functions for accessing agent configuration:
328
+
329
+ ### getAgentConfig
330
+
331
+ Get the full configuration for an agent:
332
+
333
+ ```typescript
334
+ const config = getAgentConfig('task-assistant')
335
+ // {
336
+ // provider: 'ollama',
337
+ // temperature: 0.3,
338
+ // description: '...',
339
+ // systemPrompt: 'task-assistant',
340
+ // createTools: [Function]
341
+ // }
342
+ ```
343
+
344
+ ### getAgentModelConfig
345
+
346
+ Get only the model-related configuration:
347
+
348
+ ```typescript
349
+ const modelConfig = getAgentModelConfig('task-assistant')
350
+ // {
351
+ // provider: 'ollama',
352
+ // model: undefined, // Will use env default
353
+ // temperature: 0.3
354
+ // }
355
+ ```
356
+
357
+ ### getAgentTools
358
+
359
+ Create tools with the provided context:
360
+
361
+ ```typescript
362
+ const tools = getAgentTools('task-assistant', { userId, teamId })
363
+ // [ToolDefinition, ToolDefinition, ...]
364
+ ```
365
+
366
+ ### getAgentPromptName
367
+
368
+ Get the system prompt filename:
369
+
370
+ ```typescript
371
+ const promptName = getAgentPromptName('task-assistant')
372
+ // 'task-assistant'
373
+ ```
374
+
375
+ ### getAgentSessionConfig
376
+
377
+ Get session configuration for memory customization:
378
+
379
+ ```typescript
380
+ const sessionConfig = getAgentSessionConfig('sales-assistant')
381
+ // {
382
+ // ttlHours: 24,
383
+ // maxMessages: 100
384
+ // }
385
+ ```
386
+
387
+ ### getAgentEnrichContext
388
+
389
+ Get the context enrichment function:
390
+
391
+ ```typescript
392
+ const enrichContext = getAgentEnrichContext('my-agent')
393
+ if (enrichContext) {
394
+ const enrichedContext = await enrichContext({ userId, teamId })
395
+ // { userId, teamId, user: { name: 'John', ... } }
396
+ }
397
+ ```
398
+
399
+ ### hasAgent / getAgentNames
400
+
401
+ ```typescript
402
+ hasAgent('task-assistant') // true
403
+ hasAgent('unknown-agent') // false
404
+
405
+ getAgentNames() // ['single-agent', 'orchestrator', 'task-assistant', ...]
406
+ ```
407
+
408
+ ## Environment-Based Configuration
409
+
410
+ Models are typically configured via environment variables:
411
+
412
+ ```env
413
+ # Ollama
414
+ LANGCHAIN_OLLAMA_MODEL=qwen2.5:7b
415
+
416
+ # OpenAI
417
+ LANGCHAIN_OPENAI_MODEL=gpt-4o-mini
418
+
419
+ # Anthropic
420
+ LANGCHAIN_ANTHROPIC_MODEL=claude-3-5-sonnet-20241022
421
+ ```
422
+
423
+ Override per-agent if needed:
424
+
425
+ ```typescript
426
+ 'premium-agent': {
427
+ provider: 'openai',
428
+ model: 'gpt-4o', // Override env default
429
+ temperature: 0.3,
430
+ // ...
431
+ }
432
+ ```
433
+
434
+ ## Configuration Patterns
435
+
436
+ ### Pattern 1: Single Agent
437
+
438
+ Simple applications with one unified agent:
439
+
440
+ ```typescript
441
+ export const AGENTS = {
442
+ 'assistant': {
443
+ provider: 'ollama',
444
+ temperature: 0.3,
445
+ systemPrompt: 'assistant',
446
+ createTools: (ctx) => [...allTools(ctx)],
447
+ },
448
+ }
449
+ ```
450
+
451
+ ### Pattern 2: Multi-Agent with Orchestrator
452
+
453
+ Complex applications with domain-specific agents:
454
+
455
+ ```typescript
456
+ export const AGENTS = {
457
+ 'orchestrator': {
458
+ provider: 'ollama',
459
+ temperature: 0.1,
460
+ systemPrompt: 'orchestrator',
461
+ createTools: () => createRoutingTools(),
462
+ },
463
+ 'domain-a': {
464
+ provider: 'ollama',
465
+ temperature: 0.3,
466
+ systemPrompt: 'domain-a',
467
+ createTools: (ctx) => createDomainATools(ctx),
468
+ },
469
+ 'domain-b': {
470
+ provider: 'ollama',
471
+ temperature: 0.3,
472
+ systemPrompt: 'domain-b',
473
+ createTools: (ctx) => createDomainBTools(ctx),
474
+ },
475
+ }
476
+ ```
477
+
478
+ ### Pattern 3: Provider Tiering
479
+
480
+ Different providers for different quality needs:
481
+
482
+ ```typescript
483
+ export const AGENTS = {
484
+ // Fast, cheap routing
485
+ 'router': {
486
+ provider: 'ollama',
487
+ temperature: 0.1,
488
+ // ...
489
+ },
490
+ // High-quality customer interactions
491
+ 'premium-support': {
492
+ provider: 'openai',
493
+ model: 'gpt-4o',
494
+ temperature: 0.3,
495
+ // ...
496
+ },
497
+ // Standard operations
498
+ 'general': {
499
+ provider: 'ollama',
500
+ temperature: 0.3,
501
+ // ...
502
+ },
503
+ }
504
+ ```
505
+
506
+ ## System Configuration
507
+
508
+ Beyond agent definitions, the plugin supports system-wide configuration for observability, guardrails, and other features.
509
+
510
+ ### Configuration File Location
511
+
512
+ ```
513
+ contents/themes/your-theme/langchain.config.ts
514
+ ```
515
+
516
+ ### Full Configuration Structure
517
+
518
+ ```typescript
519
+ import type { ObservabilityConfig } from '@/contents/plugins/langchain/types/observability.types'
520
+ import type { GuardrailsConfig } from '@/contents/plugins/langchain/lib/guardrails'
521
+
522
+ export interface LangChainConfig {
523
+ observability: ObservabilityConfig
524
+ guardrails?: GuardrailsConfig
525
+ }
526
+
527
+ export const langchainConfig: LangChainConfig = {
528
+ observability: { ... },
529
+ guardrails: { ... },
530
+ }
531
+ ```
532
+
533
+ ---
534
+
535
+ ## Observability Configuration
536
+
537
+ Controls tracing and monitoring of agent invocations.
538
+
539
+ ```typescript
540
+ observability: {
541
+ /** Enable observability tracing */
542
+ enabled: true,
543
+
544
+ /** Data retention settings */
545
+ retention: {
546
+ /** Days to keep trace data */
547
+ traces: 30,
548
+ },
549
+
550
+ /** Sampling configuration */
551
+ sampling: {
552
+ /** Sample rate (0.0-1.0) - 1.0 = 100% */
553
+ rate: 1.0,
554
+ /** Always trace errors regardless of sample rate */
555
+ alwaysTraceErrors: true,
556
+ },
557
+
558
+ /** PII and content processing */
559
+ pii: {
560
+ /** Mask inputs for PII (email, phone, card, SSN patterns) */
561
+ maskInputs: false,
562
+ /** Mask outputs for PII */
563
+ maskOutputs: true,
564
+ /** Truncate content at this length (characters) */
565
+ truncateAt: 10000,
566
+ },
567
+ }
568
+ ```
569
+
570
+ ### Observability Options
571
+
572
+ | Option | Type | Default | Description |
573
+ |--------|------|---------|-------------|
574
+ | `enabled` | boolean | `true` | Enable/disable tracing |
575
+ | `retention.traces` | number | `30` | Days to retain trace data |
576
+ | `sampling.rate` | number | `1.0` | Sample rate (0.0-1.0) |
577
+ | `sampling.alwaysTraceErrors` | boolean | `true` | Always trace errors |
578
+ | `pii.maskInputs` | boolean | `false` | Mask PII in inputs |
579
+ | `pii.maskOutputs` | boolean | `true` | Mask PII in outputs |
580
+ | `pii.truncateAt` | number | `10000` | Max content length |
581
+
582
+ ### Environment-based Sampling
583
+
584
+ ```typescript
585
+ // Development: trace everything
586
+ sampling: { rate: 1.0, alwaysTraceErrors: true }
587
+
588
+ // Production: trace 10% + all errors
589
+ sampling: { rate: 0.1, alwaysTraceErrors: true }
590
+
591
+ // High traffic: trace 1% + errors
592
+ sampling: { rate: 0.01, alwaysTraceErrors: true }
593
+ ```
594
+
595
+ > **Full Documentation**: [Observability](../04-advanced/01-observability.md)
596
+
597
+ ---
598
+
599
+ ## Guardrails Configuration
600
+
601
+ Controls security middleware for prompt injection detection, PII masking, and content filtering.
602
+
603
+ ```typescript
604
+ guardrails: {
605
+ promptInjection: {
606
+ enabled: true,
607
+ action: 'block', // 'block' | 'warn' | 'log'
608
+ customPatterns: [], // Additional regex patterns
609
+ },
610
+ piiMasking: {
611
+ enabled: true,
612
+ types: ['email', 'phone', 'ssn', 'creditCard', 'ipAddress'],
613
+ action: 'mask', // 'mask' | 'remove' | 'log'
614
+ },
615
+ contentFilter: {
616
+ enabled: true,
617
+ customPatterns: [], // Content patterns to filter
618
+ action: 'redact', // 'block' | 'redact'
619
+ },
620
+ }
621
+ ```
622
+
623
+ ### Guardrails Options
624
+
625
+ | Section | Option | Type | Description |
626
+ |---------|--------|------|-------------|
627
+ | `promptInjection` | `enabled` | boolean | Enable injection detection |
628
+ | | `action` | string | `block`, `warn`, or `log` |
629
+ | | `customPatterns` | RegExp[] | Additional detection patterns |
630
+ | `piiMasking` | `enabled` | boolean | Enable PII masking |
631
+ | | `types` | string[] | PII types to mask |
632
+ | | `action` | string | `mask`, `remove`, or `log` |
633
+ | `contentFilter` | `enabled` | boolean | Enable output filtering |
634
+ | | `customPatterns` | RegExp[] | Patterns to filter |
635
+ | | `action` | string | `block` or `redact` |
636
+
637
+ > **Full Documentation**: [Guardrails](../04-advanced/04-guardrails.md)
638
+
639
+ ---
640
+
641
+ ## Graph Orchestrator Configuration
642
+
643
+ Enable the modern graph-based orchestration approach.
644
+
645
+ ### Environment Variable
646
+
647
+ ```env
648
+ # Enable graph-based orchestrator (recommended)
649
+ LANGCHAIN_USE_GRAPH_ORCHESTRATOR=true
650
+ ```
651
+
652
+ ### Per-Node Model Configuration
653
+
654
+ The graph orchestrator can use different models for different nodes:
655
+
656
+ ```typescript
657
+ // In theme code, when invoking the orchestrator
658
+ const result = await invokeOrchestrator(message, sessionId, context, history, {
659
+ modelConfig: {
660
+ router: {
661
+ provider: 'anthropic',
662
+ model: 'claude-3-haiku',
663
+ temperature: 0.1,
664
+ },
665
+ combiner: {
666
+ provider: 'openai',
667
+ model: 'gpt-4o-mini',
668
+ temperature: 0.3,
669
+ },
670
+ },
671
+ })
672
+ ```
673
+
674
+ ### Structured Output Methods
675
+
676
+ Configure how structured output works for multi-provider compatibility:
677
+
678
+ | Method | Providers | Description |
679
+ |--------|-----------|-------------|
680
+ | `functionCalling` | OpenAI, Anthropic | Native function calling |
681
+ | `jsonMode` | Most providers | JSON response mode |
682
+ | `jsonSchema` | OpenAI | JSON Schema validation |
683
+
684
+ > **Full Documentation**: [Graph Orchestrator](../03-orchestration/01-graph-orchestrator.md)
685
+
686
+ ---
687
+
688
+ ## Environment Variables
689
+
690
+ ### Provider Configuration
691
+
692
+ ```env
693
+ # Default models per provider
694
+ LANGCHAIN_OLLAMA_MODEL=qwen2.5:7b
695
+ LANGCHAIN_OPENAI_MODEL=gpt-4o-mini
696
+ LANGCHAIN_ANTHROPIC_MODEL=claude-3-5-sonnet-20241022
697
+
698
+ # OpenAI-compatible base URL (for LM Studio, local servers)
699
+ LANGCHAIN_OPENAI_BASE_URL=http://localhost:1234/v1
700
+
701
+ # API Keys (auto-detected)
702
+ OPENAI_API_KEY=sk-...
703
+ ANTHROPIC_API_KEY=sk-ant-...
704
+ ```
705
+
706
+ ### Feature Flags
707
+
708
+ ```env
709
+ # Enable graph orchestrator (recommended)
710
+ LANGCHAIN_USE_GRAPH_ORCHESTRATOR=true
711
+
712
+ # Debug mode
713
+ LANGCHAIN_DEBUG=true
714
+ ```
715
+
716
+ ---
717
+
718
+ ## Best Practices
719
+
720
+ ### 1. Use Low Temperature for Routing
721
+
722
+ ```typescript
723
+ 'orchestrator': {
724
+ temperature: 0.1, // Consistent routing decisions
725
+ }
726
+ ```
727
+
728
+ ### 2. Keep Specialized Agents Focused
729
+
730
+ Each agent should have only the tools it needs:
731
+
732
+ ```typescript
733
+ 'task-assistant': {
734
+ createTools: (ctx) => createTaskTools(ctx), // Only task tools
735
+ }
736
+ ```
737
+
738
+ ### 3. Document Agent Purpose
739
+
740
+ ```typescript
741
+ 'customer-assistant': {
742
+ description: 'Handles customer CRUD operations and search',
743
+ }
744
+ ```
745
+
746
+ ### 4. Use Environment for Secrets
747
+
748
+ Never hardcode API keys:
749
+
750
+ ```typescript
751
+ // Bad
752
+ { options: { apiKey: 'sk-...' } }
753
+
754
+ // Good - uses env automatically
755
+ { provider: 'openai' }
756
+ ```
757
+
758
+ ### 5. Enable Graph Orchestrator
759
+
760
+ The graph-based orchestrator is significantly more efficient:
761
+
762
+ ```env
763
+ LANGCHAIN_USE_GRAPH_ORCHESTRATOR=true
764
+ ```
765
+
766
+ ### 6. Configure Guardrails for Production
767
+
768
+ ```typescript
769
+ // Production guardrails
770
+ guardrails: {
771
+ promptInjection: { enabled: true, action: 'block' },
772
+ piiMasking: { enabled: true, action: 'mask' },
773
+ contentFilter: { enabled: true, action: 'redact' },
774
+ }
775
+ ```
776
+
777
+ ### 7. Sample Traces in High-Traffic Production
778
+
779
+ ```typescript
780
+ // Reduce tracing overhead
781
+ observability: {
782
+ sampling: { rate: 0.1, alwaysTraceErrors: true },
783
+ }
784
+ ```
785
+
786
+ ---
787
+
788
+ ## Next Steps
789
+
790
+ - [Create agent system prompts](../02-core-concepts/02-agents.md)
791
+ - [Build entity tools](../02-core-concepts/03-tools.md)
792
+ - [Set up graph orchestration](../03-orchestration/01-graph-orchestrator.md)
793
+ - [Configure observability](../04-advanced/01-observability.md)
794
+ - [Configure guardrails](../04-advanced/04-guardrails.md)