@astratra/ai 1.8.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 CHANGED
@@ -177,6 +177,53 @@ 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
+
196
+ ### La recherche Google intégrée de Gemini
197
+
198
+ `googleSearch` sur une requête active l'outil de recherche de Gemini
199
+ (`google_search` dans generateContent). Les fournisseurs au format OpenAI
200
+ l'ignorent. Le fournisseur `detailed` rend alors `grounding` : les recherches
201
+ faites et les pages citées, sous une forme stable.
202
+
203
+ ```js
204
+ const { value } = await router.route({
205
+ system, messages, tools,
206
+ googleSearch: true // ou { functions: 'auto' | 'combine' | 'alone' }
207
+ });
208
+ // value.grounding = { searched, queries: ['…'], sources: [{ title, url }],
209
+ // searchSuggestionsHtml, functionsDropped }
210
+ ```
211
+
212
+ Avec les fonctions de l'application : `combine` envoie les deux outils
213
+ ensemble ; `alone` n'envoie que la recherche pour ce tour (aucun appel de
214
+ fonction n'est lu) ; `auto` (défaut) les envoie ensemble et, si l'API refuse le
215
+ mélange (400), redemande avec la recherche seule — `functionsDropped: true` le
216
+ dit. Selon le modèle, l'API accepte ou non le mélange : `auto` couvre les deux.
217
+
218
+ Les pages lues sont des **données non fiables**. Le paquet n'en rend que des
219
+ titres (une ligne, 200 caractères au plus, caractères de contrôle retirés) et
220
+ des adresses `http(s)` sans identifiants, dédoublonnées (20 pages, 10 recherches
221
+ au plus) ; il ne les relit jamais comme des consignes et ne les remet jamais
222
+ dans un message. `readGeminiGrounding(réponse)` fait la même lecture sur une
223
+ réponse brute. Google demande d'afficher ses suggestions de recherche avec une
224
+ réponse sourcée : `searchSuggestionsHtml` les rend telles quelles, à afficher
225
+ dans un cadre isolé.
226
+
180
227
  ## Outils natifs : la boucle d'un agent qui appelle ses outils
181
228
 
182
229
  ```js
@@ -806,6 +853,20 @@ Errors have clean codes: `AI_NO_PROVIDER`, `AI_NO_MATCH`, `AI_UNAVAILABLE`,
806
853
  silently losing a distributed quota. Transport messages and credentials are
807
854
  not included in these errors.
808
855
 
856
+ ### Gemini Google Search grounding
857
+
858
+ Set `googleSearch` on a request to enable Gemini's built-in search tool
859
+ (`google_search`). OpenAI-format providers ignore it. A `detailed` Gemini
860
+ provider then returns `grounding: { searched, queries, sources: [{ title, url }],
861
+ searchSuggestionsHtml, functionsDropped }`. With application functions,
862
+ `combine` sends both tools, `alone` sends only search for that turn, and `auto`
863
+ (default) sends both and retries with search alone when the API rejects the
864
+ combination (HTTP 400). Pages are untrusted data: only cleaned single-line
865
+ titles and credential-free `http(s)` URLs are returned (at most 20 sources and
866
+ 10 queries); nothing from a page is ever treated as an instruction.
867
+ `readGeminiGrounding(response)` reads a raw generateContent response the same
868
+ way.
869
+
809
870
  ### Injectable state: memory, Redis, PostgreSQL
810
871
 
811
872
  ```js
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/ai",
3
- "version": "1.8.0",
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
@@ -13,10 +13,15 @@ const { readRetryAfter } = require('./providerLimits');
13
13
  * - une réponse arrêtée à sa longueur (MAX_TOKENS) le dit (`cut`), pour que le
14
14
  * routeur la garde en dernier recours seulement ;
15
15
  * - la clé part dans l'en-tête, jamais dans l'adresse (où elle finirait dans
16
- * les journaux).
16
+ * les journaux) ;
17
+ * - la recherche Google intégrée (`googleSearch` sur la requête) rend ses
18
+ * sources sous une forme stable (`grounding`) ; les pages lues sont des
19
+ * DONNÉES NON FIABLES : rien ici ne les relit comme des consignes, seuls
20
+ * des titres et des adresses http(s) nettoyés sont rendus.
17
21
  */
