@haatlabs-core/ai 0.0.0-stage → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +16 -2
- package/dist/chat.d.ts +17 -0
- package/dist/chat.js +83 -0
- package/dist/chat.js.map +1 -0
- package/dist/cjs/chat.d.ts +17 -0
- package/dist/cjs/chat.js +95 -0
- package/dist/cjs/codes.d.ts +14 -0
- package/dist/cjs/codes.js +38 -0
- package/dist/cjs/embedding.d.ts +54 -0
- package/dist/cjs/embedding.js +169 -0
- package/dist/cjs/endpoint.d.ts +33 -0
- package/dist/cjs/endpoint.js +191 -0
- package/dist/cjs/factory.d.ts +50 -0
- package/dist/cjs/factory.js +74 -0
- package/dist/cjs/index.d.ts +9 -0
- package/dist/cjs/index.js +44 -0
- package/dist/cjs/observe.d.ts +19 -0
- package/dist/cjs/observe.js +77 -0
- package/dist/cjs/package.json +8 -0
- package/dist/cjs/rate-limit.d.ts +32 -0
- package/dist/cjs/rate-limit.js +46 -0
- package/dist/cjs/retry.d.ts +29 -0
- package/dist/cjs/retry.js +50 -0
- package/dist/cjs/text.d.ts +75 -0
- package/dist/cjs/text.js +127 -0
- package/dist/codes.d.ts +14 -0
- package/dist/codes.js +10 -0
- package/dist/codes.js.map +1 -0
- package/dist/embedding.d.ts +54 -0
- package/dist/embedding.js +152 -0
- package/dist/embedding.js.map +1 -0
- package/dist/endpoint.d.ts +33 -0
- package/dist/endpoint.js +181 -0
- package/dist/endpoint.js.map +1 -0
- package/dist/factory.d.ts +50 -0
- package/dist/factory.js +62 -0
- package/dist/factory.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/observe.d.ts +19 -0
- package/dist/observe.js +64 -0
- package/dist/observe.js.map +1 -0
- package/dist/rate-limit.d.ts +32 -0
- package/dist/rate-limit.js +29 -0
- package/dist/rate-limit.js.map +1 -0
- package/dist/retry.d.ts +29 -0
- package/dist/retry.js +29 -0
- package/dist/retry.js.map +1 -0
- package/dist/text.d.ts +75 -0
- package/dist/text.js +107 -0
- package/dist/text.js.map +1 -0
- package/package.json +59 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Haatlabs
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @haatlabs-core/ai
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Text from an OpenAI-compatible chat endpoint: retries, a rate limit, and answers checked
|
|
4
|
+
against the caller's zod schema. It throws `AI_PROVIDER_ERROR`; a project spreads
|
|
5
|
+
`AI_ERRORS` into `defineErrors`.
|
|
6
|
+
|
|
7
|
+
const text = createTextProvider({ baseUrl, apiKey, model });
|
|
8
|
+
|
|
9
|
+
`temperature` (0.2 by default) and `reasoningEffort` on `TextAiConfig` and on each request;
|
|
10
|
+
`createEmbeddingProvider(config, { rateLimit })` embeds text and images, with retry and a turn
|
|
11
|
+
before each request; `cosineSimilarity`.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
pnpm add @haatlabs-core/ai
|
|
16
|
+
|
|
17
|
+
It leaves one package to your app, so the app holds one copy: `zod`.
|
package/dist/chat.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** The assistant's text from a chat-completions response, whichever form the server uses. */
|
|
2
|
+
export declare function messageText(response: unknown, what?: string): string;
|
|
3
|
+
/** Parses the first JSON object in the text, tolerating a code fence or surrounding prose. */
|
|
4
|
+
export declare function parseObject(text: string, what?: string): unknown;
|
|
5
|
+
/** What one call to a model used, as the provider reports it. */
|
|
6
|
+
export interface AiUsage {
|
|
7
|
+
inputTokens: number;
|
|
8
|
+
outputTokens: number;
|
|
9
|
+
/** What the provider says the call cost, in US dollars; null when it does not say. */
|
|
10
|
+
costUsd: number | null;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The token counts in a chat-completions response, and the cost when the provider
|
|
14
|
+
* reports one (OpenRouter does, as `usage.cost`). Null when the response carries no
|
|
15
|
+
* usable counts: what is not known is not made up.
|
|
16
|
+
*/
|
|
17
|
+
export declare function usageOf(response: unknown): AiUsage | null;
|
package/dist/chat.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { aiError } from './endpoint.js';
|
|
2
|
+
const DEFAULT_WHAT = 'an answer';
|
|
3
|
+
const unexpected = (what) => aiError(`AI provider returned ${what} in an unexpected shape`, { transient: true });
|
|
4
|
+
const incomplete = () => aiError('AI provider did not return a complete answer', { transient: false });
|
|
5
|
+
/** The assistant's text from a chat-completions response, whichever form the server uses. */
|
|
6
|
+
export function messageText(response, what = DEFAULT_WHAT) {
|
|
7
|
+
if (typeof response !== 'object' || response === null)
|
|
8
|
+
throw unexpected(what);
|
|
9
|
+
const choices = response.choices;
|
|
10
|
+
const first = Array.isArray(choices) ? choices[0] : undefined;
|
|
11
|
+
if (typeof first !== 'object' || first === null)
|
|
12
|
+
throw unexpected(what);
|
|
13
|
+
const finish = first.finish_reason;
|
|
14
|
+
if (finish === 'length' || finish === 'content_filter')
|
|
15
|
+
throw incomplete();
|
|
16
|
+
const message = first.message;
|
|
17
|
+
if (typeof message !== 'object' || message === null)
|
|
18
|
+
throw unexpected(what);
|
|
19
|
+
const refusal = message.refusal;
|
|
20
|
+
if (typeof refusal === 'string' && refusal.length > 0)
|
|
21
|
+
throw incomplete();
|
|
22
|
+
const content = message.content;
|
|
23
|
+
let text;
|
|
24
|
+
if (typeof content === 'string') {
|
|
25
|
+
text = content;
|
|
26
|
+
}
|
|
27
|
+
else if (Array.isArray(content)) {
|
|
28
|
+
text = content
|
|
29
|
+
.map((part) => typeof part === 'object' &&
|
|
30
|
+
part !== null &&
|
|
31
|
+
typeof part.text === 'string'
|
|
32
|
+
? part.text
|
|
33
|
+
: '')
|
|
34
|
+
.join('');
|
|
35
|
+
}
|
|
36
|
+
else if (content === null || content === undefined) {
|
|
37
|
+
throw incomplete();
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
throw unexpected(what);
|
|
41
|
+
}
|
|
42
|
+
if (text.trim().length === 0)
|
|
43
|
+
throw incomplete();
|
|
44
|
+
return text;
|
|
45
|
+
}
|
|
46
|
+
/** Parses the first JSON object in the text, tolerating a code fence or surrounding prose. */
|
|
47
|
+
export function parseObject(text, what = DEFAULT_WHAT) {
|
|
48
|
+
const start = text.indexOf('{');
|
|
49
|
+
const end = text.lastIndexOf('}');
|
|
50
|
+
if (start === -1 || end <= start)
|
|
51
|
+
throw unexpected(what);
|
|
52
|
+
try {
|
|
53
|
+
return JSON.parse(text.slice(start, end + 1));
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
throw unexpected(what);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.round(value) : null;
|
|
60
|
+
/**
|
|
61
|
+
* The token counts in a chat-completions response, and the cost when the provider
|
|
62
|
+
* reports one (OpenRouter does, as `usage.cost`). Null when the response carries no
|
|
63
|
+
* usable counts: what is not known is not made up.
|
|
64
|
+
*/
|
|
65
|
+
export function usageOf(response) {
|
|
66
|
+
if (typeof response !== 'object' || response === null)
|
|
67
|
+
return null;
|
|
68
|
+
const usage = response.usage;
|
|
69
|
+
if (typeof usage !== 'object' || usage === null)
|
|
70
|
+
return null;
|
|
71
|
+
const given = usage;
|
|
72
|
+
const inputTokens = count(given.prompt_tokens);
|
|
73
|
+
const outputTokens = count(given.completion_tokens);
|
|
74
|
+
if (inputTokens === null || outputTokens === null)
|
|
75
|
+
return null;
|
|
76
|
+
const cost = given.cost;
|
|
77
|
+
return {
|
|
78
|
+
inputTokens,
|
|
79
|
+
outputTokens,
|
|
80
|
+
costUsd: typeof cost === 'number' && Number.isFinite(cost) && cost >= 0 ? cost : null,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=chat.js.map
|
package/dist/chat.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat.js","sourceRoot":"","sources":["../src/chat.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,MAAM,YAAY,GAAG,WAAW,CAAC;AAEjC,MAAM,UAAU,GAAG,CAAC,IAAY,EAAW,EAAE,CAC3C,OAAO,CAAC,wBAAwB,IAAI,yBAAyB,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAEtF,MAAM,UAAU,GAAG,GAAY,EAAE,CAC/B,OAAO,CAAC,8CAA8C,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC;AAEhF,6FAA6F;AAC7F,MAAM,UAAU,WAAW,CAAC,QAAiB,EAAE,OAAe,YAAY;IACxE,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,IAAI;QAAE,MAAM,UAAU,CAAC,IAAI,CAAC,CAAC;IAC9E,MAAM,OAAO,GAAa,QAAkC,CAAC,OAAO,CAAC;IACrE,MAAM,KAAK,GAAY,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACvE,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,MAAM,UAAU,CAAC,IAAI,CAAC,CAAC;IACxE,MAAM,MAAM,GAAa,KAAqC,CAAC,aAAa,CAAC;IAC7E,IAAI,MAAM,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IAC/D,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IACxB,OAAO;QACL,WAAW;QACX,YAAY;QACZ,OAAO,EAAE,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI;KACtF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** The assistant's text from a chat-completions response, whichever form the server uses. */
|
|
2
|
+
export declare function messageText(response: unknown, what?: string): string;
|
|
3
|
+
/** Parses the first JSON object in the text, tolerating a code fence or surrounding prose. */
|
|
4
|
+
export declare function parseObject(text: string, what?: string): unknown;
|
|
5
|
+
/** What one call to a model used, as the provider reports it. */
|
|
6
|
+
export interface AiUsage {
|
|
7
|
+
inputTokens: number;
|
|
8
|
+
outputTokens: number;
|
|
9
|
+
/** What the provider says the call cost, in US dollars; null when it does not say. */
|
|
10
|
+
costUsd: number | null;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The token counts in a chat-completions response, and the cost when the provider
|
|
14
|
+
* reports one (OpenRouter does, as `usage.cost`). Null when the response carries no
|
|
15
|
+
* usable counts: what is not known is not made up.
|
|
16
|
+
*/
|
|
17
|
+
export declare function usageOf(response: unknown): AiUsage | null;
|
package/dist/cjs/chat.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var chat_exports = {};
|
|
19
|
+
__export(chat_exports, {
|
|
20
|
+
messageText: () => messageText,
|
|
21
|
+
parseObject: () => parseObject,
|
|
22
|
+
usageOf: () => usageOf
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(chat_exports);
|
|
25
|
+
var import_endpoint = require("./endpoint.js");
|
|
26
|
+
const DEFAULT_WHAT = "an answer";
|
|
27
|
+
const unexpected = (what) => (0, import_endpoint.aiError)(`AI provider returned ${what} in an unexpected shape`, { transient: true });
|
|
28
|
+
const incomplete = () => (0, import_endpoint.aiError)("AI provider did not return a complete answer", { transient: false });
|
|
29
|
+
function messageText(response, what = DEFAULT_WHAT) {
|
|
30
|
+
if (typeof response !== "object" || response === null)
|
|
31
|
+
throw unexpected(what);
|
|
32
|
+
const choices = response.choices;
|
|
33
|
+
const first = Array.isArray(choices) ? choices[0] : void 0;
|
|
34
|
+
if (typeof first !== "object" || first === null)
|
|
35
|
+
throw unexpected(what);
|
|
36
|
+
const finish = first.finish_reason;
|
|
37
|
+
if (finish === "length" || finish === "content_filter")
|
|
38
|
+
throw incomplete();
|
|
39
|
+
const message = first.message;
|
|
40
|
+
if (typeof message !== "object" || message === null)
|
|
41
|
+
throw unexpected(what);
|
|
42
|
+
const refusal = message.refusal;
|
|
43
|
+
if (typeof refusal === "string" && refusal.length > 0)
|
|
44
|
+
throw incomplete();
|
|
45
|
+
const content = message.content;
|
|
46
|
+
let text;
|
|
47
|
+
if (typeof content === "string") {
|
|
48
|
+
text = content;
|
|
49
|
+
} else if (Array.isArray(content)) {
|
|
50
|
+
text = content.map((part) => typeof part === "object" && part !== null && typeof part.text === "string" ? part.text : "").join("");
|
|
51
|
+
} else if (content === null || content === void 0) {
|
|
52
|
+
throw incomplete();
|
|
53
|
+
} else {
|
|
54
|
+
throw unexpected(what);
|
|
55
|
+
}
|
|
56
|
+
if (text.trim().length === 0)
|
|
57
|
+
throw incomplete();
|
|
58
|
+
return text;
|
|
59
|
+
}
|
|
60
|
+
function parseObject(text, what = DEFAULT_WHAT) {
|
|
61
|
+
const start = text.indexOf("{");
|
|
62
|
+
const end = text.lastIndexOf("}");
|
|
63
|
+
if (start === -1 || end <= start)
|
|
64
|
+
throw unexpected(what);
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(text.slice(start, end + 1));
|
|
67
|
+
} catch {
|
|
68
|
+
throw unexpected(what);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const count = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.round(value) : null;
|
|
72
|
+
function usageOf(response) {
|
|
73
|
+
if (typeof response !== "object" || response === null)
|
|
74
|
+
return null;
|
|
75
|
+
const usage = response.usage;
|
|
76
|
+
if (typeof usage !== "object" || usage === null)
|
|
77
|
+
return null;
|
|
78
|
+
const given = usage;
|
|
79
|
+
const inputTokens = count(given.prompt_tokens);
|
|
80
|
+
const outputTokens = count(given.completion_tokens);
|
|
81
|
+
if (inputTokens === null || outputTokens === null)
|
|
82
|
+
return null;
|
|
83
|
+
const cost = given.cost;
|
|
84
|
+
return {
|
|
85
|
+
inputTokens,
|
|
86
|
+
outputTokens,
|
|
87
|
+
costUsd: typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : null
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
91
|
+
0 && (module.exports = {
|
|
92
|
+
messageText,
|
|
93
|
+
parseObject,
|
|
94
|
+
usageOf
|
|
95
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AppError } from '@haatlabs-core/errors';
|
|
2
|
+
/** The code this package throws beyond the core ones: a project spreads it into defineErrors. */
|
|
3
|
+
export declare const AI_ERRORS: {
|
|
4
|
+
readonly AI_PROVIDER_ERROR: {
|
|
5
|
+
readonly httpStatus: 503;
|
|
6
|
+
readonly transient: true;
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
export declare const AiErrorCode: {
|
|
10
|
+
readonly AI_PROVIDER_ERROR: "AI_PROVIDER_ERROR";
|
|
11
|
+
};
|
|
12
|
+
export declare const createAiError: (code: "AI_PROVIDER_ERROR", message: string, options?: import("@haatlabs-core/errors").AppErrorOptions) => AppError<"AI_PROVIDER_ERROR">;
|
|
13
|
+
/** The error this package throws: a project that spreads in AI_ERRORS takes it as its own. */
|
|
14
|
+
export type AiError = AppError<keyof typeof AI_ERRORS>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var codes_exports = {};
|
|
19
|
+
__export(codes_exports, {
|
|
20
|
+
AI_ERRORS: () => AI_ERRORS,
|
|
21
|
+
AiErrorCode: () => AiErrorCode,
|
|
22
|
+
createAiError: () => createAiError
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(codes_exports);
|
|
25
|
+
var import_errors = require("@haatlabs-core/errors");
|
|
26
|
+
const AI_ERRORS = {
|
|
27
|
+
// Something this API depends on failed: 503, never 502 or 504 (see @haatlabs-core/errors).
|
|
28
|
+
AI_PROVIDER_ERROR: { httpStatus: 503, transient: true }
|
|
29
|
+
};
|
|
30
|
+
const ai = (0, import_errors.domainErrors)(AI_ERRORS);
|
|
31
|
+
const AiErrorCode = ai.codes;
|
|
32
|
+
const createAiError = ai.create;
|
|
33
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
34
|
+
0 && (module.exports = {
|
|
35
|
+
AI_ERRORS,
|
|
36
|
+
AiErrorCode,
|
|
37
|
+
createAiError
|
|
38
|
+
});
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { AiUsage } from './chat.js';
|
|
2
|
+
import type { AiEndpointOptions } from './endpoint.js';
|
|
3
|
+
import type { RetryOptions } from './retry.js';
|
|
4
|
+
export interface EmbeddingOptions {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
/**
|
|
7
|
+
* Told what an answered call used, and by which model, whether or not the answer was
|
|
8
|
+
* usable: it was paid for. What it throws is ignored.
|
|
9
|
+
*/
|
|
10
|
+
onUsage?: (usage: AiUsage | null, model: string) => void | Promise<void>;
|
|
11
|
+
/** What the call is for, as the app names it in its ledger: put on its span and metrics. */
|
|
12
|
+
feature?: string;
|
|
13
|
+
}
|
|
14
|
+
/** A picture to embed, as it is stored. */
|
|
15
|
+
export interface EmbeddingImage {
|
|
16
|
+
bytes: Uint8Array;
|
|
17
|
+
contentType: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Turns text or an image into a vector, so similar things can be found by distance. A
|
|
21
|
+
* text and an image can be compared only when one model made both vectors.
|
|
22
|
+
*/
|
|
23
|
+
export interface EmbeddingProvider {
|
|
24
|
+
readonly name: string;
|
|
25
|
+
embedText(text: string, options?: EmbeddingOptions): Promise<number[]>;
|
|
26
|
+
embedImage(image: EmbeddingImage, options?: EmbeddingOptions): Promise<number[]>;
|
|
27
|
+
}
|
|
28
|
+
export declare const MAX_EMBEDDING_TEXT_LENGTH = 8000;
|
|
29
|
+
export declare const MAX_EMBEDDING_DIMENSIONS = 8192;
|
|
30
|
+
/**
|
|
31
|
+
* What an embedding call used: the tokens read, none written, and the provider's own cost
|
|
32
|
+
* when it gives one (OpenRouter does, as `usage.cost`). Null when it does not say.
|
|
33
|
+
*/
|
|
34
|
+
export declare function embeddingUsageOf(response: unknown): AiUsage | null;
|
|
35
|
+
/**
|
|
36
|
+
* Embeddings from an OpenAI-compatible `embeddings` endpoint. Text goes as that protocol
|
|
37
|
+
* has it. An image goes as a picture part, the way OpenRouter takes one for a model that
|
|
38
|
+
* reads images; an endpoint or model that does not will refuse it, and that refusal is the
|
|
39
|
+
* provider's error, not a vector.
|
|
40
|
+
*/
|
|
41
|
+
export declare class OpenAICompatibleEmbeddingProvider implements EmbeddingProvider {
|
|
42
|
+
readonly name = "openai-compatible";
|
|
43
|
+
private readonly endpoint;
|
|
44
|
+
private readonly model;
|
|
45
|
+
constructor(options: AiEndpointOptions & {
|
|
46
|
+
model: string;
|
|
47
|
+
});
|
|
48
|
+
private embed;
|
|
49
|
+
embedText(text: string, options?: EmbeddingOptions): Promise<number[]>;
|
|
50
|
+
embedImage(image: EmbeddingImage, options?: EmbeddingOptions): Promise<number[]>;
|
|
51
|
+
}
|
|
52
|
+
/** Cosine of the angle between two vectors: 1 same direction, 0 unrelated, -1 opposite. */
|
|
53
|
+
export declare function cosineSimilarity(a: readonly number[], b: readonly number[]): number;
|
|
54
|
+
export declare function withEmbeddingRetry(provider: EmbeddingProvider, options?: RetryOptions): EmbeddingProvider;
|