@memberjunction/ai-gemini 6.3.0-edge.0 → 6.3.0-edge.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,84 @@
1
+ import { AIErrorType, BaseHostedSystemOneDecision, DecisionMediaType, DecisionParams, DecisionResult, SystemOneWireObject } from '@memberjunction/ai';
2
+ /**
3
+ * A `BaseDecision` driver for Google's Gemini Decisions API
4
+ * (`POST https://generativelanguage.googleapis.com/v1beta/decisions`), served by Gemini Decision 1
5
+ * (`gemini-decision-1`). The model scores closed-set questions in one forward pass instead of
6
+ * generating text, so a call bills input tokens only.
7
+ *
8
+ * Gemini's wire is the System One format with three differences, which this class handles; the
9
+ * answer mapping, renormalisation and the endpoint, key and error handling come from
10
+ * {@link BaseHostedSystemOneDecision}:
11
+ * - **Authentication** is the `x-goog-api-key` header, not a bearer token.
12
+ * - **The shared state is `input`**, not `state`. It takes text or `Content` blocks (text, image, audio,
13
+ * video, PDF). A request without media sends the state as text, an object state as JSON; a request
14
+ * with `DecisionParams.Media` sends a text block followed by one block per item, so the model reads
15
+ * them as one input.
16
+ * - **Usage** is `total_input_tokens` / `total_output_tokens`, mapped here onto the System One names.
17
+ * No `model` or `cost` field is returned on Google's `200` wire response (`ResolvedModel` falls back
18
+ * to the requested model unless a proxy or later revision includes `model`, so calibrations and run
19
+ * fitting can identify it); MJ prices the call from the model's cost rows.
20
+ *
21
+ * Questions go out as System One questions keyed by name: a Likelihood as `noul`, a Choice's options as
22
+ * `criteria: { value: description }`, a Score's levels as `criteria: [...]`, lowest first. Answers come
23
+ * back keyed the same way, with Choice probabilities keyed by option value and Score probabilities by
24
+ * 0-based level index (`"0"`..`"254"`), exactly as the System One mapping reads them. A Score answer's
25
+ * `legend` is ignored: MJ already holds the level names.
26
+ *
27
+ * Google answers a request it rejects, and a key it does not accept, with gateway `400 INVALID_ARGUMENT`,
28
+ * service `400 invalid_request`, or `403 PERMISSION_DENIED`; {@link GetHTTPErrorType} keeps all of them
29
+ * failover-eligible.
30
+ *
31
+ * When Gemini's input filter blocks the request (`prompt_feedback.block_reason`), the response has no
32
+ * answers; this driver fails the call with the block reason, as a failover-eligible error, since
33
+ * another decision model may answer.
34
+ */
35
+ export declare class GeminiDecision extends BaseHostedSystemOneDecision {
36
+ /** The Gemini Decisions API endpoint (Gemini API, v1beta). */
37
+ static readonly DEFAULT_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/decisions";
38
+ /** The model used when DecisionParams.Model is empty (Google accepts bare `gemini-decision-1` and `models/gemini-decision-1`). */
39
+ static readonly DEFAULT_MODEL = "gemini-decision-1";
40
+ protected get ServiceName(): string;
41
+ protected get DefaultModel(): string;
42
+ protected get DefaultEndpoint(): string;
43
+ protected get APIKeyDescription(): string;
44
+ protected get LegacyKeyVariable(): string;
45
+ /** Gemini Decision 1 reads images, audio, video and PDFs alongside the text state. */
46
+ get SupportedMediaTypes(): readonly DecisionMediaType[];
47
+ /** Google's API-key header, which the Gemini API takes in place of a bearer token. */
48
+ protected GetRequestHeaders(_model: string): Record<string, string>;
49
+ /**
50
+ * The request body: `{ model, input, questions }`. The System One body with its `state` sent as
51
+ * `input`: the state as text (an object state as JSON), or, with media, a text block followed by one
52
+ * `Content` block per item.
53
+ */
54
+ protected BuildRequestBody(model: string, params: DecisionParams): SystemOneWireObject;
55
+ /**
56
+ * Fixes two statuses whose `ErrorAnalyzer` reading is wrong for this API. `Default Decision` reaches
57
+ * Gemini Decision 1 as a power-matched fallback, and a `Fatal` error there would end its failover
58
+ * loop before the candidates behind it:
59
+ * - `400` — both Google's gateway `INVALID_ARGUMENT` (an invalid or expired API key) and the
60
+ * decisions service's `invalid_request` (`"* CreateDecisionRequest...: must have ..."`, which
61
+ * `ErrorAnalyzer` would classify as `VendorValidationError` or `InvalidRequest`) — is `ModelError`,
62
+ * since another model may answer. The message still names the cause.
63
+ * - `403` (`PERMISSION_DENIED`: missing key, restricted key, or API disabled for its project) reads
64
+ * as `Authentication` when the message names a permission; it is `ModelError` too.
65
+ *
66
+ * Not `Authentication` or `VendorValidationError`: on those the runner drops the vendor's other
67
+ * candidates, and the index it continues from then skips the next candidate (`BaseModelRunner`).
68
+ * `ErrorAnalyzer` keeps the rest: `401` stays a fatal `Authentication` error, `404` (`not_found` for
69
+ * an unknown model) reads as `ModelError`, and `429` (`RESOURCE_EXHAUSTED`) and `5xx` allow failover.
70
+ */
71
+ protected GetHTTPErrorType(status: number): AIErrorType | undefined;
72
+ /**
73
+ * Google's `200` wire response omits `model`. When the response names none, record the requested
74
+ * model (`ResolveModel(params)`) so `ModelSpecificResponseDetails`, calibration lookups and
75
+ * `fit-decision-calibration` identify the answering model.
76
+ */
77
+ protected DoDecide(params: DecisionParams): Promise<DecisionResult>;
78
+ /**
79
+ * Turns Gemini's `{ answers, usage, prompt_feedback }` into the System One `{ model, answers, usage }`,
80
+ * and throws when the input filter blocked the request.
81
+ */
82
+ protected UnwrapResponse(body: unknown, status: number): unknown;
83
+ }
84
+ //# sourceMappingURL=geminiDecision.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geminiDecision.d.ts","sourceRoot":"","sources":["../src/geminiDecision.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,WAAW,EAEX,2BAA2B,EAG3B,iBAAiB,EACjB,cAAc,EACd,cAAc,EAId,mBAAmB,EACtB,MAAM,oBAAoB,CAAC;AAG5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBACa,cAAe,SAAQ,2BAA2B;IAC3D,8DAA8D;IAC9D,gBAAuB,gBAAgB,gEAAgE;IAEvG,kIAAkI;IAClI,gBAAuB,aAAa,uBAAuB;IAE3D,SAAS,KAAK,WAAW,IAAI,MAAM,CAElC;IAED,SAAS,KAAK,YAAY,IAAI,MAAM,CAEnC;IAED,SAAS,KAAK,eAAe,IAAI,MAAM,CAEtC;IAED,SAAS,KAAK,iBAAiB,IAAI,MAAM,CAExC;IAED,SAAS,KAAK,iBAAiB,IAAI,MAAM,CAExC;IAED,sFAAsF;IACtF,IAAoB,mBAAmB,IAAI,SAAS,iBAAiB,EAAE,CAEtE;IAED,sFAAsF;cACnE,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAI5E;;;;OAIG;cACgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB;IAS/F;;;;;;;;;;;;;;;OAeG;cACgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS;IAI5E;;;;OAIG;cACsB,QAAQ,CAAC,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;IAQlF;;;OAGG;cACgB,cAAc,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO;CAW5E"}
@@ -0,0 +1,163 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var GeminiDecision_1;
8
+ import { BaseDecision, BaseHostedSystemOneDecision, CreateSystemOneHTTPError, IsSystemOneWireObject, NonEmptyString, RedactSecret, } from '@memberjunction/ai';
9
+ import { RegisterClass } from '@memberjunction/global';
10
+ /**
11
+ * A `BaseDecision` driver for Google's Gemini Decisions API
12
+ * (`POST https://generativelanguage.googleapis.com/v1beta/decisions`), served by Gemini Decision 1
13
+ * (`gemini-decision-1`). The model scores closed-set questions in one forward pass instead of
14
+ * generating text, so a call bills input tokens only.
15
+ *
16
+ * Gemini's wire is the System One format with three differences, which this class handles; the
17
+ * answer mapping, renormalisation and the endpoint, key and error handling come from
18
+ * {@link BaseHostedSystemOneDecision}:
19
+ * - **Authentication** is the `x-goog-api-key` header, not a bearer token.
20
+ * - **The shared state is `input`**, not `state`. It takes text or `Content` blocks (text, image, audio,
21
+ * video, PDF). A request without media sends the state as text, an object state as JSON; a request
22
+ * with `DecisionParams.Media` sends a text block followed by one block per item, so the model reads
23
+ * them as one input.
24
+ * - **Usage** is `total_input_tokens` / `total_output_tokens`, mapped here onto the System One names.
25
+ * No `model` or `cost` field is returned on Google's `200` wire response (`ResolvedModel` falls back
26
+ * to the requested model unless a proxy or later revision includes `model`, so calibrations and run
27
+ * fitting can identify it); MJ prices the call from the model's cost rows.
28
+ *
29
+ * Questions go out as System One questions keyed by name: a Likelihood as `noul`, a Choice's options as
30
+ * `criteria: { value: description }`, a Score's levels as `criteria: [...]`, lowest first. Answers come
31
+ * back keyed the same way, with Choice probabilities keyed by option value and Score probabilities by
32
+ * 0-based level index (`"0"`..`"254"`), exactly as the System One mapping reads them. A Score answer's
33
+ * `legend` is ignored: MJ already holds the level names.
34
+ *
35
+ * Google answers a request it rejects, and a key it does not accept, with gateway `400 INVALID_ARGUMENT`,
36
+ * service `400 invalid_request`, or `403 PERMISSION_DENIED`; {@link GetHTTPErrorType} keeps all of them
37
+ * failover-eligible.
38
+ *
39
+ * When Gemini's input filter blocks the request (`prompt_feedback.block_reason`), the response has no
40
+ * answers; this driver fails the call with the block reason, as a failover-eligible error, since
41
+ * another decision model may answer.
42
+ */
43
+ let GeminiDecision = class GeminiDecision extends BaseHostedSystemOneDecision {
44
+ static { GeminiDecision_1 = this; }
45
+ /** The Gemini Decisions API endpoint (Gemini API, v1beta). */
46
+ static { this.DEFAULT_ENDPOINT = 'https://generativelanguage.googleapis.com/v1beta/decisions'; }
47
+ /** The model used when DecisionParams.Model is empty (Google accepts bare `gemini-decision-1` and `models/gemini-decision-1`). */
48
+ static { this.DEFAULT_MODEL = 'gemini-decision-1'; }
49
+ get ServiceName() {
50
+ return 'Gemini Decisions API';
51
+ }
52
+ get DefaultModel() {
53
+ return GeminiDecision_1.DEFAULT_MODEL;
54
+ }
55
+ get DefaultEndpoint() {
56
+ return GeminiDecision_1.DEFAULT_ENDPOINT;
57
+ }
58
+ get APIKeyDescription() {
59
+ return 'a Gemini API key from Google AI Studio';
60
+ }
61
+ get LegacyKeyVariable() {
62
+ return 'AI_VENDOR_API_KEY__GEMINIDECISION';
63
+ }
64
+ /** Gemini Decision 1 reads images, audio, video and PDFs alongside the text state. */
65
+ get SupportedMediaTypes() {
66
+ return GEMINI_DECISION_MEDIA_TYPES;
67
+ }
68
+ /** Google's API-key header, which the Gemini API takes in place of a bearer token. */
69
+ GetRequestHeaders(_model) {
70
+ return { 'x-goog-api-key': this.Credential.APIKey, 'Content-Type': 'application/json' };
71
+ }
72
+ /**
73
+ * The request body: `{ model, input, questions }`. The System One body with its `state` sent as
74
+ * `input`: the state as text (an object state as JSON), or, with media, a text block followed by one
75
+ * `Content` block per item.
76
+ */
77
+ BuildRequestBody(model, params) {
78
+ const systemOneBody = super.BuildRequestBody(model, params);
79
+ const text = typeof params.State === 'string' ? params.State : JSON.stringify(params.State);
80
+ const input = params.Media && params.Media.length > 0
81
+ ? [{ type: 'text', text }, ...params.Media.map(toGeminiContent)]
82
+ : text;
83
+ return { model: systemOneBody['model'], input, questions: systemOneBody['questions'] };
84
+ }
85
+ /**
86
+ * Fixes two statuses whose `ErrorAnalyzer` reading is wrong for this API. `Default Decision` reaches
87
+ * Gemini Decision 1 as a power-matched fallback, and a `Fatal` error there would end its failover
88
+ * loop before the candidates behind it:
89
+ * - `400` — both Google's gateway `INVALID_ARGUMENT` (an invalid or expired API key) and the
90
+ * decisions service's `invalid_request` (`"* CreateDecisionRequest...: must have ..."`, which
91
+ * `ErrorAnalyzer` would classify as `VendorValidationError` or `InvalidRequest`) — is `ModelError`,
92
+ * since another model may answer. The message still names the cause.
93
+ * - `403` (`PERMISSION_DENIED`: missing key, restricted key, or API disabled for its project) reads
94
+ * as `Authentication` when the message names a permission; it is `ModelError` too.
95
+ *
96
+ * Not `Authentication` or `VendorValidationError`: on those the runner drops the vendor's other
97
+ * candidates, and the index it continues from then skips the next candidate (`BaseModelRunner`).
98
+ * `ErrorAnalyzer` keeps the rest: `401` stays a fatal `Authentication` error, `404` (`not_found` for
99
+ * an unknown model) reads as `ModelError`, and `429` (`RESOURCE_EXHAUSTED`) and `5xx` allow failover.
100
+ */
101
+ GetHTTPErrorType(status) {
102
+ return status === 400 || status === 403 ? 'ModelError' : undefined;
103
+ }
104
+ /**
105
+ * Google's `200` wire response omits `model`. When the response names none, record the requested
106
+ * model (`ResolveModel(params)`) so `ModelSpecificResponseDetails`, calibration lookups and
107
+ * `fit-decision-calibration` identify the answering model.
108
+ */
109
+ async DoDecide(params) {
110
+ const result = await super.DoDecide(params);
111
+ if (result.success && !NonEmptyString(result.ResolvedModel)) {
112
+ result.ResolvedModel = this.ResolveModel(params);
113
+ }
114
+ return result;
115
+ }
116
+ /**
117
+ * Turns Gemini's `{ answers, usage, prompt_feedback }` into the System One `{ model, answers, usage }`,
118
+ * and throws when the input filter blocked the request.
119
+ */
120
+ UnwrapResponse(body, status) {
121
+ if (!IsSystemOneWireObject(body)) {
122
+ return body;
123
+ }
124
+ const blockReason = readBlockReason(body['prompt_feedback']);
125
+ if (blockReason) {
126
+ const safeReason = RedactSecret(blockReason, this.Credential.APIKey);
127
+ throw CreateSystemOneHTTPError(`${this.ServiceName} blocked the input: ${safeReason}`, status, 'ModelError');
128
+ }
129
+ return { model: body['model'], answers: body['answers'], usage: toSystemOneUsage(body['usage']) };
130
+ }
131
+ };
132
+ GeminiDecision = GeminiDecision_1 = __decorate([
133
+ RegisterClass(BaseDecision, 'GeminiDecision')
134
+ ], GeminiDecision);
135
+ export { GeminiDecision };
136
+ /** The media types Gemini Decision 1 reads. */
137
+ const GEMINI_DECISION_MEDIA_TYPES = Object.freeze(['image', 'audio', 'video', 'document']);
138
+ /** One media item as a Gemini `Content` block: `{ type, mime_type, data | uri }`. */
139
+ function toGeminiContent(media) {
140
+ return media.URI
141
+ ? { type: media.Type, mime_type: media.MimeType, uri: media.URI }
142
+ : { type: media.Type, mime_type: media.MimeType, data: media.Data };
143
+ }
144
+ /** The block reason and its message from `prompt_feedback`, or undefined when the input was not blocked. */
145
+ function readBlockReason(feedback) {
146
+ if (!IsSystemOneWireObject(feedback)) {
147
+ return undefined;
148
+ }
149
+ const reason = NonEmptyString(feedback['block_reason']);
150
+ if (!reason || reason.toUpperCase() === 'BLOCK_REASON_UNSPECIFIED') {
151
+ return undefined;
152
+ }
153
+ const message = NonEmptyString(feedback['block_reason_message']);
154
+ return message ? `${reason} (${message})` : reason;
155
+ }
156
+ /** Maps Gemini's `{ total_input_tokens, total_output_tokens }` onto the System One `{ input_tokens, output_tokens }`. */
157
+ function toSystemOneUsage(usage) {
158
+ if (!IsSystemOneWireObject(usage)) {
159
+ return undefined;
160
+ }
161
+ return { input_tokens: usage['total_input_tokens'], output_tokens: usage['total_output_tokens'] ?? 0 };
162
+ }
163
+ //# sourceMappingURL=geminiDecision.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geminiDecision.js","sourceRoot":"","sources":["../src/geminiDecision.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAEH,YAAY,EACZ,2BAA2B,EAC3B,wBAAwB,EAKxB,qBAAqB,EACrB,cAAc,EACd,YAAY,GAEf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAe,SAAQ,2BAA2B;;IAC3D,8DAA8D;aACvC,qBAAgB,GAAG,4DAA4D,AAA/D,CAAgE;IAEvG,kIAAkI;aAC3G,kBAAa,GAAG,mBAAmB,AAAtB,CAAuB;IAE3D,IAAc,WAAW;QAC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I,CAAC,EAAE,CAAC;AAC3G,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,15 @@
1
1
  import { GoogleGenAI, Content, Part } from "@google/genai";