18
22
 
19
23
  const { providerResult, readWrittenAnswer, withoutThinking } = require('./modelAnswers');
24
+ const { readServerEvents, textReporter } = require('./streamedAnswer');
20
25
 
21
26
  const DEFAULT_ENDPOINT = 'https://generativelanguage.googleapis.com/v1beta/models';
22
27
  const DEFAULT_TIMEOUT_MS = 45_000;
@@ -43,14 +48,90 @@ function contentsOf(messages) {
43
48
  });
44
49
  }
45
50
 
51
+ /* ─────────── Recherche Google intégrée ─────────── */
52
+
53
+ const SEARCH_FUNCTION_MODES = new Set(['auto', 'combine', 'alone']);
54
+ const MAX_QUERIES = 10;
55
+ const MAX_SOURCES = 20;
56
+ const MAX_QUERY_LENGTH = 300;
57
+ const MAX_TITLE_LENGTH = 200;
58
+ const MAX_URL_LENGTH = 2048;
59
+
60
+ /**
61
+ * L'option `googleSearch` d'une requête : `true` vaut `{ functions: 'auto' }`.
62
+ * - 'combine' : l'outil de recherche part avec les fonctions de l'application ;
63
+ * - 'alone' : pour ce tour, la recherche seule (les fonctions ne partent pas) ;
64
+ * - 'auto' : d'abord ensemble ; si l'API refuse le mélange (400), une seconde
65
+ * demande part avec la recherche seule.
66
+ */
67
+ function searchOptions(value) {
68
+ if (!value) return null;
69
+ const functions = value === true ? 'auto' : (value.functions || 'auto');
70
+ if (!SEARCH_FUNCTION_MODES.has(functions)) throw new TypeError('googleSearch.functions must be "auto", "combine" or "alone".');
71
+ return { functions };
72
+ }
73
+
74
+ /* Une chaîne lue dans une page : caractères de contrôle retirés, espaces resserrés, bornée. */
75
+ function cleanLine(value, max) {
76
+ if (typeof value !== 'string') return '';
77
+ // eslint-disable-next-line no-control-regex
78
+ const line = value.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069]/g, ' ').replace(/\s+/g, ' ').trim();
79
+ return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;
80
+ }
81
+
82
+ /* Une adresse http(s) seulement, sans identifiants ; sinon null. */
83
+ function cleanUrl(value) {
84
+ if (typeof value !== 'string' || value.length > MAX_URL_LENGTH) return null;
85
+ let url;
86
+ try {
87
+ url = new URL(value.trim());
88
+ } catch (_error) {
89
+ return null;
90
+ }
91
+ if ((url.protocol !== 'https:' && url.protocol !== 'http:') || url.username || url.password) return null;
92
+ return url.href;
93
+ }
94
+
95
+ /**
96
+ * Les sources d'une réponse Gemini (`groundingMetadata`) : les recherches faites,
97
+ * et les pages (titre, adresse) dédoublonnées et bornées. Accepte la réponse
98
+ * entière de generateContent ou l'un de ses candidats. Ne lève jamais.
99
+ * @returns {{ searched: boolean, queries: string[], sources: { title: string, url: string }[], searchSuggestionsHtml: string|null }}
100
+ */
101
+ function readGeminiGrounding(answer) {
102
+ const candidate = answer && Array.isArray(answer.candidates) ? answer.candidates[0] : answer;
103
+ const metadata = (candidate && typeof candidate === 'object' && candidate.groundingMetadata) || {};
104
+ const queries = [];
105
+ for (const raw of Array.isArray(metadata.webSearchQueries) ? metadata.webSearchQueries : []) {
106
+ const query = cleanLine(raw, MAX_QUERY_LENGTH);
107
+ if (query && !queries.includes(query) && queries.length < MAX_QUERIES) queries.push(query);
108
+ }
109
+ const sources = [];
110
+ for (const chunk of Array.isArray(metadata.groundingChunks) ? metadata.groundingChunks : []) {
111
+ const web = chunk && typeof chunk === 'object' ? chunk.web : null;
112
+ const url = web ? cleanUrl(web.uri) : null;
113
+ if (!url || sources.some((source) => source.url === url)) continue;
114
+ const title = cleanLine(web.title, MAX_TITLE_LENGTH) || new URL(url).hostname;
115
+ sources.push({ title, url });
116
+ if (sources.length >= MAX_SOURCES) break;
117
+ }
118
+ const entry = metadata.searchEntryPoint && typeof metadata.searchEntryPoint.renderedContent === 'string'
119
+ ? metadata.searchEntryPoint.renderedContent
120
+ : null;
121
+ return { searched: queries.length > 0 || sources.length > 0, queries, sources, searchSuggestionsHtml: entry };
122
+ }
123
+
46
124
  /** Le corps de la requête pour un modèle. */
