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