2
2
  import { BaseLLM, ChatMessage, ChatParams, ChatResult, SummarizeParams, SummarizeResult, ChatMessageContent, FileCapabilities } from "@memberjunction/ai";
3
3
  /**
4
- * The user turn Gemini is given when a conversation would otherwise open with a model turn.
4
+ * The user turn every Gemini conversation opens with.
5
+ *
6
+ * It is the prompt-cache anchor. Gemini's implicit cache reuses a previous request only when the new
7
+ * request repeats it past the system instruction into the first `contents` turn; a match on the system
8
+ * instruction alone is not reused (measured on Gemini 3.8 Flash: 0 of 8 such requests hit, against 7 of
9
+ * 8 with this fixed opening turn, each caching all but the last ~2,050 tokens of the previous request).
10
+ * An agent loop changes its first turn between its first and second call (the first call's only turn is
11
+ * per-turn state that the second call replaces), so without a fixed opening its second call never hits.
12
+ * A conversation whose first turn already is this text is left as it is.
5
13
  *
6
14
  * Gemini requires `contents` to begin with a user turn, and enforces it hard for tool calls: a
7
15
  * `functionCall` turn is valid only "immediately after a user turn or after a function response
@@ -23,6 +31,17 @@ export declare const GEMINI_LEADING_USER_TURN_TEXT = "Proceed with the task desc
23
31
  * prefill, so no caller means a trailing model turn as one.
24
32
  */