47
- function requestBody(model, request, noSystemInstruction) {
125
+ function requestBody(model, request, noSystemInstruction, search = null, dropFunctions = false) {
48
126
  const contents = contentsOf(request.messages);
49
127
  const generationConfig = {
50
128
  temperature: request.temperature === undefined ? 0.4 : request.temperature,
51
129
  maxOutputTokens: request.maxTokens || 1200
52
130
  };
53
- const functions = request.tools && request.tools.length ? { tools: [{ functionDeclarations: request.tools }] } : {};
131
+ const toolList = [];
132
+ if (request.tools && request.tools.length && !dropFunctions) toolList.push({ functionDeclarations: request.tools });
133
+ if (search) toolList.push({ google_search: {} });
134
+ const functions = toolList.length ? { tools: toolList } : {};
54
135
  const system = request.system || '';
55
136
  if (!noSystemInstruction(model)) {
56
137
  return { ...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}), contents, generationConfig, ...functions };
@@ -69,38 +150,76 @@ function requestBody(model, request, noSystemInstruction) {
69
150
  /**
70
151
  * Demande à un modèle Gemini.
71
152
  * @param {string} model
72
- * @param {{ system?: string, messages: object[], tools?: object[], maxTokens?: number, temperature?: number }} request
153
+ * @param {{ system?: string, messages: object[], tools?: object[], maxTokens?: number, temperature?: number, googleSearch?: boolean|{ functions?: 'auto'|'combine'|'alone' } }} request
73
154
  * @param {{ key: string, fetch: Function, signal?: AbortSignal, timeoutMs?: number, endpoint?: string, noSystemInstruction?: Function }} io
74
- * @returns {Promise<{ status: number, text?: string|null, toolCalls?: object[], cut?: boolean }>}
75
- * Un refus se résout en `{ status }` — rien n'est levé pour lui.
155
+ * @returns {Promise<{ status: number, text?: string|null, toolCalls?: object[], cut?: boolean, grounding?: object }>}
156
+ * Un refus se résout en `{ status }` — rien n'est levé pour lui. Avec
157
+ * `googleSearch`, la réponse porte `grounding` (voir readGeminiGrounding),
158
+ * plus `functionsDropped` : vrai quand les fonctions ne sont pas parties.
76
159
  */
77
160
  async function askGeminiModel(model, request, io = {}) {
78
161
  if (typeof io.fetch !== 'function') throw new Error('askGeminiModel requires io.fetch.');
162
+ const search = searchOptions(request.googleSearch);
163
+ const hasFunctions = Boolean(request.tools && request.tools.length);
79
164
  const timeout = globalThis.AbortSignal.timeout(io.timeoutMs || DEFAULT_TIMEOUT_MS);
80
165
  const signal = io.signal ? globalThis.AbortSignal.any([io.signal, timeout]) : timeout;
81
- const response = await io.fetch(`${io.endpoint || DEFAULT_ENDPOINT}/${model}:generateContent`, {
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}`, {
82
170
  method: 'POST',
83
171
  headers: { 'content-type': 'application/json', 'x-goog-api-key': io.key },
84
- body: JSON.stringify({ ...requestBody(model, request, io.noSystemInstruction || noSystemInstructionByDefault), ...(io.extra || {}) }),
172
+ body: JSON.stringify({ ...requestBody(model, request, io.noSystemInstruction || noSystemInstructionByDefault, search, dropFunctions), ...(io.extra || {}) }),
85
173
  signal
86
174
  });
175
+ let functionsDropped = Boolean(search && hasFunctions && search.functions === 'alone');
176
+ let response = await send(functionsDropped);
177
+ /* Le mélange recherche + fonctions refusé par l'API : la recherche seule, pour ce tour. */
178
+ if (!response.ok && response.status === 400 && search && hasFunctions && search.functions === 'auto') {
179
+ functionsDropped = true;
180
+ response = await send(true);
181
+ }
87
182
  if (!response.ok) {
88
183
  const retryAfterMs = readRetryAfter(response);
89
184
  return { status: response.status, ...(retryAfterMs === null ? {} : { retryAfterMs }) };
90
185
  }
91
- const answer = await response.json();
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();
92
188
  const candidate = (answer && answer.candidates && answer.candidates[0]) || {};
189
+ const grounding = search ? { grounding: { ...readGeminiGrounding(candidate), functionsDropped } } : {};
93
190
  const parts = (candidate.content && candidate.content.parts) || [];
94
- const toolCalls = parts.filter((part) => part.functionCall).map((part, index) => ({
191
+ const toolCalls = functionsDropped ? [] : parts.filter((part) => part.functionCall).map((part, index) => ({
95
192
  id: part.functionCall.id || `call_${index}`,
96
193
  name: part.functionCall.name,
97
194
  args: argsOf(part.functionCall.args)
98
195
  }));
99
- if (toolCalls.length) return { status: response.status, text: null, toolCalls };
100
- const text = withoutThinking(parts.filter((part) => !part.thought).map((part) => part.text || '').join(''));
101
- const written = readWrittenAnswer(text, Boolean(request.tools && request.tools.length));
102
- if (written) return { status: response.status, ...written };
103
- return { status: response.status, text, cut: candidate.finishReason === 'MAX_TOKENS' };
196
+ if (toolCalls.length) return { status: response.status, text: null, toolCalls, ...grounding };
197
+ const text = withoutThinking(parts.filter((part) => !part.thought && !part.functionCall).map((part) => part.text || '').join(''));
198
+ const written = readWrittenAnswer(text, hasFunctions && !functionsDropped);
199
+ if (written) return { status: response.status, ...written, ...grounding };
200
+ return { status: response.status, text, cut: candidate.finishReason === 'MAX_TOKENS', ...grounding };
201
+ }
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 } : {}) }] };
104
223
  }
105
224
 
106
225
  /**
@@ -148,6 +267,7 @@ function createGeminiProvider(options = {}) {
148
267
  timeoutMs: ctx.timeoutMs || options.timeoutMs,
149
268
  endpoint: options.endpoint,
150
269
  noSystemInstruction: options.noSystemInstruction,
270
+ onText: ctx.onText,
151
271
  extra: { ...(options.extra || {}), ...(model.extra || {}) }
152
272
  });
153
273
  return providerResult(id, answer, options.detailed);
@@ -155,4 +275,4 @@ function createGeminiProvider(options = {}) {
155
275
  };
156
276
  }
157
277
 
158
- module.exports = { askGeminiModel, createGeminiProvider };
278
+ module.exports = { askGeminiModel, createGeminiProvider, readGeminiGrounding };
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. */
@@ -615,12 +629,41 @@ export function readWrittenToolCalls(text: string): Array<{ id: string; name: st
615
629
  /** Le raisonnement entre balises think retiré, même ouvert sans fin ou fermé sans ouverture. */
616
630
  export function withoutThinking(content: unknown): string;
617
631
 
632
+ /**
633
+ * La recherche Google intégrée de Gemini (outil `google_search`). Ignorée par
634
+ * les fournisseurs au format OpenAI.
635
+ * - 'combine' : la recherche part avec les fonctions de l'application ;
636
+ * - 'alone' : la recherche seule pour ce tour (les fonctions ne partent pas) ;
637
+ * - 'auto' : ensemble d'abord, puis la recherche seule si l'API refuse le mélange (400).
638
+ */
639
+ export type GoogleSearchOption = boolean | { functions?: 'auto' | 'combine' | 'alone' };
640
+
641
+ /** Une page citée par la recherche : titre (une ligne, bornée) et adresse http(s). Données non fiables. */
642
+ export interface GroundingSource {
643
+ title: string;
644
+ url: string;
645
+ }
646
+
647
+ /** Les sources d'une réponse Gemini avec recherche Google. */
648
+ export interface GeminiGrounding {
649
+ /** Vrai quand le modèle a vraiment cherché (requêtes ou pages). */
650
+ searched: boolean;
651
+ /** Les recherches faites, dédoublonnées, au plus 10. */
652
+ queries: string[];
653
+ /** Les pages, dédoublonnées par adresse, au plus 20. */
654
+ sources: GroundingSource[];
655
+ /** Les suggestions de recherche que Google demande d'afficher (HTML tel que rendu par l'API), ou null. */
656
+ searchSuggestionsHtml: string | null;
657
+ }
658
+
618
659
  export interface ChatRequest {
619
660
  system?: string;
620
661
  messages: ChatMessage[];
621
662
  tools?: Array<Record<string, unknown>>;
622
663
  maxTokens?: number;
623
664
  temperature?: number;
665
+ /** Gemini seulement : active la recherche Google intégrée pour cette requête. */
666
+ googleSearch?: GoogleSearchOption;
624
667
  }
625
668
 
626
669
  /** Ce qu'un fournisseur `detailed` rend au routeur. */
@@ -628,6 +671,8 @@ export interface DetailedAnswer {
628
671
  text: string | null;
629
672
  toolCalls: ChatToolCall[];
630
673
  cut: boolean;
674
+ /** Présent quand la requête demandait `googleSearch` à un fournisseur Gemini. */
675
+ grounding?: GeminiGrounding & { functionsDropped: boolean };
631
676
  }
632
677
 
633
678
  export interface ChatProviderOptions {
@@ -654,8 +699,11 @@ export function createOpenAICompatibleProvider(options: ChatProviderOptions & {
654
699
  export function askGeminiModel(
655
700
  model: string,
656
701
  request: ChatRequest,
657
- io: { key: string; fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; endpoint?: string; noSystemInstruction?: (model: string) => boolean; extra?: Record<string, unknown> }
658
- ): Promise<{ status: number; text?: string | null; toolCalls?: ChatToolCall[]; cut?: boolean; retryAfterMs?: number }>;
702
+ io: { key: string; fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; endpoint?: string; noSystemInstruction?: (model: string) => boolean; extra?: Record<string, unknown>; onText?: (shown: string) => void }
703
+ ): Promise<{ status: number; text?: string | null; toolCalls?: ChatToolCall[]; cut?: boolean; retryAfterMs?: number; grounding?: GeminiGrounding & { functionsDropped: boolean } }>;
704
+
705
+ /** Les sources d'une réponse generateContent (ou d'un de ses candidats), nettoyées et bornées. Ne lève jamais. */
706
+ export function readGeminiGrounding(answer: unknown): GeminiGrounding;
659
707
 
660
708
  export function createGeminiProvider(options: ChatProviderOptions & {
661
709
  id?: string;
package/src/index.js CHANGED
@@ -16,6 +16,7 @@ module.exports = {
16
16
  ...require('./openaiCompatible'),
17
17
  ...require('./llamaCpp'),
18
18
  ...require('./gemini'),
19
+ ...require('./streamedAnswer'),
19
20
  ...require('./nativeTools'),
20
21
  ...require('./eventStream'),
21
22
  ...require('./webSearch'),
@@ -107,7 +107,14 @@ function providerResult(id, answer, detailed) {
107
107
  if (answer.retryAfterMs != null) failure.retryAfterMs = answer.retryAfterMs;
108
108
  throw failure;
109
109
  }
110
- if (detailed) return { text: answer.text === undefined ? null : answer.text, toolCalls: answer.toolCalls || [], cut: Boolean(answer.cut) };
110
+ if (detailed) {
111
+ return {
112
+ text: answer.text === undefined ? null : answer.text,
113
+ toolCalls: answer.toolCalls || [],
114
+ cut: Boolean(answer.cut),
115
+ ...(answer.grounding ? { grounding: answer.grounding } : {})
116
+ };
117
+ }
111
118
  if (answer.toolCalls && answer.toolCalls.length) return { toolCalls: answer.toolCalls };
112
119
  if (!answer.text) {
113
120
  const empty = new Error(`Provider "${id}" gave no text.`);
@@ -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 answer = await response.json();
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
  }
@@ -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
- const send = async () => provider.call(outbound ? await masker.maskAsync(prompt) : prompt, providerCtx, model);
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 };