@memberjunction/ai-prompts 2.47.0 → 2.49.0
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.
- package/README.md +565 -29
- package/dist/AIPromptCategoryExtended.d.ts.map +1 -1
- package/dist/AIPromptCategoryExtended.js +2 -2
- package/dist/AIPromptCategoryExtended.js.map +1 -1
- package/dist/AIPromptRunner.d.ts +4 -85
- package/dist/AIPromptRunner.d.ts.map +1 -1
- package/dist/AIPromptRunner.js +235 -103
- package/dist/AIPromptRunner.js.map +1 -1
- package/dist/ParallelExecutionCoordinator.d.ts +1 -1
- package/dist/ParallelExecutionCoordinator.d.ts.map +1 -1
- package/dist/ParallelExecutionCoordinator.js +14 -11
- package/dist/ParallelExecutionCoordinator.js.map +1 -1
- package/dist/SystemPlaceholders.d.ts +18 -0
- package/dist/SystemPlaceholders.d.ts.map +1 -0
- package/dist/SystemPlaceholders.js +239 -0
- package/dist/SystemPlaceholders.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +101 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +14 -0
- package/dist/types.js.map +1 -0
- package/package.json +10 -7
package/README.md
CHANGED
|
@@ -1,24 +1,206 @@
|
|
|
1
1
|
# @memberjunction/ai-prompts
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Advanced AI prompt execution engine with hierarchical template composition, intelligent model selection, parallel execution, output validation, and comprehensive execution tracking.
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/@memberjunction/ai-prompts)
|
|
6
6
|
[](https://opensource.org/licenses/ISC)
|
|
7
7
|
|
|
8
|
-
## Features
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
8
|
+
## Key Features
|
|
9
|
+
|
|
10
|
+
### 🎯 Dynamic Hierarchical Template Composition
|
|
11
|
+
|
|
12
|
+
#### Why Dynamic Template Composition?
|
|
13
|
+
|
|
14
|
+
While MemberJunction's template system already supports static template composition (where Template A always includes Templates B and C), the AI Prompts system adds **dynamic template composition** - the ability to inject ANY prompt template into ANY other prompt template at runtime.
|
|
15
|
+
|
|
16
|
+
**Static Composition (MJ Templates):** Perfect for fixed relationships like email headers/footers
|
|
17
|
+
```liquid
|
|
18
|
+
<!-- Email template always includes same header -->
|
|
19
|
+
{% include 'email-header' %}
|
|
20
|
+
{{ content }}
|
|
21
|
+
{% include 'email-footer' %}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
**Dynamic Composition (AI Prompts):** Essential for flexible runtime relationships
|
|
25
|
+
```typescript
|
|
26
|
+
// Inject ANY child prompt into ANY parent prompt at runtime
|
|
27
|
+
const params = new AIPromptParams();
|
|
28
|
+
params.prompt = systemPrompt; // e.g., Agent Type's control flow prompt
|
|
29
|
+
params.childPrompts = [
|
|
30
|
+
new ChildPromptParam(agentPrompt, 'agentInstructions') // Specific agent's prompt
|
|
31
|
+
];
|
|
32
|
+
// System prompt can use {{ agentInstructions }} to embed the agent's specific logic
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
#### The Agent System Use Case
|
|
36
|
+
|
|
37
|
+
This dynamic composition is crucial for AI Agents:
|
|
38
|
+
- **Agent Types** have **System Prompts** that control execution flow and response format
|
|
39
|
+
- **Individual Agents** have their own **specific prompts** with domain logic
|
|
40
|
+
- At runtime, any agent's prompt is dynamically injected into its type's system prompt
|
|
41
|
+
- This creates a complete prompt combining the control wrapper with agent-specific instructions
|
|
42
|
+
|
|
43
|
+
```typescript
|
|
44
|
+
// Agent Type System Prompt (controls flow)
|
|
45
|
+
const systemPrompt = {
|
|
46
|
+
templateText: `You are an AI agent. Follow these instructions:
|
|
47
|
+
|
|
48
|
+
{{ agentInstructions }} <!-- Dynamically injected at runtime -->
|
|
49
|
+
|
|
50
|
+
Respond in JSON format with: { decision: ..., reasoning: ... }`
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// Individual Agent Prompt (domain logic)
|
|
54
|
+
const dataGatherAgent = {
|
|
55
|
+
templateText: `Your role is to gather data from: {{ dataSources }}`
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// At runtime, compose them dynamically
|
|
59
|
+
params.childPrompts = [
|
|
60
|
+
new ChildPromptParam(dataGatherAgent, 'agentInstructions')
|
|
61
|
+
];
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### 🔄 System Placeholders
|
|
65
|
+
Automatically inject common values into all templates without manual data passing. Includes date/time, user context, prompt metadata, and more.
|
|
66
|
+
|
|
67
|
+
```liquid
|
|
68
|
+
Current user: {{ _USER_NAME }}
|
|
69
|
+
Date: {{ _CURRENT_DATE }}
|
|
70
|
+
Expected output: {{ _OUTPUT_EXAMPLE }}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## System Placeholders Reference
|
|
74
|
+
|
|
75
|
+
System placeholders are automatically available in all AI prompt templates, providing dynamic values like current date/time, prompt metadata, and user context without requiring manual data passing.
|
|
76
|
+
|
|
77
|
+
### Available System Placeholders
|
|
78
|
+
|
|
79
|
+
#### Date/Time Placeholders
|
|
80
|
+
- `{{ _CURRENT_DATE }}` - Current date in YYYY-MM-DD format
|
|
81
|
+
- `{{ _CURRENT_TIME }}` - Current time in HH:MM AM/PM format with timezone
|
|
82
|
+
- `{{ _CURRENT_DATE_AND_TIME }}` - Full timestamp with date and time
|
|
83
|
+
- `{{ _CURRENT_DAY_OF_WEEK }}` - Current day name (e.g., Monday, Tuesday)
|
|
84
|
+
- `{{ _CURRENT_TIMEZONE }}` - Current timezone identifier
|
|
85
|
+
- `{{ _CURRENT_TIMESTAMP_UTC }}` - Current UTC timestamp in ISO format
|
|
86
|
+
|
|
87
|
+
#### Prompt Metadata Placeholders
|
|
88
|
+
- `{{ _OUTPUT_EXAMPLE }}` - The expected output example from the prompt configuration
|
|
89
|
+
- `{{ _PROMPT_NAME }}` - The name of the current prompt
|
|
90
|
+
- `{{ _PROMPT_DESCRIPTION }}` - The description of the current prompt
|
|
91
|
+
- `{{ _EXPECTED_OUTPUT_TYPE }}` - The expected output type (string, object, number, etc.)
|
|
92
|
+
- `{{ _RESPONSE_FORMAT }}` - The expected response format from the prompt
|
|
93
|
+
|
|
94
|
+
#### User Context Placeholders
|
|
95
|
+
- `{{ _USER_NAME }}` - Current user's full name
|
|
96
|
+
- `{{ _USER_EMAIL }}` - Current user's email address
|
|
97
|
+
- `{{ _USER_ID }}` - Current user's unique identifier
|
|
98
|
+
|
|
99
|
+
#### Environment Placeholders
|
|
100
|
+
- `{{ _ENVIRONMENT }}` - Current environment (development, staging, production)
|
|
101
|
+
- `{{ _API_VERSION }}` - Current API version
|
|
102
|
+
|
|
103
|
+
### System Placeholder Usage Examples
|
|
104
|
+
|
|
105
|
+
#### Example 1: Time-Aware Agent Prompt
|
|
106
|
+
```liquid
|
|
107
|
+
You are an AI assistant helping {{ _USER_NAME }} on {{ _CURRENT_DAY_OF_WEEK }}, {{ _CURRENT_DATE }} at {{ _CURRENT_TIME }}.
|
|
108
|
+
|
|
109
|
+
User's request: {{ userRequest }}
|
|
110
|
+
|
|
111
|
+
Please provide a helpful response considering the current time and day.
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
#### Example 2: Agent Type System Prompt with Metadata
|
|
115
|
+
```liquid
|
|
116
|
+
# Agent Type: Loop Decision Maker
|
|
117
|
+
|
|
118
|
+
Current execution context:
|
|
119
|
+
- Date/Time: {{ _CURRENT_DATE_AND_TIME }}
|
|
120
|
+
- User: {{ _USER_NAME }} ({{ _USER_EMAIL }})
|
|
121
|
+
- Environment: {{ _ENVIRONMENT }}
|
|
122
|
+
|
|
123
|
+
## Expected Output Format
|
|
124
|
+
{{ _OUTPUT_EXAMPLE }}
|
|
125
|
+
|
|
126
|
+
## Agent Specific Instructions
|
|
127
|
+
{{ agentResponse }}
|
|
128
|
+
|
|
129
|
+
Based on the above agent response and the expected output format ({{ _EXPECTED_OUTPUT_TYPE }}), determine the next step.
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
#### Example 3: Debug-Friendly Prompt
|
|
133
|
+
```liquid
|
|
134
|
+
[Debug Info]
|
|
135
|
+
- Prompt: {{ _PROMPT_NAME }}
|
|
136
|
+
- Description: {{ _PROMPT_DESCRIPTION }}
|
|
137
|
+
- Expected Output: {{ _EXPECTED_OUTPUT_TYPE }}
|
|
138
|
+
- User ID: {{ _USER_ID }}
|
|
139
|
+
- Timestamp: {{ _CURRENT_TIMESTAMP_UTC }}
|
|
140
|
+
|
|
141
|
+
[Task]
|
|
142
|
+
{{ taskDescription }}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Adding Custom System Placeholders
|
|
146
|
+
|
|
147
|
+
You can add custom system placeholders programmatically:
|
|
148
|
+
|
|
149
|
+
```typescript
|
|
150
|
+
import { SystemPlaceholderManager } from '@memberjunction/ai-prompts';
|
|
151
|
+
|
|
152
|
+
// Add a custom placeholder
|
|
153
|
+
SystemPlaceholderManager.addPlaceholder({
|
|
154
|
+
name: '_ORGANIZATION_NAME',
|
|
155
|
+
description: 'Current organization name',
|
|
156
|
+
getValue: async (params) => {
|
|
157
|
+
// Custom logic to get organization name
|
|
158
|
+
return params.contextUser?.OrganizationName || 'Default Organization';
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
// Or add directly to the array
|
|
163
|
+
const placeholders = SystemPlaceholderManager.getPlaceholders();
|
|
164
|
+
placeholders.push({
|
|
165
|
+
name: '_CUSTOM_VALUE',
|
|
166
|
+
description: 'My custom value',
|
|
167
|
+
getValue: async (params) => 'custom result'
|
|
168
|
+
});
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Data Merge Priority Order
|
|
172
|
+
|
|
173
|
+
When rendering templates, data is merged in this priority order (highest to lowest):
|
|
174
|
+
1. Template-specific data (`templateData` parameter)
|
|
175
|
+
2. Child template renders (for hierarchical template composition)
|
|
176
|
+
3. User-provided data (`data` parameter)
|
|
177
|
+
4. System placeholders (lowest priority)
|
|
178
|
+
|
|
179
|
+
This means users can override system placeholders by providing their own values with the same names.
|
|
180
|
+
|
|
181
|
+
### ⚡ Parallel Processing
|
|
182
|
+
Multi-model execution with intelligent result selection strategies and AI judge ranking for optimal results.
|
|
183
|
+
|
|
184
|
+
### ✅ Output Validation
|
|
185
|
+
JSON schema validation against OutputExample with intelligent retry logic and configurable validation behaviors.
|
|
186
|
+
|
|
187
|
+
### 🚫 Cancellation Support
|
|
188
|
+
AbortSignal integration for graceful execution cancellation with proper cleanup and partial result preservation.
|
|
189
|
+
|
|
190
|
+
### 📈 Progress & Streaming
|
|
191
|
+
Real-time progress callbacks and streaming response support for responsive user interfaces.
|
|
192
|
+
|
|
193
|
+
### 📊 Comprehensive Tracking
|
|
194
|
+
Hierarchical execution logging with the AIPromptRun entity, including token usage, timing, and validation attempts.
|
|
195
|
+
|
|
196
|
+
### 🤖 Agent Integration
|
|
197
|
+
Seamless integration with AI Agents through hierarchical prompts and execution tracking.
|
|
198
|
+
|
|
199
|
+
### 💾 Intelligent Caching
|
|
200
|
+
Vector similarity matching and TTL-based result caching for performance optimization.
|
|
201
|
+
|
|
202
|
+
### 🔧 Template Integration
|
|
203
|
+
Dynamic prompt generation with MemberJunction template system supporting conditionals, loops, and data injection.
|
|
22
204
|
|
|
23
205
|
## Installation
|
|
24
206
|
|
|
@@ -37,6 +219,25 @@ npm install @memberjunction/ai-prompts
|
|
|
37
219
|
|
|
38
220
|
## Core Architecture
|
|
39
221
|
|
|
222
|
+
### Dynamic vs Static Template Composition
|
|
223
|
+
|
|
224
|
+
The AI Prompts system introduces **dynamic template composition** that extends beyond MemberJunction's built-in static template features:
|
|
225
|
+
|
|
226
|
+
#### Static Template Composition (MJ Templates)
|
|
227
|
+
MemberJunction's template system supports embedding templates within templates through `{% include %}` directives. This is perfect for fixed relationships:
|
|
228
|
+
- Email templates with standard headers/footers
|
|
229
|
+
- Report templates with consistent formatting sections
|
|
230
|
+
- Any scenario where Template A always includes Templates B and C
|
|
231
|
+
|
|
232
|
+
#### Dynamic Template Composition (AI Prompts)
|
|
233
|
+
The AI Prompts system adds runtime template composition where relationships are determined dynamically:
|
|
234
|
+
- **Runtime Flexibility**: Inject ANY prompt template into ANY other prompt template
|
|
235
|
+
- **Context-Aware**: Choose which child templates to inject based on runtime conditions
|
|
236
|
+
- **Agent Architecture**: Combine system prompts (control flow) with agent prompts (domain logic)
|
|
237
|
+
- **Modular Design**: Build complex prompts from reusable components selected at runtime
|
|
238
|
+
|
|
239
|
+
**Key Difference**: While MJ Templates handle "Template A always includes B", AI Prompts handle "Template A includes X, where X is determined at runtime"
|
|
240
|
+
|
|
40
241
|
### AIPromptRunner Class
|
|
41
242
|
|
|
42
243
|
The `AIPromptRunner` class is the central component for executing prompts with advanced features:
|
|
@@ -64,9 +265,14 @@ const result = await runner.ExecutePrompt(params);
|
|
|
64
265
|
if (result.success) {
|
|
65
266
|
console.log("Summary:", result.result);
|
|
66
267
|
console.log(`Execution time: ${result.executionTimeMS}ms`);
|
|
67
|
-
console.log(`
|
|
268
|
+
console.log(`Prompt tokens: ${result.promptTokens}`);
|
|
269
|
+
console.log(`Completion tokens: ${result.completionTokens}`);
|
|
270
|
+
console.log(`Total tokens: ${result.tokensUsed}`);
|
|
271
|
+
if (result.cost) {
|
|
272
|
+
console.log(`Cost: ${result.cost} ${result.costCurrency || 'USD'}`);
|
|
273
|
+
}
|
|
68
274
|
} else {
|
|
69
|
-
console.error("Error:", result.
|
|
275
|
+
console.error("Error:", result.errorMessage);
|
|
70
276
|
}
|
|
71
277
|
```
|
|
72
278
|
|
|
@@ -150,7 +356,56 @@ if (result.promptRun?.Messages) {
|
|
|
150
356
|
}
|
|
151
357
|
```
|
|
152
358
|
|
|
153
|
-
### 4.
|
|
359
|
+
### 4. Dynamic Template Composition for AI Agents
|
|
360
|
+
|
|
361
|
+
This example demonstrates the primary use case for dynamic template composition - the AI Agent system:
|
|
362
|
+
|
|
363
|
+
```typescript
|
|
364
|
+
import { AIPromptRunner, ChildPromptParam } from '@memberjunction/ai-prompts';
|
|
365
|
+
|
|
366
|
+
// Agent Type System Prompt - Controls execution flow and response format
|
|
367
|
+
const agentTypeSystemPrompt = {
|
|
368
|
+
Name: "Data Analysis Agent Type System Prompt",
|
|
369
|
+
TemplateID: "system-prompt-template-id",
|
|
370
|
+
// Template contains: "You are an AI agent. {{ agentInstructions }} Respond with JSON..."
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
// Individual Agent Prompt - Contains domain-specific logic
|
|
374
|
+
const specificAgentPrompt = {
|
|
375
|
+
Name: "Customer Churn Analysis Agent",
|
|
376
|
+
TemplateID: "churn-agent-template-id",
|
|
377
|
+
// Template contains: "Analyze customer data for churn risk factors..."
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
// At runtime, dynamically compose the prompts
|
|
381
|
+
const runner = new AIPromptRunner();
|
|
382
|
+
const result = await runner.ExecutePrompt({
|
|
383
|
+
prompt: agentTypeSystemPrompt, // Parent template
|
|
384
|
+
childPrompts: [
|
|
385
|
+
// Dynamically inject the specific agent's instructions
|
|
386
|
+
new ChildPromptParam(specificAgentPrompt, 'agentInstructions')
|
|
387
|
+
],
|
|
388
|
+
data: {
|
|
389
|
+
customerData: analysisData,
|
|
390
|
+
thresholds: { churnRisk: 0.7 }
|
|
391
|
+
},
|
|
392
|
+
contextUser: currentUser
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
// The system executed ONE prompt that combined:
|
|
396
|
+
// 1. System prompt wrapper (control flow)
|
|
397
|
+
// 2. Specific agent instructions (domain logic)
|
|
398
|
+
// 3. Runtime data
|
|
399
|
+
console.log("Agent decision:", result.result);
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
**Why This Matters:**
|
|
403
|
+
- Different agents can use the SAME system prompt template
|
|
404
|
+
- System prompt enforces consistent response format across all agents
|
|
405
|
+
- Agent-specific logic is cleanly separated and reusable
|
|
406
|
+
- Runtime composition allows flexible agent architectures
|
|
407
|
+
|
|
408
|
+
### 5. Complete Example with All New Features
|
|
154
409
|
|
|
155
410
|
```typescript
|
|
156
411
|
import { AIPromptRunner } from '@memberjunction/ai-prompts';
|
|
@@ -606,9 +861,85 @@ TokensUsed int -- Total tokens consumed
|
|
|
606
861
|
TokensPrompt int -- Prompt tokens used
|
|
607
862
|
TokensCompletion int -- Completion tokens generated
|
|
608
863
|
|
|
864
|
+
-- Cost tracking
|
|
865
|
+
Cost decimal(19,8) -- Cost of this specific execution
|
|
866
|
+
CostCurrency nvarchar(10) -- ISO 4217 currency code (USD, EUR, etc.)
|
|
867
|
+
|
|
868
|
+
-- Hierarchical rollup fields (NEW)
|
|
869
|
+
TokensUsedRollup int -- Total tokens including all children
|
|
870
|
+
TokensPromptRollup int -- Total prompt tokens including all children
|
|
871
|
+
TokensCompletionRollup int -- Total completion tokens including all children
|
|
872
|
+
-- Note: TotalCost (existing field) serves as the cost rollup
|
|
873
|
+
|
|
609
874
|
-- Context and configuration
|
|
610
875
|
Messages nvarchar(max) -- JSON with input data and metadata
|
|
611
876
|
ConfigurationID uniqueidentifier -- Environment configuration used
|
|
877
|
+
AgentRunID uniqueidentifier -- Links to parent AIAgentRun if applicable
|
|
878
|
+
```
|
|
879
|
+
|
|
880
|
+
### Hierarchical Token and Cost Tracking
|
|
881
|
+
|
|
882
|
+
The AI Prompts system implements a sophisticated rollup pattern for tracking token usage and costs across hierarchical prompt executions:
|
|
883
|
+
|
|
884
|
+
#### Prompt Execution Rollup Pattern
|
|
885
|
+
|
|
886
|
+
For hierarchical prompt executions (parent prompts with child prompts), each node in the tree contains:
|
|
887
|
+
- **Direct fields** (`TokensPrompt`, `TokensCompletion`, `Cost`): Usage for just that execution
|
|
888
|
+
- **Rollup fields** (`TokensPromptRollup`, `TokensCompletionRollup`, `TotalCost`): Total including all descendants
|
|
889
|
+
|
|
890
|
+
**Example:**
|
|
891
|
+
```
|
|
892
|
+
Parent Prompt (100 prompt, 200 completion tokens, $0.05)
|
|
893
|
+
├── Child A (50 prompt, 100 completion, $0.02)
|
|
894
|
+
└── Child B (75 prompt, 150 completion, $0.03)
|
|
895
|
+
|
|
896
|
+
Database records:
|
|
897
|
+
- Parent: TokensPrompt=100, TokensPromptRollup=225 (100+50+75)
|
|
898
|
+
TokensCompletion=200, TokensCompletionRollup=450 (200+100+150)
|
|
899
|
+
Cost=0.05, TotalCost=0.10 (0.05+0.02+0.03)
|
|
900
|
+
- Child A: TokensPrompt=50, TokensPromptRollup=50 (leaf node)
|
|
901
|
+
Cost=0.02, TotalCost=0.02 (leaf node)
|
|
902
|
+
- Child B: TokensPrompt=75, TokensPromptRollup=75 (leaf node)
|
|
903
|
+
Cost=0.03, TotalCost=0.03 (leaf node)
|
|
904
|
+
```
|
|
905
|
+
|
|
906
|
+
This enables efficient queries like:
|
|
907
|
+
- "What was the total cost of this hierarchical prompt?" → Check root's `TotalCost`
|
|
908
|
+
- "How many tokens did this sub-prompt and its children use?" → Check that node's rollup fields
|
|
909
|
+
- No complex SQL joins or recursive CTEs needed!
|
|
910
|
+
|
|
911
|
+
#### Agent Run Token Tracking
|
|
912
|
+
|
|
913
|
+
The `AIAgentRun` entity tracks aggregate token usage across all prompt executions during an agent's lifecycle:
|
|
914
|
+
|
|
915
|
+
```sql
|
|
916
|
+
-- New fields in AIAgentRun
|
|
917
|
+
TotalTokensUsed int -- Total tokens (existing)
|
|
918
|
+
TotalPromptTokensUsed int -- Breakdown: prompt tokens (NEW)
|
|
919
|
+
TotalCompletionTokensUsed int -- Breakdown: completion tokens (NEW)
|
|
920
|
+
TotalCost decimal -- Total cost (existing)
|
|
921
|
+
|
|
922
|
+
-- Hierarchical agent rollup fields (NEW)
|
|
923
|
+
TotalTokensUsedRollup int -- Including sub-agent runs
|
|
924
|
+
TotalPromptTokensUsedRollup int -- Including sub-agent runs
|
|
925
|
+
TotalCompletionTokensUsedRollup int -- Including sub-agent runs
|
|
926
|
+
TotalCostRollup decimal -- Including sub-agent runs
|
|
927
|
+
```
|
|
928
|
+
|
|
929
|
+
**Agent Hierarchy Example:**
|
|
930
|
+
```
|
|
931
|
+
Parent Agent (A)
|
|
932
|
+
├── Own prompts: 200 prompt, 400 completion tokens
|
|
933
|
+
├── Sub-Agent (B)
|
|
934
|
+
│ └── Own prompts: 100 prompt, 200 completion tokens
|
|
935
|
+
└── Sub-Agent (C)
|
|
936
|
+
└── Own prompts: 150 prompt, 300 completion tokens
|
|
937
|
+
|
|
938
|
+
Rollup values:
|
|
939
|
+
- Agent A: TotalPromptTokensUsedRollup = 450 (200+100+150)
|
|
940
|
+
TotalCompletionTokensUsedRollup = 900 (400+200+300)
|
|
941
|
+
- Agent B: TotalPromptTokensUsedRollup = 100 (leaf agent)
|
|
942
|
+
- Agent C: TotalPromptTokensUsedRollup = 150 (leaf agent)
|
|
612
943
|
```
|
|
613
944
|
|
|
614
945
|
### Querying Hierarchical Log Data
|
|
@@ -1142,6 +1473,7 @@ interface AIPromptParams {
|
|
|
1142
1473
|
cancellationToken?: AbortSignal; // Cancellation token for aborting execution
|
|
1143
1474
|
onProgress?: ExecutionProgressCallback; // Progress update callback
|
|
1144
1475
|
onStreaming?: ExecutionStreamingCallback; // Streaming content callback
|
|
1476
|
+
agentRunId?: string; // Optional agent run ID to link prompt executions to parent agent run
|
|
1145
1477
|
}
|
|
1146
1478
|
|
|
1147
1479
|
/**
|
|
@@ -1185,19 +1517,35 @@ class AIPromptCategoryEntityExtended extends AIPromptCategoryEntity {
|
|
|
1185
1517
|
### Key Interfaces and Types
|
|
1186
1518
|
|
|
1187
1519
|
```typescript
|
|
1188
|
-
interface AIPromptRunResult {
|
|
1520
|
+
interface AIPromptRunResult<T = unknown> {
|
|
1189
1521
|
success: boolean; // Whether the execution was successful
|
|
1190
1522
|
status?: ExecutionStatus; // Current execution status
|
|
1191
1523
|
cancelled?: boolean; // Whether the execution was cancelled
|
|
1192
1524
|
cancellationReason?: CancellationReason; // Reason for cancellation if applicable
|
|
1193
1525
|
rawResult?: string; // The raw result from the AI model
|
|
1194
|
-
result?:
|
|
1526
|
+
result?: T; // The parsed/validated result based on OutputType
|
|
1195
1527
|
errorMessage?: string; // Error message if execution failed
|
|
1196
1528
|
promptRun?: AIPromptRunEntity; // The AIPromptRun entity that was created for tracking
|
|
1197
1529
|
executionTimeMS?: number; // Total execution time in milliseconds
|
|
1198
|
-
|
|
1530
|
+
|
|
1531
|
+
// Token tracking (follows ModelUsage convention)
|
|
1532
|
+
promptTokens?: number; // Prompt/input tokens for this execution
|
|
1533
|
+
completionTokens?: number; // Completion/output tokens for this execution
|
|
1534
|
+
tokensUsed?: number; // Total tokens (calculated getter)
|
|
1535
|
+
|
|
1536
|
+
// Hierarchical token tracking
|
|
1537
|
+
combinedPromptTokens?: number; // Total prompt tokens including all children
|
|
1538
|
+
combinedCompletionTokens?: number; // Total completion tokens including all children
|
|
1539
|
+
combinedTokensUsed?: number; // Total tokens including all children (calculated)
|
|
1540
|
+
|
|
1541
|
+
// Cost tracking
|
|
1542
|
+
cost?: number; // Cost of this execution
|
|
1543
|
+
costCurrency?: string; // ISO 4217 currency code (USD, EUR, etc.)
|
|
1544
|
+
combinedCost?: number; // Total cost including all children
|
|
1545
|
+
|
|
1199
1546
|
validationResult?: ValidationResult; // Validation result if output validation was performed
|
|
1200
|
-
|
|
1547
|
+
validationAttempts?: ValidationAttempt[]; // Detailed validation attempts
|
|
1548
|
+
additionalResults?: AIPromptRunResult<T>[]; // Additional results from parallel execution, ranked by judge
|
|
1201
1549
|
ranking?: number; // Ranking assigned by judge (1 = best, 2 = second best, etc.)
|
|
1202
1550
|
judgeRationale?: string; // Judge's rationale for this ranking
|
|
1203
1551
|
modelInfo?: ModelInfo; // Model information for this result
|
|
@@ -1267,23 +1615,25 @@ const result = await runner.ExecutePrompt({ prompt, data, contextUser });
|
|
|
1267
1615
|
|
|
1268
1616
|
### With AI Agents
|
|
1269
1617
|
|
|
1270
|
-
AI Agents can leverage the prompt system for sophisticated operations:
|
|
1618
|
+
AI Agents can leverage the prompt system for sophisticated operations with comprehensive execution tracking:
|
|
1271
1619
|
|
|
1272
1620
|
```typescript
|
|
1273
|
-
// Agents use prompts for their intelligence
|
|
1274
|
-
import {
|
|
1621
|
+
// Agents use prompts for their intelligence with hierarchical logging
|
|
1622
|
+
import { AgentRunner } from '@memberjunction/ai-agents';
|
|
1275
1623
|
import { AIPromptRunner } from '@memberjunction/ai-prompts';
|
|
1276
1624
|
|
|
1277
|
-
class IntelligentAgent extends
|
|
1625
|
+
class IntelligentAgent extends AgentRunner {
|
|
1278
1626
|
private promptRunner = new AIPromptRunner();
|
|
1279
1627
|
|
|
1280
|
-
async execute(context:
|
|
1628
|
+
async execute(context: AgentExecutionContext): Promise<AgentExecutionResult> {
|
|
1281
1629
|
const prompt = this.getPromptForContext(context);
|
|
1282
1630
|
|
|
1631
|
+
// Link prompt execution to agent run for comprehensive tracking
|
|
1283
1632
|
const result = await this.promptRunner.ExecutePrompt({
|
|
1284
1633
|
prompt: prompt,
|
|
1285
1634
|
data: context.data,
|
|
1286
|
-
contextUser: context.user
|
|
1635
|
+
contextUser: context.user,
|
|
1636
|
+
agentRunId: context.agentRun?.ID // Links prompt to parent agent run
|
|
1287
1637
|
});
|
|
1288
1638
|
|
|
1289
1639
|
return this.formatAgentResult(result);
|
|
@@ -1291,6 +1641,63 @@ class IntelligentAgent extends BaseAgent {
|
|
|
1291
1641
|
}
|
|
1292
1642
|
```
|
|
1293
1643
|
|
|
1644
|
+
#### Agent-Prompt Integration Features
|
|
1645
|
+
|
|
1646
|
+
The AI Prompts system provides seamless integration with AI Agents through the `agentRunId` parameter:
|
|
1647
|
+
|
|
1648
|
+
**Hierarchical Execution Tracking:**
|
|
1649
|
+
- Prompt executions are linked to their parent agent runs via `AgentRunID` foreign key
|
|
1650
|
+
- Provides complete audit trail from agent decision to prompt execution
|
|
1651
|
+
- Enables comprehensive resource usage tracking across agent workflows
|
|
1652
|
+
|
|
1653
|
+
**Usage Patterns:**
|
|
1654
|
+
```typescript
|
|
1655
|
+
// 1. Direct agent-prompt linking
|
|
1656
|
+
const result = await promptRunner.ExecutePrompt({
|
|
1657
|
+
prompt: myPrompt,
|
|
1658
|
+
data: promptData,
|
|
1659
|
+
agentRunId: agentRun.ID, // Links to parent agent execution
|
|
1660
|
+
contextUser: user
|
|
1661
|
+
});
|
|
1662
|
+
|
|
1663
|
+
// 2. Parallel execution with agent tracking
|
|
1664
|
+
const parallelResult = await promptRunner.ExecutePrompt({
|
|
1665
|
+
prompt: parallelPrompt, // ParallelizationMode: 'ModelSpecific'
|
|
1666
|
+
data: analysisData,
|
|
1667
|
+
agentRunId: agentRun.ID, // All parallel child prompts link to agent
|
|
1668
|
+
contextUser: user
|
|
1669
|
+
});
|
|
1670
|
+
|
|
1671
|
+
// 3. Context compression with agent linking (automatic in AgentRunner)
|
|
1672
|
+
// When agents use context compression, compression prompts are automatically
|
|
1673
|
+
// linked to the parent agent run for complete execution visibility
|
|
1674
|
+
```
|
|
1675
|
+
|
|
1676
|
+
**Database Schema Integration:**
|
|
1677
|
+
```sql
|
|
1678
|
+
-- Query agent execution with all related prompts
|
|
1679
|
+
SELECT
|
|
1680
|
+
ar.ID as AgentRunID,
|
|
1681
|
+
ar.Status as AgentStatus,
|
|
1682
|
+
ar.StartedAt,
|
|
1683
|
+
ar.CompletedAt,
|
|
1684
|
+
pr.ID as PromptRunID,
|
|
1685
|
+
pr.RunType,
|
|
1686
|
+
pr.Success as PromptSuccess,
|
|
1687
|
+
pr.ExecutionTimeMS,
|
|
1688
|
+
pr.TokensUsed
|
|
1689
|
+
FROM AIAgentRun ar
|
|
1690
|
+
LEFT JOIN AIPromptRun pr ON ar.ID = pr.AgentRunID
|
|
1691
|
+
WHERE ar.ID = 'your-agent-run-id'
|
|
1692
|
+
ORDER BY pr.RunAt;
|
|
1693
|
+
```
|
|
1694
|
+
|
|
1695
|
+
**Benefits:**
|
|
1696
|
+
- **Complete Traceability**: Track all AI model usage from agent decisions to prompt executions
|
|
1697
|
+
- **Resource Attribution**: Understand token usage and costs at the agent level
|
|
1698
|
+
- **Performance Analysis**: Analyze execution patterns across the agent-prompt hierarchy
|
|
1699
|
+
- **Debugging Support**: Full execution history for troubleshooting agent workflows
|
|
1700
|
+
|
|
1294
1701
|
## Dependencies
|
|
1295
1702
|
|
|
1296
1703
|
- `@memberjunction/core` (v2.43.0): MemberJunction core library
|
|
@@ -1564,4 +1971,133 @@ const defaultPrompt = {
|
|
|
1564
1971
|
};
|
|
1565
1972
|
```
|
|
1566
1973
|
|
|
1567
|
-
For additional configuration options and advanced use cases, refer to the source code and entity definitions in the MemberJunction core system.
|
|
1974
|
+
For additional configuration options and advanced use cases, refer to the source code and entity definitions in the MemberJunction core system.
|
|
1975
|
+
|
|
1976
|
+
## System Prompt Embedding
|
|
1977
|
+
|
|
1978
|
+
The AI Prompt Runner provides sophisticated system prompt embedding capabilities for agent architectures through the template engine integration.
|
|
1979
|
+
|
|
1980
|
+
### Architecture Overview
|
|
1981
|
+
|
|
1982
|
+
When `systemPromptId` is provided in AIPromptParams, the runner:
|
|
1983
|
+
1. Loads the system prompt template from the database
|
|
1984
|
+
2. Embeds the agent-specific AI prompt using `{% PromptEmbed %}` syntax
|
|
1985
|
+
3. Renders the complete system prompt with agent context
|
|
1986
|
+
4. Uses the rendered system prompt instead of the regular AI prompt template
|
|
1987
|
+
|
|
1988
|
+
This enables sophisticated agent architectures where:
|
|
1989
|
+
- **System prompts** provide execution control and enforce deterministic JSON response format
|
|
1990
|
+
- **Agent prompts** contain domain-specific logic (e.g., DATA_GATHER instructions)
|
|
1991
|
+
- **Available actions and sub-agents** are injected for agent decision-making
|
|
1992
|
+
|
|
1993
|
+
### Template Syntax
|
|
1994
|
+
|
|
1995
|
+
System prompt templates use the `{% PromptEmbed %}` syntax to embed AI prompts:
|
|
1996
|
+
|
|
1997
|
+
```nunjucks
|
|
1998
|
+
# System Prompt Template Example
|
|
1999
|
+
|
|
2000
|
+
You are an AI agent with the following specialized instructions:
|
|
2001
|
+
|
|
2002
|
+
{% PromptEmbed %}
|
|
2003
|
+
|
|
2004
|
+
## Available Actions
|
|
2005
|
+
{{#each availableActions}}
|
|
2006
|
+
- **{{this.name}}**: {{this.description}}
|
|
2007
|
+
{{/each}}
|
|
2008
|
+
|
|
2009
|
+
## Available Sub-Agents
|
|
2010
|
+
{{#each availableSubAgents}}
|
|
2011
|
+
- **{{this.name}}**: {{this.description}}
|
|
2012
|
+
{{/each}}
|
|
2013
|
+
|
|
2014
|
+
## Response Format
|
|
2015
|
+
You must respond with valid JSON following this structure:
|
|
2016
|
+
{
|
|
2017
|
+
"decision": "execute_action|execute_subagent|complete_task|request_clarification",
|
|
2018
|
+
"reasoning": "Explanation of your decision",
|
|
2019
|
+
"executionPlan": [
|
|
2020
|
+
{
|
|
2021
|
+
"type": "action|subagent",
|
|
2022
|
+
"targetId": "action-or-agent-id",
|
|
2023
|
+
"parameters": {},
|
|
2024
|
+
"executionOrder": 1,
|
|
2025
|
+
"allowParallel": true
|
|
2026
|
+
}
|
|
2027
|
+
],
|
|
2028
|
+
"isTaskComplete": false,
|
|
2029
|
+
"confidence": 0.95
|
|
2030
|
+
}
|
|
2031
|
+
```
|
|
2032
|
+
|
|
2033
|
+
### Validation and Security
|
|
2034
|
+
|
|
2035
|
+
The system includes comprehensive validation to ensure proper prompt embedding:
|
|
2036
|
+
|
|
2037
|
+
```typescript
|
|
2038
|
+
// Validation process:
|
|
2039
|
+
// 1. Verify system prompt exists and has template
|
|
2040
|
+
// 2. Check agent-prompt relationships via AIAgentPrompt table
|
|
2041
|
+
// 3. Ensure agents using system prompt are linked to current prompt
|
|
2042
|
+
// 4. Validate template contains {% PromptEmbed %} syntax
|
|
2043
|
+
|
|
2044
|
+
const params = new AIPromptParams();
|
|
2045
|
+
params.prompt = agentSpecificPrompt;
|
|
2046
|
+
params.systemPromptId = 'system-prompt-id'; // Triggers validation
|
|
2047
|
+
params.data = { agentName: 'DataGather', availableActions: [...] };
|
|
2048
|
+
```
|
|
2049
|
+
|
|
2050
|
+
### Integration with AI Agents
|
|
2051
|
+
|
|
2052
|
+
The AgentRunner seamlessly uses system prompt embedding:
|
|
2053
|
+
|
|
2054
|
+
```typescript
|
|
2055
|
+
// AgentRunner delegates to AIPromptRunner with system prompt embedding
|
|
2056
|
+
const promptParams = new AIPromptParams();
|
|
2057
|
+
promptParams.prompt = primaryAgentPrompt.prompt;
|
|
2058
|
+
promptParams.systemPromptId = this.agentType.SystemPromptID;
|
|
2059
|
+
promptParams.data = promptData;
|
|
2060
|
+
promptParams.agentRunId = context.agentRun.ID;
|
|
2061
|
+
|
|
2062
|
+
const promptResult = await this._promptRunner.ExecutePrompt(promptParams);
|
|
2063
|
+
```
|
|
2064
|
+
|
|
2065
|
+
### Database Schema Integration
|
|
2066
|
+
|
|
2067
|
+
The system prompt embedding feature integrates with several database entities:
|
|
2068
|
+
|
|
2069
|
+
#### Entity Relationships
|
|
2070
|
+
|
|
2071
|
+
```sql
|
|
2072
|
+
-- System prompts are stored as AIPrompt entities with templates
|
|
2073
|
+
AIPrompt (SystemPromptID) -> Template -> TemplateContent (contains {% PromptEmbed %})
|
|
2074
|
+
|
|
2075
|
+
-- Agent types reference system prompts
|
|
2076
|
+
AIAgentType.SystemPromptID -> AIPrompt (system prompt)
|
|
2077
|
+
|
|
2078
|
+
-- Agents belong to agent types
|
|
2079
|
+
AIAgent.TypeID -> AIAgentType
|
|
2080
|
+
|
|
2081
|
+
-- Agent prompts link agents to their specific prompts
|
|
2082
|
+
AIAgentPrompt: AgentID + PromptID
|
|
2083
|
+
|
|
2084
|
+
-- Validation ensures proper linkage:
|
|
2085
|
+
-- Agent -> AgentType -> SystemPrompt
|
|
2086
|
+
-- Agent -> AIAgentPrompt -> AIPrompt (to be embedded)
|
|
2087
|
+
```
|
|
2088
|
+
|
|
2089
|
+
#### Storage Structure
|
|
2090
|
+
|
|
2091
|
+
```sql
|
|
2092
|
+
-- Example system prompt template storage
|
|
2093
|
+
INSERT INTO Template (Name, Description)
|
|
2094
|
+
VALUES ('AI Agent System Prompt', 'Control wrapper for agent decision-making');
|
|
2095
|
+
|
|
2096
|
+
INSERT INTO TemplateContent (TemplateID, TemplateText, Priority)
|
|
2097
|
+
VALUES (@TemplateID, 'You are {{agentName}}... {% PromptEmbed %}... Respond with JSON...', 100);
|
|
2098
|
+
|
|
2099
|
+
INSERT INTO AIPrompt (Name, Description, TemplateID, Category)
|
|
2100
|
+
VALUES ('System Prompt', 'Agent execution control wrapper', @TemplateID, 'System');
|
|
2101
|
+
|
|
2102
|
+
UPDATE AIAgentType SET SystemPromptID = @SystemPromptID WHERE Name = 'DataGatherAgent';
|
|
2103
|
+
```
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AIPromptCategoryExtended.d.ts","sourceRoot":"","sources":["../src/AIPromptCategoryExtended.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"AIPromptCategoryExtended.d.ts","sourceRoot":"","sources":["../src/AIPromptCategoryExtended.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAGvF,qBACa,8BAA+B,SAAQ,sBAAsB;IACxE,OAAO,CAAC,QAAQ,CAAwB;IACxC,IAAW,OAAO,IAAI,cAAc,EAAE,CAErC;CACF"}
|