henergyqueai-sdk 0.1.0 → 0.2.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 +173 -157
- package/package.json +52 -36
- package/src/index.d.ts +311 -244
- package/src/index.js +110 -4
package/README.md
CHANGED
|
@@ -1,157 +1,173 @@
|
|
|
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
|
-
##
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
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
|
+
## Traitement par lots et webhooks
|
|
119
|
+
|
|
120
|
+
```js
|
|
121
|
+
import { HenergyqueAI, verifyWebhook } from "henergyqueai-sdk";
|
|
122
|
+
|
|
123
|
+
const client = new HenergyqueAI();
|
|
124
|
+
const input = await client.files.create({ file: fs.readFileSync("lot.jsonl"), filename: "lot.jsonl", purpose: "batch" });
|
|
125
|
+
await client.batches.create({ input_file_id: input.id, webhook_url: "https://exemple.fr/webhooks/henergyqueai" });
|
|
126
|
+
|
|
127
|
+
// Sur votre serveur, avec le corps brut de la requête :
|
|
128
|
+
const event = await verifyWebhook(process.env.HENERGYQUEAI_WEBHOOK_SECRET, request.headers, rawBody);
|
|
129
|
+
if (event.type === "batch.completed") console.log(event.data.output_file_id);
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Le secret `whsec_…` se trouve sur la plateforme, page « Clés d’API ». `verifyWebhook` lève `WebhookVerificationError` si la signature ou l’horodatage ne conviennent pas.
|
|
133
|
+
|
|
134
|
+
## Erreurs
|
|
135
|
+
|
|
136
|
+
Chaque erreur de l’API devient une exception typée, avec `status`, `type`, `code`, `param`, `requestId` et, si l’API le précise, `retryAfter`.
|
|
137
|
+
|
|
138
|
+
```js
|
|
139
|
+
import { RateLimitError, AuthenticationError } from "henergyqueai-sdk";
|
|
140
|
+
|
|
141
|
+
try {
|
|
142
|
+
await client.ask("Bonjour");
|
|
143
|
+
} catch (erreur) {
|
|
144
|
+
if (erreur instanceof RateLimitError) console.log(`Réessayez dans ${erreur.retryAfter} s.`);
|
|
145
|
+
else if (erreur instanceof AuthenticationError) console.log("Clé invalide.");
|
|
146
|
+
else throw erreur;
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Les autres classes sont `InvalidRequestError`, `PermissionDeniedError`, `NotFoundError`, `ServerError`, `ConnectionError` et `TimeoutError`, toutes filles de `HenergyqueAIError`.
|
|
151
|
+
|
|
152
|
+
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.
|
|
153
|
+
|
|
154
|
+
## Options
|
|
155
|
+
|
|
156
|
+
```js
|
|
157
|
+
const client = new HenergyqueAI({
|
|
158
|
+
apiKey: "hak_…", // sinon HENERGYQUEAI_API_KEY
|
|
159
|
+
timeout: 60_000, // attente maximale d’une réponse, en ms (10 minutes par défaut)
|
|
160
|
+
maxRetries: 3, // 2 par défaut
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// Pour un seul appel :
|
|
164
|
+
await client.chat.create(params, { signal: controleur.signal, timeout: 30_000, maxRetries: 0 });
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Sécurité
|
|
168
|
+
|
|
169
|
+
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.
|
|
170
|
+
|
|
171
|
+
## Licence
|
|
172
|
+
|
|
173
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,36 +1,52 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "henergyqueai-sdk",
|
|
3
|
-
"version": "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
|
-
|
|
36
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "henergyqueai-sdk",
|
|
3
|
+
"version": "0.2.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
|
+
"sdk",
|
|
35
|
+
"api-client",
|
|
36
|
+
"ai",
|
|
37
|
+
"llm",
|
|
38
|
+
"chat",
|
|
39
|
+
"chat-completions",
|
|
40
|
+
"streaming",
|
|
41
|
+
"tool-calling",
|
|
42
|
+
"function-calling",
|
|
43
|
+
"json-mode",
|
|
44
|
+
"typescript",
|
|
45
|
+
"javascript",
|
|
46
|
+
"nodejs",
|
|
47
|
+
"deno",
|
|
48
|
+
"bun",
|
|
49
|
+
"french"
|
|
50
|
+
],
|
|
51
|
+
"homepage": "https://henergyqueai.fr/plateforme/docs#bibliotheques"
|
|
52
|
+
}
|
package/src/index.d.ts
CHANGED
|
@@ -1,244 +1,311 @@
|
|
|
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
|
-
// ───
|
|
203
|
-
|
|
204
|
-
export
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
export declare class
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
1
|
+
export declare const VERSION: string;
|
|
2
|
+
|
|
3
|
+
export type ModelId = "velys" | "oryne" | "aelyr" | "aelyr-4" | (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
|
+
// ─── Embeddings, fichiers et lots ──────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
export interface EmbeddingList {
|
|
205
|
+
object: "list";
|
|
206
|
+
model: "henergyque-embed";
|
|
207
|
+
data: { object: "embedding"; index: number; embedding: number[] }[];
|
|
208
|
+
usage: { prompt_tokens: number; total_tokens: number };
|
|
209
|
+
}
|
|
210
|
+
export interface FileObject {
|
|
211
|
+
id: string;
|
|
212
|
+
object: "file";
|
|
213
|
+
bytes: number;
|
|
214
|
+
created_at: number;
|
|
215
|
+
filename: string;
|
|
216
|
+
purpose: "user_data" | "batch" | "batch_output";
|
|
217
|
+
}
|
|
218
|
+
export interface Batch {
|
|
219
|
+
id: string;
|
|
220
|
+
object: "batch";
|
|
221
|
+
endpoint: "/v1/chat/completions";
|
|
222
|
+
input_file_id: string;
|
|
223
|
+
completion_window: "24h";
|
|
224
|
+
status: "in_progress" | "completed" | "failed" | "cancelling" | "cancelled";
|
|
225
|
+
output_file_id: string | null;
|
|
226
|
+
error_file_id: string | null;
|
|
227
|
+
created_at: number;
|
|
228
|
+
in_progress_at: number | null;
|
|
229
|
+
completed_at: number | null;
|
|
230
|
+
cancelled_at: number | null;
|
|
231
|
+
request_counts: { total: number; completed: number; failed: number };
|
|
232
|
+
metadata: Record<string, string> | null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ─── Client ────────────────────────────────────────────────────────────
|
|
236
|
+
|
|
237
|
+
export declare class HenergyqueAI {
|
|
238
|
+
constructor(options?: ClientOptions);
|
|
239
|
+
readonly baseURL: string;
|
|
240
|
+
chat: {
|
|
241
|
+
create(params: ChatParams & { stream: true }, options?: RequestOptions): Promise<ChatStream>;
|
|
242
|
+
create(params: ChatParams, options?: RequestOptions): Promise<ChatCompletion>;
|
|
243
|
+
stream(params: ChatParams, options?: RequestOptions): ChatStream;
|
|
244
|
+
};
|
|
245
|
+
messages: {
|
|
246
|
+
create(params: MessageParams & { stream: true }, options?: RequestOptions): Promise<MessageStream>;
|
|
247
|
+
create(params: MessageParams, options?: RequestOptions): Promise<Message>;
|
|
248
|
+
stream(params: MessageParams, options?: RequestOptions): MessageStream;
|
|
249
|
+
countTokens(params: Omit<MessageParams, "max_tokens" | "stream">, options?: RequestOptions): Promise<{ input_tokens: number }>;
|
|
250
|
+
};
|
|
251
|
+
models: {
|
|
252
|
+
list(options?: RequestOptions): Promise<Model[]>;
|
|
253
|
+
retrieve(id: ModelId, options?: RequestOptions): Promise<Model>;
|
|
254
|
+
};
|
|
255
|
+
embeddings: {
|
|
256
|
+
/** Un texte ou jusqu’à 100 textes : un vecteur par texte. */
|
|
257
|
+
create(params: { input: string | string[]; model?: "henergyque-embed" }, options?: RequestOptions): Promise<EmbeddingList>;
|
|
258
|
+
};
|
|
259
|
+
files: {
|
|
260
|
+
create(
|
|
261
|
+
params: { file: string | Uint8Array | ArrayBuffer | Blob; filename: string; purpose?: "user_data" | "batch" },
|
|
262
|
+
options?: RequestOptions,
|
|
263
|
+
): Promise<FileObject>;
|
|
264
|
+
list(options?: RequestOptions): Promise<FileObject[]>;
|
|
265
|
+
retrieve(id: string, options?: RequestOptions): Promise<FileObject>;
|
|
266
|
+
content(id: string, options?: RequestOptions): Promise<string>;
|
|
267
|
+
delete(id: string, options?: RequestOptions): Promise<{ id: string; object: "file"; deleted: true }>;
|
|
268
|
+
};
|
|
269
|
+
batches: {
|
|
270
|
+
create(params: { input_file_id: string; metadata?: Record<string, string>; webhook_url?: string }, options?: RequestOptions): Promise<Batch>;
|
|
271
|
+
retrieve(id: string, options?: RequestOptions): Promise<Batch>;
|
|
272
|
+
list(options?: RequestOptions): Promise<Batch[]>;
|
|
273
|
+
cancel(id: string, options?: RequestOptions): Promise<Batch>;
|
|
274
|
+
};
|
|
275
|
+
/** Une question, une réponse en texte. Modèle Velys par défaut. */
|
|
276
|
+
ask(prompt: string, params?: Partial<Omit<ChatParams, "messages" | "stream">> & { system?: string }, options?: RequestOptions): Promise<string>;
|
|
277
|
+
usage(options?: RequestOptions): Promise<Usage>;
|
|
278
|
+
}
|
|
279
|
+
export default HenergyqueAI;
|
|
280
|
+
|
|
281
|
+
export declare class HenergyqueAIError extends Error {
|
|
282
|
+
status: number | null;
|
|
283
|
+
type: string | null;
|
|
284
|
+
code: string | null;
|
|
285
|
+
param: string | null;
|
|
286
|
+
requestId: string | null;
|
|
287
|
+
/** Secondes à attendre, quand l'API le précise. */
|
|
288
|
+
retryAfter: number | null;
|
|
289
|
+
}
|
|
290
|
+
export declare class InvalidRequestError extends HenergyqueAIError {}
|
|
291
|
+
export declare class AuthenticationError extends HenergyqueAIError {}
|
|
292
|
+
export declare class PermissionDeniedError extends HenergyqueAIError {}
|
|
293
|
+
export declare class NotFoundError extends HenergyqueAIError {}
|
|
294
|
+
export declare class RateLimitError extends HenergyqueAIError {}
|
|
295
|
+
export declare class ServerError extends HenergyqueAIError {}
|
|
296
|
+
export declare class ConnectionError extends HenergyqueAIError {}
|
|
297
|
+
export declare class TimeoutError extends ConnectionError {}
|
|
298
|
+
|
|
299
|
+
export class WebhookVerificationError extends HenergyqueAIError {}
|
|
300
|
+
export interface WebhookEvent {
|
|
301
|
+
type: "batch.completed" | "batch.failed" | "batch.cancelled";
|
|
302
|
+
created_at: number;
|
|
303
|
+
data: Batch;
|
|
304
|
+
}
|
|
305
|
+
/** Vérifie un webhook (format Standard Webhooks) sur le corps brut ; renvoie l’événement. */
|
|
306
|
+
export function verifyWebhook(
|
|
307
|
+
secret: string,
|
|
308
|
+
headers: Headers | Record<string, string | undefined>,
|
|
309
|
+
body: string | Uint8Array,
|
|
310
|
+
options?: { tolerance?: number; now?: number },
|
|
311
|
+
): Promise<WebhookEvent>;
|
package/src/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Sans dépendance : elle s'appuie sur fetch, présent dans Node 18+, Deno, Bun
|
|
3
3
|
// et les navigateurs.
|
|
4
4
|
|
|
5
|
-
export const VERSION = "0.
|
|
5
|
+
export const VERSION = "0.2.0";
|
|
6
6
|
const DEFAULT_BASE_URL = "https://henergyqueai.fr/api/v1";
|
|
7
7
|
const env = (name) => globalThis.process?.env?.[name] || undefined;
|
|
8
8
|
|
|
@@ -287,6 +287,109 @@ class Models {
|
|
|
287
287
|
}
|
|
288
288
|
}
|
|
289
289
|
|
|
290
|
+
class Embeddings {
|
|
291
|
+
constructor(client) {
|
|
292
|
+
this._client = client;
|
|
293
|
+
}
|
|
294
|
+
// Un texte ou une liste de textes (100 au plus) : un vecteur par texte.
|
|
295
|
+
create({ input, model = "henergyque-embed" }, options) {
|
|
296
|
+
return this._client._json("POST", "/embeddings", { model, input }, options);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Envoi d'un texte, d'octets ou d'un Blob ; le serveur lit le format au contenu.
|
|
301
|
+
async function bytesOf(file) {
|
|
302
|
+
if (typeof file === "string") return new TextEncoder().encode(file);
|
|
303
|
+
if (file instanceof Uint8Array) return file;
|
|
304
|
+
if (file instanceof ArrayBuffer) return new Uint8Array(file);
|
|
305
|
+
if (typeof Blob !== "undefined" && file instanceof Blob) return new Uint8Array(await file.arrayBuffer());
|
|
306
|
+
throw new HenergyqueAIError("file doit être un texte, un Uint8Array, un ArrayBuffer ou un Blob.");
|
|
307
|
+
}
|
|
308
|
+
class Files {
|
|
309
|
+
constructor(client) {
|
|
310
|
+
this._client = client;
|
|
311
|
+
}
|
|
312
|
+
async create({ file, filename, purpose = "user_data" }, options) {
|
|
313
|
+
if (!filename) throw new HenergyqueAIError("filename est obligatoire (par exemple « donnees.jsonl »).");
|
|
314
|
+
const query = `?filename=${encodeURIComponent(filename)}&purpose=${encodeURIComponent(purpose)}`;
|
|
315
|
+
const { response } = await this._client._request("POST", `/files${query}`, undefined, { ...options, raw: await bytesOf(file) });
|
|
316
|
+
return response.json();
|
|
317
|
+
}
|
|
318
|
+
async list(options) {
|
|
319
|
+
return (await this._client._json("GET", "/files", undefined, options)).data;
|
|
320
|
+
}
|
|
321
|
+
retrieve(id, options) {
|
|
322
|
+
return this._client._json("GET", `/files/${encodeURIComponent(id)}`, undefined, options);
|
|
323
|
+
}
|
|
324
|
+
async content(id, options) {
|
|
325
|
+
const { response } = await this._client._request("GET", `/files/${encodeURIComponent(id)}/content`, undefined, options);
|
|
326
|
+
return response.text();
|
|
327
|
+
}
|
|
328
|
+
delete(id, options) {
|
|
329
|
+
return this._client._json("DELETE", `/files/${encodeURIComponent(id)}`, undefined, options);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
class Batches {
|
|
334
|
+
constructor(client) {
|
|
335
|
+
this._client = client;
|
|
336
|
+
}
|
|
337
|
+
// input_file_id : un fichier JSONL envoyé avec purpose « batch ».
|
|
338
|
+
// webhook_url : une adresse https prévenue (signée) à la fin du lot.
|
|
339
|
+
create({ input_file_id, metadata, webhook_url }, options) {
|
|
340
|
+
return this._client._json(
|
|
341
|
+
"POST",
|
|
342
|
+
"/batches",
|
|
343
|
+
{
|
|
344
|
+
input_file_id,
|
|
345
|
+
endpoint: "/v1/chat/completions",
|
|
346
|
+
completion_window: "24h",
|
|
347
|
+
...(metadata ? { metadata } : {}),
|
|
348
|
+
...(webhook_url ? { webhook_url } : {}),
|
|
349
|
+
},
|
|
350
|
+
options,
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
retrieve(id, options) {
|
|
354
|
+
return this._client._json("GET", `/batches/${encodeURIComponent(id)}`, undefined, options);
|
|
355
|
+
}
|
|
356
|
+
async list(options) {
|
|
357
|
+
return (await this._client._json("GET", "/batches", undefined, options)).data;
|
|
358
|
+
}
|
|
359
|
+
cancel(id, options) {
|
|
360
|
+
return this._client._json("POST", `/batches/${encodeURIComponent(id)}/cancel`, undefined, options);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// ─── Webhooks ─────────────────────────────────────────────────────────────
|
|
365
|
+
|
|
366
|
+
// Vérifie un webhook reçu (format Standard Webhooks) : la signature calculée
|
|
367
|
+
// avec votre secret whsec_…, sur le corps brut, et un horodatage récent.
|
|
368
|
+
// Renvoie l'événement lu, ou lève WebhookVerificationError.
|
|
369
|
+
export class WebhookVerificationError extends HenergyqueAIError {}
|
|
370
|
+
const header = (headers, name) =>
|
|
371
|
+
typeof headers?.get === "function" ? headers.get(name) : headers?.[name] ?? headers?.[name.toLowerCase()];
|
|
372
|
+
export async function verifyWebhook(secret, headers, body, { tolerance = 300, now = Date.now() } = {}) {
|
|
373
|
+
const id = header(headers, "webhook-id");
|
|
374
|
+
const timestamp = Number(header(headers, "webhook-timestamp"));
|
|
375
|
+
const signatures = String(header(headers, "webhook-signature") || "").split(" ");
|
|
376
|
+
const text = typeof body === "string" ? body : new TextDecoder().decode(body);
|
|
377
|
+
if (!id || !Number.isFinite(timestamp)) throw new WebhookVerificationError("En-têtes de webhook manquants.");
|
|
378
|
+
if (Math.abs(now / 1000 - timestamp) > tolerance) throw new WebhookVerificationError("Webhook trop ancien ou daté dans le futur.");
|
|
379
|
+
const raw = atob(String(secret).replace(/^whsec_/, ""));
|
|
380
|
+
const key = await crypto.subtle.importKey("raw", Uint8Array.from(raw, (c) => c.charCodeAt(0)), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
381
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${timestamp}.${text}`)));
|
|
382
|
+
const expected = `v1,${btoa(String.fromCharCode(...mac))}`;
|
|
383
|
+
const same = (a, b) => {
|
|
384
|
+
if (a.length !== b.length) return false;
|
|
385
|
+
let diff = 0;
|
|
386
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
387
|
+
return diff === 0;
|
|
388
|
+
};
|
|
389
|
+
if (!signatures.some((candidate) => same(candidate, expected))) throw new WebhookVerificationError("Signature de webhook invalide.");
|
|
390
|
+
return JSON.parse(text);
|
|
391
|
+
}
|
|
392
|
+
|
|
290
393
|
// ─── Client ───────────────────────────────────────────────────────────────
|
|
291
394
|
|
|
292
395
|
const pause = (ms, signal) =>
|
|
@@ -322,6 +425,9 @@ export class HenergyqueAI {
|
|
|
322
425
|
this.chat = new Chat(this);
|
|
323
426
|
this.messages = new Messages(this);
|
|
324
427
|
this.models = new Models(this);
|
|
428
|
+
this.embeddings = new Embeddings(this);
|
|
429
|
+
this.files = new Files(this);
|
|
430
|
+
this.batches = new Batches(this);
|
|
325
431
|
}
|
|
326
432
|
|
|
327
433
|
// Le plus court chemin : une question, une réponse en texte.
|
|
@@ -350,7 +456,7 @@ export class HenergyqueAI {
|
|
|
350
456
|
return new Kind(response, controller);
|
|
351
457
|
}
|
|
352
458
|
|
|
353
|
-
async _request(method, path, body, { signal, timeout = this.timeout, maxRetries = this.maxRetries, headers = {}, stream = false } = {}) {
|
|
459
|
+
async _request(method, path, body, { signal, timeout = this.timeout, maxRetries = this.maxRetries, headers = {}, stream = false, raw } = {}) {
|
|
354
460
|
for (let attempt = 0; ; attempt += 1) {
|
|
355
461
|
const deadline = new AbortController();
|
|
356
462
|
const timer = setTimeout(() => deadline.abort(new TimeoutError(`Pas de réponse après ${Math.round(timeout / 1000)} s.`)), timeout);
|
|
@@ -364,11 +470,11 @@ export class HenergyqueAI {
|
|
|
364
470
|
headers: {
|
|
365
471
|
Authorization: `Bearer ${this.apiKey}`,
|
|
366
472
|
Accept: stream ? "text/event-stream" : "application/json",
|
|
367
|
-
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
473
|
+
...(raw ? { "Content-Type": "application/octet-stream" } : body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
368
474
|
...this._headers,
|
|
369
475
|
...headers,
|
|
370
476
|
},
|
|
371
|
-
body: body === undefined ? undefined : JSON.stringify(body),
|
|
477
|
+
body: raw ?? (body === undefined ? undefined : JSON.stringify(body)),
|
|
372
478
|
signal: deadline.signal,
|
|
373
479
|
});
|
|
374
480
|
} catch (error) {
|