@astratra/ai 1.4.0 → 1.5.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 +134 -7
- package/package.json +1 -1
- package/src/answerText.js +21 -1
- package/src/askLimit.js +5 -1
- package/src/eventStream.js +47 -0
- package/src/gemini.js +152 -0
- package/src/index.d.ts +209 -12
- package/src/index.js +5 -1
- package/src/modelAnswers.js +119 -0
- package/src/nativeTools.js +256 -0
- package/src/openaiCompatible.js +33 -45
- package/src/providerRouter.js +154 -40
- package/src/webSearch.js +71 -0
package/src/index.d.ts
CHANGED
|
@@ -14,15 +14,34 @@ export interface Provider {
|
|
|
14
14
|
models: ProviderModel[];
|
|
15
15
|
/** False for a model running on this machine: the router does not mask for it. */
|
|
16
16
|
external?: boolean;
|
|
17
|
-
|
|
17
|
+
/** Faux (sans clé, éteint) : le routeur le saute sans rien lui demander ni compter d'échec. */
|
|
18
|
+
available?(ctx: Record<string, unknown>): Awaitable<boolean>;
|
|
19
|
+
/** Une voie : une clé à elle pour cet usage, qui se repose seule ("fournisseur:modèle@voie"). */
|
|
20
|
+
lane?(ctx: Record<string, unknown>): string | null | undefined;
|
|
21
|
+
call(prompt: any, ctx: Record<string, unknown>, model: ProviderModel): Awaitable<unknown>;
|
|
18
22
|
[key: string]: unknown;
|
|
19
23
|
}
|
|
20
24
|
|
|
25
|
+
/** Un candidat de `request.candidates` : un modèle d'un fournisseur, avec ses champs (extra, vision…). */
|
|
26
|
+
export interface RouteCandidate {
|
|
27
|
+
provider: string;
|
|
28
|
+
model: string;
|
|
29
|
+
[field: string]: unknown;
|
|
30
|
+
}
|
|
31
|
+
|
|
21
32
|
export interface ProviderRequest {
|
|
22
33
|
complexity?: string;
|
|
23
34
|
estimatedTokens?: number;
|
|
24
35
|
intent?: string;
|
|
25
36
|
maxTokens?: number;
|
|
37
|
+
/** L'ordre de CETTE demande, à travers les fournisseurs. */
|
|
38
|
+
candidates?: RouteCandidate[];
|
|
39
|
+
/** Ne garde que les modèles aptes à cette demande (une photo : ceux qui voient). */
|
|
40
|
+
select?: (model: ProviderModel, provider: Provider) => boolean;
|
|
41
|
+
/** Faux : la réponse est refusée, le modèle suivant est demandé (ce n'est pas une panne du modèle). */
|
|
42
|
+
accepts?: (value: any) => boolean;
|
|
43
|
+
/** Vrai : réponse coupée, gardée en dernier recours seulement. */
|
|
44
|
+
partial?: (value: any) => boolean;
|
|
26
45
|
[key: string]: unknown;
|
|
27
46
|
}
|
|
28
47
|
|
|
@@ -37,8 +56,32 @@ export interface ProviderRouterConfig {
|
|
|
37
56
|
redisUrl?: string;
|
|
38
57
|
/** One circuit per provider: a factory (providerId) => breaker, or a pool. */
|
|
39
58
|
breakers?: ((providerId: string) => BreakerLike) | BreakerPool;
|
|
59
|
+
/** Ce qui met un modèle au repos (cooldownMs). Défaut : un 429. */
|
|
60
|
+
cooldownOn?: (error: any) => boolean;
|
|
61
|
+
/** 'try' : quand tous les candidats se reposent, on les essaie quand même. Défaut 'skip'. */
|
|
62
|
+
whenAllCooling?: 'skip' | 'try';
|
|
63
|
+
/** L'horloge des repos et des quotas. Défaut Date.now. */
|
|
64
|
+
now?: () => number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface RouteResult<T = unknown> {
|
|
68
|
+
value: T;
|
|
69
|
+
provider: string;
|
|
70
|
+
model: string;
|
|
71
|
+
/** "fournisseur:modèle", suivi de "@voie" quand le fournisseur en a une pour cet appel. */
|
|
72
|
+
key: string;
|
|
73
|
+
/** La réponse coupée gardée en dernier recours. */
|
|
74
|
+
partial: boolean;
|
|
40
75
|
}
|
|
41
76
|
|
|
77
|
+
/**
|
|
78
|
+
* Levée par ask/route (AppError 503) : `code` vaut 'AI_NO_PROVIDER' (aucun
|
|
79
|
+
* fournisseur disponible), 'AI_NO_MATCH' (aucun ne convient à la demande) ou
|
|
80
|
+
* 'AI_UNAVAILABLE' (tous essayés, aucun n'a répondu ; `errors` les porte).
|
|
81
|
+
* Une demande abandonnée (ctx.signal) lève la raison de l'appelant.
|
|
82
|
+
*/
|
|
83
|
+
export type RouterErrorCode = 'AI_NO_PROVIDER' | 'AI_NO_MATCH' | 'AI_UNAVAILABLE';
|
|
84
|
+
|
|
42
85
|
export interface ProviderStats {
|
|
43
86
|
provider: string;
|
|
44
87
|
rpm_now: number;
|
|
@@ -55,9 +98,13 @@ export interface ProviderStats {
|
|
|
55
98
|
}
|
|
56
99
|
|
|
57
100
|
export interface ProviderRouter {
|
|
58
|
-
ask(prompt:
|
|
59
|
-
/**
|
|
101
|
+
ask(prompt: any, request?: ProviderRequest, ctx?: Record<string, unknown>): Promise<unknown>;
|
|
102
|
+
/** Comme ask, et dit qui a répondu. */
|
|
103
|
+
route(prompt: any, request?: ProviderRequest, ctx?: Record<string, unknown>): Promise<RouteResult>;
|
|
104
|
+
/** Les entrées sont indexées par "providerId:modelId" (et "@voie"). */
|
|
60
105
|
getStats(): Record<string, ProviderStats>;
|
|
106
|
+
/** Oublie repos, dégradations, échecs et usage. */
|
|
107
|
+
reset(): void;
|
|
61
108
|
stop(): void;
|
|
62
109
|
breakers: BreakerPool | null;
|
|
63
110
|
}
|
|
@@ -455,7 +502,10 @@ export function rerankResults<R, S, F extends { results: R[]; sources?: S[] }>(
|
|
|
455
502
|
/* ─────────────────── Answer text ─────────────────── */
|
|
456
503
|
|
|
457
504
|
export function plainText(text: unknown): string;
|
|
458
|
-
|
|
505
|
+
/** `remove` : des expressions globales retirées après les marques (ce que l'app ne montre jamais). */
|
|
506
|
+
export function tidyMarkdown(text: unknown, options?: { removeEmoji?: boolean; remove?: RegExp[] }): string;
|
|
507
|
+
/** Un texte coupé ramené à sa dernière phrase entière. */
|
|
508
|
+
export function wholeSentences(text: unknown, options?: { marks?: string[] }): string;
|
|
459
509
|
export function isFaithfulQuotation(quoted: string, source: string): boolean;
|
|
460
510
|
export function verifyQuotations<Refs = unknown>(text: string, options: {
|
|
461
511
|
findReferences: (text: string) => Awaitable<Array<{ start: number; end: number; refs: Refs }>>;
|
|
@@ -514,6 +564,10 @@ export interface ChatToolCall {
|
|
|
514
564
|
args: Record<string, unknown> | null;
|
|
515
565
|
/** The model sent arguments that are not a JSON object. */
|
|
516
566
|
invalid?: true;
|
|
567
|
+
/** Pourquoi : 'not_json' (illisible) ou 'not_object'. */
|
|
568
|
+
invalidReason?: 'not_json' | 'not_object';
|
|
569
|
+
/** L'erreur de lecture, pour 'not_json'. */
|
|
570
|
+
invalidDetail?: string;
|
|
517
571
|
}
|
|
518
572
|
|
|
519
573
|
export type FetchLike = (url: string, init: { method: string; headers: Record<string, string>; body: string; signal?: AbortSignal }) => Promise<{ ok: boolean; status: number; json(): Promise<any> }>;
|
|
@@ -524,16 +578,159 @@ export function askChatModel(
|
|
|
524
578
|
io: { fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number }
|
|
525
579
|
): Promise<{ status: number; text?: string | null; toolCalls?: ChatToolCall[]; cut?: boolean }>;
|
|
526
580
|
|
|
527
|
-
export function readToolArguments(raw: unknown): { args: Record<string, unknown> | null; invalid: boolean };
|
|
581
|
+
export function readToolArguments(raw: unknown): { args: Record<string, unknown> | null; invalid: boolean; reason?: 'not_json' | 'not_object'; detail?: string };
|
|
528
582
|
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
583
|
+
/** Les appels d'outil écrits dans un texte (<function=…>, <tool_call>{…}</tool_call>), relus. */
|
|
584
|
+
export function readWrittenToolCalls(text: string): Array<{ id: string; name: string; args: Record<string, unknown> }>;
|
|
585
|
+
/** Le raisonnement entre balises think retiré, même ouvert sans fin ou fermé sans ouverture. */
|
|
586
|
+
export function withoutThinking(content: unknown): string;
|
|
587
|
+
|
|
588
|
+
export interface ChatRequest {
|
|
589
|
+
system?: string;
|
|
590
|
+
messages: ChatMessage[];
|
|
591
|
+
tools?: Array<Record<string, unknown>>;
|
|
592
|
+
maxTokens?: number;
|
|
593
|
+
temperature?: number;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** Ce qu'un fournisseur `detailed` rend au routeur. */
|
|
597
|
+
export interface DetailedAnswer {
|
|
598
|
+
text: string | null;
|
|
599
|
+
toolCalls: ChatToolCall[];
|
|
600
|
+
cut: boolean;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
export interface ChatProviderOptions {
|
|
604
|
+
getKey: (ctx: Record<string, unknown>) => Awaitable<string | null | undefined>;
|
|
605
|
+
models?: ProviderModel[];
|
|
606
|
+
/** `ctx.fetch` le remplace pour un appel. */
|
|
534
607
|
fetch: FetchLike;
|
|
535
|
-
external?: boolean;
|
|
536
608
|
timeoutMs?: number;
|
|
609
|
+
lane?: (ctx: Record<string, unknown>) => string | null | undefined;
|
|
610
|
+
/** Vrai : l'appel rend { text, toolCalls, cut } au lieu du texte seul. */
|
|
611
|
+
detailed?: boolean;
|
|
612
|
+
toRequest?: (prompt: any, ctx: Record<string, unknown>) => ChatRequest;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
export function createOpenAICompatibleProvider(options: ChatProviderOptions & {
|
|
616
|
+
id: string;
|
|
617
|
+
url: string | ((ctx: Record<string, unknown>) => string | null | undefined);
|
|
618
|
+
external?: boolean;
|
|
537
619
|
extra?: Record<string, unknown>;
|
|
538
|
-
toRequest?: (prompt: string, ctx: Record<string, unknown>) => { system?: string; messages: ChatMessage[] };
|
|
539
620
|
}): Provider;
|
|
621
|
+
|
|
622
|
+
/* ─────────────────── Gemini ─────────────────── */
|
|
623
|
+
|
|
624
|
+
export function askGeminiModel(
|
|
625
|
+
model: string,
|
|
626
|
+
request: ChatRequest,
|
|
627
|
+
io: { key: string; fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; endpoint?: string; noSystemInstruction?: (model: string) => boolean }
|
|
628
|
+
): Promise<{ status: number; text?: string | null; toolCalls?: ChatToolCall[]; cut?: boolean }>;
|
|
629
|
+
|
|
630
|
+
export function createGeminiProvider(options: ChatProviderOptions & {
|
|
631
|
+
id?: string;
|
|
632
|
+
endpoint?: string;
|
|
633
|
+
/** Défaut : les modèles Gemma, qui ne prennent pas de consigne système. */
|
|
634
|
+
noSystemInstruction?: (model: string) => boolean;
|
|
635
|
+
}): Provider;
|
|
636
|
+
|
|
637
|
+
/* ─────────────────── Outils natifs et leur boucle ─────────────────── */
|
|
638
|
+
|
|
639
|
+
export type NativeToolKind = 'read' | 'write' | 'confirm' | string;
|
|
640
|
+
|
|
641
|
+
export interface NativeToolResult {
|
|
642
|
+
data?: unknown;
|
|
643
|
+
sources?: Array<Record<string, unknown>>;
|
|
644
|
+
card?: Record<string, unknown>;
|
|
645
|
+
undo?: unknown;
|
|
646
|
+
[key: string]: unknown;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
export interface NativeTool<Ctx = Record<string, unknown>> {
|
|
650
|
+
name: string;
|
|
651
|
+
description: string;
|
|
652
|
+
parameters: { type: 'object'; [key: string]: unknown };
|
|
653
|
+
kind: NativeToolKind;
|
|
654
|
+
summary?: (args: Record<string, unknown>) => Record<string, string | number>;
|
|
655
|
+
run(args: Record<string, unknown>, ctx: Ctx & { signal: AbortSignal }): Awaitable<NativeToolResult | null | undefined>;
|
|
656
|
+
perform?(args: Record<string, unknown>, ctx: Ctx): Awaitable<NativeToolResult | null | undefined>;
|
|
657
|
+
undo?(undo: unknown, ctx: Ctx): Awaitable<unknown>;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
export const NATIVE_TOOL_KINDS: string[];
|
|
661
|
+
export function validateNativeTools<T extends NativeTool<any>>(tools: T[], options?: { kinds?: string[]; requireSummary?: boolean }): T[];
|
|
662
|
+
export function toolSpecs(tools: NativeTool<any>[]): Array<{ name: string; description: string; parameters: Record<string, unknown> }>;
|
|
663
|
+
export function stepParams(tool: NativeTool<any> | null | undefined, args: unknown, options?: { max?: number }): Record<string, string | number>;
|
|
664
|
+
|
|
665
|
+
export interface NativeToolCall {
|
|
666
|
+
id: string;
|
|
667
|
+
name: string;
|
|
668
|
+
args: Record<string, unknown> | null;
|
|
669
|
+
invalid?: boolean;
|
|
670
|
+
invalidReason?: 'not_json' | 'not_object';
|
|
671
|
+
invalidDetail?: string;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
export interface ToolMessage {
|
|
675
|
+
role: 'tool';
|
|
676
|
+
toolCallId: string;
|
|
677
|
+
name: string;
|
|
678
|
+
result: unknown;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
export function createToolCaller<Ctx = Record<string, unknown>>(options: {
|
|
682
|
+
tools: Map<string, NativeTool<Ctx>> | NativeTool<Ctx>[];
|
|
683
|
+
context?: Ctx;
|
|
684
|
+
signal?: AbortSignal;
|
|
685
|
+
timeoutMs?: number;
|
|
686
|
+
now?: () => number;
|
|
687
|
+
emit?: (type: 'step' | 'step_done', data: Record<string, unknown>) => void;
|
|
688
|
+
keep?: (sources: unknown, data: unknown) => void;
|
|
689
|
+
record?: (entry: { tool: NativeTool<Ctx>; args: Record<string, unknown> | null; found: NativeToolResult }) => Awaitable<void>;
|
|
690
|
+
onCall?: (stats: { name: string; ms: number; ok: boolean }) => void;
|
|
691
|
+
resultMax?: number;
|
|
692
|
+
messages?: {
|
|
693
|
+
unknownTool?: (name: string) => string;
|
|
694
|
+
timeout?: () => string;
|
|
695
|
+
invalidArguments?: (call: { name: string; invalidReason?: string; invalidDetail?: string }) => string;
|
|
696
|
+
waiting?: string;
|
|
697
|
+
};
|
|
698
|
+
}): (call: NativeToolCall) => Promise<ToolMessage>;
|
|
699
|
+
|
|
700
|
+
export interface ToolTurn {
|
|
701
|
+
text: string | null;
|
|
702
|
+
toolCalls: NativeToolCall[];
|
|
703
|
+
model?: string;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/** Lève une AppError de code 'AI_NO_ANSWER' quand un tour ne donne ni texte ni outil. */
|
|
707
|
+
export function runToolLoop(options: {
|
|
708
|
+
system: string;
|
|
709
|
+
messages: Array<ChatMessage | ToolMessage | Record<string, unknown>>;
|
|
710
|
+
tools?: Array<Record<string, unknown>>;
|
|
711
|
+
turn: (request: { system: string; messages: any[]; tools: Array<Record<string, unknown>> }) => Awaitable<ToolTurn>;
|
|
712
|
+
callTool: (call: NativeToolCall) => Promise<ToolMessage>;
|
|
713
|
+
maxTurns?: number;
|
|
714
|
+
maxMs?: number;
|
|
715
|
+
finalInstruction?: string;
|
|
716
|
+
now?: () => number;
|
|
717
|
+
signal?: AbortSignal;
|
|
718
|
+
}): Promise<{ text: string; turns: number }>;
|
|
719
|
+
|
|
720
|
+
/* ─────────────────── Flux d'évènements (SSE) ─────────────────── */
|
|
721
|
+
|
|
722
|
+
export const EVENT_STREAM_HEADERS: Record<string, string>;
|
|
723
|
+
export function openEventStream(
|
|
724
|
+
res: { statusCode: number; setHeader(name: string, value: string): unknown; flushHeaders(): void; write(chunk: string): unknown; end(): unknown; on(event: 'close', listener: () => void): unknown; writableEnded: boolean },
|
|
725
|
+
options?: { headers?: Record<string, string> }
|
|
726
|
+
): { send(type: string, data: unknown): void; close(): void; signal: AbortSignal };
|
|
727
|
+
|
|
728
|
+
/* ─────────────────── Recherche web ─────────────────── */
|
|
729
|
+
|
|
730
|
+
export interface WebResult { title: string; url: string; snippet: string; date: string | null }
|
|
731
|
+
|
|
732
|
+
/** Lève une erreur de code 'WEB_SEARCH_NO_KEY' (rien n'est demandé) ou 'WEB_SEARCH_FAILED'. */
|
|
733
|
+
export function searchSerper(
|
|
734
|
+
search: { query: string; sites?: string[]; hl?: string; num?: number },
|
|
735
|
+
io: { key: string | null | undefined; fetch: FetchLike; accept?: (result: WebResult, url: URL) => boolean; timeoutMs?: number; endpoint?: string }
|
|
736
|
+
): Promise<WebResult[]>;
|
package/src/index.js
CHANGED
|
@@ -13,5 +13,9 @@ module.exports = {
|
|
|
13
13
|
...require('./answerText'),
|
|
14
14
|
...require('./language'),
|
|
15
15
|
...require('./askLimit'),
|
|
16
|
-
...require('./openaiCompatible')
|
|
16
|
+
...require('./openaiCompatible'),
|
|
17
|
+
...require('./gemini'),
|
|
18
|
+
...require('./nativeTools'),
|
|
19
|
+
...require('./eventStream'),
|
|
20
|
+
...require('./webSearch')
|
|
17
21
|
};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lire la réponse d'un modèle, quel que soit le fournisseur (format OpenAI,
|
|
3
|
+
* Gemini…) : son raisonnement retiré, ses appels d'outil lus — y compris ceux
|
|
4
|
+
* qu'il a écrits dans son texte au lieu de les demander —, et ce que le
|
|
5
|
+
* fournisseur rend au routeur. Module interne : les adaptateurs le partagent.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Le raisonnement d'un modèle écrit entre balises think n'est jamais montré.
|
|
10
|
+
* Un raisonnement resté ouvert (réponse coupée à sa longueur) part jusqu'à la
|
|
11
|
+
* fin ; une balise fermante sans ouvrante (un gabarit qui l'a ouverte lui-même)
|
|
12
|
+
* emporte tout ce qui la précède.
|
|
13
|
+
*/
|
|
14
|
+
function withoutThinking(content) {
|
|
15
|
+
let text = String(content === null || content === undefined ? '' : content).replace(/<think>[\s\S]*?<\/think>/gi, '');
|
|
16
|
+
const closing = text.toLowerCase().lastIndexOf('</think>');
|
|
17
|
+
if (closing >= 0) text = text.slice(closing + '</think>'.length);
|
|
18
|
+
const opening = text.toLowerCase().indexOf('<think>');
|
|
19
|
+
if (opening >= 0) text = text.slice(0, opening);
|
|
20
|
+
return text.trim();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/* Un appel d'outil écrit dans le texte au lieu d'être demandé (façons de Qwen et de Hermes). */
|
|
24
|
+
const WRITTEN_CALL = /<tool_call>|<function=/;
|
|
25
|
+
|
|
26
|
+
/** Une valeur telle que le modèle l'a écrite : du JSON quand c'en est (un nombre, une liste), les mots sinon. */
|
|
27
|
+
function writtenValue(written) {
|
|
28
|
+
const text = written.trim();
|
|
29
|
+
try {
|
|
30
|
+
return JSON.parse(text);
|
|
31
|
+
} catch (_error) {
|
|
32
|
+
return text;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Les appels d'outil écrits en texte, relus en vrais appels :
|
|
38
|
+
* <function=nom><parameter=clé>valeur</parameter></function>, ou un JSON
|
|
39
|
+
* {"name", "arguments"} entre balises <tool_call>. Ce qui ne se relit pas
|
|
40
|
+
* proprement est laissé de côté.
|
|
41
|
+
* @returns {{ id: string, name: string, args: object }[]}
|
|
42
|
+
*/
|
|
43
|
+
function readWrittenToolCalls(text) {
|
|
44
|
+
const calls = [];
|
|
45
|
+
for (const [, name, body] of String(text || '').matchAll(/<function=([\w.-]+)>([\s\S]*?)<\/function>/g)) {
|
|
46
|
+
const args = Object.fromEntries([...body.matchAll(/<parameter=([\w.-]+)>([\s\S]*?)<\/parameter>/g)].map(([, key, value]) => [key, writtenValue(value)]));
|
|
47
|
+
calls.push({ name, args });
|
|
48
|
+
}
|
|
49
|
+
for (const [, body] of String(text || '').matchAll(/<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/g)) {
|
|
50
|
+
try {
|
|
51
|
+
const { name, arguments: args } = JSON.parse(body);
|
|
52
|
+
const parsed = typeof args === 'string' ? JSON.parse(args) : args;
|
|
53
|
+
if (typeof name === 'string' && parsed && typeof parsed === 'object' && !Array.isArray(parsed)) calls.push({ name, args: parsed });
|
|
54
|
+
} catch (_error) {
|
|
55
|
+
/* Illisible : laissé de côté. */
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return calls.map((call, index) => ({ id: `written-${index + 1}`, ...call }));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Une réponse en texte qui contient un appel écrit n'est JAMAIS une réponse à
|
|
63
|
+
* montrer : ses appels lisibles deviennent de vrais appels quand des outils
|
|
64
|
+
* étaient proposés, sinon il ne reste rien (le routeur passe au modèle suivant).
|
|
65
|
+
*/
|
|
66
|
+
function readWrittenAnswer(text, toolsOffered) {
|
|
67
|
+
if (!WRITTEN_CALL.test(text || '')) return null;
|
|
68
|
+
return { text: null, toolCalls: toolsOffered ? readWrittenToolCalls(text) : [] };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Tool arguments as an object, or null with `invalid: true` for anything else.
|
|
73
|
+
* `reason` dit pourquoi ('not_json' : texte illisible, `detail` porte l'erreur
|
|
74
|
+
* de lecture ; 'not_object' : du JSON, mais pas un objet) — de quoi dire au
|
|
75
|
+
* modèle quoi corriger quand il redemande l'outil.
|
|
76
|
+
*/
|
|
77
|
+
function readToolArguments(raw) {
|
|
78
|
+
if (raw === undefined || raw === null || (typeof raw === 'string' && !raw.trim())) return { args: {}, invalid: false };
|
|
79
|
+
if (typeof raw === 'object') {
|
|
80
|
+
return Array.isArray(raw) ? { args: null, invalid: true, reason: 'not_object' } : { args: raw, invalid: false };
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
const parsed = JSON.parse(String(raw));
|
|
84
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? { args: parsed, invalid: false } : { args: null, invalid: true, reason: 'not_object' };
|
|
85
|
+
} catch (error) {
|
|
86
|
+
return { args: null, invalid: true, reason: 'not_json', detail: error.message };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Un appel d'outil lu : ses arguments, et quand ils sont illisibles, pourquoi. */
|
|
91
|
+
function toolCallOf(id, name, rawArguments) {
|
|
92
|
+
const { args, invalid, reason, detail } = readToolArguments(rawArguments);
|
|
93
|
+
return {
|
|
94
|
+
id,
|
|
95
|
+
name,
|
|
96
|
+
args,
|
|
97
|
+
...(invalid ? { invalid: true, invalidReason: reason, ...(detail ? { invalidDetail: detail } : {}) } : {})
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** What a provider hands the router: a failure carries its status (never the key). */
|
|
102
|
+
function providerResult(id, answer, detailed) {
|
|
103
|
+
if (answer.status < 200 || answer.status >= 300) {
|
|
104
|
+
/* The status reaches the router (429 → cooldown); the key never does. */
|
|
105
|
+
const failure = new Error(`Provider "${id}" answered ${answer.status}.`);
|
|
106
|
+
failure.statusCode = answer.status;
|
|
107
|
+
throw failure;
|
|
108
|
+
}
|
|
109
|
+
if (detailed) return { text: answer.text === undefined ? null : answer.text, toolCalls: answer.toolCalls || [], cut: Boolean(answer.cut) };
|
|
110
|
+
if (answer.toolCalls && answer.toolCalls.length) return { toolCalls: answer.toolCalls };
|
|
111
|
+
if (!answer.text) {
|
|
112
|
+
const empty = new Error(`Provider "${id}" gave no text.`);
|
|
113
|
+
empty.statusCode = 502;
|
|
114
|
+
throw empty;
|
|
115
|
+
}
|
|
116
|
+
return answer.text;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
module.exports = { withoutThinking, readWrittenToolCalls, readWrittenAnswer, readToolArguments, toolCallOf, providerResult };
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Des outils demandés par le modèle lui-même (function calling natif), et la
|
|
3
|
+
* boucle qui les fait tourner.
|
|
4
|
+
*
|
|
5
|
+
* `runAgentLoop` lit un protocole écrit dans le texte (<tool_call name="…">) ;
|
|
6
|
+
* ici le fournisseur rend des appels structurés, plusieurs à la fois, et la
|
|
7
|
+
* transcription garde des messages typés (assistant avec ses appels, un
|
|
8
|
+
* message `tool` par résultat). Ce que l'usage a appris :
|
|
9
|
+
*
|
|
10
|
+
* - un outil qui échoue ou tarde devient une erreur que le modèle LIT, jamais
|
|
11
|
+
* une boucle cassée — il peut redemander autrement ;
|
|
12
|
+
* - un outil inventé, ou des arguments illisibles, n'exécutent rien : le
|
|
13
|
+
* modèle lit pourquoi, et le plus souvent se corrige au tour suivant ;
|
|
14
|
+
* - ce qu'un outil rend au modèle est borné : une page entière noierait la
|
|
15
|
+
* conversation ;
|
|
16
|
+
* - un outil « à confirmer » n'écrit rien : il prépare, un humain dispose. Le
|
|
17
|
+
* modèle lit que rien n'est encore fait ;
|
|
18
|
+
* - la personne qui part arrête tout, outils compris ;
|
|
19
|
+
* - à court de tours ou de temps, un dernier tour sans outils répond avec ce
|
|
20
|
+
* qui a été lu, plutôt qu'une erreur.
|
|
21
|
+
*
|
|
22
|
+
* Un outil : { name, description, parameters (schéma JSON d'un objet), kind,
|
|
23
|
+
* summary?(args), run(args, ctx) }, avec perform(args, ctx) quand son genre est
|
|
24
|
+
* 'confirm' (l'écriture, une fois confirmée) et undo(annulation, ctx) quand il
|
|
25
|
+
* est 'write' (il écrit seul, on peut revenir dessus). `summary` donne les
|
|
26
|
+
* valeurs de la ligne d'étape que l'interface écrit elle-même : le serveur
|
|
27
|
+
* n'écrit aucune phrase que la personne lit.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
const { AppError } = require('@astratra/core');
|
|
31
|
+
|
|
32
|
+
const KINDS = ['read', 'write', 'confirm'];
|
|
33
|
+
const NAME = /^[a-z][a-z0-9_]{0,63}$/;
|
|
34
|
+
const DEFAULT_PARAM_MAX = 120;
|
|
35
|
+
const DEFAULT_RESULT_MAX = 6000;
|
|
36
|
+
const DEFAULT_TOOL_MS = 20_000;
|
|
37
|
+
|
|
38
|
+
const MESSAGES = {
|
|
39
|
+
unknownTool: (name) => `There is no tool called ${name}.`,
|
|
40
|
+
timeout: () => 'This tool took too long to answer.',
|
|
41
|
+
invalidArguments: (call) => (call.invalidReason === 'not_object'
|
|
42
|
+
? 'The arguments of this call must be a JSON object: call the tool again with one.'
|
|
43
|
+
: `The arguments of this call were not valid JSON${call.invalidDetail ? ` (${call.invalidDetail})` : ''}: call the tool again with a JSON object.`),
|
|
44
|
+
waiting: 'Nothing is written yet: the person must confirm it.'
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const isValue = (value) => typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value));
|
|
48
|
+
const isPlain = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Vérifie un catalogue d'outils. Un outil qui rompt le contrat arrête le
|
|
52
|
+
* serveur au démarrage, pas la personne au milieu d'une question.
|
|
53
|
+
*
|
|
54
|
+
* @param {object[]} tools
|
|
55
|
+
* @param {object} [options]
|
|
56
|
+
* @param {string[]} [options.kinds] Défaut read, write, confirm.
|
|
57
|
+
* @param {boolean} [options.requireSummary] chaque outil donne les valeurs de sa ligne d'étape. Défaut false.
|
|
58
|
+
* @returns {object[]} les mêmes outils
|
|
59
|
+
* @throws {Error} nommant le premier outil fautif, et pourquoi
|
|
60
|
+
*/
|
|
61
|
+
function validateNativeTools(tools, options = {}) {
|
|
62
|
+
const kinds = options.kinds || KINDS;
|
|
63
|
+
const seen = new Set();
|
|
64
|
+
for (const tool of Array.isArray(tools) ? tools : []) {
|
|
65
|
+
const label = typeof tool?.name === 'string' && tool.name ? tool.name : JSON.stringify(tool?.name);
|
|
66
|
+
const refuse = (reason) => {
|
|
67
|
+
throw new Error(`The agent tool ${label} is not valid: ${reason}.`);
|
|
68
|
+
};
|
|
69
|
+
if (typeof tool?.name !== 'string' || !NAME.test(tool.name)) refuse('its name is not in snake_case');
|
|
70
|
+
if (seen.has(tool.name)) throw new Error(`The agent tool ${tool.name} is declared twice.`);
|
|
71
|
+
seen.add(tool.name);
|
|
72
|
+
if (typeof tool.description !== 'string' || !tool.description.trim()) refuse('it has no description');
|
|
73
|
+
if (tool.parameters?.type !== 'object') refuse('its parameters are not the schema of an object');
|
|
74
|
+
if (!kinds.includes(tool.kind)) refuse(`its kind is not one of ${kinds.join(', ')}`);
|
|
75
|
+
if (tool.summary !== undefined || options.requireSummary) {
|
|
76
|
+
if (typeof tool.summary !== 'function') refuse('its summary is not a function');
|
|
77
|
+
let values;
|
|
78
|
+
try {
|
|
79
|
+
values = tool.summary({});
|
|
80
|
+
} catch (_error) {
|
|
81
|
+
refuse('its summary fails without arguments');
|
|
82
|
+
}
|
|
83
|
+
if (!isPlain(values) || !Object.values(values).every(isValue)) refuse('its summary does not give an object of strings and numbers');
|
|
84
|
+
}
|
|
85
|
+
if (typeof tool.run !== 'function') refuse('its run is not a function');
|
|
86
|
+
if (tool.kind === 'confirm' && typeof tool.perform !== 'function') refuse('a tool to confirm needs perform');
|
|
87
|
+
if (tool.kind === 'write' && typeof tool.undo !== 'function') refuse('a tool that writes alone needs undo');
|
|
88
|
+
}
|
|
89
|
+
return tools;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Ce que le modèle voit de chaque outil : son nom, sa description, ses paramètres. */
|
|
93
|
+
const toolSpecs = (tools) => tools.map(({ name, description, parameters }) => ({ name, description, parameters }));
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Les valeurs de la ligne d'étape d'un outil pour ces arguments : chaînes et
|
|
97
|
+
* nombres seulement, chacune coupée à `max` caractères ; {} quand le résumé échoue.
|
|
98
|
+
* @returns {Record<string, string | number>}
|
|
99
|
+
*/
|
|
100
|
+
function stepParams(tool, args, { max = DEFAULT_PARAM_MAX } = {}) {
|
|
101
|
+
if (!tool || typeof tool.summary !== 'function') return {};
|
|
102
|
+
let values;
|
|
103
|
+
try {
|
|
104
|
+
values = tool.summary(args ?? {});
|
|
105
|
+
} catch (_error) {
|
|
106
|
+
return {};
|
|
107
|
+
}
|
|
108
|
+
if (!isPlain(values)) return {};
|
|
109
|
+
return Object.fromEntries(
|
|
110
|
+
Object.entries(values)
|
|
111
|
+
.filter(([, value]) => isValue(value))
|
|
112
|
+
.map(([key, value]) => [key, typeof value === 'string' && value.length > max ? `${value.slice(0, max - 1)}…` : value])
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
class ToolTimeout extends Error {}
|
|
117
|
+
|
|
118
|
+
/* Une promesse qui abandonne quand le signal s'interrompt, avec la raison du signal. */
|
|
119
|
+
function abortable(promise, signal) {
|
|
120
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
121
|
+
return new Promise((resolve, reject) => {
|
|
122
|
+
const stop = () => reject(signal.reason);
|
|
123
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
124
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', stop));
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Le lanceur d'outils du modèle, partagé par tout ce qui fait appeler des
|
|
130
|
+
* outils (une conversation écrite, un appel vocal).
|
|
131
|
+
*
|
|
132
|
+
* @param {object} options
|
|
133
|
+
* @param {Map<string, object>|object[]} options.tools
|
|
134
|
+
* @param {object} [options.context] donné à chaque outil (run(args, { ...context, signal })).
|
|
135
|
+
* @param {AbortSignal} [options.signal] la personne est partie : l'appel lève sa raison.
|
|
136
|
+
* @param {number} [options.timeoutMs] par outil. Défaut 20 s.
|
|
137
|
+
* @param {Function} [options.now]
|
|
138
|
+
* @param {Function} [options.emit] (type, data) : 'step' { id, tool, params } puis 'step_done' { id, ok }.
|
|
139
|
+
* @param {Function} [options.keep] (sources, data) : ce qu'un outil a trouvé (createSourceLedger().keep).
|
|
140
|
+
* @param {Function} [options.record] async ({ tool, args, found }) : garder une action (à confirmer, à annuler).
|
|
141
|
+
* @param {Function} [options.onCall] ({ name, ms, ok }) : pour mesurer.
|
|
142
|
+
* @param {number} [options.resultMax] caractères de JSON rendus au modèle. Défaut 6000.
|
|
143
|
+
* @param {object} [options.messages] { unknownTool(name), timeout(), invalidArguments(call), waiting } — ce que lit le modèle.
|
|
144
|
+
* @returns {(call: { id: string, name: string, args: object|null, invalid?: boolean }) => Promise<{ role: 'tool', toolCallId: string, name: string, result: unknown }>}
|
|
145
|
+
*/
|
|
146
|
+
function createToolCaller(options = {}) {
|
|
147
|
+
const tools = options.tools instanceof Map
|
|
148
|
+
? options.tools
|
|
149
|
+
: new Map((options.tools || []).map((tool) => [tool.name, tool]));
|
|
150
|
+
const context = options.context || {};
|
|
151
|
+
const signal = options.signal || new globalThis.AbortController().signal;
|
|
152
|
+
const timeoutMs = options.timeoutMs || DEFAULT_TOOL_MS;
|
|
153
|
+
const now = options.now || Date.now;
|
|
154
|
+
const emit = options.emit || (() => {});
|
|
155
|
+
const keep = options.keep || (() => {});
|
|
156
|
+
const record = options.record || null;
|
|
157
|
+
const onCall = options.onCall || (() => {});
|
|
158
|
+
const resultMax = options.resultMax || DEFAULT_RESULT_MAX;
|
|
159
|
+
const messages = { ...MESSAGES, ...(options.messages || {}) };
|
|
160
|
+
let steps = 0;
|
|
161
|
+
|
|
162
|
+
function bounded(data) {
|
|
163
|
+
const json = JSON.stringify(data ?? null);
|
|
164
|
+
return json.length > resultMax ? `${json.slice(0, resultMax)}…` : data;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return async function call({ id, name, args, invalid, invalidReason, invalidDetail }) {
|
|
168
|
+
const tool = tools.get(name);
|
|
169
|
+
const step = `s${(steps += 1)}`;
|
|
170
|
+
/* Un outil inventé, ou un résumé qui échoue, montre quand même son étape, sans valeurs. */
|
|
171
|
+
emit('step', { id: step, tool: name, params: stepParams(tool, args) });
|
|
172
|
+
const begun = now();
|
|
173
|
+
const timeout = new globalThis.AbortController();
|
|
174
|
+
const timer = setTimeout(() => timeout.abort(new ToolTimeout(messages.timeout())), timeoutMs);
|
|
175
|
+
let result;
|
|
176
|
+
let ok = true;
|
|
177
|
+
try {
|
|
178
|
+
if (!tool) throw new Error(messages.unknownTool(name));
|
|
179
|
+
if (invalid) throw new Error(messages.invalidArguments({ name, invalidReason, invalidDetail }));
|
|
180
|
+
const toolSignal = globalThis.AbortSignal.any([signal, timeout.signal]);
|
|
181
|
+
const found = await abortable(Promise.resolve().then(() => tool.run(args, { ...context, signal: toolSignal })), toolSignal);
|
|
182
|
+
keep(found?.sources, found?.data);
|
|
183
|
+
if (record) await record({ tool, args, found: found ?? {} });
|
|
184
|
+
result = tool.kind === 'confirm' ? { data: bounded(found?.data), status: messages.waiting } : bounded(found?.data);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (signal.aborted) throw signal.reason;
|
|
187
|
+
ok = false;
|
|
188
|
+
result = { error: error.message };
|
|
189
|
+
} finally {
|
|
190
|
+
clearTimeout(timer);
|
|
191
|
+
}
|
|
192
|
+
onCall({ name, ms: now() - begun, ok });
|
|
193
|
+
emit('step_done', { id: step, ok });
|
|
194
|
+
return { role: 'tool', toolCallId: id, name, result };
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* La boucle : le modèle lit la question avec la liste des outils, en demande,
|
|
200
|
+
* lit ce qu'ils rendent, et recommence jusqu'à répondre.
|
|
201
|
+
*
|
|
202
|
+
* @param {object} options
|
|
203
|
+
* @param {string} options.system
|
|
204
|
+
* @param {object[]} options.messages la transcription (modifiée en place : les tours s'y ajoutent).
|
|
205
|
+
* @param {object[]} [options.tools] ce que voit le modèle (toolSpecs).
|
|
206
|
+
* @param {Function} options.turn async ({ system, messages, tools }) => { text, toolCalls, model? }.
|
|
207
|
+
* @param {Function} options.callTool un appel => le message `tool` (createToolCaller).
|
|
208
|
+
* @param {number} [options.maxTurns] tours avec outils. Défaut 6.
|
|
209
|
+
* @param {number} [options.maxMs] budget de temps. Défaut 60 s.
|
|
210
|
+
* @param {string} [options.finalInstruction] ajoutée à la consigne du dernier tour, sans outils.
|
|
211
|
+
* @param {Function} [options.now]
|
|
212
|
+
* @param {AbortSignal} [options.signal]
|
|
213
|
+
* @returns {Promise<{ text: string, turns: number }>}
|
|
214
|
+
* @throws {AppError} code 'AI_NO_ANSWER' quand un tour ne donne ni texte ni outil
|
|
215
|
+
*/
|
|
216
|
+
async function runToolLoop(options = {}) {
|
|
217
|
+
const { system, messages, turn, callTool } = options;
|
|
218
|
+
if (typeof turn !== 'function') throw new Error('runToolLoop requires options.turn.');
|
|
219
|
+
if (typeof callTool !== 'function') throw new Error('runToolLoop requires options.callTool.');
|
|
220
|
+
if (!Array.isArray(messages)) throw new Error('runToolLoop requires options.messages.');
|
|
221
|
+
const tools = options.tools || [];
|
|
222
|
+
const maxTurns = options.maxTurns === undefined ? 6 : options.maxTurns;
|
|
223
|
+
const maxMs = options.maxMs === undefined ? 60_000 : options.maxMs;
|
|
224
|
+
const now = options.now || Date.now;
|
|
225
|
+
const signal = options.signal;
|
|
226
|
+
const started = now();
|
|
227
|
+
let turns = 0;
|
|
228
|
+
|
|
229
|
+
const answerOf = (response) => {
|
|
230
|
+
if (!response || !response.text) {
|
|
231
|
+
const error = new AppError(`${(response && response.model) || 'The model'} gave no text.`, 503);
|
|
232
|
+
error.code = 'AI_NO_ANSWER';
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
return { text: response.text, turns };
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
while (turns < maxTurns && now() - started < maxMs) {
|
|
239
|
+
if (signal && signal.aborted) throw signal.reason;
|
|
240
|
+
turns += 1;
|
|
241
|
+
const response = await turn({ system, messages, tools });
|
|
242
|
+
const calls = (response && response.toolCalls) || [];
|
|
243
|
+
if (!calls.length) return answerOf(response);
|
|
244
|
+
messages.push({ role: 'assistant', text: response.text ?? null, toolCalls: calls });
|
|
245
|
+
/* Les outils demandés ensemble tournent en même temps ; leurs résultats gardent l'ordre des appels. */
|
|
246
|
+
messages.push(...(await Promise.all(calls.map(callTool))));
|
|
247
|
+
}
|
|
248
|
+
if (signal && signal.aborted) throw signal.reason;
|
|
249
|
+
turns += 1;
|
|
250
|
+
const final = typeof options.finalInstruction === 'string' && options.finalInstruction.trim()
|
|
251
|
+
? `${system}\n${options.finalInstruction}`
|
|
252
|
+
: system;
|
|
253
|
+
return answerOf(await turn({ system: final, messages, tools: [] }));
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
module.exports = { validateNativeTools, toolSpecs, stepParams, createToolCaller, runToolLoop, NATIVE_TOOL_KINDS: KINDS };
|