@astratra/ai 1.9.0 → 1.10.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 +16 -0
- package/package.json +1 -1
- package/src/gemini.js +30 -2
- package/src/index.d.ts +16 -2
- package/src/index.js +1 -0
- package/src/openaiCompatible.js +36 -4
- package/src/providerRouter.js +3 -1
- package/src/streamedAnswer.js +83 -0
package/README.md
CHANGED
|
@@ -177,6 +177,22 @@ appel — et n'est jamais une réponse à montrer. Des arguments illisibles gard
|
|
|
177
177
|
l'appel, marqué `invalid` avec `invalidReason` (`not_json`, `not_object`), et
|
|
178
178
|
repartent en `{}` au tour suivant.
|
|
179
179
|
|
|
180
|
+
### La réponse petit à petit (`onText`)
|
|
181
|
+
|
|
182
|
+
Passé dans le contexte de `route()` (`router.route(requete, options, { onText })`) ou dans `io` d'`askChatModel` /
|
|
183
|
+
`askGeminiModel`, `onText` demande la réponse en flux (`stream: true` au format OpenAI, `streamGenerateContent` chez
|
|
184
|
+
Gemini) et reçoit le texte montrable **entier** à chaque avancée :
|
|
185
|
+
|
|
186
|
+
- jamais la réflexion (balises think, parties `thought` de Gemini), jamais une balise coupée en deux ;
|
|
187
|
+
- rien quand le modèle écrit un appel d'outil dans son texte ou commence par du JSON ;
|
|
188
|
+
- au modèle suivant du routeur, le texte repart de zéro et remplace le précédent ;
|
|
189
|
+
- la valeur rendue (texte, appels d'outils, `cut`, sources) est la même que sans flux ;
|
|
190
|
+
- jamais passé à un fournisseur masqué : un texte masqué ne se montre pas en cours de route.
|
|
191
|
+
|
|
192
|
+
```js
|
|
193
|
+
await router.route(requete, { accepts }, { onText: (texte) => ecrireBrouillon(texte) });
|
|
194
|
+
```
|
|
195
|
+
|
|
180
196
|
### La recherche Google intégrée de Gemini
|
|
181
197
|
|
|
182
198
|
`googleSearch` sur une requête active l'outil de recherche de Gemini
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/ai",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.10.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
|
@@ -21,6 +21,7 @@ const { readRetryAfter } = require('./providerLimits');
|
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
23
|
const { providerResult, readWrittenAnswer, withoutThinking } = require('./modelAnswers');
|
|
24
|
+
const { readServerEvents, textReporter } = require('./streamedAnswer');
|
|
24
25
|
|
|
25
26
|
const DEFAULT_ENDPOINT = 'https://generativelanguage.googleapis.com/v1beta/models';
|
|
26
27
|
const DEFAULT_TIMEOUT_MS = 45_000;
|
|
@@ -162,7 +163,10 @@ async function askGeminiModel(model, request, io = {}) {
|
|
|
162
163
|
const hasFunctions = Boolean(request.tools && request.tools.length);
|
|
163
164
|
const timeout = globalThis.AbortSignal.timeout(io.timeoutMs || DEFAULT_TIMEOUT_MS);
|
|
164
165
|
const signal = io.signal ? globalThis.AbortSignal.any([io.signal, timeout]) : timeout;
|
|
165
|
-
|
|
166
|
+
/* `onText` : la réponse en flux (streamGenerateContent), le texte montrable entier à chaque avancée. */
|
|
167
|
+
const report = textReporter(io.onText);
|
|
168
|
+
const method = report ? 'streamGenerateContent?alt=sse' : 'generateContent';
|
|
169
|
+
const send = (dropFunctions) => io.fetch(`${io.endpoint || DEFAULT_ENDPOINT}/${model}:${method}`, {
|
|
166
170
|
method: 'POST',
|
|
167
171
|
headers: { 'content-type': 'application/json', 'x-goog-api-key': io.key },
|
|
168
172
|
body: JSON.stringify({ ...requestBody(model, request, io.noSystemInstruction || noSystemInstructionByDefault, search, dropFunctions), ...(io.extra || {}) }),
|
|
@@ -179,7 +183,8 @@ async function askGeminiModel(model, request, io = {}) {
|
|
|
179
183
|
const retryAfterMs = readRetryAfter(response);
|
|
180
184
|
return { status: response.status, ...(retryAfterMs === null ? {} : { retryAfterMs }) };
|
|
181
185
|
}
|
|
182
|
-
const
|
|
186
|
+
const contentType = (response.headers && typeof response.headers.get === 'function' && response.headers.get('content-type')) || '';
|
|
187
|
+
const answer = report && contentType.includes('text/event-stream') ? await readGeminiStream(response, report) : await response.json();
|
|
183
188
|
const candidate = (answer && answer.candidates && answer.candidates[0]) || {};
|
|
184
189
|
const grounding = search ? { grounding: { ...readGeminiGrounding(candidate), functionsDropped } } : {};
|
|
185
190
|
const parts = (candidate.content && candidate.content.parts) || [];
|
|
@@ -195,6 +200,28 @@ async function askGeminiModel(model, request, io = {}) {
|
|
|
195
200
|
return { status: response.status, text, cut: candidate.finishReason === 'MAX_TOKENS', ...grounding };
|
|
196
201
|
}
|
|
197
202
|
|
|
203
|
+
/* Une réponse en flux, rassemblée en un seul candidat : ses parties (texte, réflexion, appels), sa fin, ses sources. */
|
|
204
|
+
async function readGeminiStream(response, report) {
|
|
205
|
+
const parts = [];
|
|
206
|
+
let finishReason;
|
|
207
|
+
let groundingMetadata;
|
|
208
|
+
let shown = '';
|
|
209
|
+
await readServerEvents(response, (event) => {
|
|
210
|
+
const candidate = event && Array.isArray(event.candidates) ? event.candidates[0] : null;
|
|
211
|
+
if (!candidate) return;
|
|
212
|
+
if (candidate.finishReason) finishReason = candidate.finishReason;
|
|
213
|
+
if (candidate.groundingMetadata) groundingMetadata = candidate.groundingMetadata;
|
|
214
|
+
for (const part of (candidate.content && candidate.content.parts) || []) {
|
|
215
|
+
parts.push(part);
|
|
216
|
+
if (!part.thought && !part.functionCall && typeof part.text === 'string') {
|
|
217
|
+
shown += part.text;
|
|
218
|
+
report(shown);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
return { candidates: [{ content: { parts }, ...(finishReason ? { finishReason } : {}), ...(groundingMetadata ? { groundingMetadata } : {}) }] };
|
|
223
|
+
}
|
|
224
|
+
|
|
198
225
|
/**
|
|
199
226
|
* Un fournisseur Gemini pour createProviderRouter : mêmes options que
|
|
200
227
|
* createOpenAICompatibleProvider, sans adresse (le point d'accès de Google,
|
|
@@ -240,6 +267,7 @@ function createGeminiProvider(options = {}) {
|
|
|
240
267
|
timeoutMs: ctx.timeoutMs || options.timeoutMs,
|
|
241
268
|
endpoint: options.endpoint,
|
|
242
269
|
noSystemInstruction: options.noSystemInstruction,
|
|
270
|
+
onText: ctx.onText,
|
|
243
271
|
extra: { ...(options.extra || {}), ...(model.extra || {}) }
|
|
244
272
|
});
|
|
245
273
|
return providerResult(id, answer, options.detailed);
|
package/src/index.d.ts
CHANGED
|
@@ -605,9 +605,23 @@ export type FetchLike = (url: string, init: { method: string; headers: Record<st
|
|
|
605
605
|
export function askChatModel(
|
|
606
606
|
target: { url: string; key: string; model: string; extra?: Record<string, unknown> },
|
|
607
607
|
request: { system?: string; messages: ChatMessage[]; tools?: Array<Record<string, unknown>>; maxTokens?: number; temperature?: number },
|
|
608
|
-
io: { fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number }
|
|
608
|
+
io: { fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; onText?: (shown: string) => void }
|
|
609
609
|
): Promise<{ status: number; text?: string | null; toolCalls?: ChatToolCall[]; cut?: boolean; retryAfterMs?: number }>;
|
|
610
610
|
|
|
611
|
+
/* ─────────────────── Réponse en flux ─────────────────── */
|
|
612
|
+
|
|
613
|
+
/**
|
|
614
|
+
* `onText` (sur `io`, ou sur le contexte de `route()` : `{ onText }`) demande la réponse en flux et reçoit
|
|
615
|
+
* le texte montrable ENTIER à chaque avancée : sans réflexion (think), sans balise coupée, et vide quand le
|
|
616
|
+
* modèle écrit un appel d'outil dans son texte. Au modèle suivant du routeur, il repart de zéro. La valeur
|
|
617
|
+
* rendue est la même que sans flux. Jamais passé à un fournisseur masqué (le texte serait masqué).
|
|
618
|
+
*/
|
|
619
|
+
export function visibleSoFar(raw: string): string;
|
|
620
|
+
/** Les événements `data:` d'un corps text/event-stream, un objet JSON chacun. */
|
|
621
|
+
export function readServerEvents(response: { body?: unknown; text?: () => Promise<string> }, onEvent: (event: any) => void): Promise<void>;
|
|
622
|
+
/** Un onText qui ne prévient que quand le texte montré change, et ne lève jamais. */
|
|
623
|
+
export function textReporter(onText?: (shown: string) => void): ((raw: string) => void) | null;
|
|
624
|
+
|
|
611
625
|
export function readToolArguments(raw: unknown): { args: Record<string, unknown> | null; invalid: boolean; reason?: 'not_json' | 'not_object'; detail?: string };
|
|
612
626
|
|
|
613
627
|
/** Les appels d'outil écrits dans un texte (<function=…>, <tool_call>{…}</tool_call>), relus. */
|
|
@@ -685,7 +699,7 @@ export function createOpenAICompatibleProvider(options: ChatProviderOptions & {
|
|
|
685
699
|
export function askGeminiModel(
|
|
686
700
|
model: string,
|
|
687
701
|
request: ChatRequest,
|
|
688
|
-
io: { key: string; fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; endpoint?: string; noSystemInstruction?: (model: string) => boolean; extra?: Record<string, unknown
|
|
702
|
+
io: { key: string; fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; endpoint?: string; noSystemInstruction?: (model: string) => boolean; extra?: Record<string, unknown>; onText?: (shown: string) => void }
|
|
689
703
|
): Promise<{ status: number; text?: string | null; toolCalls?: ChatToolCall[]; cut?: boolean; retryAfterMs?: number; grounding?: GeminiGrounding & { functionsDropped: boolean } }>;
|
|
690
704
|
|
|
691
705
|
/** Les sources d'une réponse generateContent (ou d'un de ses candidats), nettoyées et bornées. Ne lève jamais. */
|
package/src/index.js
CHANGED
package/src/openaiCompatible.js
CHANGED
|
@@ -15,6 +15,7 @@ const { readRetryAfter } = require('./providerLimits');
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
const { providerResult, readToolArguments, readWrittenAnswer, readWrittenToolCalls, toolCallOf, withoutThinking } = require('./modelAnswers');
|
|
18
|
+
const { readServerEvents, textReporter } = require('./streamedAnswer');
|
|
18
19
|
|
|
19
20
|
function toTranscript(messages) {
|
|
20
21
|
return (Array.isArray(messages) ? messages : []).map((message) => {
|
|
@@ -55,7 +56,9 @@ function toTranscript(messages) {
|
|
|
55
56
|
* Ask one model.
|
|
56
57
|
* @param {{ url: string, key: string, model: string, extra?: object }} target
|
|
57
58
|
* @param {{ system?: string, messages: object[], tools?: object[], maxTokens?: number, temperature?: number }} request
|
|
58
|
-
* @param {{ fetch: Function, signal?: AbortSignal, timeoutMs?: number }} io
|
|
59
|
+
* @param {{ fetch: Function, signal?: AbortSignal, timeoutMs?: number, onText?: Function }} io
|
|
60
|
+
* `onText` : la réponse est demandée en flux (`stream`) et `onText(texte)` reçoit le texte montrable
|
|
61
|
+
* entier à chaque avancée ; la valeur rendue est la même que sans flux.
|
|
59
62
|
* @returns {Promise<{ status: number, text?: string|null, toolCalls?: object[], cut?: boolean }>}
|
|
60
63
|
* A non-2xx answer resolves `{ status }` — nothing is thrown for it.
|
|
61
64
|
*/
|
|
@@ -66,6 +69,7 @@ async function askChatModel(target, request, io = {}) {
|
|
|
66
69
|
const Signal = globalThis.AbortSignal;
|
|
67
70
|
const timeout = Signal.timeout(timeoutMs);
|
|
68
71
|
const signal = io.signal && typeof Signal.any === 'function' ? Signal.any([io.signal, timeout]) : (io.signal || timeout);
|
|
72
|
+
const report = textReporter(io.onText);
|
|
69
73
|
const messages = [
|
|
70
74
|
...(request.system ? [{ role: 'system', content: request.system }] : []),
|
|
71
75
|
...toTranscript(request.messages)
|
|
@@ -79,7 +83,8 @@ async function askChatModel(target, request, io = {}) {
|
|
|
79
83
|
temperature: request.temperature === undefined ? 0.4 : request.temperature,
|
|
80
84
|
max_tokens: request.maxTokens || 1200,
|
|
81
85
|
...(request.tools && request.tools.length ? { tools: request.tools.map((tool) => ({ type: 'function', function: tool })) } : {}),
|
|
82
|
-
...extra
|
|
86
|
+
...extra,
|
|
87
|
+
...(report ? { stream: true } : {})
|
|
83
88
|
}),
|
|
84
89
|
signal
|
|
85
90
|
});
|
|
@@ -87,7 +92,8 @@ async function askChatModel(target, request, io = {}) {
|
|
|
87
92
|
const retryAfterMs = readRetryAfter(response);
|
|
88
93
|
return { status: response.status, ...(retryAfterMs === null ? {} : { retryAfterMs }) };
|
|
89
94
|
}
|
|
90
|
-
const
|
|
95
|
+
const contentType = (response.headers && typeof response.headers.get === 'function' && response.headers.get('content-type')) || '';
|
|
96
|
+
const answer = report && contentType.includes('text/event-stream') ? await readChatStream(response, report) : await response.json();
|
|
91
97
|
const choice = (answer && answer.choices && answer.choices[0]) || {};
|
|
92
98
|
const message = choice.message || {};
|
|
93
99
|
if (Array.isArray(message.tool_calls) && message.tool_calls.length) {
|
|
@@ -103,6 +109,32 @@ async function askChatModel(target, request, io = {}) {
|
|
|
103
109
|
return { status: response.status, text, cut: choice.finish_reason === 'length' };
|
|
104
110
|
}
|
|
105
111
|
|
|
112
|
+
/* Une réponse en flux, rassemblée dans la forme d'une réponse entière (message, appels d'outils, fin). */
|
|
113
|
+
async function readChatStream(response, report) {
|
|
114
|
+
let content = '';
|
|
115
|
+
let finish = null;
|
|
116
|
+
const calls = [];
|
|
117
|
+
await readServerEvents(response, (event) => {
|
|
118
|
+
const choice = event && Array.isArray(event.choices) ? event.choices[0] : null;
|
|
119
|
+
if (!choice) return;
|
|
120
|
+
if (choice.finish_reason) finish = choice.finish_reason;
|
|
121
|
+
const delta = choice.delta || {};
|
|
122
|
+
if (typeof delta.content === 'string' && delta.content) {
|
|
123
|
+
content += delta.content;
|
|
124
|
+
report(content);
|
|
125
|
+
}
|
|
126
|
+
for (const part of Array.isArray(delta.tool_calls) ? delta.tool_calls : []) {
|
|
127
|
+
const index = Number.isInteger(part.index) ? part.index : calls.length;
|
|
128
|
+
const call = calls[index] || (calls[index] = { id: '', function: { name: '', arguments: '' } });
|
|
129
|
+
if (part.id) call.id = part.id;
|
|
130
|
+
if (part.function && part.function.name) call.function.name += part.function.name;
|
|
131
|
+
if (part.function && typeof part.function.arguments === 'string') call.function.arguments += part.function.arguments;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
const toolCalls = calls.filter(Boolean).map((call, index) => ({ ...call, id: call.id || `call_${index}` }));
|
|
135
|
+
return { choices: [{ message: { content, ...(toolCalls.length ? { tool_calls: toolCalls } : {}) }, finish_reason: finish }] };
|
|
136
|
+
}
|
|
137
|
+
|
|
106
138
|
/**
|
|
107
139
|
* A provider for createProviderRouter, over an OpenAI-compatible endpoint.
|
|
108
140
|
*
|
|
@@ -152,7 +184,7 @@ function createOpenAICompatibleProvider(options = {}) {
|
|
|
152
184
|
const answer = await askChatModel(
|
|
153
185
|
{ url, key, model: model.id, extra: { ...(options.extra || {}), ...(model.extra || {}) } },
|
|
154
186
|
{ maxTokens: model.maxTokens, ...toRequest(prompt, ctx) },
|
|
155
|
-
{ fetch: typeof ctx.fetch === 'function' ? ctx.fetch : options.fetch, signal: ctx.signal, timeoutMs: ctx.timeoutMs || options.timeoutMs }
|
|
187
|
+
{ fetch: typeof ctx.fetch === 'function' ? ctx.fetch : options.fetch, signal: ctx.signal, timeoutMs: ctx.timeoutMs || options.timeoutMs, onText: ctx.onText }
|
|
156
188
|
);
|
|
157
189
|
return providerResult(options.id, answer, options.detailed);
|
|
158
190
|
}
|
package/src/providerRouter.js
CHANGED
|
@@ -114,7 +114,9 @@ function createProviderRouter(config = {}) {
|
|
|
114
114
|
/* Masked at the moment it leaves: a provider that runs on this machine
|
|
115
115
|
(`external: false`) gets the text as it is. */
|
|
116
116
|
const outbound = masker && provider.external !== false;
|
|
117
|
-
|
|
117
|
+
/* Un texte masqué ne se montre pas en cours de route : `onText` ne part qu'aux fournisseurs non masqués. */
|
|
118
|
+
const callCtx = outbound && providerCtx.onText ? { ...providerCtx, onText: undefined } : providerCtx;
|
|
119
|
+
const send = async () => provider.call(outbound ? await masker.maskAsync(prompt) : prompt, callCtx, model);
|
|
118
120
|
|
|
119
121
|
let raw;
|
|
120
122
|
try {
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Une réponse qui arrive petit à petit (`stream`) : le texte est montré pendant qu'il s'écrit.
|
|
3
|
+
*
|
|
4
|
+
* - readServerEvents lit les événements d'un corps `text/event-stream` (lignes `data:`), un objet JSON chacun ;
|
|
5
|
+
* - visibleSoFar dit ce qu'on peut montrer du texte reçu jusqu'ici : jamais la réflexion entre balises think
|
|
6
|
+
* (même pas encore fermée), jamais une balise coupée en deux, et rien du tout quand le modèle écrit un appel
|
|
7
|
+
* d'outil dans son texte (<tool_call>, <function=…>) ou commence par du JSON.
|
|
8
|
+
*
|
|
9
|
+
* `onText` reçoit toujours le texte ENTIER montré jusqu'ici (pas un morceau) : quand le routeur passe au modèle
|
|
10
|
+
* suivant, le texte repart de zéro et remplace le précédent, sans rien à recoller.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const { withoutThinking } = require('./modelAnswers');
|
|
14
|
+
|
|
15
|
+
const WRITTEN_CALL = /<tool_call>|<function=/;
|
|
16
|
+
|
|
17
|
+
async function readServerEvents(response, onEvent) {
|
|
18
|
+
const body = response && response.body;
|
|
19
|
+
if (!body || typeof body.getReader !== 'function') {
|
|
20
|
+
/* Un corps sans flux (un double de test, un relais qui a tout gardé) : lu d'un coup. */
|
|
21
|
+
const text = typeof response.text === 'function' ? await response.text() : '';
|
|
22
|
+
for (const line of text.split(/\r?\n/)) readLine(line, onEvent);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const reader = body.getReader();
|
|
26
|
+
const decoder = new globalThis.TextDecoder();
|
|
27
|
+
let pending = '';
|
|
28
|
+
for (;;) {
|
|
29
|
+
const { value, done } = await reader.read();
|
|
30
|
+
if (done) break;
|
|
31
|
+
pending += decoder.decode(value, { stream: true });
|
|
32
|
+
let end;
|
|
33
|
+
while ((end = pending.indexOf('\n')) >= 0) {
|
|
34
|
+
readLine(pending.slice(0, end), onEvent);
|
|
35
|
+
pending = pending.slice(end + 1);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
pending += decoder.decode();
|
|
39
|
+
if (pending) readLine(pending, onEvent);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function readLine(raw, onEvent) {
|
|
43
|
+
const line = raw.replace(/\r$/, '');
|
|
44
|
+
if (!line.startsWith('data:')) return;
|
|
45
|
+
const data = line.slice(5).trim();
|
|
46
|
+
if (!data || data === '[DONE]') return;
|
|
47
|
+
let event;
|
|
48
|
+
try {
|
|
49
|
+
event = JSON.parse(data);
|
|
50
|
+
} catch (_error) {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
onEvent(event);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function visibleSoFar(raw) {
|
|
57
|
+
const text = String(raw || '');
|
|
58
|
+
if (WRITTEN_CALL.test(text)) return '';
|
|
59
|
+
let shown = withoutThinking(text);
|
|
60
|
+
/* Une balise pas encore fermée en fin de texte (« <thi », « <tool_c ») : attendue avant d'être montrée. */
|
|
61
|
+
const open = shown.lastIndexOf('<');
|
|
62
|
+
if (open >= 0 && !shown.includes('>', open)) shown = shown.slice(0, open).trimEnd();
|
|
63
|
+
if (/^[[{]/.test(shown)) return '';
|
|
64
|
+
return shown;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Un `onText` qui ne prévient que quand le texte montré change, et qui ne lève jamais chez l'appelant. */
|
|
68
|
+
function textReporter(onText) {
|
|
69
|
+
if (typeof onText !== 'function') return null;
|
|
70
|
+
let last = '';
|
|
71
|
+
return (raw) => {
|
|
72
|
+
const shown = visibleSoFar(raw);
|
|
73
|
+
if (shown === last) return;
|
|
74
|
+
last = shown;
|
|
75
|
+
try {
|
|
76
|
+
onText(shown);
|
|
77
|
+
} catch (_error) {
|
|
78
|
+
/* L'affichage d'un morceau n'arrête jamais la réponse. */
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
module.exports = { readServerEvents, visibleSoFar, textReporter };
|