@memberjunction/aiengine 3.4.0 → 4.1.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 +123 -666
- package/dist/AIEngine.d.ts +243 -13
- package/dist/AIEngine.d.ts.map +1 -1
- package/dist/AIEngine.js +406 -154
- package/dist/AIEngine.js.map +1 -1
- package/dist/index.d.ts +8 -8
- package/dist/index.js +8 -24
- package/dist/index.js.map +1 -1
- package/dist/services/ActionEmbeddingService.d.ts +72 -1
- package/dist/services/ActionEmbeddingService.d.ts.map +1 -1
- package/dist/services/ActionEmbeddingService.js +88 -12
- package/dist/services/ActionEmbeddingService.js.map +1 -1
- package/dist/services/AgentEmbeddingService.d.ts +70 -1
- package/dist/services/AgentEmbeddingService.d.ts.map +1 -1
- package/dist/services/AgentEmbeddingService.js +87 -13
- package/dist/services/AgentEmbeddingService.js.map +1 -1
- package/dist/services/ConversationAttachmentService.d.ts +126 -0
- package/dist/services/ConversationAttachmentService.d.ts.map +1 -1
- package/dist/services/ConversationAttachmentService.js +180 -25
- package/dist/services/ConversationAttachmentService.js.map +1 -1
- package/dist/types/ActionMatchResult.d.ts +48 -0
- package/dist/types/ActionMatchResult.d.ts.map +1 -1
- package/dist/types/ActionMatchResult.js +1 -2
- package/dist/types/AgentMatchResult.d.ts +52 -0
- package/dist/types/AgentMatchResult.d.ts.map +1 -1
- package/dist/types/AgentMatchResult.js +1 -2
- package/dist/types/ExampleMatchResult.d.ts +8 -0
- package/dist/types/ExampleMatchResult.d.ts.map +1 -1
- package/dist/types/ExampleMatchResult.js +1 -2
- package/dist/types/NoteMatchResult.d.ts +8 -0
- package/dist/types/NoteMatchResult.d.ts.map +1 -1
- package/dist/types/NoteMatchResult.js +1 -2
- package/package.json +16 -15
package/README.md
CHANGED
|
@@ -1,736 +1,193 @@
|
|
|
1
1
|
# @memberjunction/aiengine
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Server-side AI Engine for MemberJunction. Wraps `AIEngineBase` and adds server-only capabilities including LLM execution, embedding generation, vector-based semantic search for agents and actions, and conversation attachment management. This package is the main orchestration layer for AI operations on the server.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Architecture
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
- **⚡ Simple Prompt Execution**: Basic prompt execution for quick AI tasks
|
|
12
|
-
- **🏗️ Agent Type System**: Defines agent types and their behavioral characteristics
|
|
13
|
-
- **🔍 Semantic Search**: Find similar agents, actions, notes, and examples using vector embeddings
|
|
7
|
+
```mermaid
|
|
8
|
+
graph TD
|
|
9
|
+
AIB["AIEngineBase<br/>Metadata Cache"]
|
|
10
|
+
style AIB fill:#2d6a9f,stroke:#1a4971,color:#fff
|
|
14
11
|
|
|
15
|
-
|
|
12
|
+
AIE["AIEngine<br/>Server-Side Singleton"]
|
|
13
|
+
style AIE fill:#2d8659,stroke:#1a5c3a,color:#fff
|
|
16
14
|
|
|
17
|
-
|
|
15
|
+
subgraph "Server Capabilities"
|
|
16
|
+
LLM["LLM Execution<br/>ChatCompletion, Classify, Summarize"]
|
|
17
|
+
style LLM fill:#7c5295,stroke:#563a6b,color:#fff
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
- Extended entity classes for AI operations
|
|
22
|
-
- Agent type definitions and factory interfaces
|
|
23
|
-
- The new `agent-types.ts` file with agent type classes
|
|
24
|
-
- **Base AI types** are imported from `@memberjunction/ai` (Core)
|
|
25
|
-
- **Agent execution types** are imported from `@memberjunction/ai-agents`
|
|
26
|
-
- **Prompt types** are imported from `@memberjunction/ai-prompts`
|
|
19
|
+
EMB["Embedding Services<br/>Agent & Action Embeddings"]
|
|
20
|
+
style EMB fill:#7c5295,stroke:#563a6b,color:#fff
|
|
27
21
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
```bash
|
|
31
|
-
npm install @memberjunction/aiengine
|
|
32
|
-
```
|
|
33
|
-
|
|
34
|
-
## Requirements
|
|
35
|
-
|
|
36
|
-
- Node.js 16+
|
|
37
|
-
- MemberJunction Core libraries
|
|
38
|
-
- [@memberjunction/ai](../Core/README.md) for base AI types
|
|
39
|
-
- At least one AI model provider (e.g., `@memberjunction/ai-openai`)
|
|
40
|
-
|
|
41
|
-
## Core Architecture
|
|
42
|
-
|
|
43
|
-
### AI Agents
|
|
44
|
-
|
|
45
|
-
**AI Agents** are the primary interface for interacting with AI capabilities. Each agent has:
|
|
46
|
-
|
|
47
|
-
- **Specialized Purpose**: Domain-specific knowledge and capabilities
|
|
48
|
-
- **Model Configuration**: Associated AI models for different tasks
|
|
49
|
-
- **Context Management**: Maintains conversation context and state
|
|
50
|
-
- **Action Library**: Predefined actions the agent can perform
|
|
51
|
-
- **Note System**: Learning and memory capabilities
|
|
22
|
+
VS["Vector Search<br/>Semantic Agent/Action/Note Matching"]
|
|
23
|
+
style VS fill:#b8762f,stroke:#8a5722,color:#fff
|
|
52
24
|
|
|
53
|
-
|
|
54
|
-
|
|
25
|
+
ATT["Attachment Service<br/>Conversation Media Management"]
|
|
26
|
+
style ATT fill:#b8762f,stroke:#8a5722,color:#fff
|
|
27
|
+
end
|
|
55
28
|
|
|
56
|
-
|
|
57
|
-
|
|
29
|
+
AIB --> AIE
|
|
30
|
+
AIE --> LLM
|
|
31
|
+
AIE --> EMB
|
|
32
|
+
AIE --> VS
|
|
33
|
+
AIE --> ATT
|
|
58
34
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
35
|
+
subgraph "Result Types"
|
|
36
|
+
AMR["AgentMatchResult"]
|
|
37
|
+
style AMR fill:#7c5295,stroke:#563a6b,color:#fff
|
|
62
38
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
console.log(`Purpose: ${dataAnalysisAgent.Purpose}`);
|
|
66
|
-
console.log(`Available Actions: ${dataAnalysisAgent.Actions.length}`);
|
|
67
|
-
```
|
|
39
|
+
ACMR["ActionMatchResult"]
|
|
40
|
+
style ACMR fill:#7c5295,stroke:#563a6b,color:#fff
|
|
68
41
|
|
|
69
|
-
|
|
42
|
+
NMR["NoteMatchResult"]
|
|
43
|
+
style NMR fill:#7c5295,stroke:#563a6b,color:#fff
|
|
70
44
|
|
|
71
|
-
|
|
45
|
+
EMR["ExampleMatchResult"]
|
|
46
|
+
style EMR fill:#7c5295,stroke:#563a6b,color:#fff
|
|
47
|
+
end
|
|
72
48
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
currentUser,
|
|
78
|
-
"You are a helpful programming tutor who explains concepts clearly."
|
|
79
|
-
);
|
|
80
|
-
|
|
81
|
-
console.log("AI Response:", response);
|
|
82
|
-
|
|
83
|
-
// With specific model
|
|
84
|
-
const specificModel = allModels.find(m => m.Name === 'GPT-4');
|
|
85
|
-
const response2 = await AIEngine.Instance.SimpleLLMCompletion(
|
|
86
|
-
"Analyze this code for potential issues",
|
|
87
|
-
currentUser,
|
|
88
|
-
"You are an expert code reviewer",
|
|
89
|
-
specificModel
|
|
90
|
-
);
|
|
49
|
+
VS --> AMR
|
|
50
|
+
VS --> ACMR
|
|
51
|
+
VS --> NMR
|
|
52
|
+
VS --> EMR
|
|
91
53
|
```
|
|
92
54
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
### Model Management
|
|
98
|
-
|
|
99
|
-
The engine maintains a comprehensive registry of AI models:
|
|
100
|
-
|
|
101
|
-
```typescript
|
|
102
|
-
// Get all available models
|
|
103
|
-
const allModels = AIEngine.Instance.Models;
|
|
104
|
-
const llmModels = AIEngine.Instance.LanguageModels;
|
|
105
|
-
|
|
106
|
-
// Get the most powerful model for a specific vendor
|
|
107
|
-
const bestOpenAI = await AIEngine.Instance.GetHighestPowerLLM('OpenAI', currentUser);
|
|
108
|
-
const bestModel = await AIEngine.Instance.GetHighestPowerModel(null, 'LLM', currentUser);
|
|
109
|
-
|
|
110
|
-
// Models are automatically selected based on:
|
|
111
|
-
// - PowerRank: Relative capability ranking
|
|
112
|
-
// - ModelType: LLM, Vision, Audio, etc.
|
|
113
|
-
// - Vendor: OpenAI, Anthropic, Google, etc.
|
|
114
|
-
// - Cost and performance characteristics
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
### Performance Monitoring & Analytics
|
|
119
|
-
|
|
120
|
-
The engine provides basic tracking and analytics for AI operations. Advanced execution metrics, caching analytics, and parallel execution analytics are available in the [@memberjunction/ai-prompts](../Prompts/README.md) package.
|
|
121
|
-
|
|
122
|
-
## API Reference
|
|
123
|
-
|
|
124
|
-
### AIEngine Class
|
|
125
|
-
|
|
126
|
-
The central orchestration class for all AI operations.
|
|
127
|
-
|
|
128
|
-
#### Key Methods
|
|
129
|
-
|
|
130
|
-
##### Initialization
|
|
131
|
-
- `Config(forceRefresh?: boolean, contextUser?: UserInfo, provider?: IMetadataProvider)`: Load AI configuration metadata from the MemberJunction system
|
|
132
|
-
|
|
133
|
-
##### Simple LLM Operations
|
|
134
|
-
- `SimpleLLMCompletion(userPrompt: string, contextUser: UserInfo, systemPrompt?: string, model?: AIModelEntityExtended, apiKey?: string)`: Quick text completion for basic use cases
|
|
135
|
-
- `ParallelLLMCompletions(userPrompt: string, contextUser: UserInfo, systemPrompt?: string, iterations?: number, temperatureIncrement?: number, baseTemperature?: number, model?: AIModelEntityExtended, apiKey?: string, callbacks?: ParallelChatCompletionsCallbacks)`: Execute multiple parallel completions with different parameters
|
|
136
|
-
|
|
137
|
-
##### Model Management
|
|
138
|
-
- `GetHighestPowerModel(vendorName: string, modelType: string, contextUser?: UserInfo)`: Get the most powerful model of a specific type from a vendor
|
|
139
|
-
- `GetHighestPowerLLM(vendorName?: string, contextUser?: UserInfo)`: Get the most powerful LLM, optionally filtered by vendor
|
|
140
|
-
- `PrepareLLMInstance(contextUser: UserInfo, model?: AIModelEntityExtended, apiKey?: string)`: Prepare an LLM instance with proper configuration
|
|
141
|
-
- `PrepareChatMessages(userPrompt: string, systemPrompt?: string)`: Format chat messages in the standard format
|
|
142
|
-
|
|
143
|
-
##### Agent Management
|
|
144
|
-
- `GetAgentByName(agentName: string)`: Get a specific AI agent by name
|
|
145
|
-
- `AgenteNoteTypeIDByName(agentNoteTypeName: string)`: Get the ID of an agent note type by name
|
|
146
|
-
|
|
147
|
-
#### Key Properties
|
|
148
|
-
|
|
149
|
-
##### Models and Databases
|
|
150
|
-
- `Models`: All registered AI models with extended capabilities
|
|
151
|
-
- `LanguageModels`: Filtered list of LLM type models
|
|
152
|
-
- `VectorDatabases`: Available vector database configurations
|
|
153
|
-
- `ArtifactTypes`: Registered artifact types for AI outputs
|
|
154
|
-
|
|
155
|
-
##### AI Agents
|
|
156
|
-
- `Agents`: Available AI agents with their capabilities and configurations
|
|
157
|
-
- `AgentActions`: All available agent actions
|
|
158
|
-
- `AgentModels`: Model associations for agents (deprecated)
|
|
159
|
-
- `AgentNoteTypes`: Types of notes agents can create
|
|
160
|
-
- `AgentNotes`: All agent notes/learnings
|
|
161
|
-
|
|
162
|
-
##### Prompts (Reference Only)
|
|
163
|
-
- `Prompts`: All registered prompts (use @memberjunction/ai-prompts for execution)
|
|
164
|
-
- `PromptModels`: Model associations for prompts
|
|
165
|
-
- `PromptTypes`: Available prompt types
|
|
166
|
-
- `PromptCategories`: Prompt category hierarchy
|
|
167
|
-
|
|
168
|
-
##### Deprecated Properties
|
|
169
|
-
- `Actions`: Legacy AI actions (deprecated)
|
|
170
|
-
- `EntityAIActions`: Legacy entity AI actions (deprecated)
|
|
171
|
-
- `ModelActions`: Legacy model actions (deprecated)
|
|
172
|
-
|
|
173
|
-
> **Note**: `Prompts` and `PromptCategories` properties are now available in the [@memberjunction/ai-prompts](../Prompts/README.md) package.
|
|
174
|
-
|
|
175
|
-
### Advanced Prompt Execution
|
|
176
|
-
|
|
177
|
-
For sophisticated prompt management with templates, parallel execution, and stored prompts, see the [@memberjunction/ai-prompts](../Prompts/README.md) package which provides the `AIPromptRunner` class and related functionality.
|
|
178
|
-
|
|
179
|
-
### Extended Entity Classes
|
|
180
|
-
|
|
181
|
-
#### AIAgentEntityExtended
|
|
182
|
-
|
|
183
|
-
Extended AI Agent entity with relationship management:
|
|
184
|
-
|
|
185
|
-
```typescript
|
|
186
|
-
class AIAgentEntityExtended extends AIAgentEntity {
|
|
187
|
-
get Actions(): AIAgentActionEntity[]; // Agent's available actions
|
|
188
|
-
get Models(): AIAgentModelEntity[]; // Associated models (deprecated - use prompts)
|
|
189
|
-
get Notes(): AIAgentNoteEntity[]; // Agent's learning notes
|
|
190
|
-
}
|
|
191
|
-
```
|
|
192
|
-
|
|
193
|
-
#### AIPromptCategoryEntityExtended
|
|
194
|
-
|
|
195
|
-
Extended prompt category with hierarchical prompt management:
|
|
196
|
-
|
|
197
|
-
```typescript
|
|
198
|
-
class AIPromptCategoryEntityExtended extends AIPromptCategoryEntity {
|
|
199
|
-
get Prompts(): AIPromptEntity[]; // Prompts in this category
|
|
200
|
-
}
|
|
201
|
-
```
|
|
202
|
-
|
|
203
|
-
#### AIModelEntityExtended
|
|
204
|
-
|
|
205
|
-
The AI Engine automatically extends AI Model entities with additional capabilities from the AI provider system. These extended models include all driver-specific functionality and API integration.
|
|
206
|
-
|
|
207
|
-
### Agent Type System
|
|
208
|
-
|
|
209
|
-
The Engine now includes specialized agent type classes in `agent-types.ts`:
|
|
210
|
-
|
|
211
|
-
```typescript
|
|
212
|
-
// Base agent type - foundation for all agent types
|
|
213
|
-
import { BaseAgentType } from '@memberjunction/aiengine';
|
|
214
|
-
|
|
215
|
-
// Specialized agent types
|
|
216
|
-
import { LoopAgentType } from '@memberjunction/aiengine';
|
|
217
|
-
|
|
218
|
-
// Agent types define behavioral characteristics:
|
|
219
|
-
// - System prompts for consistent behavior
|
|
220
|
-
// - Decision-making patterns
|
|
221
|
-
// - Execution flow control
|
|
222
|
-
```
|
|
223
|
-
|
|
224
|
-
### Type-Safe Sub-Agent Requests (New in v2.51.0)
|
|
225
|
-
|
|
226
|
-
The AI Engine now provides type-safe context propagation for sub-agent requests. Context is optional in the request definition and is provided at execution time by the framework:
|
|
55
|
+
## Installation
|
|
227
56
|
|
|
228
|
-
```
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
// Define your context type
|
|
232
|
-
interface MyContext {
|
|
233
|
-
apiEndpoint: string;
|
|
234
|
-
apiKey: string;
|
|
235
|
-
environment: 'dev' | 'staging' | 'prod';
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
// Create a typed sub-agent request - context is optional here
|
|
239
|
-
const subAgentRequest: AgentSubAgentRequest<MyContext> = {
|
|
240
|
-
id: 'sub-agent-uuid',
|
|
241
|
-
name: 'DataProcessorAgent',
|
|
242
|
-
message: 'Process the uploaded data',
|
|
243
|
-
terminateAfter: false
|
|
244
|
-
// context is NOT set by AI agents - it's provided by the framework at execution time
|
|
245
|
-
};
|
|
246
|
-
|
|
247
|
-
// Use in agent next step decisions
|
|
248
|
-
const nextStep: BaseAgentNextStep<MyContext> = {
|
|
249
|
-
step: 'sub-agent',
|
|
250
|
-
subAgent: subAgentRequest
|
|
251
|
-
};
|
|
252
|
-
|
|
253
|
-
// At execution time, the framework provides the context:
|
|
254
|
-
// The parent agent's context is automatically passed to sub-agents
|
|
255
|
-
// This ensures consistent runtime configuration across the agent hierarchy
|
|
57
|
+
```bash
|
|
58
|
+
npm install @memberjunction/aiengine
|
|
256
59
|
```
|
|
257
60
|
|
|
258
|
-
This
|
|
259
|
-
- Type safety when defining sub-agent requests
|
|
260
|
-
- Context is consistently provided by the execution framework
|
|
261
|
-
- AI agents focus on decision logic without managing runtime configuration
|
|
262
|
-
- Runtime contexts (API keys, endpoints, etc.) flow through the agent hierarchy automatically
|
|
263
|
-
|
|
61
|
+
**Note:** This package is server-side only. For metadata access on the client, use `@memberjunction/ai-engine-base` directly.
|
|
264
62
|
|
|
265
|
-
##
|
|
63
|
+
## Key Exports
|
|
266
64
|
|
|
267
|
-
###
|
|
65
|
+
### AIEngine (Singleton)
|
|
268
66
|
|
|
269
|
-
The
|
|
67
|
+
The main server-side engine. Uses composition (not inheritance) to delegate metadata operations to `AIEngineBase.Instance` while adding server-specific features.
|
|
270
68
|
|
|
271
69
|
```typescript
|
|
272
|
-
|
|
273
|
-
const results = await AIEngine.Instance.ParallelLLMCompletions(
|
|
274
|
-
"Generate creative product names for a smart water bottle",
|
|
275
|
-
currentUser,
|
|
276
|
-
"You are a creative product naming expert",
|
|
277
|
-
5, // iterations
|
|
278
|
-
0.15, // temperature increment
|
|
279
|
-
0.5, // base temperature
|
|
280
|
-
null, // use best available model
|
|
281
|
-
null, // use default API key
|
|
282
|
-
{
|
|
283
|
-
onProgress: (completed, total) => {
|
|
284
|
-
console.log(`Progress: ${completed}/${total}`);
|
|
285
|
-
},
|
|
286
|
-
onComplete: (results) => {
|
|
287
|
-
console.log(`All ${results.length} completions finished`);
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
);
|
|
291
|
-
|
|
292
|
-
// Results array contains all completion responses
|
|
293
|
-
results.forEach((result, index) => {
|
|
294
|
-
if (result.success) {
|
|
295
|
-
console.log(`Result ${index + 1}:`, result.data.choices[0].message.content);
|
|
296
|
-
}
|
|
297
|
-
});
|
|
298
|
-
```
|
|
299
|
-
|
|
300
|
-
### Model Selection Strategies
|
|
301
|
-
|
|
302
|
-
The AI Engine provides intelligent model selection:
|
|
303
|
-
|
|
304
|
-
```typescript
|
|
305
|
-
// Get the best model regardless of vendor
|
|
306
|
-
const bestModel = await AIEngine.Instance.GetHighestPowerModel(null, 'LLM', currentUser);
|
|
307
|
-
|
|
308
|
-
// Get the best OpenAI model specifically
|
|
309
|
-
const bestOpenAI = await AIEngine.Instance.GetHighestPowerLLM('OpenAI', currentUser);
|
|
310
|
-
|
|
311
|
-
// Get the best vision model
|
|
312
|
-
const bestVision = await AIEngine.Instance.GetHighestPowerModel(null, 'Vision', currentUser);
|
|
313
|
-
|
|
314
|
-
// Get the best audio model
|
|
315
|
-
const bestAudio = await AIEngine.Instance.GetHighestPowerModel(null, 'Audio', currentUser);
|
|
316
|
-
```
|
|
317
|
-
|
|
318
|
-
### Working with AI Agents
|
|
70
|
+
import { AIEngine } from '@memberjunction/aiengine';
|
|
319
71
|
|
|
320
|
-
|
|
72
|
+
// Initialize
|
|
73
|
+
await AIEngine.Instance.Config(false, contextUser);
|
|
321
74
|
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
const
|
|
325
|
-
|
|
326
|
-
// Access agent properties
|
|
327
|
-
console.log('Agent Purpose:', codeAgent.Purpose);
|
|
328
|
-
console.log('Available Actions:', codeAgent.Actions.length);
|
|
329
|
-
console.log('Learning Notes:', codeAgent.Notes.length);
|
|
330
|
-
|
|
331
|
-
// Use agent context in prompts
|
|
332
|
-
const response = await AIEngine.Instance.SimpleLLMCompletion(
|
|
333
|
-
"Review this TypeScript code for best practices",
|
|
334
|
-
currentUser,
|
|
335
|
-
`You are ${codeAgent.Name}. ${codeAgent.Purpose}`
|
|
336
|
-
);
|
|
75
|
+
// All AIEngineBase properties are delegated:
|
|
76
|
+
const models = AIEngine.Instance.Models;
|
|
77
|
+
const agents = AIEngine.Instance.Agents;
|
|
337
78
|
```
|
|
338
79
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
The AI Engine provides semantic search capabilities using vector embeddings for finding similar agents, actions, notes, and examples. All search operations support efficient metadata filtering for scoped searches.
|
|
342
|
-
|
|
343
|
-
#### Finding Similar Agents
|
|
80
|
+
#### LLM Execution
|
|
344
81
|
|
|
345
82
|
```typescript
|
|
346
|
-
//
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
5, // topK: return top 5 matches
|
|
351
|
-
0.5 // minSimilarity: minimum similarity threshold (0-1)
|
|
352
|
-
);
|
|
353
|
-
|
|
354
|
-
similarAgents.forEach(match => {
|
|
355
|
-
console.log(`Agent: ${match.agent.Name}`);
|
|
356
|
-
console.log(`Similarity: ${(match.similarity * 100).toFixed(1)}%`);
|
|
357
|
-
console.log(`Purpose: ${match.agent.Purpose}\n`);
|
|
83
|
+
// Direct chat completion
|
|
84
|
+
const result = await AIEngine.Instance.ChatCompletion({
|
|
85
|
+
model: 'gpt-4',
|
|
86
|
+
messages: [{ role: 'user', content: 'Explain quantum computing' }]
|
|
358
87
|
});
|
|
359
|
-
```
|
|
360
|
-
|
|
361
|
-
#### Finding Similar Actions
|
|
362
88
|
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
capability,
|
|
368
|
-
10, // topK
|
|
369
|
-
0.6 // minSimilarity
|
|
370
|
-
);
|
|
371
|
-
|
|
372
|
-
similarActions.forEach(match => {
|
|
373
|
-
console.log(`Action: ${match.action.Name}`);
|
|
374
|
-
console.log(`Match: ${(match.similarity * 100).toFixed(1)}%`);
|
|
375
|
-
console.log(`Description: ${match.action.Description}\n`);
|
|
89
|
+
// Summarize text
|
|
90
|
+
const summary = await AIEngine.Instance.SummarizeText({
|
|
91
|
+
model: 'gpt-4',
|
|
92
|
+
text: longDocument
|
|
376
93
|
});
|
|
377
|
-
```
|
|
378
|
-
|
|
379
|
-
#### Finding Similar Agent Notes (with Filtering)
|
|
380
94
|
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
const agentId = 'agent-uuid-here';
|
|
387
|
-
|
|
388
|
-
const similarNotes = await AIEngine.Instance.FindSimilarAgentNotes(
|
|
389
|
-
queryText,
|
|
390
|
-
agentId, // Filter by agent ID (efficient pre-filtering)
|
|
391
|
-
undefined, // userId filter (optional)
|
|
392
|
-
undefined, // companyId filter (optional)
|
|
393
|
-
5, // topK
|
|
394
|
-
0.7 // minSimilarity
|
|
395
|
-
);
|
|
396
|
-
|
|
397
|
-
similarNotes.forEach(match => {
|
|
398
|
-
console.log(`Note ID: ${match.note.ID}`);
|
|
399
|
-
console.log(`Similarity: ${(match.similarity * 100).toFixed(1)}%`);
|
|
400
|
-
console.log(`Content: ${match.note.Note}\n`);
|
|
95
|
+
// Classify text
|
|
96
|
+
const classification = await AIEngine.Instance.ClassifyText({
|
|
97
|
+
model: 'gpt-4',
|
|
98
|
+
text: inputText,
|
|
99
|
+
categories: ['positive', 'negative', 'neutral']
|
|
401
100
|
});
|
|
402
|
-
|
|
403
|
-
// Search across all agents (no filtering)
|
|
404
|
-
const allNotes = await AIEngine.Instance.FindSimilarAgentNotes(
|
|
405
|
-
queryText,
|
|
406
|
-
undefined, // No agent filter
|
|
407
|
-
undefined, // No user filter
|
|
408
|
-
undefined, // No company filter
|
|
409
|
-
10,
|
|
410
|
-
0.6
|
|
411
|
-
);
|
|
412
101
|
```
|
|
413
102
|
|
|
414
|
-
####
|
|
103
|
+
#### Semantic Search
|
|
415
104
|
|
|
416
|
-
|
|
105
|
+
Find agents, actions, notes, and examples using vector similarity:
|
|
417
106
|
|
|
418
107
|
```typescript
|
|
419
|
-
// Find
|
|
420
|
-
const
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
inputText,
|
|
425
|
-
agentId, // Filter by agent ID (efficient pre-filtering)
|
|
426
|
-
undefined, // userId filter (optional)
|
|
427
|
-
undefined, // companyId filter (optional)
|
|
428
|
-
3, // topK
|
|
429
|
-
0.75 // minSimilarity
|
|
108
|
+
// Find agents matching a user query
|
|
109
|
+
const agentMatches: AgentMatchResult[] = await AIEngine.Instance.FindSimilarAgents(
|
|
110
|
+
'Help me analyze sales data',
|
|
111
|
+
5, // topK
|
|
112
|
+
contextUser
|
|
430
113
|
);
|
|
431
114
|
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
console.log(`Input: ${match.example.ExampleInput}`);
|
|
436
|
-
console.log(`Output: ${match.example.ExampleOutput}\n`);
|
|
437
|
-
});
|
|
438
|
-
```
|
|
439
|
-
|
|
440
|
-
#### Performance Benefits of Filtering
|
|
441
|
-
|
|
442
|
-
The semantic search methods use pre-filtering for optimal performance:
|
|
443
|
-
|
|
444
|
-
```typescript
|
|
445
|
-
// ✅ EFFICIENT: Filter applied BEFORE similarity calculation
|
|
446
|
-
// For 1000 notes where 50 belong to the agent:
|
|
447
|
-
// - Filters to 50 notes (fast metadata check)
|
|
448
|
-
// - Calculates similarity for 50 vectors
|
|
449
|
-
// - Returns top 5 matches
|
|
450
|
-
const filtered = await AIEngine.Instance.FindSimilarAgentNotes(
|
|
451
|
-
queryText,
|
|
452
|
-
agentId, // Pre-filter by agent
|
|
453
|
-
undefined,
|
|
454
|
-
undefined,
|
|
115
|
+
// Find relevant actions
|
|
116
|
+
const actionMatches: ActionMatchResult[] = await AIEngine.Instance.FindSimilarActions(
|
|
117
|
+
'Send an email notification',
|
|
455
118
|
5,
|
|
456
|
-
|
|
119
|
+
contextUser
|
|
457
120
|
);
|
|
458
121
|
|
|
459
|
-
//
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
**Speedup**: Pre-filtering provides 10-20x performance improvement for scoped searches because similarity calculation is much more expensive than metadata checks.
|
|
466
|
-
|
|
467
|
-
For sophisticated parallel execution, template rendering, and stored prompt management, see the [@memberjunction/ai-prompts](../Prompts/README.md) package.
|
|
468
|
-
|
|
469
|
-
## Import Examples
|
|
470
|
-
|
|
471
|
-
```typescript
|
|
472
|
-
// Import main AI Engine class
|
|
473
|
-
import { AIEngine } from '@memberjunction/aiengine';
|
|
474
|
-
|
|
475
|
-
// Import extended entity types
|
|
476
|
-
import {
|
|
477
|
-
AIAgentEntityExtended,
|
|
478
|
-
AIPromptCategoryEntityExtended,
|
|
479
|
-
AIModelEntityExtended
|
|
480
|
-
} from '@memberjunction/aiengine';
|
|
481
|
-
|
|
482
|
-
// Import agent type classes
|
|
483
|
-
import { BaseAgentType, LoopAgentType } from '@memberjunction/aiengine';
|
|
484
|
-
|
|
485
|
-
// Import base AI types from Core
|
|
486
|
-
import { BaseLLM, ChatParams, ChatResult } from '@memberjunction/ai';
|
|
487
|
-
|
|
488
|
-
// When working with agents, import execution types
|
|
489
|
-
import { AgentExecutionParams, AgentExecutionResult } from '@memberjunction/ai-agents';
|
|
490
|
-
```
|
|
491
|
-
|
|
492
|
-
## Dependencies
|
|
493
|
-
|
|
494
|
-
- `@memberjunction/core`: MemberJunction core library
|
|
495
|
-
- `@memberjunction/global`: MemberJunction global utilities
|
|
496
|
-
- `@memberjunction/core-entities`: MemberJunction entity definitions
|
|
497
|
-
- `@memberjunction/ai`: Base AI types and interfaces (imported for core types)
|
|
498
|
-
- `@memberjunction/templates`: Template engine integration
|
|
499
|
-
- `@memberjunction/templates-base-types`: Template base type definitions
|
|
500
|
-
- `rxjs`: Reactive programming support
|
|
501
|
-
- `dotenv`: Environment variable management
|
|
502
|
-
|
|
503
|
-
## Related Packages
|
|
504
|
-
|
|
505
|
-
- `@memberjunction/ai-prompts`: Advanced prompt management with templates, parallel execution, and stored prompts
|
|
506
|
-
- `@memberjunction/ai-agents`: AI Agent implementations and specialized behaviors
|
|
507
|
-
- `@memberjunction/ai`: Core AI abstractions and interfaces
|
|
508
|
-
- AI Provider Packages:
|
|
509
|
-
- `@memberjunction/ai-openai`: OpenAI model provider
|
|
510
|
-
- `@memberjunction/ai-anthropic`: Anthropic (Claude) model provider
|
|
511
|
-
- `@memberjunction/ai-groq`: Groq model provider
|
|
512
|
-
- `@memberjunction/ai-mistral`: Mistral AI model provider
|
|
513
|
-
- `@memberjunction/ai-azure`: Azure AI model provider
|
|
514
|
-
- `@memberjunction/ai-bedrock`: AWS Bedrock model provider
|
|
515
|
-
- `@memberjunction/ai-vertex`: Google Vertex AI model provider
|
|
516
|
-
- `@memberjunction/ai-cerebras`: Cerebras model provider
|
|
517
|
-
- `@memberjunction/ai-bettybot`: BettyBot model provider
|
|
518
|
-
|
|
519
|
-
## Migration Guide
|
|
520
|
-
|
|
521
|
-
### From AI Actions to AI Prompts
|
|
522
|
-
|
|
523
|
-
If you're migrating from the deprecated AI Actions system, you can either:
|
|
524
|
-
|
|
525
|
-
1. **Use Simple LLM Completions** (basic use cases):
|
|
526
|
-
```typescript
|
|
527
|
-
// Old AI Actions approach (deprecated)
|
|
528
|
-
const actionParams: AIActionParams = {
|
|
529
|
-
actionId: 'action-id',
|
|
530
|
-
modelId: 'model-id',
|
|
531
|
-
systemPrompt: "System message",
|
|
532
|
-
userPrompt: "User message"
|
|
533
|
-
};
|
|
534
|
-
const result = await AIEngine.Instance.ExecuteAIAction(actionParams);
|
|
535
|
-
|
|
536
|
-
// New Simple LLM approach (basic cases)
|
|
537
|
-
const response = await AIEngine.Instance.SimpleLLMCompletion(
|
|
538
|
-
"User message",
|
|
539
|
-
currentUser,
|
|
540
|
-
"System message"
|
|
122
|
+
// Find relevant notes for an agent
|
|
123
|
+
const noteMatches: NoteMatchResult[] = await AIEngine.Instance.FindSimilarNotes(
|
|
124
|
+
agentId,
|
|
125
|
+
'Customer wants a refund',
|
|
126
|
+
10,
|
|
127
|
+
contextUser
|
|
541
128
|
);
|
|
542
|
-
```
|
|
543
|
-
|
|
544
|
-
2. **Use Advanced Prompts** (complex use cases): See the [@memberjunction/ai-prompts](../Prompts/README.md) package for sophisticated prompt management with templates and parallel execution.
|
|
545
129
|
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
modelId: 'model-id',
|
|
553
|
-
entityAIActionId: 'entity-action-id',
|
|
554
|
-
entityRecord: entity
|
|
555
|
-
};
|
|
556
|
-
const result = await AIEngine.Instance.ExecuteEntityAIAction(entityParams);
|
|
557
|
-
|
|
558
|
-
// New approach: Use AI Agents with either simple completions or advanced prompts
|
|
559
|
-
const agent = AIEngine.Instance.Agents.find(a => a.Name === 'Your Agent Name');
|
|
560
|
-
|
|
561
|
-
// For simple cases - use SimpleLLMCompletion
|
|
562
|
-
const entityData = JSON.stringify(entity.GetAll());
|
|
563
|
-
const response = await AIEngine.Instance.SimpleLLMCompletion(
|
|
564
|
-
`Analyze this ${entity.EntityType} entity: ${entityData}`,
|
|
565
|
-
currentUser,
|
|
566
|
-
`You are an expert ${agent.Purpose}`
|
|
130
|
+
// Find relevant examples for an agent
|
|
131
|
+
const exampleMatches: ExampleMatchResult[] = await AIEngine.Instance.FindSimilarExamples(
|
|
132
|
+
agentId,
|
|
133
|
+
'How do I reset my password?',
|
|
134
|
+
5,
|
|
135
|
+
contextUser
|
|
567
136
|
);
|
|
568
|
-
|
|
569
|
-
// For complex cases - use @memberjunction/ai-prompts package
|
|
570
137
|
```
|
|
571
138
|
|
|
572
|
-
|
|
139
|
+
### Embedding Services
|
|
573
140
|
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
141
|
+
| Class | Purpose |
|
|
142
|
+
|---|---|
|
|
143
|
+
| `AgentEmbeddingService` | Generates and manages embeddings for AI agents, enabling semantic agent discovery |
|
|
144
|
+
| `ActionEmbeddingService` | Generates and manages embeddings for actions, enabling semantic action matching |
|
|
578
145
|
|
|
579
|
-
|
|
580
|
-
npm run watch
|
|
581
|
-
```
|
|
582
|
-
|
|
583
|
-
### Running Tests
|
|
584
|
-
```bash
|
|
585
|
-
npm test
|
|
586
|
-
```
|
|
587
|
-
|
|
588
|
-
## Configuration
|
|
146
|
+
### Match Result Types
|
|
589
147
|
|
|
590
|
-
|
|
148
|
+
| Type | Fields | Description |
|
|
149
|
+
|---|---|---|
|
|
150
|
+
| `AgentMatchResult` | `agent`, `score`, `metadata` | Agent found via semantic similarity |
|
|
151
|
+
| `ActionMatchResult` | `action`, `score`, `metadata` | Action found via semantic similarity |
|
|
152
|
+
| `NoteMatchResult` | `note`, `score`, `metadata` | Agent note found via semantic similarity |
|
|
153
|
+
| `ExampleMatchResult` | `example`, `score`, `metadata` | Agent example found via semantic similarity |
|
|
591
154
|
|
|
592
|
-
|
|
593
|
-
# .env file
|
|
594
|
-
OPENAI_API_KEY=your-openai-key
|
|
595
|
-
ANTHROPIC_API_KEY=your-anthropic-key
|
|
596
|
-
GROQ_API_KEY=your-groq-key
|
|
597
|
-
MISTRAL_API_KEY=your-mistral-key
|
|
598
|
-
# ... other provider API keys
|
|
599
|
-
```
|
|
600
|
-
|
|
601
|
-
Alternatively, API keys can be passed directly to methods or configured in the MemberJunction metadata system.
|
|
155
|
+
### ConversationAttachmentService
|
|
602
156
|
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
The AI Engine provides comprehensive error handling:
|
|
157
|
+
Manages media attachments (images, audio, video, files) in agent conversations:
|
|
606
158
|
|
|
607
159
|
```typescript
|
|
608
|
-
|
|
609
|
-
const response = await AIEngine.Instance.SimpleLLMCompletion(
|
|
610
|
-
userPrompt,
|
|
611
|
-
currentUser,
|
|
612
|
-
systemPrompt
|
|
613
|
-
);
|
|
614
|
-
console.log('Success:', response);
|
|
615
|
-
} catch (error) {
|
|
616
|
-
if (error.message.includes('AI Metadata not loaded')) {
|
|
617
|
-
// Metadata needs to be loaded first
|
|
618
|
-
await AIEngine.Instance.Config(false, currentUser);
|
|
619
|
-
} else if (error.message.includes('User prompt not provided')) {
|
|
620
|
-
// Handle missing prompt
|
|
621
|
-
} else {
|
|
622
|
-
// Handle other errors
|
|
623
|
-
console.error('AI Engine Error:', error);
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
```
|
|
160
|
+
import { ConversationAttachmentService } from '@memberjunction/aiengine';
|
|
627
161
|
|
|
628
|
-
|
|
162
|
+
const service = new ConversationAttachmentService();
|
|
629
163
|
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
3. **Parallel Execution**: Use `ParallelLLMCompletions()` for improved reliability and result quality
|
|
633
|
-
4. **Caching**: For advanced caching capabilities, use the @memberjunction/ai-prompts package
|
|
634
|
-
|
|
635
|
-
## License
|
|
636
|
-
|
|
637
|
-
ISC
|
|
638
|
-
|
|
639
|
-
---
|
|
640
|
-
|
|
641
|
-
## Deprecated Features
|
|
642
|
-
|
|
643
|
-
The following features are deprecated and will be removed in a future version. Please migrate to the new AI Agents and AI Prompts system.
|
|
644
|
-
|
|
645
|
-
### AI Actions (Deprecated)
|
|
646
|
-
|
|
647
|
-
**⚠️ DEPRECATED**: AI Actions are deprecated in favor of the new AI Prompts system which provides better template support, parallel execution, and caching capabilities.
|
|
648
|
-
|
|
649
|
-
AI Actions represented different AI operations like:
|
|
650
|
-
|
|
651
|
-
- `chat`: General conversational AI
|
|
652
|
-
- `summarize`: Text summarization
|
|
653
|
-
- `classify`: Text classification
|
|
654
|
-
|
|
655
|
-
```typescript
|
|
656
|
-
// Deprecated - use AI Prompts instead
|
|
657
|
-
import { AIActionParams } from '@memberjunction/aiengine';
|
|
658
|
-
|
|
659
|
-
const params: AIActionParams = {
|
|
660
|
-
actionId: 'summarize-action-id',
|
|
661
|
-
modelId: 'gpt4-model-id',
|
|
662
|
-
systemPrompt: "You are a helpful assistant that creates concise summaries.",
|
|
663
|
-
userPrompt: "Summarize the following document: " + documentText
|
|
664
|
-
};
|
|
665
|
-
|
|
666
|
-
const result = await AIEngine.Instance.ExecuteAIAction(params);
|
|
667
|
-
console.log("Summary:", result.data?.choices[0]?.message?.content);
|
|
164
|
+
// Process uploaded attachments for a conversation
|
|
165
|
+
await service.ProcessAttachments(conversationId, attachments, contextUser);
|
|
668
166
|
```
|
|
669
167
|
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
**⚠️ DEPRECATED**: Entity AI Actions are deprecated in favor of AI Agents which provide better context management, learning capabilities, and entity integration.
|
|
673
|
-
|
|
674
|
-
Entity AI Actions connected AI actions to specific entity types, defining:
|
|
675
|
-
|
|
676
|
-
- Input preparation from entity records
|
|
677
|
-
- Output handling (save to fields or create related records)
|
|
678
|
-
- Default prompts and models to use
|
|
168
|
+
## Usage Pattern
|
|
679
169
|
|
|
680
170
|
```typescript
|
|
681
|
-
|
|
682
|
-
import { EntityAIActionParams } from '@memberjunction/aiengine';
|
|
683
|
-
import { Metadata } from '@memberjunction/core';
|
|
684
|
-
|
|
685
|
-
// Load an entity record
|
|
686
|
-
const md = new Metadata();
|
|
687
|
-
const customer = await md.GetEntityObject('Customers');
|
|
688
|
-
await customer.Load(customerId);
|
|
689
|
-
|
|
690
|
-
// Execute an AI action
|
|
691
|
-
const params: EntityAIActionParams = {
|
|
692
|
-
actionId: 'action-id-here',
|
|
693
|
-
modelId: 'model-id-here',
|
|
694
|
-
entityAIActionId: 'entity-action-id-here',
|
|
695
|
-
entityRecord: customer
|
|
696
|
-
};
|
|
697
|
-
|
|
698
|
-
const result = await AIEngine.Instance.ExecuteEntityAIAction(params);
|
|
699
|
-
|
|
700
|
-
if (result && result.success) {
|
|
701
|
-
console.log("AI processing completed successfully");
|
|
702
|
-
// The entity record has been updated if configured that way
|
|
703
|
-
} else {
|
|
704
|
-
console.error("Error:", result.errorMessage);
|
|
705
|
-
}
|
|
706
|
-
```
|
|
707
|
-
|
|
708
|
-
### Dynamic Prompt Generation (Legacy)
|
|
171
|
+
import { AIEngine } from '@memberjunction/aiengine';
|
|
709
172
|
|
|
710
|
-
|
|
173
|
+
// 1. Initialize at server startup
|
|
174
|
+
await AIEngine.Instance.Config(false, contextUser);
|
|
711
175
|
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
const
|
|
715
|
-
UserMessage: "Please summarize the customer profile for {Name} who works at {Company}."
|
|
716
|
-
};
|
|
176
|
+
// 2. Access metadata (delegated to AIEngineBase)
|
|
177
|
+
const model = AIEngine.Instance.Models.find(m => m.Name === 'GPT-4');
|
|
178
|
+
const agent = AIEngine.Instance.GetAgentByName('Sales Assistant');
|
|
717
179
|
|
|
718
|
-
//
|
|
719
|
-
|
|
180
|
+
// 3. Use server-side capabilities
|
|
181
|
+
const similar = await AIEngine.Instance.FindSimilarAgents(userQuery, 5, contextUser);
|
|
720
182
|
```
|
|
721
183
|
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
**⚠️ DEPRECATED**: Manual cache management methods are deprecated in favor of automatic caching through the prompt system.
|
|
184
|
+
## Dependencies
|
|
725
185
|
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
const result = await AIEngine.Instance.ExecuteAIAction(params);
|
|
735
|
-
await AIEngine.Instance.CacheResult(model, prompt, fullPromptText, result.data.choices[0].message.content);
|
|
736
|
-
```
|
|
186
|
+
- `@memberjunction/ai-engine-base` -- Base metadata cache (AIEngineBase)
|
|
187
|
+
- `@memberjunction/ai` -- Core AI abstractions (BaseLLM, BaseEmbeddings)
|
|
188
|
+
- `@memberjunction/ai-core-plus` -- Extended entity classes
|
|
189
|
+
- `@memberjunction/ai-vectors-memory` -- In-memory vector service for semantic search
|
|
190
|
+
- `@memberjunction/core` -- MJ framework core
|
|
191
|
+
- `@memberjunction/core-entities` -- Generated entity classes
|
|
192
|
+
- `@memberjunction/actions-base` -- Action framework integration
|
|
193
|
+
- `@memberjunction/storage` -- File storage integration for attachments
|