25
33
  export declare const GEMINI_TRAILING_USER_TURN_TEXT = "Continue with the task.";
34
+ /**
35
+ * The model turn placed between two consecutive user text turns, which Gemini would otherwise read as
36
+ * one turn. Gemini's implicit cache reuses a previous request only up to a turn boundary that the new
37
+ * request repeats, and a user turn that grows from one request to the next is never reused (measured
38
+ * on Gemini 3.8 Flash: a growing single user turn caches nothing; the same text split by a model turn
39
+ * caches everything before the last boundary). An agent's history is often all user messages — the
40
+ * envelope path keeps action results, retries and runtime state as user messages — so without a
41
+ * separator every request is the system prompt plus one changing turn, and nothing is cached.
42
+ * The Anthropic driver uses the same filler to keep roles alternating around its cache breakpoint.
43
+ */
44
+ export declare const GEMINI_USER_TURN_SEPARATOR_TEXT = "OK";
26
45
  export declare class GeminiLLM extends BaseLLM {
27
46
  protected _gemini: GoogleGenAI | null;
28
47
  private _geminiPromise;
@@ -64,17 +83,39 @@ export declare class GeminiLLM extends BaseLLM {
64
83
  * one role are combined, and the conversation opens with a user turn (see
65
84
  * {@link GEMINI_LEADING_USER_TURN_TEXT}).
66
85
  *
67
- * Two exceptions to combining:
86
+ * Exceptions to combining:
68
87
  * - A model turn with nothing in it (an assistant message with no text, no calls and no
69
- * reasoning) is dropped. It carries nothing, and Gemini rejects an empty turn.
88
+ * reasoning) is dropped. It carries nothing, and Gemini rejects an empty turn. So is a user turn of only empty text.
89
+ * - Two user turns with no function responses are kept apart by a
90
+ * {@link GEMINI_USER_TURN_SEPARATOR_TEXT} model turn, so each message is a cache boundary that
91
+ * the next request repeats. Function-response turns are never separated this way: a function
92
+ * response must follow the model turn that made the call.
70
93
  * - A user turn that follows a function-response turn is kept as a turn of its own. Vertex AI
71
94
  * rejects a turn whose function responses are followed by text with "Requests ending with a
72
95
  * model turn are not supported", although the turn is the user's. Google AI Studio accepts both
73
96
  * shapes. The agent loop sends exactly this: a tool turn, then its per-turn runtime-state message.
74
97
  */
75
98
  protected geminiMessageSpacing(messages: Content[]): Content[];
99
+ /**
100
+ * Opens shaped `contents` with the fixed {@link GEMINI_LEADING_USER_TURN_TEXT} turn and a
101
+ * {@link GEMINI_USER_TURN_SEPARATOR_TEXT} model turn — the prompt-cache anchor every request of a
102
+ * conversation shares past the system instruction. Contents that already open with that turn
103
+ * (`geminiMessageSpacing` adds it before a leading model turn) and empty contents are returned as they are.
104
+ */
105
+ protected withCacheAnchor(contents: Content[]): Content[];
106
+ /**
107
+ * Whether a turn is a user turn whose only content is empty text. Gemini treats empty text as absent, so after the
108
+ * cache-anchor turns such a request would end with the anchor's model turn and be rejected ("Requests ending with a
109
+ * model turn are not supported"). Dropped like an empty model turn; a request left with no turns sends
110
+ * {@link GEMINI_LEADING_USER_TURN_TEXT} as its message.
111
+ */
112
+ private static isEmptyUserTextTurn;
113
+ /** Whether a turn already is the fixed opening user turn. */
114
+ private static isLeadingUserTurn;
76
115
  /** Whether a turn is a model turn with nothing in it: no parts, or only empty text with no signature. */
77
116
  private static isEmptyModelTurn;
117
+ /** Whether two adjacent turns are both user turns without function responses, to be kept apart by a separator. */
118
+ private static areSeparateUserTextTurns;
78
119
  /** Whether `next` is a user turn of other parts after a function-response turn, and so must stay separate. */
79
120
  private static endsFunctionResponseTurn;
80
121
  /**
@@ -315,4 +356,5 @@ export { GEMINI_AVATAR_VIDEO_BITRATE_ENV, GEMINI_AVATAR_VIDEO_BITRATE_BPS_DEFAUL
315
356
  export { BuildGeminiLiveSetup, BuildGeminiLiveModelPath, type GeminiLiveSetupTarget } from './geminiLiveSetup.js';
316
357
  export { GeminiLiveRelayPolicy, type GeminiLiveRelayPolicyOptions } from './geminiLiveRelayPolicy.js';
317
358
  export * from './geminiEmbedding.js';
359
+ export * from './geminiDecision.js';
318
360
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAY,OAAO,EAAE,IAAI,EAAmJ,MAAM,eAAe,CAAC;AAGtN,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,eAAe,EAAE,eAAe,EAA0B,kBAAkB,EAAsD,gBAAgB,EAAoJ,MAAM,oBAAoB,CAAC;AA4CxX;;;;;;;;;;GAUG;AACH,eAAO,MAAM,6BAA6B,gEAAgE,CAAC;AAE3G;;;;;;;;;GASG;AACH,eAAO,MAAM,8BAA8B,4BAA4B,CAAC;AAExE,qBACa,SAAU,SAAQ,OAAO;IAClC,SAAS,CAAC,OAAO,EAAE,WAAW,GAAG,IAAI,CAAQ;IAC7C,OAAO,CAAC,cAAc,CAAqC;IAG3D,OAAO,CAAC,eAAe,CAUrB;IAIF,OAAO,CAAC,iBAAiB,CAAu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AM,sBAAsB,CAAC;AAG9F,OAAO,EAAE,+BAA+B,EAAE,uCAAuC,EAAE,kCAAkC,EAAE,MAAM,4BAA4B,CAAC;AAG1J,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,KAAK,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC/G,OAAO,EAAE,qBAAqB,EAAE,KAAK,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AAGnG,cAAc,mBAAmB,CAAC;AAGlC,cAAc,kBAAkB,CAAC"}
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ var GeminiLLM_1;
11
11
  // Google Gemini Import
12
12
  import { GoogleGenAI, ApiError, FunctionCallingConfigMode } from "@google/genai";
13
13
  // MJ stuff
14
- import { BaseLLM, ChatResult, ModelUsage, ErrorAnalyzer, CHAT_FINISH_REASON_TOOL_CALLS, CHAT_FINISH_REASON_MALFORMED_TOOL_CALL, CHAT_FINISH_REASON_UNEXPECTED_TOOL_CALL } from "@memberjunction/ai";
14
+ import { BaseLLM, ChatResult, ModelUsage, ErrorAnalyzer, CHAT_FINISH_REASON_TOOL_CALLS, CHAT_FINISH_REASON_MALFORMED_TOOL_CALL, CHAT_FINISH_REASON_UNEXPECTED_TOOL_CALL, NormalizeFinishReason } from "@memberjunction/ai";
15
15
  import { RegisterClass, ToJSONSafe } from "@memberjunction/global";
16
16
  import { AcceptsCustomSampling } from "./geminiSampling.js";
17
17
  import { GeminiThinkingFallback, ResolveGeminiThinkingConfig } from "./geminiThinking.js";
@@ -32,7 +32,15 @@ const THOUGHT_SIGNATURE_ORIGIN_KEY = 'thoughtSignatureOrigin';
32
32
  /** The `provider` this driver (and Vertex, which extends it) stamps on its {@link ChatReasoningBlock}s. */
33
33
  const GEMINI_REASONING_PROVIDER = 'gemini';
34
34
  /**
35
- * The user turn Gemini is given when a conversation would otherwise open with a model turn.
35
+ * The user turn every Gemini conversation opens with.
36
+ *
37
+ * It is the prompt-cache anchor. Gemini's implicit cache reuses a previous request only when the new
38
+ * request repeats it past the system instruction into the first `contents` turn; a match on the system
39
+ * instruction alone is not reused (measured on Gemini 3.8 Flash: 0 of 8 such requests hit, against 7 of
40
+ * 8 with this fixed opening turn, each caching all but the last ~2,050 tokens of the previous request).
41
+ * An agent loop changes its first turn between its first and second call (the first call's only turn is
42
+ * per-turn state that the second call replaces), so without a fixed opening its second call never hits.
43
+ * A conversation whose first turn already is this text is left as it is.
36
44
  *
37
45
  * Gemini requires `contents` to begin with a user turn, and enforces it hard for tool calls: a
38
46
  * `functionCall` turn is valid only "immediately after a user turn or after a function response
@@ -54,6 +62,17 @@ export const GEMINI_LEADING_USER_TURN_TEXT = 'Proceed with the task described in
54
62
  * prefill, so no caller means a trailing model turn as one.
55
63
  */
56
64
  export const GEMINI_TRAILING_USER_TURN_TEXT = 'Continue with the task.';
65
+ /**
66
+ * The model turn placed between two consecutive user text turns, which Gemini would otherwise read as
67
+ * one turn. Gemini's implicit cache reuses a previous request only up to a turn boundary that the new
68
+ * request repeats, and a user turn that grows from one request to the next is never reused (measured
69
+ * on Gemini 3.8 Flash: a growing single user turn caches nothing; the same text split by a model turn
70
+ * caches everything before the last boundary). An agent's history is often all user messages — the
71
+ * envelope path keeps action results, retries and runtime state as user messages — so without a
72
+ * separator every request is the system prompt plus one changing turn, and nothing is cached.
73
+ * The Anthropic driver uses the same filler to keep roles alternating around its cache breakpoint.
74
+ */
75
+ export const GEMINI_USER_TURN_SEPARATOR_TEXT = 'OK';
57
76
  let GeminiLLM = class GeminiLLM extends BaseLLM {
58
77
  static { GeminiLLM_1 = this; }
59
78
  constructor(apiKey) {
@@ -141,9 +160,13 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
141
160
  * one role are combined, and the conversation opens with a user turn (see
142
161
  * {@link GEMINI_LEADING_USER_TURN_TEXT}).
143
162
  *
144
- * Two exceptions to combining:
163
+ * Exceptions to combining:
145
164
  * - A model turn with nothing in it (an assistant message with no text, no calls and no
146
- * reasoning) is dropped. It carries nothing, and Gemini rejects an empty turn.
165
+ * reasoning) is dropped. It carries nothing, and Gemini rejects an empty turn. So is a user turn of only empty text.
166
+ * - Two user turns with no function responses are kept apart by a
167
+ * {@link GEMINI_USER_TURN_SEPARATOR_TEXT} model turn, so each message is a cache boundary that
168
+ * the next request repeats. Function-response turns are never separated this way: a function
169
+ * response must follow the model turn that made the call.
147
170
  * - A user turn that follows a function-response turn is kept as a turn of its own. Vertex AI
148
171
  * rejects a turn whose function responses are followed by text with "Requests ending with a
149
172
  * model turn are not supported", although the turn is the user's. Google AI Studio accepts both
@@ -152,11 +175,15 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
152
175
  geminiMessageSpacing(messages) {
153
176
  const result = [];
154
177
  for (const message of messages) {
155
- if (GeminiLLM_1.isEmptyModelTurn(message)) {
178
+ if (GeminiLLM_1.isEmptyModelTurn(message) || GeminiLLM_1.isEmptyUserTextTurn(message)) {
156
179
  continue;
157
180
  }
158
181
  const current = result[result.length - 1];
159
- if (current && current.role === message.role && !GeminiLLM_1.endsFunctionResponseTurn(current, message)) {
182
+ if (current && GeminiLLM_1.areSeparateUserTextTurns(current, message)) {
183
+ result.push({ role: 'model', parts: [{ text: GEMINI_USER_TURN_SEPARATOR_TEXT }] });
184
+ result.push({ role: message.role, parts: [...(message.parts ?? [])] });
185
+ }
186
+ else if (current && current.role === message.role && !GeminiLLM_1.endsFunctionResponseTurn(current, message)) {
160
187
  current.parts = [...(current.parts ?? []), ...(message.parts ?? [])];
161
188
  }
162
189
  else {
@@ -168,11 +195,47 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
168
195
  }
169
196
  return result;
170
197
  }
198
+ /**
199
+ * Opens shaped `contents` with the fixed {@link GEMINI_LEADING_USER_TURN_TEXT} turn and a
200
+ * {@link GEMINI_USER_TURN_SEPARATOR_TEXT} model turn — the prompt-cache anchor every request of a
201
+ * conversation shares past the system instruction. Contents that already open with that turn
202
+ * (`geminiMessageSpacing` adds it before a leading model turn) and empty contents are returned as they are.
203
+ */
204
+ withCacheAnchor(contents) {
205
+ if (contents.length === 0 || GeminiLLM_1.isLeadingUserTurn(contents[0])) {
206
+ return contents;
207
+ }
208
+ return [
209
+ { role: 'user', parts: [{ text: GEMINI_LEADING_USER_TURN_TEXT }] },
210
+ { role: 'model', parts: [{ text: GEMINI_USER_TURN_SEPARATOR_TEXT }] },
211
+ ...contents
212
+ ];
213
+ }
214
+ /**
215
+ * Whether a turn is a user turn whose only content is empty text. Gemini treats empty text as absent, so after the
216
+ * cache-anchor turns such a request would end with the anchor's model turn and be rejected ("Requests ending with a
217
+ * model turn are not supported"). Dropped like an empty model turn; a request left with no turns sends
218
+ * {@link GEMINI_LEADING_USER_TURN_TEXT} as its message.
219
+ */
220
+ static isEmptyUserTextTurn(content) {
221
+ const parts = content.parts ?? [];
222
+ return content.role === 'user' && parts.every((p) => p.text === '' && Object.keys(p).length === 1);
223
+ }
224
+ /** Whether a turn already is the fixed opening user turn. */
225
+ static isLeadingUserTurn(content) {
226
+ const parts = content.parts ?? [];
227
+ return content.role === 'user' && parts.length === 1 && parts[0].text === GEMINI_LEADING_USER_TURN_TEXT;
228
+ }
171
229
  /** Whether a turn is a model turn with nothing in it: no parts, or only empty text with no signature. */
172
230
  static isEmptyModelTurn(content) {
173
231
  return content.role === 'model'
174
232
  && (content.parts ?? []).every((p) => p.text === '' && !p.thoughtSignature && !p.thought && Object.keys(p).length === 1);
175
233
  }
234
+ /** Whether two adjacent turns are both user turns without function responses, to be kept apart by a separator. */
235
+ static areSeparateUserTextTurns(current, next) {
236
+ const hasResponses = (c) => (c.parts ?? []).some((p) => !!p.functionResponse);
237
+ return current.role === 'user' && next.role === 'user' && !hasResponses(current) && !hasResponses(next);
238
+ }
176
239
  /** Whether `next` is a user turn of other parts after a function-response turn, and so must stay separate. */
177
240
  static endsFunctionResponseTurn(current, next) {
178
241
  const hasResponses = (c) => (c.parts ?? []).some((p) => !!p.functionResponse);
@@ -212,7 +275,7 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
212
275
  // Convert all non-system messages and apply role alternation
213
276
  const signatureOrigin = this.thoughtSignatureOrigin(modelName);
214
277
  const convertedMessages = noSystemMessages.map(m => GeminiLLM_1.MapMJMessageToGeminiHistoryEntry(m, signatureOrigin));
215
- const tempMessages = this.geminiMessageSpacing(convertedMessages);
278
+ const tempMessages = this.withCacheAnchor(this.geminiMessageSpacing(convertedMessages));
216
279
  // All but the last user turn go in the history; that turn is the message sent. The system
217
280
  // prompt is passed via systemInstruction (below), NOT bundled into the user message —
218
281
  // bundling put the stable prompt AFTER the variable history, defeating Gemini's implicit
@@ -326,9 +389,9 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
326
389
  toolCalls: toolCalls,
327
390
  ...(reasoning ? { reasoning } : {})
328
391
  },
329
- // Normalize the tool-call case and Gemini's "tried to call a tool but the call was
330
- // unreadable" case; every other reason keeps Gemini's own value.
331
- finish_reason: toolCalls ? CHAT_FINISH_REASON_TOOL_CALLS : (rejectedCall ?? (finishReason || "completed")),
392
+ // Tool calls and Gemini's "tried to call a tool but the call was unreadable" cases
393
+ // have their own markers; every other reason goes through NormalizeFinishReason.
394
+ finish_reason: toolCalls ? CHAT_FINISH_REASON_TOOL_CALLS : (rejectedCall ?? NormalizeFinishReason(finishReason)),
332
395
  index: 0,
333
396
  ...(rejectedCall && candidate.finishMessage ? { finishMessage: candidate.finishMessage } : {})
334
397
  }],
@@ -667,7 +730,7 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
667
730
  // Convert all non-system messages and apply role alternation
668
731
  const signatureOrigin = this.thoughtSignatureOrigin(modelName);
669
732
  const convertedMessages = noSystemMessages.map(m => GeminiLLM_1.MapMJMessageToGeminiHistoryEntry(m, signatureOrigin));
670
- const tempMessages = this.geminiMessageSpacing(convertedMessages);
733
+ const tempMessages = this.withCacheAnchor(this.geminiMessageSpacing(convertedMessages));
671
734
  // All but the last user turn go in the history; that turn is the message sent (see SplitForSend).
672
735
  const { history, message: finalMessageParts } = this.SplitForSend(tempMessages);
673
736
  // Capture the request's cacheable-prefix info so the final streamed chunk's usage can be
@@ -938,7 +1001,7 @@ let GeminiLLM = class GeminiLLM extends BaseLLM {
938
1001
  content: accumulatedContent ? accumulatedContent : '',
939
1002
  thinking: thinkingContent || undefined
940
1003
  },
941
- finish_reason: finishReason,
1004
+ finish_reason: NormalizeFinishReason(finishReason),
942
1005
  index: 0
943
1006
  }],
944
1007
  usage: usage || new ModelUsage(0, 0)
@@ -1163,4 +1226,6 @@ export { BuildGeminiLiveSetup, BuildGeminiLiveModelPath } from './geminiLiveSetu
1163
1226
  export { GeminiLiveRelayPolicy } from './geminiLiveRelayPolicy.js';
1164
1227
  // Export multimodal embeddings
1165
1228
  export * from './geminiEmbedding.js';
1229
+ // Export the Gemini Decisions API driver (Gemini Decision 1)
1230
+ export * from './geminiDecision.js';
1166
1231
  //# sourceMappingURL=index.js.map