@shashu-ai/sdk 1.1.1 → 1.3.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/CHANGELOG.md +72 -42
- package/NOTICE +1 -1
- package/README.md +43 -9
- package/package.json +4 -5
- package/dist/_joiner-DGi8GsY7.d.cts +0 -38
- package/dist/_joiner-DGi8GsY7.d.ts +0 -38
- package/dist/chunk-3GAMCQ6R.js +0 -74
- package/dist/chunk-3JZXUKNA.js +0 -40
- package/dist/chunk-3X5IUBIA.js +0 -71
- package/dist/chunk-F4CXDZQB.js +0 -330
- package/dist/chunk-M7EMWSNS.js +0 -530
- package/dist/chunk-TGD6KDWT.js +0 -800
- package/dist/index.cjs +0 -2567
- package/dist/index.d.cts +0 -748
- package/dist/index.d.ts +0 -748
- package/dist/index.js +0 -974
- package/dist/langchain-DKyrUjk4.d.cts +0 -322
- package/dist/langchain-QCATTIR4.d.ts +0 -322
- package/dist/middleware/anthropic.cjs +0 -930
- package/dist/middleware/anthropic.d.cts +0 -49
- package/dist/middleware/anthropic.d.ts +0 -49
- package/dist/middleware/anthropic.js +0 -10
- package/dist/middleware/google.cjs +0 -530
- package/dist/middleware/google.d.cts +0 -71
- package/dist/middleware/google.d.ts +0 -71
- package/dist/middleware/google.js +0 -9
- package/dist/middleware/langchain.cjs +0 -1329
- package/dist/middleware/langchain.d.cts +0 -3
- package/dist/middleware/langchain.d.ts +0 -3
- package/dist/middleware/langchain.js +0 -22
- package/dist/middleware/vercel-ai.cjs +0 -927
- package/dist/middleware/vercel-ai.d.cts +0 -70
- package/dist/middleware/vercel-ai.d.ts +0 -70
- package/dist/middleware/vercel-ai.js +0 -10
- package/dist/types-BLs_TMFv.d.cts +0 -444
- package/dist/types-BLs_TMFv.d.ts +0 -444
|
@@ -1,322 +0,0 @@
|
|
|
1
|
-
import { S as ShashuConfig } from './types-BLs_TMFv.cjs';
|
|
2
|
-
import { F as FetchLike } from './_joiner-DGi8GsY7.cjs';
|
|
3
|
-
|
|
4
|
-
/** One document as `rag_context.v1` spells it. */
|
|
5
|
-
interface BusDoc {
|
|
6
|
-
id: string;
|
|
7
|
-
preview: string;
|
|
8
|
-
score?: number;
|
|
9
|
-
source_uri?: string;
|
|
10
|
-
hash?: string;
|
|
11
|
-
}
|
|
12
|
-
/** One retrieval declaration. */
|
|
13
|
-
interface RetrievalEvent {
|
|
14
|
-
kind?: 'retrieval' | 'memory';
|
|
15
|
-
corpus: string;
|
|
16
|
-
query?: string;
|
|
17
|
-
source: string;
|
|
18
|
-
docs: BusDoc[];
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Helpers for attaching structured RAG context to a chat-completion request body.
|
|
23
|
-
*
|
|
24
|
-
* The Shashu gateway scans retrieved documents on a dedicated `ingress-rag`
|
|
25
|
-
* surface when the request body carries `shashu_metadata.rag_context`.
|
|
26
|
-
* This is materially better than letting retrieved documents be scanned as
|
|
27
|
-
* plain user text — the rag scanner has access to corpus + per-doc scores +
|
|
28
|
-
* per-doc previews, which dramatically reduces false-positives on legitimate
|
|
29
|
-
* RAG flows.
|
|
30
|
-
*
|
|
31
|
-
* The gateway pops `shashu_metadata` from the body before forwarding to
|
|
32
|
-
* the LLM provider, so the upstream model never sees the control plane.
|
|
33
|
-
*
|
|
34
|
-
* @example
|
|
35
|
-
* import { attachRagContext } from "@trustgateai/sdk";
|
|
36
|
-
* const body = { model: "gpt-4o-mini", messages: [...] };
|
|
37
|
-
* attachRagContext(body, {
|
|
38
|
-
* corpus: "policy_docs_v2",
|
|
39
|
-
* query: "refinance eligibility",
|
|
40
|
-
* docs: [{ id: "POL-1", score: 0.92, preview: "..." }],
|
|
41
|
-
* });
|
|
42
|
-
* // POST `body` through your existing client (LangChain, ai-sdk, raw fetch).
|
|
43
|
-
*/
|
|
44
|
-
|
|
45
|
-
interface RagDoc {
|
|
46
|
-
id?: string;
|
|
47
|
-
score?: number;
|
|
48
|
-
/** Doc body as seen by the rag scanner. `content` / `text` also accepted by the gateway. */
|
|
49
|
-
preview?: string;
|
|
50
|
-
[key: string]: unknown;
|
|
51
|
-
}
|
|
52
|
-
interface RagContext {
|
|
53
|
-
/** Contract version. Absent means 1. Emitted by {@link buildRagContext}. */
|
|
54
|
-
v?: 1;
|
|
55
|
-
corpus?: string;
|
|
56
|
-
query?: string;
|
|
57
|
-
/** A `rag_context.v1` `source` enum value — see {@link SOURCES}. */
|
|
58
|
-
source?: RagSource;
|
|
59
|
-
docs?: RagDoc[];
|
|
60
|
-
}
|
|
61
|
-
declare function makeRagContext(input: RagContext): RagContext;
|
|
62
|
-
/**
|
|
63
|
-
* Merge a rag_context dict into `body.shashu_metadata.rag_context`
|
|
64
|
-
* without clobbering other shashu_metadata fields the caller may have set.
|
|
65
|
-
*
|
|
66
|
-
* Returns the same body object (mutated) for chaining convenience.
|
|
67
|
-
*/
|
|
68
|
-
declare function attachRagContext<T extends Record<string, unknown>>(body: T, ragContext: RagContext): T;
|
|
69
|
-
/**
|
|
70
|
-
* `rag_context.v1` `source.enum`. Restated here rather than read from the
|
|
71
|
-
* vendored schema at import time: the SDK must not need a JSON file on disk to
|
|
72
|
-
* make a call. `test/contract.test.ts` holds this tuple to the schema's enum, so
|
|
73
|
-
* the two cannot drift apart unnoticed.
|
|
74
|
-
*/
|
|
75
|
-
declare const SOURCES: readonly ["manual", "langchain", "llamaindex", "tool", "otel", "n8n", "provider", "other"];
|
|
76
|
-
type RagSource = (typeof SOURCES)[number];
|
|
77
|
-
interface DeclareRetrievalOptions {
|
|
78
|
-
/** The index the documents came from. Required by the contract. */
|
|
79
|
-
corpus: string;
|
|
80
|
-
/** The retrieval query, for the gateway's audit record. */
|
|
81
|
-
query?: string;
|
|
82
|
-
/** What produced the declaration; a `rag_context.v1` enum value. */
|
|
83
|
-
source?: RagSource;
|
|
84
|
-
}
|
|
85
|
-
/**
|
|
86
|
-
* Declare what was retrieved, wherever the retrieval happened.
|
|
87
|
-
*
|
|
88
|
-
* The declaration rides an `AsyncLocalStorage` store and is attached to the NEXT
|
|
89
|
-
* outgoing model call from this async context, by any client the SDK supplies a
|
|
90
|
-
* `fetch` to -- you do not have to be anywhere near that call.
|
|
91
|
-
*
|
|
92
|
-
* ```ts
|
|
93
|
-
* const docs = await vectorstore.similaritySearch(question, 5);
|
|
94
|
-
* declareRetrieval(docs, { corpus: "policy_docs_v2", query: question });
|
|
95
|
-
* ```
|
|
96
|
-
*
|
|
97
|
-
* `docs` may be plain strings, plain objects, or LangChain / LlamaIndex document
|
|
98
|
-
* objects (see {@link COERCIONS}). A single document may be passed unwrapped.
|
|
99
|
-
* Anything the table cannot read is dropped rather than stringified.
|
|
100
|
-
*
|
|
101
|
-
* @throws {TypeError} on a blank `corpus`, or a `source` outside the contract's
|
|
102
|
-
* enum. Both are call-site mistakes, and throwing here is the only place they
|
|
103
|
-
* can be seen -- the alternative is a payload the gateway rejects at the far end
|
|
104
|
-
* of a customer's stack.
|
|
105
|
-
*
|
|
106
|
-
* A no-op when `SHASHU_DISABLE=1`.
|
|
107
|
-
*/
|
|
108
|
-
declare function declareRetrieval(docs: unknown, options: DeclareRetrievalOptions): void;
|
|
109
|
-
/**
|
|
110
|
-
* {@link declareRetrieval} bounded to a block, and isolated from everything
|
|
111
|
-
* outside it.
|
|
112
|
-
*
|
|
113
|
-
* The declaration applies to model calls made inside `fn`, and the bus is
|
|
114
|
-
* returned to its prior state on the way out — so a retrieval that ended up not
|
|
115
|
-
* being used cannot attach itself to a later, unrelated call.
|
|
116
|
-
*
|
|
117
|
-
* ```ts
|
|
118
|
-
* await retrievalScope(docs, { corpus: "policy_docs_v2", query }, () => chain.invoke(query));
|
|
119
|
-
* ```
|
|
120
|
-
*
|
|
121
|
-
* This is also the answer to the one fan-out shape a bare `declareRetrieval()`
|
|
122
|
-
* cannot isolate: several tasks started from one frame, each declaring before
|
|
123
|
-
* its own first `await`. It is built on `AsyncLocalStorage.run`, which does not
|
|
124
|
-
* leak into the frame that started the task, where `enterWith` does. See
|
|
125
|
-
* `_bus.ts` for the measured table.
|
|
126
|
-
*
|
|
127
|
-
* A no-op wrapper when `SHASHU_DISABLE=1`: `fn` still runs, nothing is
|
|
128
|
-
* declared.
|
|
129
|
-
*/
|
|
130
|
-
declare function retrievalScope<T>(docs: unknown, options: DeclareRetrievalOptions, fn: () => T | Promise<T>): Promise<T>;
|
|
131
|
-
/**
|
|
132
|
-
* Fold carried declarations into one `rag_context.v1` block.
|
|
133
|
-
*
|
|
134
|
-
* The contract carries a single `corpus`, `query` and `source` for the whole
|
|
135
|
-
* declaration, so multiple events have to be reconciled:
|
|
136
|
-
*
|
|
137
|
-
* * `corpus` -- the one they share, or the distinct ids joined with `+`. A
|
|
138
|
-
* hybrid retrieval across two indexes is a real shape, and naming only one of
|
|
139
|
-
* them would misattribute the other's documents.
|
|
140
|
-
* * `source` -- the one they share, else `other`, the enum value that exists for
|
|
141
|
-
* exactly this.
|
|
142
|
-
* * `query` -- the most recent non-empty one: the query nearest the call.
|
|
143
|
-
*
|
|
144
|
-
* Documents are de-duplicated by `(id, preview)`, first occurrence kept. Two
|
|
145
|
-
* events CAN legitimately describe the same retrieval: a customer who installs
|
|
146
|
-
* the LangChain collector and also calls {@link declareRetrieval} for the same
|
|
147
|
-
* documents produces both. Both events are kept -- only the repeated documents
|
|
148
|
-
* go, so a second event carrying anything new still contributes it.
|
|
149
|
-
*
|
|
150
|
-
* Returns undefined when nothing survived, so the joiner never writes an empty
|
|
151
|
-
* `docs` array (`minItems: 1`).
|
|
152
|
-
*/
|
|
153
|
-
declare function buildRagContext(events: readonly RetrievalEvent[]): RagContext | undefined;
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Shashu <-> LangChain: capture the retrieval, declare it for the next model call.
|
|
157
|
-
*
|
|
158
|
-
* Two separate things live here.
|
|
159
|
-
*
|
|
160
|
-
* **The endpoint config.** `createShashuLangChainConfig()` points ChatOpenAI
|
|
161
|
-
* (and the other OpenAI-shaped LangChain integrations) at your Shashu gateway
|
|
162
|
-
* and injects workflow context so Shadow AI detection can attribute requests. It
|
|
163
|
-
* also supplies the retrieval joiner as the client's `fetch`, which is what
|
|
164
|
-
* carries a declaration onto the outgoing request.
|
|
165
|
-
*
|
|
166
|
-
* **The collector.** One line turns it on:
|
|
167
|
-
*
|
|
168
|
-
* ```ts
|
|
169
|
-
* import { install } from "@shashu-ai/sdk/middleware/langchain";
|
|
170
|
-
* await install({ corpus: "policy_docs_v2" });
|
|
171
|
-
* ```
|
|
172
|
-
*
|
|
173
|
-
* From then on every LangChain retriever that runs inside a chain in this
|
|
174
|
-
* process declares what it returned, and the joiner attaches that declaration to
|
|
175
|
-
* the model call that follows. Nothing needs to be passed to `invoke()`, no
|
|
176
|
-
* `{ callbacks: [...] }`, and the collector never touches the outgoing request.
|
|
177
|
-
*
|
|
178
|
-
* ---------------------------------------------------------------------------
|
|
179
|
-
* Why this is not simply "push to the bus at handleRetrieverEnd"
|
|
180
|
-
* ---------------------------------------------------------------------------
|
|
181
|
-
*
|
|
182
|
-
* Measured against @langchain/core 1.2.9 and @langchain/openai 1.5.11 (the probe
|
|
183
|
-
* is reproduced as `test/conformance/lcel.test.ts`):
|
|
184
|
-
*
|
|
185
|
-
* * A `Runnable` step runs in its own async context. An
|
|
186
|
-
* `AsyncLocalStorage.enterWith()` performed from `handleRetrieverEnd` is
|
|
187
|
-
* invisible to the `llm` step and to the caller -- the write lands in a
|
|
188
|
-
* sibling frame that is discarded when the step returns. This is the same
|
|
189
|
-
* isolation Python's LCEL gets from `contextvars.copy_context()`, and a
|
|
190
|
-
* collector that only pushed to the bus there would be **silently inert for
|
|
191
|
-
* LCEL**, the exact shape this module exists to support.
|
|
192
|
-
* * Callback handlers are worse than isolated: unless `awaitHandlers` is set
|
|
193
|
-
* they are dispatched onto a `p-queue` (`consumeCallback` in
|
|
194
|
-
* `@langchain/core/singletons/callbacks`), so they may run *after* the model
|
|
195
|
-
* step has already sent its request. A handler-based delivery happens to work
|
|
196
|
-
* while that queue is idle and silently drops the declaration when it is not.
|
|
197
|
-
* * Seeding a shared *mutable* carrier instead is not a fix: `enterWith` leaks
|
|
198
|
-
* upward into the frame that started the task, so eight concurrent requests
|
|
199
|
-
* find one another's carrier. Measured, that design handed every one of eight
|
|
200
|
-
* tasks every other task's documents.
|
|
201
|
-
*
|
|
202
|
-
* So capture and delivery are done where each is deterministic, by wrapping the
|
|
203
|
-
* `CallbackManager` methods themselves rather than by registering a handler:
|
|
204
|
-
*
|
|
205
|
-
* * **Capture** wraps `CallbackManagerForRetrieverRun.handleRetrieverEnd`, which
|
|
206
|
-
* runs inline before the retriever step returns. It records documents against
|
|
207
|
-
* the run they belong to -- data only, no context, no ordering assumption.
|
|
208
|
-
* * **Delivery** wraps `CallbackManager.handleChatModelStart` /
|
|
209
|
-
* `handleLLMStart`, which run inline in the model step's own async context --
|
|
210
|
-
* the same context the HTTP call is made in. Delivery calls
|
|
211
|
-
* {@link declareRetrieval}, so the caps, the coercion table and
|
|
212
|
-
* `SHASHU_DISABLE` are the one implementation shared with the manual path.
|
|
213
|
-
*
|
|
214
|
-
* `install()` also has to force a `CallbackManager` to exist at all:
|
|
215
|
-
* `CallbackManager.configure()` returns `undefined` when a chain is invoked with
|
|
216
|
-
* no callbacks configured, and then none of the wrapped methods is ever reached.
|
|
217
|
-
* {@link ShashuLangChainCallback} is injected there for that reason and does
|
|
218
|
-
* nothing else.
|
|
219
|
-
*
|
|
220
|
-
* **What this does not cover.** A retriever invoked outside any chain
|
|
221
|
-
* (`await retriever.invoke(q)` on its own, then a model call) is declaration-
|
|
222
|
-
* only: its run has no parent to associate a later model call with, and every
|
|
223
|
-
* context-based seam out of the callback was measured not to reach the caller.
|
|
224
|
-
* Use {@link declareRetrieval} there. `test/conformance/outside-chain.test.ts`
|
|
225
|
-
* holds both halves of that.
|
|
226
|
-
*/
|
|
227
|
-
|
|
228
|
-
/**
|
|
229
|
-
* Configuration to pass to LangChain's ChatOpenAI (or other OpenAI-based classes).
|
|
230
|
-
* Sets baseURL and defaultHeaders (lowercase keys) so requests go through Shashu
|
|
231
|
-
* with workflow context and x-shashu-source-tool JSON for Shadow AI detection,
|
|
232
|
-
* and a `fetch` that attaches any declared retrieval to the outgoing body.
|
|
233
|
-
*
|
|
234
|
-
* Returns `{}` when SHASHU_DISABLE is set: the provider client is then left
|
|
235
|
-
* exactly as it was — its own endpoint, its own credential, no Shashu context
|
|
236
|
-
* headers — which is the same no-op the Python SDK's patchers perform. The
|
|
237
|
-
* caller's tg_sk_ key is deliberately NOT handed back, since it would be sent to
|
|
238
|
-
* the provider directly.
|
|
239
|
-
*
|
|
240
|
-
* @throws {ShashuConfigError} when no address is configured and the SDK is
|
|
241
|
-
* not disabled. There is no default host. See ../config.ts.
|
|
242
|
-
*/
|
|
243
|
-
declare function createShashuLangChainConfig(config: ShashuConfig): {
|
|
244
|
-
configuration?: {
|
|
245
|
-
baseURL: string;
|
|
246
|
-
defaultHeaders?: Record<string, string>;
|
|
247
|
-
fetch?: FetchLike;
|
|
248
|
-
};
|
|
249
|
-
baseURL?: string;
|
|
250
|
-
defaultHeaders?: Record<string, string>;
|
|
251
|
-
};
|
|
252
|
-
/**
|
|
253
|
-
* Convert a list of LangChain `Document` objects into Shashu's canonical
|
|
254
|
-
* rag_context shape.
|
|
255
|
-
*/
|
|
256
|
-
declare function lcDocumentsToRagContext(documents: Array<{
|
|
257
|
-
pageContent?: string;
|
|
258
|
-
metadata?: Record<string, unknown>;
|
|
259
|
-
}>, options?: {
|
|
260
|
-
corpus?: string;
|
|
261
|
-
query?: string;
|
|
262
|
-
maxDocs?: number;
|
|
263
|
-
previewChars?: number;
|
|
264
|
-
}): RagContext;
|
|
265
|
-
/** `rag_context.v1` `source` for everything this module declares. */
|
|
266
|
-
declare const SOURCE = "langchain";
|
|
267
|
-
/**
|
|
268
|
-
* Used when the caller names no corpus. `rag_context.v1` requires a non-empty
|
|
269
|
-
* `corpus` and the retriever callback carries no index name, so the honest
|
|
270
|
-
* answer is "a LangChain retriever, index unnamed" rather than a guess that
|
|
271
|
-
* would misattribute the documents to a real index.
|
|
272
|
-
*/
|
|
273
|
-
declare const DEFAULT_CORPUS = "langchain-retriever";
|
|
274
|
-
/**
|
|
275
|
-
* The handler `install()` injects so a `CallbackManager` exists at all.
|
|
276
|
-
*
|
|
277
|
-
* `CallbackManager.configure()` returns `undefined` for a chain invoked with no
|
|
278
|
-
* callbacks, and then none of the wrapped manager methods is reached. This
|
|
279
|
-
* carries no capture logic of its own — the wrapped methods do that, where their
|
|
280
|
-
* ordering and async context are guaranteed. It is shaped as LangChain requires
|
|
281
|
-
* a handler to be (`ensureHandler` accepts any object with a `name`) rather than
|
|
282
|
-
* extending `BaseCallbackHandler`, so this module stays importable with
|
|
283
|
-
* @langchain/core absent.
|
|
284
|
-
*/
|
|
285
|
-
declare class ShashuLangChainCallback {
|
|
286
|
-
readonly name = "ShashuLangChainCallback";
|
|
287
|
-
readonly raiseError = false;
|
|
288
|
-
readonly awaitHandlers = false;
|
|
289
|
-
readonly ignoreLLM = false;
|
|
290
|
-
readonly ignoreChain = false;
|
|
291
|
-
readonly ignoreAgent = false;
|
|
292
|
-
readonly ignoreRetriever = false;
|
|
293
|
-
readonly ignoreCustomEvent = false;
|
|
294
|
-
copy(): this;
|
|
295
|
-
}
|
|
296
|
-
/**
|
|
297
|
-
* Collect every LangChain retrieval in this process and declare it for the model
|
|
298
|
-
* call that follows.
|
|
299
|
-
*
|
|
300
|
-
* Returns true when the collector is live, false when @langchain/core is not
|
|
301
|
-
* installed — in which case this is a clean no-op, not an error. A library that
|
|
302
|
-
* made `import` fail on a machine without LangChain would be worse than one that
|
|
303
|
-
* quietly has nothing to collect.
|
|
304
|
-
*
|
|
305
|
-
* Idempotent: calling it again re-points the corpus and does not stack a second
|
|
306
|
-
* set of wrappers.
|
|
307
|
-
*/
|
|
308
|
-
declare function install(options?: {
|
|
309
|
-
corpus?: string;
|
|
310
|
-
}): Promise<boolean>;
|
|
311
|
-
/**
|
|
312
|
-
* Stop declaring: every capture and delivery point becomes a no-op.
|
|
313
|
-
*
|
|
314
|
-
* The wrappers stay in place — unwrapping a prototype that a later import may
|
|
315
|
-
* have wrapped again is how you delete somebody else's patch — and anything
|
|
316
|
-
* captured so far is dropped.
|
|
317
|
-
*/
|
|
318
|
-
declare function uninstall(): void;
|
|
319
|
-
/** True when retrievals in this process are being declared. */
|
|
320
|
-
declare function isInstalled(): boolean;
|
|
321
|
-
|
|
322
|
-
export { type DeclareRetrievalOptions as D, type RagContext as R, SOURCES as S, type RagDoc as a, type RagSource as b, attachRagContext as c, buildRagContext as d, createShashuLangChainConfig as e, declareRetrieval as f, DEFAULT_CORPUS as g, SOURCE as h, ShashuLangChainCallback as i, install as j, isInstalled as k, lcDocumentsToRagContext as l, makeRagContext as m, retrievalScope as r, uninstall as u };
|
|
@@ -1,322 +0,0 @@
|
|
|
1
|
-
import { S as ShashuConfig } from './types-BLs_TMFv.js';
|
|
2
|
-
import { F as FetchLike } from './_joiner-DGi8GsY7.js';
|
|
3
|
-
|
|
4
|
-
/** One document as `rag_context.v1` spells it. */
|
|
5
|
-
interface BusDoc {
|
|
6
|
-
id: string;
|
|
7
|
-
preview: string;
|
|
8
|
-
score?: number;
|
|
9
|
-
source_uri?: string;
|
|
10
|
-
hash?: string;
|
|
11
|
-
}
|
|
12
|
-
/** One retrieval declaration. */
|
|
13
|
-
interface RetrievalEvent {
|
|
14
|
-
kind?: 'retrieval' | 'memory';
|
|
15
|
-
corpus: string;
|
|
16
|
-
query?: string;
|
|
17
|
-
source: string;
|
|
18
|
-
docs: BusDoc[];
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Helpers for attaching structured RAG context to a chat-completion request body.
|
|
23
|
-
*
|
|
24
|
-
* The Shashu gateway scans retrieved documents on a dedicated `ingress-rag`
|
|
25
|
-
* surface when the request body carries `shashu_metadata.rag_context`.
|
|
26
|
-
* This is materially better than letting retrieved documents be scanned as
|
|
27
|
-
* plain user text — the rag scanner has access to corpus + per-doc scores +
|
|
28
|
-
* per-doc previews, which dramatically reduces false-positives on legitimate
|
|
29
|
-
* RAG flows.
|
|
30
|
-
*
|
|
31
|
-
* The gateway pops `shashu_metadata` from the body before forwarding to
|
|
32
|
-
* the LLM provider, so the upstream model never sees the control plane.
|
|
33
|
-
*
|
|
34
|
-
* @example
|
|
35
|
-
* import { attachRagContext } from "@trustgateai/sdk";
|
|
36
|
-
* const body = { model: "gpt-4o-mini", messages: [...] };
|
|
37
|
-
* attachRagContext(body, {
|
|
38
|
-
* corpus: "policy_docs_v2",
|
|
39
|
-
* query: "refinance eligibility",
|
|
40
|
-
* docs: [{ id: "POL-1", score: 0.92, preview: "..." }],
|
|
41
|
-
* });
|
|
42
|
-
* // POST `body` through your existing client (LangChain, ai-sdk, raw fetch).
|
|
43
|
-
*/
|
|
44
|
-
|
|
45
|
-
interface RagDoc {
|
|
46
|
-
id?: string;
|
|
47
|
-
score?: number;
|
|
48
|
-
/** Doc body as seen by the rag scanner. `content` / `text` also accepted by the gateway. */
|
|
49
|
-
preview?: string;
|
|
50
|
-
[key: string]: unknown;
|
|
51
|
-
}
|
|
52
|
-
interface RagContext {
|
|
53
|
-
/** Contract version. Absent means 1. Emitted by {@link buildRagContext}. */
|
|
54
|
-
v?: 1;
|
|
55
|
-
corpus?: string;
|
|
56
|
-
query?: string;
|
|
57
|
-
/** A `rag_context.v1` `source` enum value — see {@link SOURCES}. */
|
|
58
|
-
source?: RagSource;
|
|
59
|
-
docs?: RagDoc[];
|
|
60
|
-
}
|
|
61
|
-
declare function makeRagContext(input: RagContext): RagContext;
|
|
62
|
-
/**
|
|
63
|
-
* Merge a rag_context dict into `body.shashu_metadata.rag_context`
|
|
64
|
-
* without clobbering other shashu_metadata fields the caller may have set.
|
|
65
|
-
*
|
|
66
|
-
* Returns the same body object (mutated) for chaining convenience.
|
|
67
|
-
*/
|
|
68
|
-
declare function attachRagContext<T extends Record<string, unknown>>(body: T, ragContext: RagContext): T;
|
|
69
|
-
/**
|
|
70
|
-
* `rag_context.v1` `source.enum`. Restated here rather than read from the
|
|
71
|
-
* vendored schema at import time: the SDK must not need a JSON file on disk to
|
|
72
|
-
* make a call. `test/contract.test.ts` holds this tuple to the schema's enum, so
|
|
73
|
-
* the two cannot drift apart unnoticed.
|
|
74
|
-
*/
|
|
75
|
-
declare const SOURCES: readonly ["manual", "langchain", "llamaindex", "tool", "otel", "n8n", "provider", "other"];
|
|
76
|
-
type RagSource = (typeof SOURCES)[number];
|
|
77
|
-
interface DeclareRetrievalOptions {
|
|
78
|
-
/** The index the documents came from. Required by the contract. */
|
|
79
|
-
corpus: string;
|
|
80
|
-
/** The retrieval query, for the gateway's audit record. */
|
|
81
|
-
query?: string;
|
|
82
|
-
/** What produced the declaration; a `rag_context.v1` enum value. */
|
|
83
|
-
source?: RagSource;
|
|
84
|
-
}
|
|
85
|
-
/**
|
|
86
|
-
* Declare what was retrieved, wherever the retrieval happened.
|
|
87
|
-
*
|
|
88
|
-
* The declaration rides an `AsyncLocalStorage` store and is attached to the NEXT
|
|
89
|
-
* outgoing model call from this async context, by any client the SDK supplies a
|
|
90
|
-
* `fetch` to -- you do not have to be anywhere near that call.
|
|
91
|
-
*
|
|
92
|
-
* ```ts
|
|
93
|
-
* const docs = await vectorstore.similaritySearch(question, 5);
|
|
94
|
-
* declareRetrieval(docs, { corpus: "policy_docs_v2", query: question });
|
|
95
|
-
* ```
|
|
96
|
-
*
|
|
97
|
-
* `docs` may be plain strings, plain objects, or LangChain / LlamaIndex document
|
|
98
|
-
* objects (see {@link COERCIONS}). A single document may be passed unwrapped.
|
|
99
|
-
* Anything the table cannot read is dropped rather than stringified.
|
|
100
|
-
*
|
|
101
|
-
* @throws {TypeError} on a blank `corpus`, or a `source` outside the contract's
|
|
102
|
-
* enum. Both are call-site mistakes, and throwing here is the only place they
|
|
103
|
-
* can be seen -- the alternative is a payload the gateway rejects at the far end
|
|
104
|
-
* of a customer's stack.
|
|
105
|
-
*
|
|
106
|
-
* A no-op when `SHASHU_DISABLE=1`.
|
|
107
|
-
*/
|
|
108
|
-
declare function declareRetrieval(docs: unknown, options: DeclareRetrievalOptions): void;
|
|
109
|
-
/**
|
|
110
|
-
* {@link declareRetrieval} bounded to a block, and isolated from everything
|
|
111
|
-
* outside it.
|
|
112
|
-
*
|
|
113
|
-
* The declaration applies to model calls made inside `fn`, and the bus is
|
|
114
|
-
* returned to its prior state on the way out — so a retrieval that ended up not
|
|
115
|
-
* being used cannot attach itself to a later, unrelated call.
|
|
116
|
-
*
|
|
117
|
-
* ```ts
|
|
118
|
-
* await retrievalScope(docs, { corpus: "policy_docs_v2", query }, () => chain.invoke(query));
|
|
119
|
-
* ```
|
|
120
|
-
*
|
|
121
|
-
* This is also the answer to the one fan-out shape a bare `declareRetrieval()`
|
|
122
|
-
* cannot isolate: several tasks started from one frame, each declaring before
|
|
123
|
-
* its own first `await`. It is built on `AsyncLocalStorage.run`, which does not
|
|
124
|
-
* leak into the frame that started the task, where `enterWith` does. See
|
|
125
|
-
* `_bus.ts` for the measured table.
|
|
126
|
-
*
|
|
127
|
-
* A no-op wrapper when `SHASHU_DISABLE=1`: `fn` still runs, nothing is
|
|
128
|
-
* declared.
|
|
129
|
-
*/
|
|
130
|
-
declare function retrievalScope<T>(docs: unknown, options: DeclareRetrievalOptions, fn: () => T | Promise<T>): Promise<T>;
|
|
131
|
-
/**
|
|
132
|
-
* Fold carried declarations into one `rag_context.v1` block.
|
|
133
|
-
*
|
|
134
|
-
* The contract carries a single `corpus`, `query` and `source` for the whole
|
|
135
|
-
* declaration, so multiple events have to be reconciled:
|
|
136
|
-
*
|
|
137
|
-
* * `corpus` -- the one they share, or the distinct ids joined with `+`. A
|
|
138
|
-
* hybrid retrieval across two indexes is a real shape, and naming only one of
|
|
139
|
-
* them would misattribute the other's documents.
|
|
140
|
-
* * `source` -- the one they share, else `other`, the enum value that exists for
|
|
141
|
-
* exactly this.
|
|
142
|
-
* * `query` -- the most recent non-empty one: the query nearest the call.
|
|
143
|
-
*
|
|
144
|
-
* Documents are de-duplicated by `(id, preview)`, first occurrence kept. Two
|
|
145
|
-
* events CAN legitimately describe the same retrieval: a customer who installs
|
|
146
|
-
* the LangChain collector and also calls {@link declareRetrieval} for the same
|
|
147
|
-
* documents produces both. Both events are kept -- only the repeated documents
|
|
148
|
-
* go, so a second event carrying anything new still contributes it.
|
|
149
|
-
*
|
|
150
|
-
* Returns undefined when nothing survived, so the joiner never writes an empty
|
|
151
|
-
* `docs` array (`minItems: 1`).
|
|
152
|
-
*/
|
|
153
|
-
declare function buildRagContext(events: readonly RetrievalEvent[]): RagContext | undefined;
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Shashu <-> LangChain: capture the retrieval, declare it for the next model call.
|
|
157
|
-
*
|
|
158
|
-
* Two separate things live here.
|
|
159
|
-
*
|
|
160
|
-
* **The endpoint config.** `createShashuLangChainConfig()` points ChatOpenAI
|
|
161
|
-
* (and the other OpenAI-shaped LangChain integrations) at your Shashu gateway
|
|
162
|
-
* and injects workflow context so Shadow AI detection can attribute requests. It
|
|
163
|
-
* also supplies the retrieval joiner as the client's `fetch`, which is what
|
|
164
|
-
* carries a declaration onto the outgoing request.
|
|
165
|
-
*
|
|
166
|
-
* **The collector.** One line turns it on:
|
|
167
|
-
*
|
|
168
|
-
* ```ts
|
|
169
|
-
* import { install } from "@shashu-ai/sdk/middleware/langchain";
|
|
170
|
-
* await install({ corpus: "policy_docs_v2" });
|
|
171
|
-
* ```
|
|
172
|
-
*
|
|
173
|
-
* From then on every LangChain retriever that runs inside a chain in this
|
|
174
|
-
* process declares what it returned, and the joiner attaches that declaration to
|
|
175
|
-
* the model call that follows. Nothing needs to be passed to `invoke()`, no
|
|
176
|
-
* `{ callbacks: [...] }`, and the collector never touches the outgoing request.
|
|
177
|
-
*
|
|
178
|
-
* ---------------------------------------------------------------------------
|
|
179
|
-
* Why this is not simply "push to the bus at handleRetrieverEnd"
|
|
180
|
-
* ---------------------------------------------------------------------------
|
|
181
|
-
*
|
|
182
|
-
* Measured against @langchain/core 1.2.9 and @langchain/openai 1.5.11 (the probe
|
|
183
|
-
* is reproduced as `test/conformance/lcel.test.ts`):
|
|
184
|
-
*
|
|
185
|
-
* * A `Runnable` step runs in its own async context. An
|
|
186
|
-
* `AsyncLocalStorage.enterWith()` performed from `handleRetrieverEnd` is
|
|
187
|
-
* invisible to the `llm` step and to the caller -- the write lands in a
|
|
188
|
-
* sibling frame that is discarded when the step returns. This is the same
|
|
189
|
-
* isolation Python's LCEL gets from `contextvars.copy_context()`, and a
|
|
190
|
-
* collector that only pushed to the bus there would be **silently inert for
|
|
191
|
-
* LCEL**, the exact shape this module exists to support.
|
|
192
|
-
* * Callback handlers are worse than isolated: unless `awaitHandlers` is set
|
|
193
|
-
* they are dispatched onto a `p-queue` (`consumeCallback` in
|
|
194
|
-
* `@langchain/core/singletons/callbacks`), so they may run *after* the model
|
|
195
|
-
* step has already sent its request. A handler-based delivery happens to work
|
|
196
|
-
* while that queue is idle and silently drops the declaration when it is not.
|
|
197
|
-
* * Seeding a shared *mutable* carrier instead is not a fix: `enterWith` leaks
|
|
198
|
-
* upward into the frame that started the task, so eight concurrent requests
|
|
199
|
-
* find one another's carrier. Measured, that design handed every one of eight
|
|
200
|
-
* tasks every other task's documents.
|
|
201
|
-
*
|
|
202
|
-
* So capture and delivery are done where each is deterministic, by wrapping the
|
|
203
|
-
* `CallbackManager` methods themselves rather than by registering a handler:
|
|
204
|
-
*
|
|
205
|
-
* * **Capture** wraps `CallbackManagerForRetrieverRun.handleRetrieverEnd`, which
|
|
206
|
-
* runs inline before the retriever step returns. It records documents against
|
|
207
|
-
* the run they belong to -- data only, no context, no ordering assumption.
|
|
208
|
-
* * **Delivery** wraps `CallbackManager.handleChatModelStart` /
|
|
209
|
-
* `handleLLMStart`, which run inline in the model step's own async context --
|
|
210
|
-
* the same context the HTTP call is made in. Delivery calls
|
|
211
|
-
* {@link declareRetrieval}, so the caps, the coercion table and
|
|
212
|
-
* `SHASHU_DISABLE` are the one implementation shared with the manual path.
|
|
213
|
-
*
|
|
214
|
-
* `install()` also has to force a `CallbackManager` to exist at all:
|
|
215
|
-
* `CallbackManager.configure()` returns `undefined` when a chain is invoked with
|
|
216
|
-
* no callbacks configured, and then none of the wrapped methods is ever reached.
|
|
217
|
-
* {@link ShashuLangChainCallback} is injected there for that reason and does
|
|
218
|
-
* nothing else.
|
|
219
|
-
*
|
|
220
|
-
* **What this does not cover.** A retriever invoked outside any chain
|
|
221
|
-
* (`await retriever.invoke(q)` on its own, then a model call) is declaration-
|
|
222
|
-
* only: its run has no parent to associate a later model call with, and every
|
|
223
|
-
* context-based seam out of the callback was measured not to reach the caller.
|
|
224
|
-
* Use {@link declareRetrieval} there. `test/conformance/outside-chain.test.ts`
|
|
225
|
-
* holds both halves of that.
|
|
226
|
-
*/
|
|
227
|
-
|
|
228
|
-
/**
|
|
229
|
-
* Configuration to pass to LangChain's ChatOpenAI (or other OpenAI-based classes).
|
|
230
|
-
* Sets baseURL and defaultHeaders (lowercase keys) so requests go through Shashu
|
|
231
|
-
* with workflow context and x-shashu-source-tool JSON for Shadow AI detection,
|
|
232
|
-
* and a `fetch` that attaches any declared retrieval to the outgoing body.
|
|
233
|
-
*
|
|
234
|
-
* Returns `{}` when SHASHU_DISABLE is set: the provider client is then left
|
|
235
|
-
* exactly as it was — its own endpoint, its own credential, no Shashu context
|
|
236
|
-
* headers — which is the same no-op the Python SDK's patchers perform. The
|
|
237
|
-
* caller's tg_sk_ key is deliberately NOT handed back, since it would be sent to
|
|
238
|
-
* the provider directly.
|
|
239
|
-
*
|
|
240
|
-
* @throws {ShashuConfigError} when no address is configured and the SDK is
|
|
241
|
-
* not disabled. There is no default host. See ../config.ts.
|
|
242
|
-
*/
|
|
243
|
-
declare function createShashuLangChainConfig(config: ShashuConfig): {
|
|
244
|
-
configuration?: {
|
|
245
|
-
baseURL: string;
|
|
246
|
-
defaultHeaders?: Record<string, string>;
|
|
247
|
-
fetch?: FetchLike;
|
|
248
|
-
};
|
|
249
|
-
baseURL?: string;
|
|
250
|
-
defaultHeaders?: Record<string, string>;
|
|
251
|
-
};
|
|
252
|
-
/**
|
|
253
|
-
* Convert a list of LangChain `Document` objects into Shashu's canonical
|
|
254
|
-
* rag_context shape.
|
|
255
|
-
*/
|
|
256
|
-
declare function lcDocumentsToRagContext(documents: Array<{
|
|
257
|
-
pageContent?: string;
|
|
258
|
-
metadata?: Record<string, unknown>;
|
|
259
|
-
}>, options?: {
|
|
260
|
-
corpus?: string;
|
|
261
|
-
query?: string;
|
|
262
|
-
maxDocs?: number;
|
|
263
|
-
previewChars?: number;
|
|
264
|
-
}): RagContext;
|
|
265
|
-
/** `rag_context.v1` `source` for everything this module declares. */
|
|
266
|
-
declare const SOURCE = "langchain";
|
|
267
|
-
/**
|
|
268
|
-
* Used when the caller names no corpus. `rag_context.v1` requires a non-empty
|
|
269
|
-
* `corpus` and the retriever callback carries no index name, so the honest
|
|
270
|
-
* answer is "a LangChain retriever, index unnamed" rather than a guess that
|
|
271
|
-
* would misattribute the documents to a real index.
|
|
272
|
-
*/
|
|
273
|
-
declare const DEFAULT_CORPUS = "langchain-retriever";
|
|
274
|
-
/**
|
|
275
|
-
* The handler `install()` injects so a `CallbackManager` exists at all.
|
|
276
|
-
*
|
|
277
|
-
* `CallbackManager.configure()` returns `undefined` for a chain invoked with no
|
|
278
|
-
* callbacks, and then none of the wrapped manager methods is reached. This
|
|
279
|
-
* carries no capture logic of its own — the wrapped methods do that, where their
|
|
280
|
-
* ordering and async context are guaranteed. It is shaped as LangChain requires
|
|
281
|
-
* a handler to be (`ensureHandler` accepts any object with a `name`) rather than
|
|
282
|
-
* extending `BaseCallbackHandler`, so this module stays importable with
|
|
283
|
-
* @langchain/core absent.
|
|
284
|
-
*/
|
|
285
|
-
declare class ShashuLangChainCallback {
|
|
286
|
-
readonly name = "ShashuLangChainCallback";
|
|
287
|
-
readonly raiseError = false;
|
|
288
|
-
readonly awaitHandlers = false;
|
|
289
|
-
readonly ignoreLLM = false;
|
|
290
|
-
readonly ignoreChain = false;
|
|
291
|
-
readonly ignoreAgent = false;
|
|
292
|
-
readonly ignoreRetriever = false;
|
|
293
|
-
readonly ignoreCustomEvent = false;
|
|
294
|
-
copy(): this;
|
|
295
|
-
}
|
|
296
|
-
/**
|
|
297
|
-
* Collect every LangChain retrieval in this process and declare it for the model
|
|
298
|
-
* call that follows.
|
|
299
|
-
*
|
|
300
|
-
* Returns true when the collector is live, false when @langchain/core is not
|
|
301
|
-
* installed — in which case this is a clean no-op, not an error. A library that
|
|
302
|
-
* made `import` fail on a machine without LangChain would be worse than one that
|
|
303
|
-
* quietly has nothing to collect.
|
|
304
|
-
*
|
|
305
|
-
* Idempotent: calling it again re-points the corpus and does not stack a second
|
|
306
|
-
* set of wrappers.
|
|
307
|
-
*/
|
|
308
|
-
declare function install(options?: {
|
|
309
|
-
corpus?: string;
|
|
310
|
-
}): Promise<boolean>;
|
|
311
|
-
/**
|
|
312
|
-
* Stop declaring: every capture and delivery point becomes a no-op.
|
|
313
|
-
*
|
|
314
|
-
* The wrappers stay in place — unwrapping a prototype that a later import may
|
|
315
|
-
* have wrapped again is how you delete somebody else's patch — and anything
|
|
316
|
-
* captured so far is dropped.
|
|
317
|
-
*/
|
|
318
|
-
declare function uninstall(): void;
|
|
319
|
-
/** True when retrievals in this process are being declared. */
|
|
320
|
-
declare function isInstalled(): boolean;
|
|
321
|
-
|
|
322
|
-
export { type DeclareRetrievalOptions as D, type RagContext as R, SOURCES as S, type RagDoc as a, type RagSource as b, attachRagContext as c, buildRagContext as d, createShashuLangChainConfig as e, declareRetrieval as f, DEFAULT_CORPUS as g, SOURCE as h, ShashuLangChainCallback as i, install as j, isInstalled as k, lcDocumentsToRagContext as l, makeRagContext as m, retrievalScope as r, uninstall as u };
|