@astratra/ai 1.11.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -1
- package/package.json +1 -1
- package/src/gemini.js +33 -5
- package/src/guards/createGuards.js +14 -2
- package/src/guards/index.d.ts +2 -0
- package/src/index.d.ts +9 -2
- package/src/modelAnswers.js +4 -2
- package/src/openaiCompatible.js +21 -5
package/README.md
CHANGED
|
@@ -49,6 +49,28 @@ défaut (bloquer et signaler). `failOpen` laisse passer en signalant
|
|
|
49
49
|
`degraded` ; `recommendedGuards({ readOnly: true })` l'applique à un agent qui
|
|
50
50
|
ne fait que lire. Le mode d'une exécution est `newRun({ mode: 'action' | 'read' })`.
|
|
51
51
|
|
|
52
|
+
**Textes courts (1.13.0)** : un texte de moins de `injection.minWords` mots (3 par
|
|
53
|
+
défaut ; `0` envoie tout) n'est pas soumis au modèle d'injection, qui note un ou
|
|
54
|
+
deux mots au hasard (mesuré sur Examen d'État le 20/10/2026 : « oui » 0,96,
|
|
55
|
+
« Salut » 0,72, alors que toutes les vraies attaques dépassaient 0,993 dès trois
|
|
56
|
+
mots). Le résultat porte `score: null` et la raison `too_short_to_scan`.
|
|
57
|
+
|
|
58
|
+
**Où passent les messages de la personne** : par `input()`, jamais par
|
|
59
|
+
`toolResult(…, { external: true })`. `toolResult` sert à ce qui vient de
|
|
60
|
+
l'extérieur (page web, fichier, réponse d'un service) ; un message de la
|
|
61
|
+
personne passé par là peut marquer toute l'exécution `requiresConfirmation`, et
|
|
62
|
+
un agent qui revérifie tout l'historique à chaque tour reste alors bloqué.
|
|
63
|
+
|
|
64
|
+
**À savoir avec `recommendedGuards`** :
|
|
65
|
+
- sans `readOnly`, la politique est `failClosed` partout : si le modèle
|
|
66
|
+
d'entités ne répond plus (par exemple son disjoncteur ouvert après des délais
|
|
67
|
+
dépassés quand un tour vérifie beaucoup de messages en parallèle), `input`
|
|
68
|
+
bloque et l'agent entier s'arrête. Pour un agent qui ne fait que lire,
|
|
69
|
+
`readOnly: true` ; sinon, limiter ce qui est revérifié à chaque tour ;
|
|
70
|
+
- l'ancrage (`output.grounding`, NLI phrase par phrase) coûte de l'ordre de 3 s
|
|
71
|
+
par réponse sur un processeur ; c'est un signal, `output: { grounding: false }`
|
|
72
|
+
le coupe quand la latence compte plus.
|
|
73
|
+
|
|
52
74
|
**Événements** : chaque décision appelle `onEvent({ type: 'guard', guard, decision,
|
|
53
75
|
reasons, degraded, metrics, runId, mode, at })`. Ils ne contiennent jamais le
|
|
54
76
|
texte (ni saisie, ni résultat d'outil, ni réponse) : des nombres, des codes et
|
|
@@ -78,7 +100,10 @@ suspected, forbids every action without a human for the rest of the run
|
|
|
78
100
|
(`beforeAction`), `output` unmasks the reply and checks grounding against the
|
|
79
101
|
sources, personal-data leaks and moderation. Failure policy is `failClosed` for
|
|
80
102
|
actions by default, `failOpen` possible for read-only runs. Events never carry
|
|
81
|
-
the text. Mocks for tests: `@astratra/ai/guards/testing`.
|
|
103
|
+
the text. Mocks for tests: `@astratra/ai/guards/testing`. Since 1.13.0, texts
|
|
104
|
+
under `injection.minWords` words (default 3) are not sent to the injection
|
|
105
|
+
model, which scores one or two words at random; the person's own messages go
|
|
106
|
+
through `input()`, never `toolResult(…, { external: true })`.
|
|
82
107
|
|
|
83
108
|
## Routeur de providers
|
|
84
109
|
|
|
@@ -182,6 +207,26 @@ appel — et n'est jamais une réponse à montrer. Des arguments illisibles gard
|
|
|
182
207
|
l'appel, marqué `invalid` avec `invalidReason` (`not_json`, `not_object`), et
|
|
183
208
|
repartent en `{}` au tour suivant.
|
|
184
209
|
|
|
210
|
+
**Schémas d'outils chez Gemini (1.13.0)** : l'API Gemini native refuse
|
|
211
|
+
`additionalProperties`, `$schema` et `$id` dans les paramètres d'une fonction
|
|
212
|
+
(400 « Unknown name "additionalProperties" »). Ils sont retirés à toute
|
|
213
|
+
profondeur avant l'envoi (une *propriété* qui porte un de ces noms reste) ; les
|
|
214
|
+
schémas stricts produits par `toolSpecs` passent donc tels quels.
|
|
215
|
+
|
|
216
|
+
**Signatures de pensée (Gemini 3, 1.12.0)** : chaque appel d'outil de Gemini 3
|
|
217
|
+
porte une signature, à rendre telle quelle au tour suivant, sinon Gemini répond
|
|
218
|
+
400. Elle arrive dans `toolCalls[i].signature` (directement chez Gemini, par
|
|
219
|
+
l'API compatible OpenAI de Google, ou par la passerelle Centrale) : **gardez
|
|
220
|
+
l'appel tel quel** dans le message `assistant` de l'historique, elle repart
|
|
221
|
+
avec lui (`thoughtSignature` chez Gemini, `extra_content.google.thought_signature`
|
|
222
|
+
au format OpenAI). Au format OpenAI, elle n'est envoyée qu'à `*.googleapis.com`,
|
|
223
|
+
ou à une cible qui le demande : `thoughtSignatures: true` (dans la cible
|
|
224
|
+
d'`askChatModel` ou les options de `createOpenAICompatibleProvider` ;
|
|
225
|
+
`modeleDiscussion()` de `@astratra/centrale` 1.7.0 le donne) ; jamais à un
|
|
226
|
+
autre fournisseur, qui pourrait refuser le champ. Un premier appel sans
|
|
227
|
+
signature (venu d'un autre fournisseur) part chez Gemini avec la valeur de
|
|
228
|
+
contournement de Google (`skip_thought_signature_validator`), sauf pour Gemma.
|
|
229
|
+
|
|
185
230
|
### La réponse petit à petit (`onText`)
|
|
186
231
|
|
|
187
232
|
Passé dans le contexte de `route()` (`router.route(requete, options, { onText })`) ou dans `io` d'`askChatModel` /
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/ai",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.13.0",
|
|
4
4
|
"description": "Generic AI provider routing, tool registry, and agent loop utilities for Astratra, plus agent guards (@astratra/ai/guards): outbound masking, prompt-injection handling for untrusted tool results, reply checks.",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=20"
|
package/src/gemini.js
CHANGED
|
@@ -30,13 +30,22 @@ const noSystemInstructionByDefault = (model) => String(model).startsWith('gemma-
|
|
|
30
30
|
/* Des arguments illisibles (null) repartent en objet vide : Gemini refuse autre chose. */
|
|
31
31
|
const argsOf = (args) => (args && typeof args === 'object' && !Array.isArray(args) ? args : {});
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
/* Gemini 3 vérifie la signature de pensée du premier appel de chaque étape (les appels parallèles suivants n'en ont pas).
|
|
34
|
+
Un appel sans signature (venu d'un autre fournisseur, ou d'un historique d'avant) reçoit la valeur de contournement
|
|
35
|
+
documentée par Google plutôt qu'un 400 ; Gemma n'a pas de signatures. */
|
|
36
|
+
const BYPASS_SIGNATURE = 'skip_thought_signature_validator';
|
|
37
|
+
|
|
38
|
+
function contentsOf(messages, model = '') {
|
|
39
|
+
const bypass = !String(model).startsWith('gemma-');
|
|
34
40
|
return (Array.isArray(messages) ? messages : []).map((message) => {
|
|
35
41
|
if (message.role === 'assistant') {
|
|
36
42
|
const parts = [];
|
|
37
43
|
const text = message.text === undefined ? message.content : message.text;
|
|
38
44
|
if (text) parts.push({ text });
|
|
39
|
-
|
|
45
|
+
(message.toolCalls || []).forEach((call, index) => {
|
|
46
|
+
const signature = call.signature || (index === 0 && bypass ? BYPASS_SIGNATURE : null);
|
|
47
|
+
parts.push({ functionCall: { name: call.name, args: argsOf(call.args) }, ...(signature ? { thoughtSignature: signature } : {}) });
|
|
48
|
+
});
|
|
40
49
|
return { role: 'model', parts };
|
|
41
50
|
}
|
|
42
51
|
if (message.role === 'tool') {
|
|
@@ -121,15 +130,33 @@ function readGeminiGrounding(answer) {
|
|
|
121
130
|
return { searched: queries.length > 0 || sources.length > 0, queries, sources, searchSuggestionsHtml: entry };
|
|
122
131
|
}
|
|
123
132
|
|
|
133
|
+
/* L'API Gemini native refuse ces mots de JSON Schema dans `parameters` (400 « Unknown name "additionalProperties" »),
|
|
134
|
+
alors que les schémas stricts en portent souvent (`additionalProperties: false`). Ils sont retirés à toute profondeur,
|
|
135
|
+
sans toucher à une propriété qui porte un de ces noms (les clés de `properties` sont des noms, pas des mots du schéma). */
|
|
136
|
+
const GEMINI_UNSUPPORTED = new Set(['additionalProperties', '$schema', '$id']);
|
|
137
|
+
function geminiSchema(value) {
|
|
138
|
+
if (Array.isArray(value)) return value.map(geminiSchema);
|
|
139
|
+
if (!value || typeof value !== 'object') return value;
|
|
140
|
+
const out = {};
|
|
141
|
+
for (const [key, child] of Object.entries(value)) {
|
|
142
|
+
if (GEMINI_UNSUPPORTED.has(key)) continue;
|
|
143
|
+
out[key] = key === 'properties' && child && typeof child === 'object' && !Array.isArray(child)
|
|
144
|
+
? Object.fromEntries(Object.entries(child).map(([name, schema]) => [name, geminiSchema(schema)]))
|
|
145
|
+
: geminiSchema(child);
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
const geminiDeclaration = (tool) => (tool && tool.parameters ? { ...tool, parameters: geminiSchema(tool.parameters) } : tool);
|
|
150
|
+
|
|
124
151
|
/** Le corps de la requête pour un modèle. */
|
|
125
152
|
function requestBody(model, request, noSystemInstruction, search = null, dropFunctions = false) {
|
|
126
|
-
const contents = contentsOf(request.messages);
|
|
153
|
+
const contents = contentsOf(request.messages, model);
|
|
127
154
|
const generationConfig = {
|
|
128
155
|
temperature: request.temperature === undefined ? 0.4 : request.temperature,
|
|
129
156
|
maxOutputTokens: request.maxTokens || 1200
|
|
130
157
|
};
|
|
131
158
|
const toolList = [];
|
|
132
|
-
if (request.tools && request.tools.length && !dropFunctions) toolList.push({ functionDeclarations: request.tools });
|
|
159
|
+
if (request.tools && request.tools.length && !dropFunctions) toolList.push({ functionDeclarations: request.tools.map(geminiDeclaration) });
|
|
133
160
|
if (search) toolList.push({ google_search: {} });
|
|
134
161
|
const functions = toolList.length ? { tools: toolList } : {};
|
|
135
162
|
const system = request.system || '';
|
|
@@ -191,7 +218,8 @@ async function askGeminiModel(model, request, io = {}) {
|
|
|
191
218
|
const toolCalls = functionsDropped ? [] : parts.filter((part) => part.functionCall).map((part, index) => ({
|
|
192
219
|
id: part.functionCall.id || `call_${index}`,
|
|
193
220
|
name: part.functionCall.name,
|
|
194
|
-
args: argsOf(part.functionCall.args)
|
|
221
|
+
args: argsOf(part.functionCall.args),
|
|
222
|
+
...(typeof part.thoughtSignature === 'string' && part.thoughtSignature ? { signature: part.thoughtSignature } : {})
|
|
195
223
|
}));
|
|
196
224
|
if (toolCalls.length) return { status: response.status, text: null, toolCalls, ...grounding };
|
|
197
225
|
const text = withoutThinking(parts.filter((part) => !part.thought && !part.functionCall).map((part) => part.text || '').join(''));
|
|
@@ -27,6 +27,9 @@ const FAIL_OPEN = 'failOpen';
|
|
|
27
27
|
const DECISIONS = Object.freeze(['allow', 'flag', 'block']);
|
|
28
28
|
const SEVERITY = { allow: 0, flag: 1, block: 2 };
|
|
29
29
|
const DEFAULT_MAX_SCAN_CHARS = 100000;
|
|
30
|
+
const DEFAULT_MIN_WORDS = 3;
|
|
31
|
+
/* Words that carry letters or digits: emoji and punctuation alone are not words. */
|
|
32
|
+
const wordCount = (text) => String(text).split(/\s+/).filter((word) => /[\p{L}\p{N}]/u.test(word)).length;
|
|
30
33
|
const WITHHELD = '[content withheld by a guard]';
|
|
31
34
|
|
|
32
35
|
const keyHash = (key) => crypto.createHash('sha256').update(String(key)).digest('hex');
|
|
@@ -77,7 +80,8 @@ function lazyVerifySources() {
|
|
|
77
80
|
* @param {Function} [options.onEvent]
|
|
78
81
|
* @param {string[]} [options.names] register names always masked.
|
|
79
82
|
* @param {string[]} [options.entityLabels] default ['person'].
|
|
80
|
-
* @param {object} [options.injection] { threshold = 0.5, actionThreshold = threshold, maxScanChars, chunkChars, overlapChars
|
|
83
|
+
* @param {object} [options.injection] { threshold = 0.5, actionThreshold = threshold, maxScanChars, chunkChars, overlapChars,
|
|
84
|
+
* minWords = 3 (shorter texts are not sent to the injection model; 0 sends everything) }.
|
|
81
85
|
* @param {object} [options.output] { grounding = true, leak = true, moderation = true, minSupport = 0.5, leakTypes }.
|
|
82
86
|
* @param {Function} [options.verifySources] (answer, sources, { nli }) => report; default: @astratra/rag if installed.
|
|
83
87
|
* @param {'action'|'read'} [options.defaultMode] mode of a run that does not name one. Default 'action'.
|
|
@@ -101,6 +105,8 @@ function createGuards(options = {}) {
|
|
|
101
105
|
const maxScanChars = injectionOptions.maxScanChars || DEFAULT_MAX_SCAN_CHARS;
|
|
102
106
|
const chunkChars = injectionOptions.chunkChars || 6000;
|
|
103
107
|
const overlapChars = injectionOptions.overlapChars === undefined ? 300 : injectionOptions.overlapChars;
|
|
108
|
+
const minWords = injectionOptions.minWords === undefined ? DEFAULT_MIN_WORDS : injectionOptions.minWords;
|
|
109
|
+
if (!Number.isInteger(minWords) || minWords < 0) throw new TypeError('injection.minWords must be an integer >= 0.');
|
|
104
110
|
const outputOptions = { grounding: true, leak: true, moderation: true, minSupport: 0.5, ...(options.output || {}) };
|
|
105
111
|
const verifySources = options.verifySources || (outputOptions.grounding ? lazyVerifySources() : null);
|
|
106
112
|
|
|
@@ -233,6 +239,9 @@ function createGuards(options = {}) {
|
|
|
233
239
|
/* ---- toolResult --------------------------------------------------------- */
|
|
234
240
|
|
|
235
241
|
async function scanForInjection(content, threshold) {
|
|
242
|
+
/* One or two words carry no instruction, and the injection model scores them at random (« oui » 0.96,
|
|
243
|
+
« Salut » 0.72 on Examen d'État, 20/10/2026, where every real attack scored ≥ 0.993 from three words up). */
|
|
244
|
+
if (wordCount(content) < minWords) return { score: null, suspected: false, chunks: 0, short: true };
|
|
236
245
|
const pieces = windowsOf(content, chunkChars, overlapChars);
|
|
237
246
|
let max = 0;
|
|
238
247
|
for (let i = 0; i < pieces.length; i += 8) {
|
|
@@ -271,7 +280,10 @@ function createGuards(options = {}) {
|
|
|
271
280
|
} else {
|
|
272
281
|
const scan = await scanForInjection(content, run.mode === 'action' ? actionThreshold : injectionThreshold);
|
|
273
282
|
if (scan.failed) degraded.push('injection');
|
|
274
|
-
else
|
|
283
|
+
else {
|
|
284
|
+
({ score, suspected, chunks } = scan);
|
|
285
|
+
if (scan.short) reasons.push('too_short_to_scan');
|
|
286
|
+
}
|
|
275
287
|
}
|
|
276
288
|
if (degraded.length) {
|
|
277
289
|
reasons.push('injection_check_unavailable');
|
package/src/guards/index.d.ts
CHANGED
|
@@ -65,6 +65,8 @@ export interface CreateGuardsOptions {
|
|
|
65
65
|
maxScanChars?: number;
|
|
66
66
|
chunkChars?: number;
|
|
67
67
|
overlapChars?: number;
|
|
68
|
+
/** Texts with fewer words are not sent to the injection model (it scores one or two words at random). Default 3; 0 sends everything. */
|
|
69
|
+
minWords?: number;
|
|
68
70
|
};
|
|
69
71
|
output?: {
|
|
70
72
|
grounding?: boolean;
|
package/src/index.d.ts
CHANGED
|
@@ -583,7 +583,7 @@ export interface ChatMessage {
|
|
|
583
583
|
text?: string;
|
|
584
584
|
content?: string;
|
|
585
585
|
images?: Array<{ mimeType: string; data: string }>;
|
|
586
|
-
toolCalls?: Array<{ id: string; name: string; args: unknown }>;
|
|
586
|
+
toolCalls?: Array<{ id: string; name: string; args: unknown; signature?: string }>;
|
|
587
587
|
toolCallId?: string;
|
|
588
588
|
result?: unknown;
|
|
589
589
|
}
|
|
@@ -598,12 +598,15 @@ export interface ChatToolCall {
|
|
|
598
598
|
invalidReason?: 'not_json' | 'not_object';
|
|
599
599
|
/** L'erreur de lecture, pour 'not_json'. */
|
|
600
600
|
invalidDetail?: string;
|
|
601
|
+
/** La signature de pensée de Gemini 3 : gardez l'appel tel quel dans l'historique, elle repart avec lui (sinon Gemini répond 400). */
|
|
602
|
+
signature?: string;
|
|
601
603
|
}
|
|
602
604
|
|
|
603
605
|
export type FetchLike = (url: string, init: { method: string; headers: Record<string, string>; body: string; signal?: AbortSignal }) => Promise<{ ok: boolean; status: number; json(): Promise<any> }>;
|
|
604
606
|
|
|
605
607
|
export function askChatModel(
|
|
606
|
-
|
|
608
|
+
/** `thoughtSignatures` : renvoyer les signatures de pensée de Gemini 3 (par défaut : seulement vers *.googleapis.com ; true pour la passerelle Centrale). */
|
|
609
|
+
target: { url: string; key: string; model: string; extra?: Record<string, unknown>; thoughtSignatures?: boolean },
|
|
607
610
|
request: { system?: string; messages: ChatMessage[]; tools?: Array<Record<string, unknown>>; maxTokens?: number; temperature?: number },
|
|
608
611
|
io: { fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; onText?: (shown: string) => void }
|
|
609
612
|
): Promise<{ status: number; text?: string | null; toolCalls?: ChatToolCall[]; cut?: boolean; retryAfterMs?: number }>;
|
|
@@ -692,6 +695,8 @@ export function createOpenAICompatibleProvider(options: ChatProviderOptions & {
|
|
|
692
695
|
url: string | ((ctx: Record<string, unknown>) => string | null | undefined);
|
|
693
696
|
external?: boolean;
|
|
694
697
|
extra?: Record<string, unknown>;
|
|
698
|
+
/** Renvoyer les signatures de pensée de Gemini 3 (par défaut : seulement vers *.googleapis.com ; true pour la passerelle Centrale). */
|
|
699
|
+
thoughtSignatures?: boolean;
|
|
695
700
|
}): Provider;
|
|
696
701
|
|
|
697
702
|
/* ─────────────────── Gemini ─────────────────── */
|
|
@@ -750,6 +755,8 @@ export interface NativeToolCall {
|
|
|
750
755
|
invalid?: boolean;
|
|
751
756
|
invalidReason?: 'not_json' | 'not_object';
|
|
752
757
|
invalidDetail?: string;
|
|
758
|
+
/** La signature de pensée de Gemini 3, rendue avec l'appel au tour suivant. */
|
|
759
|
+
signature?: string;
|
|
753
760
|
}
|
|
754
761
|
|
|
755
762
|
export interface ToolMessage {
|
package/src/modelAnswers.js
CHANGED
|
@@ -88,13 +88,15 @@ function readToolArguments(raw) {
|
|
|
88
88
|
}
|
|
89
89
|
|
|
90
90
|
/** Un appel d'outil lu : ses arguments, et quand ils sont illisibles, pourquoi. */
|
|
91
|
-
function toolCallOf(id, name, rawArguments) {
|
|
91
|
+
function toolCallOf(id, name, rawArguments, signature) {
|
|
92
92
|
const { args, invalid, reason, detail } = readToolArguments(rawArguments);
|
|
93
93
|
return {
|
|
94
94
|
id,
|
|
95
95
|
name,
|
|
96
96
|
args,
|
|
97
|
-
...(invalid ? { invalid: true, invalidReason: reason, ...(detail ? { invalidDetail: detail } : {}) } : {})
|
|
97
|
+
...(invalid ? { invalid: true, invalidReason: reason, ...(detail ? { invalidDetail: detail } : {}) } : {}),
|
|
98
|
+
/* La « signature de pensée » de Gemini 3 : à rendre telle quelle avec l'appel au tour suivant, sinon Gemini répond 400. */
|
|
99
|
+
...(typeof signature === 'string' && signature ? { signature } : {})
|
|
98
100
|
};
|
|
99
101
|
}
|
|
100
102
|
|
package/src/openaiCompatible.js
CHANGED
|
@@ -17,7 +17,18 @@ const { readRetryAfter } = require('./providerLimits');
|
|
|
17
17
|
const { providerResult, readToolArguments, readWrittenAnswer, readWrittenToolCalls, toolCallOf, withoutThinking } = require('./modelAnswers');
|
|
18
18
|
const { readServerEvents, textReporter } = require('./streamedAnswer');
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
/* Les signatures de pensée de Gemini 3 voyagent dans `extra_content.google.thought_signature`, une extension de Google :
|
|
21
|
+
envoyées à Google, ou à une cible qui les demande (`thoughtSignatures: true`, la passerelle Centrale), jamais ailleurs. */
|
|
22
|
+
const signatureOf = (call) => {
|
|
23
|
+
const signature = call && call.extra_content && call.extra_content.google && call.extra_content.google.thought_signature;
|
|
24
|
+
return typeof signature === 'string' && signature ? signature : undefined;
|
|
25
|
+
};
|
|
26
|
+
function sendsSignatures(target) {
|
|
27
|
+
if (typeof target.thoughtSignatures === 'boolean') return target.thoughtSignatures;
|
|
28
|
+
try { return new URL(target.url).hostname.endsWith('.googleapis.com'); } catch (_error) { return false; }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function toTranscript(messages, signatures = false) {
|
|
21
32
|
return (Array.isArray(messages) ? messages : []).map((message) => {
|
|
22
33
|
if (message.role === 'assistant') {
|
|
23
34
|
return {
|
|
@@ -28,7 +39,8 @@ function toTranscript(messages) {
|
|
|
28
39
|
id: call.id,
|
|
29
40
|
type: 'function',
|
|
30
41
|
/* Des arguments illisibles (null) repartent en objet vide : le fournisseur refuserait « null ». */
|
|
31
|
-
function: { name: call.name, arguments: JSON.stringify(call.args && typeof call.args === 'object' ? call.args : {}) }
|
|
42
|
+
function: { name: call.name, arguments: JSON.stringify(call.args && typeof call.args === 'object' ? call.args : {}) },
|
|
43
|
+
...(signatures && call.signature ? { extra_content: { google: { thought_signature: call.signature } } } : {})
|
|
32
44
|
}))
|
|
33
45
|
} : {})
|
|
34
46
|
};
|
|
@@ -72,7 +84,7 @@ async function askChatModel(target, request, io = {}) {
|
|
|
72
84
|
const report = textReporter(io.onText);
|
|
73
85
|
const messages = [
|
|
74
86
|
...(request.system ? [{ role: 'system', content: request.system }] : []),
|
|
75
|
-
...toTranscript(request.messages)
|
|
87
|
+
...toTranscript(request.messages, sendsSignatures(target || {}))
|
|
76
88
|
];
|
|
77
89
|
const response = await io.fetch(url, {
|
|
78
90
|
method: 'POST',
|
|
@@ -100,7 +112,7 @@ async function askChatModel(target, request, io = {}) {
|
|
|
100
112
|
return {
|
|
101
113
|
status: response.status,
|
|
102
114
|
text: null,
|
|
103
|
-
toolCalls: message.tool_calls.map((call) => toolCallOf(call.id, call.function && call.function.name, call.function && call.function.arguments))
|
|
115
|
+
toolCalls: message.tool_calls.map((call) => toolCallOf(call.id, call.function && call.function.name, call.function && call.function.arguments, signatureOf(call)))
|
|
104
116
|
};
|
|
105
117
|
}
|
|
106
118
|
const text = withoutThinking(message.content);
|
|
@@ -129,6 +141,7 @@ async function readChatStream(response, report) {
|
|
|
129
141
|
if (part.id) call.id = part.id;
|
|
130
142
|
if (part.function && part.function.name) call.function.name += part.function.name;
|
|
131
143
|
if (part.function && typeof part.function.arguments === 'string') call.function.arguments += part.function.arguments;
|
|
144
|
+
if (signatureOf(part)) call.extra_content = part.extra_content;
|
|
132
145
|
}
|
|
133
146
|
});
|
|
134
147
|
const toolCalls = calls.filter(Boolean).map((call, index) => ({ ...call, id: call.id || `call_${index}` }));
|
|
@@ -153,6 +166,8 @@ async function readChatStream(response, report) {
|
|
|
153
166
|
* @param {boolean} [options.detailed] true: the call resolves { text, toolCalls, cut } (an empty text
|
|
154
167
|
* included, for the router's `accepts` to judge) instead of the text alone.
|
|
155
168
|
* @param {Function} [options.toRequest] (prompt, ctx) => { system?, messages, tools?, maxTokens? }. Default: the prompt as one user message.
|
|
169
|
+
* @param {boolean} [options.thoughtSignatures] send the thought signatures of Gemini 3 back (default: only to *.googleapis.com);
|
|
170
|
+
* true for a gateway that relays them (Centrale).
|
|
156
171
|
*/
|
|
157
172
|
function createOpenAICompatibleProvider(options = {}) {
|
|
158
173
|
if (typeof options.id !== 'string' || !options.id) throw new Error('createOpenAICompatibleProvider requires options.id.');
|
|
@@ -182,7 +197,8 @@ function createOpenAICompatibleProvider(options = {}) {
|
|
|
182
197
|
throw missing;
|
|
183
198
|
}
|
|
184
199
|
const answer = await askChatModel(
|
|
185
|
-
{ url, key, model: model.id, extra: { ...(options.extra || {}), ...(model.extra || {}) }
|
|
200
|
+
{ url, key, model: model.id, extra: { ...(options.extra || {}), ...(model.extra || {}) },
|
|
201
|
+
...(typeof options.thoughtSignatures === 'boolean' ? { thoughtSignatures: options.thoughtSignatures } : {}) },
|
|
186
202
|
{ maxTokens: model.maxTokens, ...toRequest(prompt, ctx) },
|
|
187
203
|
{ fetch: typeof ctx.fetch === 'function' ? ctx.fetch : options.fetch, signal: ctx.signal, timeoutMs: ctx.timeoutMs || options.timeoutMs, onText: ctx.onText }
|
|
188
204
|
);
|