henergyqueai-sdk 0.1.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/LICENSE +21 -0
- package/README.md +157 -0
- package/package.json +36 -0
- package/src/index.d.ts +244 -0
- package/src/index.js +402 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 HenergyqueAI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# henergyqueai-sdk
|
|
2
|
+
|
|
3
|
+
La bibliothèque officielle de l’API [HenergyqueAI](https://henergyqueai.fr) pour JavaScript et TypeScript : Velys, Oryne et Aelyr en quelques lignes.
|
|
4
|
+
|
|
5
|
+
- Aucune dépendance, 5 Ko compressée.
|
|
6
|
+
- Node 18+, Deno et Bun : partout où `fetch` existe.
|
|
7
|
+
- Types TypeScript inclus.
|
|
8
|
+
- Streaming, outils, images, sorties JSON.
|
|
9
|
+
- Nouvelles tentatives automatiques sur les erreurs passagères.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install henergyqueai-sdk
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Créez une clé sur [henergyqueai.fr/plateforme/cles](https://henergyqueai.fr/plateforme/cles), puis :
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
export HENERGYQUEAI_API_KEY="hak_…"
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Premier appel
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
import HenergyqueAI from "henergyqueai-sdk";
|
|
25
|
+
|
|
26
|
+
const client = new HenergyqueAI(); // lit HENERGYQUEAI_API_KEY
|
|
27
|
+
|
|
28
|
+
console.log(await client.ask("Donne-moi trois idées de prénom pour un chat."));
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`ask` utilise Velys par défaut. Pour choisir le modèle ou ajouter une consigne :
|
|
32
|
+
|
|
33
|
+
```js
|
|
34
|
+
await client.ask("Relis cette fonction.", { model: "oryne", system: "Réponds en une phrase." });
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Conversation complète
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
const reponse = await client.chat.create({
|
|
41
|
+
model: "oryne",
|
|
42
|
+
messages: [
|
|
43
|
+
{ role: "system", content: "Tu es un relecteur de code exigeant." },
|
|
44
|
+
{ role: "user", content: "Que penses-tu de `for (i in tableau)` ?" },
|
|
45
|
+
],
|
|
46
|
+
temperature: 0.3,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
console.log(reponse.text); // le texte, déjà extrait
|
|
50
|
+
console.log(reponse.usage); // { prompt_tokens, completion_tokens, total_tokens }
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Streaming
|
|
54
|
+
|
|
55
|
+
```js
|
|
56
|
+
const flux = client.chat.stream({
|
|
57
|
+
model: "velys",
|
|
58
|
+
messages: [{ role: "user", content: "Raconte une histoire courte." }],
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
for await (const texte of flux.textStream()) process.stdout.write(texte);
|
|
62
|
+
|
|
63
|
+
const finale = await flux.finalCompletion(); // la réponse entière, une fois terminée
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`flux.abort()` arrête la génération en cours.
|
|
67
|
+
|
|
68
|
+
## Outils
|
|
69
|
+
|
|
70
|
+
```js
|
|
71
|
+
const reponse = await client.chat.create({
|
|
72
|
+
model: "oryne",
|
|
73
|
+
messages: [{ role: "user", content: "Quel temps fait-il à Nantes ?" }],
|
|
74
|
+
tools: [
|
|
75
|
+
{
|
|
76
|
+
type: "function",
|
|
77
|
+
function: {
|
|
78
|
+
name: "meteo",
|
|
79
|
+
description: "La météo actuelle d’une ville",
|
|
80
|
+
parameters: { type: "object", properties: { ville: { type: "string" } }, required: ["ville"] },
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
for (const appel of reponse.choices[0].message.tool_calls ?? []) {
|
|
87
|
+
const { ville } = JSON.parse(appel.function.arguments);
|
|
88
|
+
// … exécutez l’outil, puis renvoyez son résultat dans un message { role: "tool", tool_call_id: appel.id, content }
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Format messages
|
|
93
|
+
|
|
94
|
+
L’API accepte aussi le format messages, avec des blocs de contenu. `max_tokens` vaut 1024 par défaut dans la bibliothèque.
|
|
95
|
+
|
|
96
|
+
```js
|
|
97
|
+
const message = await client.messages.create({
|
|
98
|
+
model: "aelyr",
|
|
99
|
+
system: "Tu es précis et concis.",
|
|
100
|
+
messages: [{ role: "user", content: "Explique la différence entre TCP et UDP." }],
|
|
101
|
+
});
|
|
102
|
+
console.log(message.text);
|
|
103
|
+
|
|
104
|
+
const flux = client.messages.stream({ model: "aelyr", messages: [{ role: "user", content: "Un haïku." }] });
|
|
105
|
+
for await (const texte of flux.textStream()) process.stdout.write(texte);
|
|
106
|
+
|
|
107
|
+
const { input_tokens } = await client.messages.countTokens({ model: "velys", messages: [{ role: "user", content: "Bonjour" }] });
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Modèles et consommation
|
|
111
|
+
|
|
112
|
+
```js
|
|
113
|
+
const modeles = await client.models.list(); // [{ id: "velys", … }, …]
|
|
114
|
+
const oryne = await client.models.retrieve("oryne");
|
|
115
|
+
const conso = await client.usage(); // { plan, requests: { used, limit, remaining, resets_at }, key }
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## Erreurs
|
|
119
|
+
|
|
120
|
+
Chaque erreur de l’API devient une exception typée, avec `status`, `type`, `code`, `param`, `requestId` et, si l’API le précise, `retryAfter`.
|
|
121
|
+
|
|
122
|
+
```js
|
|
123
|
+
import { RateLimitError, AuthenticationError } from "henergyqueai-sdk";
|
|
124
|
+
|
|
125
|
+
try {
|
|
126
|
+
await client.ask("Bonjour");
|
|
127
|
+
} catch (erreur) {
|
|
128
|
+
if (erreur instanceof RateLimitError) console.log(`Réessayez dans ${erreur.retryAfter} s.`);
|
|
129
|
+
else if (erreur instanceof AuthenticationError) console.log("Clé invalide.");
|
|
130
|
+
else throw erreur;
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Les autres classes sont `InvalidRequestError`, `PermissionDeniedError`, `NotFoundError`, `ServerError`, `ConnectionError` et `TimeoutError`, toutes filles de `HenergyqueAIError`.
|
|
135
|
+
|
|
136
|
+
Les erreurs passagères (429, 5xx, coupure réseau) sont retentées deux fois, en respectant `retry-after`. La limite quotidienne de votre offre n’est jamais retentée.
|
|
137
|
+
|
|
138
|
+
## Options
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
const client = new HenergyqueAI({
|
|
142
|
+
apiKey: "hak_…", // sinon HENERGYQUEAI_API_KEY
|
|
143
|
+
timeout: 60_000, // attente maximale d’une réponse, en ms (10 minutes par défaut)
|
|
144
|
+
maxRetries: 3, // 2 par défaut
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
// Pour un seul appel :
|
|
148
|
+
await client.chat.create(params, { signal: controleur.signal, timeout: 30_000, maxRetries: 0 });
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Sécurité
|
|
152
|
+
|
|
153
|
+
Gardez la clé côté serveur. Ne l’incluez jamais dans le code d’une page web, d’une application mobile ou d’un dépôt Git.
|
|
154
|
+
|
|
155
|
+
## Licence
|
|
156
|
+
|
|
157
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "henergyqueai-sdk",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Bibliothèque officielle de l’API HenergyqueAI : Velys, Oryne et Aelyr depuis JavaScript et TypeScript.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"types": "./src/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.d.ts",
|
|
11
|
+
"default": "./src/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"src",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"test": "node --test test/*.test.js"
|
|
21
|
+
},
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=18.17"
|
|
24
|
+
},
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"keywords": [
|
|
28
|
+
"henergyqueai",
|
|
29
|
+
"api",
|
|
30
|
+
"ia",
|
|
31
|
+
"velys",
|
|
32
|
+
"oryne",
|
|
33
|
+
"aelyr"
|
|
34
|
+
],
|
|
35
|
+
"homepage": "https://henergyqueai.fr/plateforme/docs#bibliotheques"
|
|
36
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
export declare const VERSION: string;
|
|
2
|
+
|
|
3
|
+
export type ModelId = "velys" | "oryne" | "aelyr" | (string & {});
|
|
4
|
+
|
|
5
|
+
export interface ClientOptions {
|
|
6
|
+
/** Clé d'API `hak_…`. Par défaut : la variable HENERGYQUEAI_API_KEY. */
|
|
7
|
+
apiKey?: string;
|
|
8
|
+
/** Par défaut : https://henergyqueai.fr/api/v1 (ou HENERGYQUEAI_BASE_URL). */
|
|
9
|
+
baseURL?: string;
|
|
10
|
+
/** Délai d'attente de la réponse, en millisecondes. 10 minutes par défaut. */
|
|
11
|
+
timeout?: number;
|
|
12
|
+
/** Nouvelles tentatives sur 429, 5xx et coupures réseau. 2 par défaut. */
|
|
13
|
+
maxRetries?: number;
|
|
14
|
+
fetch?: typeof fetch;
|
|
15
|
+
defaultHeaders?: Record<string, string>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface RequestOptions {
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
timeout?: number;
|
|
21
|
+
maxRetries?: number;
|
|
22
|
+
headers?: Record<string, string>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// ─── Format conversation ───────────────────────────────────────────────
|
|
26
|
+
|
|
27
|
+
export type ChatContentPart =
|
|
28
|
+
| { type: "text"; text: string }
|
|
29
|
+
| { type: "image_url"; image_url: { url: string } };
|
|
30
|
+
|
|
31
|
+
export interface ChatToolCall {
|
|
32
|
+
id: string;
|
|
33
|
+
type: "function";
|
|
34
|
+
function: { name: string; arguments: string };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type ChatMessage =
|
|
38
|
+
| { role: "system" | "developer"; content: string | { type: "text"; text: string }[] }
|
|
39
|
+
| { role: "user"; content: string | ChatContentPart[] }
|
|
40
|
+
| { role: "assistant"; content: string | null; tool_calls?: ChatToolCall[] }
|
|
41
|
+
| { role: "tool"; tool_call_id: string; content: string };
|
|
42
|
+
|
|
43
|
+
export interface ChatTool {
|
|
44
|
+
type: "function";
|
|
45
|
+
function: { name: string; description?: string; parameters?: Record<string, unknown> };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface ChatParams {
|
|
49
|
+
model: ModelId;
|
|
50
|
+
messages: ChatMessage[];
|
|
51
|
+
max_tokens?: number;
|
|
52
|
+
max_completion_tokens?: number;
|
|
53
|
+
temperature?: number;
|
|
54
|
+
top_p?: number;
|
|
55
|
+
presence_penalty?: number;
|
|
56
|
+
frequency_penalty?: number;
|
|
57
|
+
seed?: number;
|
|
58
|
+
stop?: string | string[];
|
|
59
|
+
tools?: ChatTool[];
|
|
60
|
+
tool_choice?: "none" | "auto" | "required" | { type: "function"; function: { name: string } };
|
|
61
|
+
response_format?:
|
|
62
|
+
| { type: "text" }
|
|
63
|
+
| { type: "json_object" }
|
|
64
|
+
| { type: "json_schema"; json_schema: { name: string; schema: Record<string, unknown>; strict?: boolean } };
|
|
65
|
+
stream?: boolean;
|
|
66
|
+
stream_options?: { include_usage?: boolean };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface ChatUsage {
|
|
70
|
+
prompt_tokens: number;
|
|
71
|
+
completion_tokens: number;
|
|
72
|
+
total_tokens: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface ChatCompletion {
|
|
76
|
+
id: string;
|
|
77
|
+
object: "chat.completion";
|
|
78
|
+
created: number;
|
|
79
|
+
model: string;
|
|
80
|
+
choices: {
|
|
81
|
+
index: number;
|
|
82
|
+
message: { role: "assistant"; content: string | null; tool_calls?: ChatToolCall[] };
|
|
83
|
+
finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | null;
|
|
84
|
+
}[];
|
|
85
|
+
usage: ChatUsage | null;
|
|
86
|
+
/** Le texte de la réponse, déjà extrait. */
|
|
87
|
+
readonly text: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface ChatChunk {
|
|
91
|
+
id: string;
|
|
92
|
+
object: "chat.completion.chunk";
|
|
93
|
+
created: number;
|
|
94
|
+
model: string;
|
|
95
|
+
choices: {
|
|
96
|
+
index: number;
|
|
97
|
+
delta: {
|
|
98
|
+
role?: "assistant";
|
|
99
|
+
content?: string;
|
|
100
|
+
tool_calls?: { index: number; id?: string; type?: "function"; function: { name?: string; arguments: string } }[];
|
|
101
|
+
};
|
|
102
|
+
finish_reason: string | null;
|
|
103
|
+
}[];
|
|
104
|
+
usage?: ChatUsage;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
declare class BaseStream<T> implements AsyncIterable<T> {
|
|
108
|
+
[Symbol.asyncIterator](): AsyncIterator<T>;
|
|
109
|
+
/** Seulement les morceaux de texte, au fil de l'eau. */
|
|
110
|
+
textStream(): AsyncGenerator<string>;
|
|
111
|
+
abort(): void;
|
|
112
|
+
}
|
|
113
|
+
export declare class ChatStream extends BaseStream<ChatChunk> {
|
|
114
|
+
finalCompletion(): Promise<ChatCompletion>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ─── Format messages ───────────────────────────────────────────────────
|
|
118
|
+
|
|
119
|
+
export type ContentBlock =
|
|
120
|
+
| { type: "text"; text: string }
|
|
121
|
+
| { type: "image"; source: { type: "base64"; media_type: string; data: string } | { type: "url"; url: string } }
|
|
122
|
+
| { type: "tool_use"; id: string; name: string; input: Record<string, unknown> }
|
|
123
|
+
| { type: "tool_result"; tool_use_id: string; content: string | { type: "text"; text: string }[]; is_error?: boolean };
|
|
124
|
+
|
|
125
|
+
export interface MessageParam {
|
|
126
|
+
role: "user" | "assistant";
|
|
127
|
+
content: string | ContentBlock[];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface MessageTool {
|
|
131
|
+
name: string;
|
|
132
|
+
description?: string;
|
|
133
|
+
input_schema?: Record<string, unknown>;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export interface MessageParams {
|
|
137
|
+
model: ModelId;
|
|
138
|
+
messages: MessageParam[];
|
|
139
|
+
/** 1024 par défaut dans cette bibliothèque. */
|
|
140
|
+
max_tokens?: number;
|
|
141
|
+
system?: string | { type: "text"; text: string }[];
|
|
142
|
+
temperature?: number;
|
|
143
|
+
top_p?: number;
|
|
144
|
+
stop_sequences?: string[];
|
|
145
|
+
tools?: MessageTool[];
|
|
146
|
+
tool_choice?: { type: "auto" } | { type: "any" } | { type: "none" } | { type: "tool"; name: string };
|
|
147
|
+
stream?: boolean;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface Message {
|
|
151
|
+
id: string;
|
|
152
|
+
type: "message";
|
|
153
|
+
role: "assistant";
|
|
154
|
+
model: string;
|
|
155
|
+
content: (
|
|
156
|
+
| { type: "text"; text: string }
|
|
157
|
+
| { type: "tool_use"; id: string; name: string; input: Record<string, unknown> }
|
|
158
|
+
)[];
|
|
159
|
+
stop_reason: "end_turn" | "max_tokens" | "tool_use" | "refusal" | null;
|
|
160
|
+
stop_sequence: string | null;
|
|
161
|
+
usage: { input_tokens: number; output_tokens: number };
|
|
162
|
+
/** Le texte de la réponse, déjà extrait. */
|
|
163
|
+
readonly text: string;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export type MessageStreamEvent =
|
|
167
|
+
| { type: "message_start"; message: Omit<Message, "text"> }
|
|
168
|
+
| { type: "content_block_start"; index: number; content_block: Message["content"][number] }
|
|
169
|
+
| {
|
|
170
|
+
type: "content_block_delta";
|
|
171
|
+
index: number;
|
|
172
|
+
delta: { type: "text_delta"; text: string } | { type: "input_json_delta"; partial_json: string };
|
|
173
|
+
}
|
|
174
|
+
| { type: "content_block_stop"; index: number }
|
|
175
|
+
| { type: "message_delta"; delta: { stop_reason: Message["stop_reason"]; stop_sequence: string | null }; usage: { output_tokens: number } }
|
|
176
|
+
| { type: "message_stop" };
|
|
177
|
+
|
|
178
|
+
export declare class MessageStream extends BaseStream<MessageStreamEvent> {
|
|
179
|
+
finalMessage(): Promise<Message>;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ─── Modèles et consommation ───────────────────────────────────────────
|
|
183
|
+
|
|
184
|
+
export interface Model {
|
|
185
|
+
id: string;
|
|
186
|
+
object: "model";
|
|
187
|
+
display_name: string;
|
|
188
|
+
description: string;
|
|
189
|
+
available: boolean;
|
|
190
|
+
requires_subscription: boolean;
|
|
191
|
+
max_output_tokens: number;
|
|
192
|
+
capabilities: { streaming: boolean; tools: boolean; images: boolean; json_output: boolean; reasoning: boolean };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export interface Usage {
|
|
196
|
+
object: "usage";
|
|
197
|
+
plan: string;
|
|
198
|
+
requests: { used: number; limit: number; remaining: number; resets_at: string };
|
|
199
|
+
key: { id: string; name: string; requests_today: number; daily_limit: number | null } | null;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ─── Client ────────────────────────────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
export declare class HenergyqueAI {
|
|
205
|
+
constructor(options?: ClientOptions);
|
|
206
|
+
readonly baseURL: string;
|
|
207
|
+
chat: {
|
|
208
|
+
create(params: ChatParams & { stream: true }, options?: RequestOptions): Promise<ChatStream>;
|
|
209
|
+
create(params: ChatParams, options?: RequestOptions): Promise<ChatCompletion>;
|
|
210
|
+
stream(params: ChatParams, options?: RequestOptions): ChatStream;
|
|
211
|
+
};
|
|
212
|
+
messages: {
|
|
213
|
+
create(params: MessageParams & { stream: true }, options?: RequestOptions): Promise<MessageStream>;
|
|
214
|
+
create(params: MessageParams, options?: RequestOptions): Promise<Message>;
|
|
215
|
+
stream(params: MessageParams, options?: RequestOptions): MessageStream;
|
|
216
|
+
countTokens(params: Omit<MessageParams, "max_tokens" | "stream">, options?: RequestOptions): Promise<{ input_tokens: number }>;
|
|
217
|
+
};
|
|
218
|
+
models: {
|
|
219
|
+
list(options?: RequestOptions): Promise<Model[]>;
|
|
220
|
+
retrieve(id: ModelId, options?: RequestOptions): Promise<Model>;
|
|
221
|
+
};
|
|
222
|
+
/** Une question, une réponse en texte. Modèle Velys par défaut. */
|
|
223
|
+
ask(prompt: string, params?: Partial<Omit<ChatParams, "messages" | "stream">> & { system?: string }, options?: RequestOptions): Promise<string>;
|
|
224
|
+
usage(options?: RequestOptions): Promise<Usage>;
|
|
225
|
+
}
|
|
226
|
+
export default HenergyqueAI;
|
|
227
|
+
|
|
228
|
+
export declare class HenergyqueAIError extends Error {
|
|
229
|
+
status: number | null;
|
|
230
|
+
type: string | null;
|
|
231
|
+
code: string | null;
|
|
232
|
+
param: string | null;
|
|
233
|
+
requestId: string | null;
|
|
234
|
+
/** Secondes à attendre, quand l'API le précise. */
|
|
235
|
+
retryAfter: number | null;
|
|
236
|
+
}
|
|
237
|
+
export declare class InvalidRequestError extends HenergyqueAIError {}
|
|
238
|
+
export declare class AuthenticationError extends HenergyqueAIError {}
|
|
239
|
+
export declare class PermissionDeniedError extends HenergyqueAIError {}
|
|
240
|
+
export declare class NotFoundError extends HenergyqueAIError {}
|
|
241
|
+
export declare class RateLimitError extends HenergyqueAIError {}
|
|
242
|
+
export declare class ServerError extends HenergyqueAIError {}
|
|
243
|
+
export declare class ConnectionError extends HenergyqueAIError {}
|
|
244
|
+
export declare class TimeoutError extends ConnectionError {}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
// Bibliothèque officielle de l'API HenergyqueAI.
|
|
2
|
+
// Sans dépendance : elle s'appuie sur fetch, présent dans Node 18+, Deno, Bun
|
|
3
|
+
// et les navigateurs.
|
|
4
|
+
|
|
5
|
+
export const VERSION = "0.1.0";
|
|
6
|
+
const DEFAULT_BASE_URL = "https://henergyqueai.fr/api/v1";
|
|
7
|
+
const env = (name) => globalThis.process?.env?.[name] || undefined;
|
|
8
|
+
|
|
9
|
+
// ─── Erreurs ──────────────────────────────────────────────────────────────
|
|
10
|
+
|
|
11
|
+
export class HenergyqueAIError extends Error {
|
|
12
|
+
constructor(message, { status = null, type = null, code = null, param = null, requestId = null, retryAfter = null, cause } = {}) {
|
|
13
|
+
super(message, cause ? { cause } : undefined);
|
|
14
|
+
this.name = new.target.name;
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.type = type;
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.param = param;
|
|
19
|
+
this.requestId = requestId;
|
|
20
|
+
this.retryAfter = retryAfter;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export class InvalidRequestError extends HenergyqueAIError {}
|
|
24
|
+
export class AuthenticationError extends HenergyqueAIError {}
|
|
25
|
+
export class PermissionDeniedError extends HenergyqueAIError {}
|
|
26
|
+
export class NotFoundError extends HenergyqueAIError {}
|
|
27
|
+
export class RateLimitError extends HenergyqueAIError {}
|
|
28
|
+
export class ServerError extends HenergyqueAIError {}
|
|
29
|
+
export class ConnectionError extends HenergyqueAIError {}
|
|
30
|
+
export class TimeoutError extends ConnectionError {}
|
|
31
|
+
|
|
32
|
+
const errorClass = (status) =>
|
|
33
|
+
status === 400 || status === 413
|
|
34
|
+
? InvalidRequestError
|
|
35
|
+
: status === 401
|
|
36
|
+
? AuthenticationError
|
|
37
|
+
: status === 403
|
|
38
|
+
? PermissionDeniedError
|
|
39
|
+
: status === 404
|
|
40
|
+
? NotFoundError
|
|
41
|
+
: status === 429
|
|
42
|
+
? RateLimitError
|
|
43
|
+
: status >= 500
|
|
44
|
+
? ServerError
|
|
45
|
+
: HenergyqueAIError;
|
|
46
|
+
|
|
47
|
+
// Les deux formats de l'API renvoient leurs erreurs un peu différemment :
|
|
48
|
+
// { error: { message, type, param, code } } ou { type: "error", error: { type, message } }.
|
|
49
|
+
async function errorFrom(response) {
|
|
50
|
+
const body = await response.json().catch(() => null);
|
|
51
|
+
const error = body?.error;
|
|
52
|
+
const message = (typeof error === "string" ? error : error?.message) || `Erreur ${response.status}.`;
|
|
53
|
+
const retry = Number(response.headers.get("retry-after"));
|
|
54
|
+
const Kind = errorClass(response.status);
|
|
55
|
+
return new Kind(message, {
|
|
56
|
+
status: response.status,
|
|
57
|
+
type: error?.type ?? null,
|
|
58
|
+
code: error?.code ?? null,
|
|
59
|
+
param: error?.param ?? null,
|
|
60
|
+
requestId: response.headers.get("x-request-id"),
|
|
61
|
+
retryAfter: Number.isFinite(retry) && retry > 0 ? retry : null,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ─── Lecture du streaming (Server-Sent Events) ────────────────────────────
|
|
66
|
+
|
|
67
|
+
async function* readEvents(body) {
|
|
68
|
+
const reader = body.getReader();
|
|
69
|
+
const decoder = new TextDecoder();
|
|
70
|
+
let buffer = "";
|
|
71
|
+
let finished = false;
|
|
72
|
+
try {
|
|
73
|
+
for (;;) {
|
|
74
|
+
const { done, value } = await reader.read();
|
|
75
|
+
buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
|
|
76
|
+
buffer = buffer.replace(/\r\n/g, "\n");
|
|
77
|
+
let cut;
|
|
78
|
+
while ((cut = buffer.indexOf("\n\n")) !== -1) {
|
|
79
|
+
const frame = buffer.slice(0, cut);
|
|
80
|
+
buffer = buffer.slice(cut + 2);
|
|
81
|
+
let event = "message";
|
|
82
|
+
const data = [];
|
|
83
|
+
for (const line of frame.split("\n")) {
|
|
84
|
+
if (!line || line.startsWith(":")) continue;
|
|
85
|
+
const colon = line.indexOf(":");
|
|
86
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
87
|
+
const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
88
|
+
if (field === "event") event = value;
|
|
89
|
+
else if (field === "data") data.push(value);
|
|
90
|
+
}
|
|
91
|
+
if (data.length) yield { event, data: data.join("\n") };
|
|
92
|
+
}
|
|
93
|
+
if (done) {
|
|
94
|
+
finished = true;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
} finally {
|
|
99
|
+
if (!finished) await reader.cancel().catch(() => {});
|
|
100
|
+
else reader.releaseLock?.();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const withText = (object, text) => Object.defineProperty(object, "text", { value: text, enumerable: false });
|
|
105
|
+
const chatText = (completion) => completion?.choices?.[0]?.message?.content ?? "";
|
|
106
|
+
const messageText = (message) =>
|
|
107
|
+
(message?.content || [])
|
|
108
|
+
.filter((block) => block.type === "text")
|
|
109
|
+
.map((block) => block.text)
|
|
110
|
+
.join("");
|
|
111
|
+
|
|
112
|
+
// Un flux se lit une seule fois : soit morceau par morceau, soit d'un bloc
|
|
113
|
+
// avec final…(). Les deux peuvent se combiner : final…() termine la lecture.
|
|
114
|
+
class BaseStream {
|
|
115
|
+
#response;
|
|
116
|
+
#controller;
|
|
117
|
+
#started = false;
|
|
118
|
+
#finished = false;
|
|
119
|
+
#events = [];
|
|
120
|
+
constructor(response, controller) {
|
|
121
|
+
this.#response = response;
|
|
122
|
+
this.#controller = controller;
|
|
123
|
+
}
|
|
124
|
+
abort() {
|
|
125
|
+
this.#controller.abort();
|
|
126
|
+
}
|
|
127
|
+
async *[Symbol.asyncIterator]() {
|
|
128
|
+
if (this.#started) throw new HenergyqueAIError("Ce flux a déjà été lu.");
|
|
129
|
+
this.#started = true;
|
|
130
|
+
const response = await this.#response;
|
|
131
|
+
for await (const event of readEvents(response.body)) {
|
|
132
|
+
const item = this._take(event);
|
|
133
|
+
if (item === undefined) continue;
|
|
134
|
+
if (item === null) break;
|
|
135
|
+
yield item;
|
|
136
|
+
}
|
|
137
|
+
this.#finished = true;
|
|
138
|
+
}
|
|
139
|
+
async *textStream() {
|
|
140
|
+
for await (const item of this) {
|
|
141
|
+
const text = this._textOf(item);
|
|
142
|
+
if (text) yield text;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async _drain() {
|
|
146
|
+
if (!this.#started) for await (const _ of this);
|
|
147
|
+
else if (!this.#finished) throw new HenergyqueAIError("Terminez d’abord la lecture du flux en cours.");
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export class ChatStream extends BaseStream {
|
|
152
|
+
#id = null;
|
|
153
|
+
#model = null;
|
|
154
|
+
#created = null;
|
|
155
|
+
#content = "";
|
|
156
|
+
#calls = [];
|
|
157
|
+
#finish = null;
|
|
158
|
+
#usage = null;
|
|
159
|
+
_take({ data }) {
|
|
160
|
+
if (data === "[DONE]") return null;
|
|
161
|
+
const chunk = JSON.parse(data);
|
|
162
|
+
if (chunk.error) throw new ServerError(chunk.error.message || "Le flux a été interrompu.", { type: chunk.error.type ?? null });
|
|
163
|
+
this.#id ??= chunk.id;
|
|
164
|
+
this.#model ??= chunk.model;
|
|
165
|
+
this.#created ??= chunk.created;
|
|
166
|
+
if (chunk.usage) this.#usage = chunk.usage;
|
|
167
|
+
const choice = chunk.choices?.[0];
|
|
168
|
+
if (choice?.finish_reason) this.#finish = choice.finish_reason;
|
|
169
|
+
const delta = choice?.delta || {};
|
|
170
|
+
if (typeof delta.content === "string") this.#content += delta.content;
|
|
171
|
+
for (const part of delta.tool_calls || []) {
|
|
172
|
+
const call = (this.#calls[part.index] ||= { id: "", type: "function", function: { name: "", arguments: "" } });
|
|
173
|
+
if (part.id) call.id = part.id;
|
|
174
|
+
if (part.function?.name) call.function.name = part.function.name;
|
|
175
|
+
if (part.function?.arguments) call.function.arguments += part.function.arguments;
|
|
176
|
+
}
|
|
177
|
+
return chunk;
|
|
178
|
+
}
|
|
179
|
+
_textOf(chunk) {
|
|
180
|
+
return chunk.choices?.[0]?.delta?.content || "";
|
|
181
|
+
}
|
|
182
|
+
async finalCompletion() {
|
|
183
|
+
await this._drain();
|
|
184
|
+
const calls = this.#calls.filter(Boolean);
|
|
185
|
+
const completion = {
|
|
186
|
+
id: this.#id,
|
|
187
|
+
object: "chat.completion",
|
|
188
|
+
created: this.#created,
|
|
189
|
+
model: this.#model,
|
|
190
|
+
choices: [
|
|
191
|
+
{
|
|
192
|
+
index: 0,
|
|
193
|
+
message: { role: "assistant", content: this.#content || null, ...(calls.length ? { tool_calls: calls } : {}) },
|
|
194
|
+
finish_reason: this.#finish,
|
|
195
|
+
},
|
|
196
|
+
],
|
|
197
|
+
usage: this.#usage,
|
|
198
|
+
};
|
|
199
|
+
return withText(completion, this.#content);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export class MessageStream extends BaseStream {
|
|
204
|
+
#message = null;
|
|
205
|
+
#json = new Map();
|
|
206
|
+
_take({ event, data }) {
|
|
207
|
+
const payload = JSON.parse(data);
|
|
208
|
+
const type = payload.type || event;
|
|
209
|
+
if (type === "error") throw new ServerError(payload.error?.message || "Le flux a été interrompu.", { type: payload.error?.type ?? null });
|
|
210
|
+
if (type === "ping") return undefined;
|
|
211
|
+
if (type === "message_start") this.#message = { ...payload.message, content: [] };
|
|
212
|
+
else if (type === "content_block_start") this.#message.content[payload.index] = { ...payload.content_block };
|
|
213
|
+
else if (type === "content_block_delta") {
|
|
214
|
+
const block = this.#message.content[payload.index];
|
|
215
|
+
if (payload.delta.type === "text_delta") block.text += payload.delta.text;
|
|
216
|
+
else if (payload.delta.type === "input_json_delta")
|
|
217
|
+
this.#json.set(payload.index, (this.#json.get(payload.index) || "") + payload.delta.partial_json);
|
|
218
|
+
} else if (type === "content_block_stop") {
|
|
219
|
+
const block = this.#message.content[payload.index];
|
|
220
|
+
if (block?.type === "tool_use" && this.#json.has(payload.index)) {
|
|
221
|
+
try {
|
|
222
|
+
block.input = JSON.parse(this.#json.get(payload.index));
|
|
223
|
+
} catch {
|
|
224
|
+
block.input = {};
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
} else if (type === "message_delta") {
|
|
228
|
+
Object.assign(this.#message, payload.delta);
|
|
229
|
+
this.#message.usage = { ...this.#message.usage, ...payload.usage };
|
|
230
|
+
}
|
|
231
|
+
return payload;
|
|
232
|
+
}
|
|
233
|
+
_textOf(event) {
|
|
234
|
+
return event.type === "content_block_delta" && event.delta.type === "text_delta" ? event.delta.text : "";
|
|
235
|
+
}
|
|
236
|
+
async finalMessage() {
|
|
237
|
+
await this._drain();
|
|
238
|
+
const message = { ...this.#message, content: this.#message.content.filter(Boolean) };
|
|
239
|
+
return withText(message, messageText(message));
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ─── Ressources ───────────────────────────────────────────────────────────
|
|
244
|
+
|
|
245
|
+
class Chat {
|
|
246
|
+
constructor(client) {
|
|
247
|
+
this._client = client;
|
|
248
|
+
}
|
|
249
|
+
// Format conversation : POST /chat/completions.
|
|
250
|
+
async create(params, options) {
|
|
251
|
+
if (params?.stream) return this.stream(params, options);
|
|
252
|
+
const completion = await this._client._json("POST", "/chat/completions", { ...params, stream: false }, options);
|
|
253
|
+
return withText(completion, chatText(completion));
|
|
254
|
+
}
|
|
255
|
+
stream(params, options) {
|
|
256
|
+
return this._client._stream(ChatStream, "/chat/completions", { ...params, stream: true }, options);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
class Messages {
|
|
261
|
+
constructor(client) {
|
|
262
|
+
this._client = client;
|
|
263
|
+
}
|
|
264
|
+
// Format messages : POST /messages. max_tokens y est obligatoire.
|
|
265
|
+
async create(params, options) {
|
|
266
|
+
if (params?.stream) return this.stream(params, options);
|
|
267
|
+
const message = await this._client._json("POST", "/messages", { max_tokens: 1024, ...params, stream: false }, options);
|
|
268
|
+
return withText(message, messageText(message));
|
|
269
|
+
}
|
|
270
|
+
stream(params, options) {
|
|
271
|
+
return this._client._stream(MessageStream, "/messages", { max_tokens: 1024, ...params, stream: true }, options);
|
|
272
|
+
}
|
|
273
|
+
countTokens(params, options) {
|
|
274
|
+
return this._client._json("POST", "/messages/count_tokens", params, options);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
class Models {
|
|
279
|
+
constructor(client) {
|
|
280
|
+
this._client = client;
|
|
281
|
+
}
|
|
282
|
+
async list(options) {
|
|
283
|
+
return (await this._client._json("GET", "/models", undefined, options)).data;
|
|
284
|
+
}
|
|
285
|
+
retrieve(id, options) {
|
|
286
|
+
return this._client._json("GET", `/models/${encodeURIComponent(id)}`, undefined, options);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// ─── Client ───────────────────────────────────────────────────────────────
|
|
291
|
+
|
|
292
|
+
const pause = (ms, signal) =>
|
|
293
|
+
new Promise((resolve, reject) => {
|
|
294
|
+
const timer = setTimeout(resolve, ms);
|
|
295
|
+
signal?.addEventListener(
|
|
296
|
+
"abort",
|
|
297
|
+
() => {
|
|
298
|
+
clearTimeout(timer);
|
|
299
|
+
reject(signal.reason);
|
|
300
|
+
},
|
|
301
|
+
{ once: true },
|
|
302
|
+
);
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
export class HenergyqueAI {
|
|
306
|
+
constructor({
|
|
307
|
+
apiKey = env("HENERGYQUEAI_API_KEY"),
|
|
308
|
+
baseURL = env("HENERGYQUEAI_BASE_URL") || DEFAULT_BASE_URL,
|
|
309
|
+
timeout = 600_000,
|
|
310
|
+
maxRetries = 2,
|
|
311
|
+
fetch: fetchImpl = globalThis.fetch,
|
|
312
|
+
defaultHeaders = {},
|
|
313
|
+
} = {}) {
|
|
314
|
+
if (!apiKey) throw new HenergyqueAIError("Clé d’API manquante : passez apiKey ou définissez HENERGYQUEAI_API_KEY.");
|
|
315
|
+
if (typeof fetchImpl !== "function") throw new HenergyqueAIError("fetch est introuvable : utilisez Node 18 ou plus, ou passez l’option fetch.");
|
|
316
|
+
this.apiKey = apiKey;
|
|
317
|
+
this.baseURL = String(baseURL).replace(/\/+$/, "");
|
|
318
|
+
this.timeout = timeout;
|
|
319
|
+
this.maxRetries = maxRetries;
|
|
320
|
+
this._fetch = fetchImpl;
|
|
321
|
+
this._headers = defaultHeaders;
|
|
322
|
+
this.chat = new Chat(this);
|
|
323
|
+
this.messages = new Messages(this);
|
|
324
|
+
this.models = new Models(this);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Le plus court chemin : une question, une réponse en texte.
|
|
328
|
+
async ask(prompt, { model = "velys", system, ...params } = {}, options) {
|
|
329
|
+
const messages = [...(system ? [{ role: "system", content: system }] : []), { role: "user", content: prompt }];
|
|
330
|
+
return (await this.chat.create({ model, messages, ...params }, options)).text;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
usage(options) {
|
|
334
|
+
return this._json("GET", "/usage", undefined, options);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async _json(method, path, body, options) {
|
|
338
|
+
const { response } = await this._request(method, path, body, options);
|
|
339
|
+
return response.json();
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
_stream(Kind, path, body, options) {
|
|
343
|
+
const controller = new AbortController();
|
|
344
|
+
const outer = options?.signal;
|
|
345
|
+
if (outer?.aborted) controller.abort(outer.reason);
|
|
346
|
+
else outer?.addEventListener("abort", () => controller.abort(outer.reason), { once: true });
|
|
347
|
+
const signal = controller.signal;
|
|
348
|
+
const response = this._request("POST", path, body, { ...options, signal, stream: true }).then(({ response }) => response);
|
|
349
|
+
response.catch(() => {});
|
|
350
|
+
return new Kind(response, controller);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async _request(method, path, body, { signal, timeout = this.timeout, maxRetries = this.maxRetries, headers = {}, stream = false } = {}) {
|
|
354
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
355
|
+
const deadline = new AbortController();
|
|
356
|
+
const timer = setTimeout(() => deadline.abort(new TimeoutError(`Pas de réponse après ${Math.round(timeout / 1000)} s.`)), timeout);
|
|
357
|
+
const onAbort = () => deadline.abort(signal.reason);
|
|
358
|
+
if (signal?.aborted) throw signal.reason;
|
|
359
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
360
|
+
let response;
|
|
361
|
+
try {
|
|
362
|
+
response = await this._fetch(`${this.baseURL}${path}`, {
|
|
363
|
+
method,
|
|
364
|
+
headers: {
|
|
365
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
366
|
+
Accept: stream ? "text/event-stream" : "application/json",
|
|
367
|
+
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
368
|
+
...this._headers,
|
|
369
|
+
...headers,
|
|
370
|
+
},
|
|
371
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
372
|
+
signal: deadline.signal,
|
|
373
|
+
});
|
|
374
|
+
} catch (error) {
|
|
375
|
+
clearTimeout(timer);
|
|
376
|
+
signal?.removeEventListener("abort", onAbort);
|
|
377
|
+
if (signal?.aborted) throw signal.reason;
|
|
378
|
+
if (deadline.signal.reason instanceof TimeoutError) throw deadline.signal.reason;
|
|
379
|
+
if (attempt < maxRetries) {
|
|
380
|
+
await pause(500 * 2 ** attempt, signal);
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
throw new ConnectionError("Impossible de joindre l’API HenergyqueAI.", { cause: error });
|
|
384
|
+
}
|
|
385
|
+
// Le délai couvre l'attente de la réponse ; un flux peut ensuite durer,
|
|
386
|
+
// et reste interruptible par le signal de l'appelant.
|
|
387
|
+
clearTimeout(timer);
|
|
388
|
+
if (!stream || !response.ok) signal?.removeEventListener("abort", onAbort);
|
|
389
|
+
if (response.ok) return { response };
|
|
390
|
+
const error = await errorFrom(response);
|
|
391
|
+
const retryable = [408, 429, 500, 502, 503, 504].includes(response.status) && error.code !== "daily_limit_reached";
|
|
392
|
+
const wait = error.retryAfter ? error.retryAfter * 1000 : 500 * 2 ** attempt;
|
|
393
|
+
if (retryable && attempt < maxRetries && wait <= 60_000) {
|
|
394
|
+
await pause(wait, signal);
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
throw error;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export default HenergyqueAI;
|