@memberjunction/ai-agents 5.33.0 → 5.34.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/dist/agent-pre-execution-rag.d.ts +149 -0
- package/dist/agent-pre-execution-rag.d.ts.map +1 -0
- package/dist/agent-pre-execution-rag.js +376 -0
- package/dist/agent-pre-execution-rag.js.map +1 -0
- package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts +24 -0
- package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts.map +1 -0
- package/dist/artifact-tools/SearchResultSetToolLibrary.js +320 -0
- package/dist/artifact-tools/SearchResultSetToolLibrary.js.map +1 -0
- package/dist/base-agent.d.ts +35 -0
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +82 -5
- package/dist/base-agent.js.map +1 -1
- 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/package.json +17 -15
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Agent pre-execution RAG — Phase 1C of plans/search-scopes-rag-plus.md.
|
|
3
|
+
*
|
|
4
|
+
* Runs in parallel with the rest of `BaseAgent.Execute()` Phase 2 to retrieve and inject
|
|
5
|
+
* scoped search context before the agent's first LLM call. Follows the same pattern as
|
|
6
|
+
* `AgentContextInjector` (notes/examples) so the two subsystems coexist cleanly:
|
|
7
|
+
*
|
|
8
|
+
* 1. Load the agent's active `AIAgentSearchScope` rows where Phase IN ('PreExecution','Both')
|
|
9
|
+
* and the row is within its Status + StartAt/EndAt window.
|
|
10
|
+
* 2. For each active scope, render the `QueryTemplateID` via MJ TemplateEngineServer
|
|
11
|
+
* (or fall back to `lastUserMessage`).
|
|
12
|
+
* 3. Call `SearchEngine.Search()` with `ScopeIDs: [scopeId]`, honoring per-agent overrides
|
|
13
|
+
* (MaxResults, MinScore, FusionWeightsOverride) and the agent's multi-tenant context
|
|
14
|
+
* (PrimaryScopeRecordID, SecondaryScopes).
|
|
15
|
+
* 4. Cross-scope RRF when multiple scopes produced results.
|
|
16
|
+
* 5. Format results as a `<retrieved_context>` system message and return.
|
|
17
|
+
*
|
|
18
|
+
* @module @memberjunction/ai-agents
|
|
19
|
+
*/
|
|
20
|
+
import { UserInfo } from '@memberjunction/core';
|
|
21
|
+
import { MJAIAgentEntity, MJAIAgentSearchScopeEntity } from '@memberjunction/core-entities';
|
|
22
|
+
import { SearchResultItem, SearchContext } from '@memberjunction/search-engine';
|
|
23
|
+
import { ChatMessage } from '@memberjunction/ai';
|
|
24
|
+
import { SecondaryScopeValue } from '@memberjunction/ai-core-plus';
|
|
25
|
+
/**
|
|
26
|
+
* Parameters for executing pre-execution RAG for an agent.
|
|
27
|
+
*/
|
|
28
|
+
export interface AgentPreExecutionRAGParams {
|
|
29
|
+
/** The agent currently being executed. */
|
|
30
|
+
agent: MJAIAgentEntity;
|
|
31
|
+
/** The most recent user message — used as the default query when no template is configured. */
|
|
32
|
+
lastUserMessage: string;
|
|
33
|
+
/** Optional recent messages (role + content) for template rendering. */
|
|
34
|
+
recentMessages?: ChatMessage[];
|
|
35
|
+
/** Optional conversation summary. */
|
|
36
|
+
conversationSummary?: string;
|
|
37
|
+
/** Agent's current payload state. Available to templates under `payload`. */
|
|
38
|
+
payload?: unknown;
|
|
39
|
+
/** Multi-tenant primary scope record ID (flows into `SearchContext.PrimaryScopeRecordID`). */
|
|
40
|
+
primaryScopeRecordId?: string;
|
|
41
|
+
/** Multi-tenant primary scope entity ID. */
|
|
42
|
+
primaryScopeEntityId?: string;
|
|
43
|
+
/** Multi-tenant secondary scope dimensions. */
|
|
44
|
+
secondaryScopes?: Record<string, SecondaryScopeValue>;
|
|
45
|
+
/** Calling user — threaded through to SearchEngine + Metadata. */
|
|
46
|
+
contextUser: UserInfo;
|
|
47
|
+
/**
|
|
48
|
+
* Phase 2C: when true, consume SearchEngine.streamSearch() instead of
|
|
49
|
+
* the synchronous Search() per scope. The final aggregate is identical
|
|
50
|
+
* — what changes is that intermediate provider traces are written to
|
|
51
|
+
* `streamingTrace` (when supplied) so the agent's pre-execution
|
|
52
|
+
* scratchpad can show "while you wait" progress. Default false.
|
|
53
|
+
*/
|
|
54
|
+
streamingEnabled?: boolean;
|
|
55
|
+
/**
|
|
56
|
+
* Optional sink for streamingEnabled traces. Caller pushes nothing
|
|
57
|
+
* itself — the RAG hook appends one markdown line per provider event
|
|
58
|
+
* per scope. Caller decides what to do with the lines (typically
|
|
59
|
+
* concat into the agent's pre-prompt scratchpad).
|
|
60
|
+
*/
|
|
61
|
+
streamingTrace?: string[];
|
|
62
|
+
}
|
|
63
|
+
/** Structured result of a single scope's search, used for formatting + artifact persistence. */
|
|
64
|
+
export interface ScopeSearchResult {
|
|
65
|
+
scopeID: string;
|
|
66
|
+
scopeName: string;
|
|
67
|
+
scopeDescription: string | null;
|
|
68
|
+
scopeIcon: string | null;
|
|
69
|
+
query: string;
|
|
70
|
+
results: SearchResultItem[];
|
|
71
|
+
minScore: number;
|
|
72
|
+
}
|
|
73
|
+
/** Final aggregate result of `AgentPreExecutionRAG.Execute()`. */
|
|
74
|
+
export interface AgentPreExecutionRAGResult {
|
|
75
|
+
/** Formatted `<retrieved_context>` system-message content ready for `unshift()`. */
|
|
76
|
+
formattedSystemMessage: string;
|
|
77
|
+
/** Per-scope result detail (for observability + artifact persistence). */
|
|
78
|
+
perScopeResults: ScopeSearchResult[];
|
|
79
|
+
/** Cross-scope fused result list (deduped, truncated). */
|
|
80
|
+
combinedResults: SearchResultItem[];
|
|
81
|
+
/** Combined search context passed into the engine. */
|
|
82
|
+
searchContext?: SearchContext;
|
|
83
|
+
/** Scope IDs actually queried (inactive/expired ones dropped). */
|
|
84
|
+
queriedScopeIDs: string[];
|
|
85
|
+
/** Raw agent-scope rows used (for debugging). */
|
|
86
|
+
agentScopeRows: MJAIAgentSearchScopeEntity[];
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Orchestrator for agent pre-execution RAG. Stateless — create a fresh instance per call.
|
|
90
|
+
*/
|
|
91
|
+
export declare class AgentPreExecutionRAG {
|
|
92
|
+
/**
|
|
93
|
+
* Main entry point. Returns a filled-in `AgentPreExecutionRAGResult` when the agent
|
|
94
|
+
* has any active PreExecution/Both scopes; otherwise returns `null` so callers can
|
|
95
|
+
* skip injection entirely.
|
|
96
|
+
*/
|
|
97
|
+
Execute(params: AgentPreExecutionRAGParams): Promise<AgentPreExecutionRAGResult | null>;
|
|
98
|
+
/**
|
|
99
|
+
* Load active PreExecution/Both AIAgentSearchScope rows for the agent,
|
|
100
|
+
* sorted by Priority ascending (lower number = higher priority).
|
|
101
|
+
*/
|
|
102
|
+
private loadActiveAgentScopeRows;
|
|
103
|
+
/**
|
|
104
|
+
* Resolve + render the query for one agent-scope row, run the search
|
|
105
|
+
* (sync or streaming), and shape the per-scope result. Returns null when
|
|
106
|
+
* the row is unusable (inactive scope, empty query, search failure, or
|
|
107
|
+
* empty result set) — the caller decides whether to keep iterating.
|
|
108
|
+
*/
|
|
109
|
+
private searchOneAgentScope;
|
|
110
|
+
/**
|
|
111
|
+
* Phase 2C streaming-mode helper — consume `SearchEngine.streamSearch()`
|
|
112
|
+
* and shape the events back into a `SearchResult` so the rest of the
|
|
113
|
+
* pipeline doesn't need to know about streaming. Per-provider trace
|
|
114
|
+
* lines are appended to `params.streamingTrace` (markdown over JSON,
|
|
115
|
+
* per RAG_plan §2.2) so the agent's pre-prompt scratchpad can show
|
|
116
|
+
* "while you wait" progress.
|
|
117
|
+
*/
|
|
118
|
+
private streamSearchOneScope;
|
|
119
|
+
/**
|
|
120
|
+
* Cross-scope reciprocal rank fusion — when 2+ scopes contributed, run
|
|
121
|
+
* RRF + dedup so the merged list reflects each scope's contribution.
|
|
122
|
+
* Single-scope cases skip fusion and return the only result list directly.
|
|
123
|
+
*/
|
|
124
|
+
private combineAcrossScopes;
|
|
125
|
+
/**
|
|
126
|
+
* Shape the result into a Data-Snapshot-compatible payload so `ProcessAgentArtifacts`
|
|
127
|
+
* can persist it as a `Search Result Set` artifact. See Section 6.3 of the plan.
|
|
128
|
+
* Returns `undefined` when there is nothing to persist.
|
|
129
|
+
*/
|
|
130
|
+
BuildArtifactPayload(result: AgentPreExecutionRAGResult): Record<string, unknown> | undefined;
|
|
131
|
+
/**
|
|
132
|
+
* Resolve the search query for one scope. If the agent-scope row has a QueryTemplateID,
|
|
133
|
+
* render it via `TemplateEngineServer`. Otherwise fall back to `lastUserMessage`.
|
|
134
|
+
*/
|
|
135
|
+
private resolveQuery;
|
|
136
|
+
/**
|
|
137
|
+
* Load a Template entity + its highest-priority content row.
|
|
138
|
+
* Uses the cached `TemplateEngineServer.FindTemplate` when available; falls back to a
|
|
139
|
+
* direct RunView when not.
|
|
140
|
+
*/
|
|
141
|
+
private loadTemplate;
|
|
142
|
+
private parseFusionWeights;
|
|
143
|
+
/**
|
|
144
|
+
* Format the per-scope results into a `<retrieved_context>` system-message block.
|
|
145
|
+
* Matches the shape documented in Section 4.2 of the plan.
|
|
146
|
+
*/
|
|
147
|
+
private formatAsSystemMessage;
|
|
148
|
+
}
|
|
149
|
+
//# sourceMappingURL=agent-pre-execution-rag.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-pre-execution-rag.d.ts","sourceRoot":"","sources":["../src/agent-pre-execution-rag.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAgC,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EACH,eAAe,EACf,0BAA0B,EAK7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEH,gBAAgB,EAChB,aAAa,EAGhB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAEnE;;GAEG;AACH,MAAM,WAAW,0BAA0B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cAAc,EAAE,0BAA0B,EAAE,CAAC;CAChD;AAED;;GAEG;AACH,qBAAa,oBAAoB;IAC7B;;;;OAIG;IACU,OAAO,CAAC,MAAM,EAAE,0BAA0B,GAAG,OAAO,CAAC,0BAA0B,GAAG,IAAI,CAAC;IAuCpG;;;OAGG;IACH,OAAO,CAAC,wBAAwB;IAKhC;;;;;OAKG;YACW,mBAAmB;IA0DjC;;;;;;;OAOG;YACW,oBAAoB;IA+ClC;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;IAS3B;;;;OAIG;IACI,oBAAoB,CACvB,MAAM,EAAE,0BAA0B,GACnC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS;IAuDtC;;;OAGG;YACW,YAAY;IAsC1B;;;;OAIG;YACW,YAAY;IAoC1B,OAAO,CAAC,kBAAkB;IAe1B;;;OAGG;IACH,OAAO,CAAC,qBAAqB;CA2BhC"}
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Agent pre-execution RAG — Phase 1C of plans/search-scopes-rag-plus.md.
|
|
3
|
+
*
|
|
4
|
+
* Runs in parallel with the rest of `BaseAgent.Execute()` Phase 2 to retrieve and inject
|
|
5
|
+
* scoped search context before the agent's first LLM call. Follows the same pattern as
|
|
6
|
+
* `AgentContextInjector` (notes/examples) so the two subsystems coexist cleanly:
|
|
7
|
+
*
|
|
8
|
+
* 1. Load the agent's active `AIAgentSearchScope` rows where Phase IN ('PreExecution','Both')
|
|
9
|
+
* and the row is within its Status + StartAt/EndAt window.
|
|
10
|
+
* 2. For each active scope, render the `QueryTemplateID` via MJ TemplateEngineServer
|
|
11
|
+
* (or fall back to `lastUserMessage`).
|
|
12
|
+
* 3. Call `SearchEngine.Search()` with `ScopeIDs: [scopeId]`, honoring per-agent overrides
|
|
13
|
+
* (MaxResults, MinScore, FusionWeightsOverride) and the agent's multi-tenant context
|
|
14
|
+
* (PrimaryScopeRecordID, SecondaryScopes).
|
|
15
|
+
* 4. Cross-scope RRF when multiple scopes produced results.
|
|
16
|
+
* 5. Format results as a `<retrieved_context>` system message and return.
|
|
17
|
+
*
|
|
18
|
+
* @module @memberjunction/ai-agents
|
|
19
|
+
*/
|
|
20
|
+
import { LogError, LogStatus, RunView } from '@memberjunction/core';
|
|
21
|
+
import { SearchEngineBase, } from '@memberjunction/core-entities';
|
|
22
|
+
import { SearchEngine, SearchFusion, } from '@memberjunction/search-engine';
|
|
23
|
+
import { TemplateEngineServer } from '@memberjunction/templates';
|
|
24
|
+
/**
|
|
25
|
+
* Orchestrator for agent pre-execution RAG. Stateless — create a fresh instance per call.
|
|
26
|
+
*/
|
|
27
|
+
export class AgentPreExecutionRAG {
|
|
28
|
+
/**
|
|
29
|
+
* Main entry point. Returns a filled-in `AgentPreExecutionRAGResult` when the agent
|
|
30
|
+
* has any active PreExecution/Both scopes; otherwise returns `null` so callers can
|
|
31
|
+
* skip injection entirely.
|
|
32
|
+
*/
|
|
33
|
+
async Execute(params) {
|
|
34
|
+
if (!params.agent?.ID)
|
|
35
|
+
return null;
|
|
36
|
+
await SearchEngineBase.Instance.Config(false, params.contextUser);
|
|
37
|
+
// 1. Load active PreExecution/Both scope rows for this agent (sorted by priority)
|
|
38
|
+
const agentScopeRows = this.loadActiveAgentScopeRows(params.agent.ID);
|
|
39
|
+
if (agentScopeRows.length === 0)
|
|
40
|
+
return null;
|
|
41
|
+
const searchContext = {
|
|
42
|
+
PrimaryScopeEntityID: params.primaryScopeEntityId,
|
|
43
|
+
PrimaryScopeRecordID: params.primaryScopeRecordId,
|
|
44
|
+
SecondaryScopes: params.secondaryScopes
|
|
45
|
+
};
|
|
46
|
+
const hasContext = !!(searchContext.PrimaryScopeRecordID || (searchContext.SecondaryScopes && Object.keys(searchContext.SecondaryScopes).length > 0));
|
|
47
|
+
// 2–3. For each agent-scope row, render the query and run scoped search.
|
|
48
|
+
const perScopeResults = [];
|
|
49
|
+
for (const row of agentScopeRows) {
|
|
50
|
+
const r = await this.searchOneAgentScope(row, params, searchContext, hasContext);
|
|
51
|
+
if (r)
|
|
52
|
+
perScopeResults.push(r);
|
|
53
|
+
}
|
|
54
|
+
if (perScopeResults.length === 0)
|
|
55
|
+
return null;
|
|
56
|
+
// 4. Cross-scope RRF when multiple scopes contributed
|
|
57
|
+
const combined = this.combineAcrossScopes(perScopeResults);
|
|
58
|
+
// 5. Format for system-message injection
|
|
59
|
+
const formatted = this.formatAsSystemMessage(perScopeResults);
|
|
60
|
+
return {
|
|
61
|
+
formattedSystemMessage: formatted,
|
|
62
|
+
perScopeResults,
|
|
63
|
+
combinedResults: combined,
|
|
64
|
+
searchContext: hasContext ? searchContext : undefined,
|
|
65
|
+
queriedScopeIDs: perScopeResults.map(s => s.scopeID),
|
|
66
|
+
agentScopeRows
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Load active PreExecution/Both AIAgentSearchScope rows for the agent,
|
|
71
|
+
* sorted by Priority ascending (lower number = higher priority).
|
|
72
|
+
*/
|
|
73
|
+
loadActiveAgentScopeRows(agentID) {
|
|
74
|
+
const rows = SearchEngineBase.Instance.GetAgentScopes(agentID, 'PreExecution');
|
|
75
|
+
return [...rows].sort((a, b) => a.Priority - b.Priority);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Resolve + render the query for one agent-scope row, run the search
|
|
79
|
+
* (sync or streaming), and shape the per-scope result. Returns null when
|
|
80
|
+
* the row is unusable (inactive scope, empty query, search failure, or
|
|
81
|
+
* empty result set) — the caller decides whether to keep iterating.
|
|
82
|
+
*/
|
|
83
|
+
async searchOneAgentScope(row, params, searchContext, hasContext) {
|
|
84
|
+
const scope = SearchEngineBase.Instance.GetActiveScopeByID(row.SearchScopeID);
|
|
85
|
+
if (!scope) {
|
|
86
|
+
LogStatus(`AgentPreExecutionRAG: Scope "${row.SearchScopeID}" not active — skipping.`);
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
const query = await this.resolveQuery(row, scope, params);
|
|
90
|
+
if (!query || !query.trim())
|
|
91
|
+
return null;
|
|
92
|
+
const fusionWeights = this.parseFusionWeights(row.FusionWeightsOverride);
|
|
93
|
+
const minScore = row.MinScore ?? 0;
|
|
94
|
+
const maxResults = row.MaxResults ?? 10;
|
|
95
|
+
try {
|
|
96
|
+
const sr = params.streamingEnabled
|
|
97
|
+
? await this.streamSearchOneScope({ scope, query, maxResults, minScore, fusionWeights, searchContext, hasContext, params })
|
|
98
|
+
: await SearchEngine.Instance.Search({
|
|
99
|
+
Query: query,
|
|
100
|
+
MaxResults: maxResults,
|
|
101
|
+
MinScore: minScore,
|
|
102
|
+
ScopeIDs: [scope.ID],
|
|
103
|
+
SearchContext: hasContext ? searchContext : undefined,
|
|
104
|
+
FusionWeightsOverride: fusionWeights,
|
|
105
|
+
Mode: 'full',
|
|
106
|
+
// P3.2 — thread AIAgentID so SearchExecutionLog rows
|
|
107
|
+
// attribute pre-execution RAG searches to the calling
|
|
108
|
+
// agent. Without this, the analytics dashboard's "top
|
|
109
|
+
// searches by agent" view is blind to the RAG path.
|
|
110
|
+
AIAgentID: params.agent.ID,
|
|
111
|
+
}, params.contextUser);
|
|
112
|
+
if (sr.Success && sr.Results.length > 0) {
|
|
113
|
+
return {
|
|
114
|
+
scopeID: scope.ID,
|
|
115
|
+
scopeName: scope.Name,
|
|
116
|
+
scopeDescription: scope.Description,
|
|
117
|
+
scopeIcon: scope.Icon,
|
|
118
|
+
query,
|
|
119
|
+
results: sr.Results,
|
|
120
|
+
minScore,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
if (!sr.Success) {
|
|
124
|
+
LogError(`AgentPreExecutionRAG: Search in scope "${scope.Name}" failed: ${sr.ErrorMessage}`);
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
130
|
+
LogError(`AgentPreExecutionRAG: Exception searching scope "${scope.Name}": ${msg}`);
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Phase 2C streaming-mode helper — consume `SearchEngine.streamSearch()`
|
|
136
|
+
* and shape the events back into a `SearchResult` so the rest of the
|
|
137
|
+
* pipeline doesn't need to know about streaming. Per-provider trace
|
|
138
|
+
* lines are appended to `params.streamingTrace` (markdown over JSON,
|
|
139
|
+
* per RAG_plan §2.2) so the agent's pre-prompt scratchpad can show
|
|
140
|
+
* "while you wait" progress.
|
|
141
|
+
*/
|
|
142
|
+
async streamSearchOneScope(input) {
|
|
143
|
+
let finalResults = [];
|
|
144
|
+
let sourceCounts = { Vector: 0, FullText: 0, Entity: 0, Storage: 0 };
|
|
145
|
+
let elapsedMs = 0;
|
|
146
|
+
let errorMsg;
|
|
147
|
+
const traces = [];
|
|
148
|
+
for await (const ev of SearchEngine.Instance.streamSearch({
|
|
149
|
+
Query: input.query,
|
|
150
|
+
MaxResults: input.maxResults,
|
|
151
|
+
MinScore: input.minScore,
|
|
152
|
+
ScopeIDs: [input.scope.ID],
|
|
153
|
+
SearchContext: input.hasContext ? input.searchContext : undefined,
|
|
154
|
+
FusionWeightsOverride: input.fusionWeights,
|
|
155
|
+
Mode: 'full',
|
|
156
|
+
AIAgentID: input.params.agent.ID,
|
|
157
|
+
}, input.params.contextUser)) {
|
|
158
|
+
if (ev.phase === 'provider') {
|
|
159
|
+
traces.push(`### Provider \`${ev.providerName}\` returned ${ev.results.length} rows in ${ev.durationMs}ms`);
|
|
160
|
+
}
|
|
161
|
+
else if (ev.phase === 'final') {
|
|
162
|
+
finalResults = ev.results;
|
|
163
|
+
sourceCounts = ev.sourceCounts;
|
|
164
|
+
elapsedMs = ev.elapsedMs;
|
|
165
|
+
}
|
|
166
|
+
else if (ev.phase === 'error') {
|
|
167
|
+
errorMsg = ev.error;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (input.params.streamingTrace)
|
|
171
|
+
input.params.streamingTrace.push(...traces);
|
|
172
|
+
return {
|
|
173
|
+
Success: !errorMsg,
|
|
174
|
+
Results: finalResults,
|
|
175
|
+
TotalCount: finalResults.length,
|
|
176
|
+
ElapsedMs: elapsedMs,
|
|
177
|
+
SourceCounts: sourceCounts,
|
|
178
|
+
Providers: [],
|
|
179
|
+
ErrorMessage: errorMsg,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Cross-scope reciprocal rank fusion — when 2+ scopes contributed, run
|
|
184
|
+
* RRF + dedup so the merged list reflects each scope's contribution.
|
|
185
|
+
* Single-scope cases skip fusion and return the only result list directly.
|
|
186
|
+
*/
|
|
187
|
+
combineAcrossScopes(perScopeResults) {
|
|
188
|
+
if (perScopeResults.length === 1)
|
|
189
|
+
return perScopeResults[0].results;
|
|
190
|
+
const fusion = new SearchFusion();
|
|
191
|
+
const map = new Map();
|
|
192
|
+
for (const s of perScopeResults)
|
|
193
|
+
map.set(s.scopeID, s.results);
|
|
194
|
+
const maxAcrossScopes = Math.max(...perScopeResults.map(s => s.results.length));
|
|
195
|
+
return fusion.Deduplicate(fusion.CrossScopeFusion(map, Math.max(10, maxAcrossScopes)));
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Shape the result into a Data-Snapshot-compatible payload so `ProcessAgentArtifacts`
|
|
199
|
+
* can persist it as a `Search Result Set` artifact. See Section 6.3 of the plan.
|
|
200
|
+
* Returns `undefined` when there is nothing to persist.
|
|
201
|
+
*/
|
|
202
|
+
BuildArtifactPayload(result) {
|
|
203
|
+
if (!result || result.combinedResults.length === 0)
|
|
204
|
+
return undefined;
|
|
205
|
+
const rows = result.combinedResults.map(r => ({
|
|
206
|
+
id: r.ID,
|
|
207
|
+
recordID: r.RecordID,
|
|
208
|
+
entity: r.EntityName,
|
|
209
|
+
title: r.Title,
|
|
210
|
+
snippet: r.Snippet,
|
|
211
|
+
score: r.Score,
|
|
212
|
+
source: r.SourceType,
|
|
213
|
+
tags: r.Tags,
|
|
214
|
+
matchedAt: r.MatchedAt?.toISOString?.() ?? null,
|
|
215
|
+
scopeID: r.ProviderId
|
|
216
|
+
}));
|
|
217
|
+
return {
|
|
218
|
+
title: `Pre-execution RAG (${result.queriedScopeIDs.length} scope(s))`,
|
|
219
|
+
tables: [
|
|
220
|
+
{
|
|
221
|
+
name: 'results',
|
|
222
|
+
description: 'Ranked search results after per-scope and cross-scope RRF fusion.',
|
|
223
|
+
source: 'search',
|
|
224
|
+
columns: [
|
|
225
|
+
{ field: 'id', displayName: 'ID', sqlBaseType: 'nvarchar' },
|
|
226
|
+
{ field: 'recordID', displayName: 'Record ID', sqlBaseType: 'uniqueidentifier' },
|
|
227
|
+
{ field: 'entity', displayName: 'Entity', sqlBaseType: 'nvarchar' },
|
|
228
|
+
{ field: 'title', displayName: 'Title', sqlBaseType: 'nvarchar' },
|
|
229
|
+
{ field: 'snippet', displayName: 'Snippet', sqlBaseType: 'nvarchar' },
|
|
230
|
+
{ field: 'score', displayName: 'Score', sqlBaseType: 'decimal', isSummary: true },
|
|
231
|
+
{ field: 'source', displayName: 'Source', sqlBaseType: 'nvarchar' },
|
|
232
|
+
{ field: 'tags', displayName: 'Tags', sqlBaseType: 'nvarchar' },
|
|
233
|
+
{ field: 'matchedAt', displayName: 'Matched At', sqlBaseType: 'datetimeoffset' },
|
|
234
|
+
{ field: 'scopeID', displayName: 'Scope', sqlBaseType: 'uniqueidentifier' }
|
|
235
|
+
],
|
|
236
|
+
rows,
|
|
237
|
+
sorting: [{ field: 'score', direction: 'desc' }],
|
|
238
|
+
metadata: { rowCount: rows.length }
|
|
239
|
+
}
|
|
240
|
+
],
|
|
241
|
+
computations: [
|
|
242
|
+
{ name: 'Total Results', type: 'count', value: rows.length, formattedValue: String(rows.length) },
|
|
243
|
+
{ name: 'Top Score', type: 'max', field: 'score', value: rows[0]?.score ?? 0 }
|
|
244
|
+
],
|
|
245
|
+
interpretation: `Retrieved ${rows.length} result(s) across ${result.queriedScopeIDs.length} scope(s) during pre-execution RAG.`,
|
|
246
|
+
scopeIDs: result.queriedScopeIDs,
|
|
247
|
+
queries: result.perScopeResults.map(s => ({ scopeID: s.scopeID, scopeName: s.scopeName, query: s.query })),
|
|
248
|
+
searchContext: result.searchContext,
|
|
249
|
+
searchedAt: new Date().toISOString()
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
// ────────────────────────────────────────────────────────────────
|
|
253
|
+
// Query resolution
|
|
254
|
+
// ────────────────────────────────────────────────────────────────
|
|
255
|
+
/**
|
|
256
|
+
* Resolve the search query for one scope. If the agent-scope row has a QueryTemplateID,
|
|
257
|
+
* render it via `TemplateEngineServer`. Otherwise fall back to `lastUserMessage`.
|
|
258
|
+
*/
|
|
259
|
+
async resolveQuery(row, scope, params) {
|
|
260
|
+
if (!row.QueryTemplateID)
|
|
261
|
+
return params.lastUserMessage;
|
|
262
|
+
try {
|
|
263
|
+
const tmpl = await this.loadTemplate(row.QueryTemplateID, params.contextUser);
|
|
264
|
+
if (!tmpl)
|
|
265
|
+
return params.lastUserMessage;
|
|
266
|
+
const content = tmpl.template.GetHighestPriorityContent?.() ?? tmpl.content;
|
|
267
|
+
if (!content)
|
|
268
|
+
return params.lastUserMessage;
|
|
269
|
+
const data = {
|
|
270
|
+
lastUserMessage: params.lastUserMessage,
|
|
271
|
+
recentMessages: params.recentMessages ?? [],
|
|
272
|
+
conversationSummary: params.conversationSummary ?? '',
|
|
273
|
+
payload: params.payload ?? {},
|
|
274
|
+
agentName: params.agent.Name,
|
|
275
|
+
agentDescription: params.agent.Description ?? '',
|
|
276
|
+
scopeName: scope.Name,
|
|
277
|
+
scopeDescription: scope.Description ?? ''
|
|
278
|
+
};
|
|
279
|
+
const rendered = await TemplateEngineServer.Instance.RenderTemplate(tmpl.template, content, data);
|
|
280
|
+
if (rendered?.Success && rendered.Output) {
|
|
281
|
+
return rendered.Output.trim();
|
|
282
|
+
}
|
|
283
|
+
LogError(`AgentPreExecutionRAG: Template "${row.QueryTemplateID}" render failed: ${rendered?.Message ?? 'unknown'}`);
|
|
284
|
+
return params.lastUserMessage;
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
288
|
+
LogError(`AgentPreExecutionRAG: Template "${row.QueryTemplateID}" exception: ${msg}`);
|
|
289
|
+
return params.lastUserMessage;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Load a Template entity + its highest-priority content row.
|
|
294
|
+
* Uses the cached `TemplateEngineServer.FindTemplate` when available; falls back to a
|
|
295
|
+
* direct RunView when not.
|
|
296
|
+
*/
|
|
297
|
+
async loadTemplate(templateID, contextUser) {
|
|
298
|
+
try {
|
|
299
|
+
await TemplateEngineServer.Instance.Config(false, contextUser);
|
|
300
|
+
const t = TemplateEngineServer.Instance.FindTemplate?.(templateID);
|
|
301
|
+
if (t) {
|
|
302
|
+
const content = t.GetHighestPriorityContent?.() ?? null;
|
|
303
|
+
return { template: t, content };
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
// fall through to RunView
|
|
308
|
+
}
|
|
309
|
+
const rv = new RunView();
|
|
310
|
+
const tResult = await rv.RunView({
|
|
311
|
+
EntityName: 'Templates',
|
|
312
|
+
ExtraFilter: `ID='${templateID}'`,
|
|
313
|
+
ResultType: 'entity_object'
|
|
314
|
+
}, contextUser);
|
|
315
|
+
if (!tResult.Success || tResult.Results.length === 0)
|
|
316
|
+
return null;
|
|
317
|
+
const template = tResult.Results[0];
|
|
318
|
+
const cResult = await rv.RunView({
|
|
319
|
+
EntityName: 'Template Contents',
|
|
320
|
+
ExtraFilter: `TemplateID='${templateID}'`,
|
|
321
|
+
OrderBy: 'Priority DESC, __mj_CreatedAt ASC',
|
|
322
|
+
MaxRows: 1,
|
|
323
|
+
ResultType: 'entity_object'
|
|
324
|
+
}, contextUser);
|
|
325
|
+
const content = cResult.Success && cResult.Results.length > 0 ? cResult.Results[0] : null;
|
|
326
|
+
return { template, content };
|
|
327
|
+
}
|
|
328
|
+
parseFusionWeights(raw) {
|
|
329
|
+
if (!raw)
|
|
330
|
+
return undefined;
|
|
331
|
+
try {
|
|
332
|
+
const parsed = JSON.parse(raw);
|
|
333
|
+
if (parsed && typeof parsed === 'object')
|
|
334
|
+
return parsed;
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
LogError(`AgentPreExecutionRAG: Invalid FusionWeightsOverride JSON — ignoring: ${raw.substring(0, 120)}`);
|
|
338
|
+
}
|
|
339
|
+
return undefined;
|
|
340
|
+
}
|
|
341
|
+
// ────────────────────────────────────────────────────────────────
|
|
342
|
+
// Output formatting
|
|
343
|
+
// ────────────────────────────────────────────────────────────────
|
|
344
|
+
/**
|
|
345
|
+
* Format the per-scope results into a `<retrieved_context>` system-message block.
|
|
346
|
+
* Matches the shape documented in Section 4.2 of the plan.
|
|
347
|
+
*/
|
|
348
|
+
formatAsSystemMessage(perScope) {
|
|
349
|
+
const lines = [];
|
|
350
|
+
lines.push('<retrieved_context>');
|
|
351
|
+
lines.push('The following information was retrieved from your configured knowledge scopes based on the current conversation.');
|
|
352
|
+
lines.push('Use this context to inform your response. If the retrieved information conflicts with your training data, prefer the retrieved information — it may be more current or tenant-specific.');
|
|
353
|
+
lines.push('');
|
|
354
|
+
let globalIndex = 1;
|
|
355
|
+
for (const s of perScope) {
|
|
356
|
+
const header = `--- Results from "${s.scopeName}" (${s.results.length} result(s)${s.minScore > 0 ? `, min score ${s.minScore.toFixed(2)}` : ''}) ---`;
|
|
357
|
+
lines.push(header);
|
|
358
|
+
if (s.scopeDescription)
|
|
359
|
+
lines.push(`(${s.scopeDescription})`);
|
|
360
|
+
lines.push('');
|
|
361
|
+
for (const r of s.results) {
|
|
362
|
+
const titleLine = `${globalIndex}. [${r.Title || r.RecordID}] (score: ${r.Score.toFixed(2)}, source: ${r.SourceType}${r.EntityName ? `, entity: ${r.EntityName}` : ''})`;
|
|
363
|
+
lines.push(titleLine);
|
|
364
|
+
if (r.Snippet)
|
|
365
|
+
lines.push(` ${r.Snippet}`);
|
|
366
|
+
if (r.Tags && r.Tags.length)
|
|
367
|
+
lines.push(` tags: ${r.Tags.join(', ')}`);
|
|
368
|
+
lines.push('');
|
|
369
|
+
globalIndex++;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
lines.push('</retrieved_context>');
|
|
373
|
+
return lines.join('\n');
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
//# sourceMappingURL=agent-pre-execution-rag.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-pre-execution-rag.js","sourceRoot":"","sources":["../src/agent-pre-execution-rag.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAY,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EAGH,gBAAgB,GAInB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACH,YAAY,EAIZ,YAAY,GACf,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAsEjE;;GAEG;AACH,MAAM,OAAO,oBAAoB;IAC7B;;;;OAIG;IACI,KAAK,CAAC,OAAO,CAAC,MAAkC;QACnD,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE;YAAE,OAAO,IAAI,CAAC;QACnC,MAAM,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC;QAElE,kFAAkF;QAClF,MAAM,cAAc,GAAG,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACtE,IAAI,cAAc,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAE7C,MAAM,aAAa,GAAkB;YACjC,oBAAoB,EAAE,MAAM,CAAC,oBAAoB;YACj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,IAAI,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBACzE,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBACf,WAAW,EAAE,CAAC;YAClB,CAAC;QACL,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;QACnC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;CACJ"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { BaseArtifactToolLibrary, type ArtifactToolDefinition, type ArtifactToolResult } from '@memberjunction/ai-core-plus';
|
|
2
|
+
/**
|
|
3
|
+
* Register the library so the ArtifactToolManager can resolve it by the
|
|
4
|
+
* artifact type's ToolLibraryClass column ('SearchResultSetToolLibrary').
|
|
5
|
+
*/
|
|
6
|
+
export declare class SearchResultSetToolLibrary extends BaseArtifactToolLibrary {
|
|
7
|
+
/**
|
|
8
|
+
* Tools provided in addition to whatever the parent chain (DataSnapshot
|
|
9
|
+
* → Data → ...) supplies. Naming and shape mirror the spec's mockup #5.
|
|
10
|
+
*/
|
|
11
|
+
GetToolList(): ArtifactToolDefinition[];
|
|
12
|
+
InvokeTool(toolName: string, input: Record<string, unknown>, artifactContent: string | Buffer): Promise<ArtifactToolResult>;
|
|
13
|
+
private filterByScore;
|
|
14
|
+
private groupBySourceProvider;
|
|
15
|
+
private getMatchingChunks;
|
|
16
|
+
private followSourceLink;
|
|
17
|
+
private rerankInline;
|
|
18
|
+
/** Strip internal UUID before handing a row to the LLM. */
|
|
19
|
+
private toAgentRow;
|
|
20
|
+
}
|
|
21
|
+
/** Tree-shake-prevention hook. Call from consumer index to ensure the
|
|
22
|
+
* @RegisterClass side-effect runs. */
|
|
23
|
+
export declare function LoadSearchResultSetToolLibrary(): void;
|
|
24
|
+
//# sourceMappingURL=SearchResultSetToolLibrary.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SearchResultSetToolLibrary.d.ts","sourceRoot":"","sources":["../../src/artifact-tools/SearchResultSetToolLibrary.ts"],"names":[],"mappings":"AAqBA,OAAO,EACH,uBAAuB,EACvB,KAAK,sBAAsB,EAC3B,KAAK,kBAAkB,EAC1B,MAAM,8BAA8B,CAAC;AAkJtC;;;GAGG;AACH,qBACa,0BAA2B,SAAQ,uBAAuB;IACnE;;;OAGG;IACH,WAAW,IAAI,sBAAsB,EAAE;IA0DjC,UAAU,CACZ,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,eAAe,EAAE,MAAM,GAAG,MAAM,GACjC,OAAO,CAAC,kBAAkB,CAAC;IAqB9B,OAAO,CAAC,aAAa;IAgBrB,OAAO,CAAC,qBAAqB;IA4B7B,OAAO,CAAC,iBAAiB;IAiBzB,OAAO,CAAC,gBAAgB;IAwBxB,OAAO,CAAC,YAAY;IAsBpB,2DAA2D;IAC3D,OAAO,CAAC,UAAU;CAOrB;AAED;sCACsC;AACtC,wBAAgB,8BAA8B,IAAI,IAAI,CAGrD"}
|