@molecule/api-ai-local 1.0.5 → 1.0.7
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 +111 -24
- package/README.md +204 -11
- package/dist/provider.d.ts.map +1 -1
- package/dist/provider.js +49 -5
- package/package.json +5 -5
package/LICENSE
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
|
|
1
2
|
Apache License
|
|
2
3
|
Version 2.0, January 2004
|
|
3
4
|
http://www.apache.org/licenses/
|
|
@@ -34,21 +35,33 @@
|
|
|
34
35
|
|
|
35
36
|
"Work" shall mean the work of authorship, whether in Source or
|
|
36
37
|
Object form, made available under the License, as indicated by a
|
|
37
|
-
copyright notice that is included in or attached to the work
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
38
40
|
|
|
39
41
|
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
42
|
form, that is based on (or derived from) the Work and for which the
|
|
41
43
|
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
-
represent, as a whole, an original work of authorship.
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
49
62
|
|
|
50
63
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
-
on behalf of whom a Contribution has been received by
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
52
65
|
subsequently incorporated within the Work.
|
|
53
66
|
|
|
54
67
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
@@ -61,8 +74,18 @@
|
|
|
61
74
|
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
75
|
this License, each Contributor hereby grants to You a perpetual,
|
|
63
76
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
-
|
|
65
|
-
and otherwise transfer the Work
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
66
89
|
|
|
67
90
|
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
91
|
Work or Derivative Works thereof in any medium, with or without
|
|
@@ -84,23 +107,87 @@
|
|
|
84
107
|
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
108
|
distribution, then any Derivative Works that You distribute must
|
|
86
109
|
include a readable copy of the attribution notices contained
|
|
87
|
-
within such NOTICE file
|
|
88
|
-
|
|
89
|
-
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
90
138
|
|
|
91
139
|
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
-
names, trademarks, service marks, or product names of the Licensor
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
93
143
|
|
|
94
144
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
-
agreed to in writing, Licensor provides the Work
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
104
191
|
|
|
105
192
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
193
|
you may not use this file except in compliance with the License.
|
package/README.md
CHANGED
|
@@ -3,21 +3,21 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
|
|
|
3
3
|
Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
|
|
4
4
|
Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
|
|
5
5
|
To change this document, edit the module-level JSDoc in src/index.ts.
|
|
6
|
-
Generated: 2026-10-
|
|
6
|
+
Generated: 2026-10-16T23:28:28.190Z
|
|
7
7
|
-->
|
|
8
8
|
|
|
9
9
|
# @molecule/api-ai-local
|
|
10
10
|
|
|
11
|
-
> **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
|
|
12
|
-
> It is written to be read by coding agents as much as by people, and is generated from this
|
|
13
|
-
> package's source — edit `src/index.ts` JSDoc, not this file.
|
|
14
|
-
|
|
15
11
|
Local (OpenAI-compatible) ai-local provider for molecule.dev.
|
|
16
12
|
|
|
17
13
|
Streams chat completions from any local inference server that speaks the
|
|
18
14
|
OpenAI `chat/completions` protocol (Ollama, LM Studio, llama.cpp, vLLM),
|
|
19
15
|
keyless by default.
|
|
20
16
|
|
|
17
|
+
> **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
|
|
18
|
+
> It is written to be read by coding agents as much as by people, and is generated from this
|
|
19
|
+
> package's source — edit `src/index.ts` JSDoc, not this file.
|
|
20
|
+
|
|
21
21
|
## Quick Start
|
|
22
22
|
|
|
23
23
|
```typescript
|
|
@@ -87,6 +87,199 @@ Local (OpenAI-compatible) chat provider implementing the `AIProvider`
|
|
|
87
87
|
interface. Mirrors `@molecule/api-ai-openai` so the same handler code can
|
|
88
88
|
dispatch to a local endpoint.
|
|
89
89
|
|
|
90
|
+
```typescript
|
|
91
|
+
class LocalAIProvider implements AIProvider {
|
|
92
|
+
readonly name = 'local'
|
|
93
|
+
private apiKey: string
|
|
94
|
+
private defaultModel: string
|
|
95
|
+
private maxTokens: number
|
|
96
|
+
private baseUrl: string
|
|
97
|
+
private onRateLimit?: AiRateLimitCallback
|
|
98
|
+
|
|
99
|
+
constructor(config: LocalConfig = {}) {
|
|
100
|
+
// Keyless by default — many local servers ignore auth. Empty string means
|
|
101
|
+
// "no key", so no Authorization header is sent. NEVER throws for a missing
|
|
102
|
+
// key at construction.
|
|
103
|
+
this.apiKey = config.apiKey ?? process.env.LOCAL_AI_API_KEY ?? ''
|
|
104
|
+
this.defaultModel = config.model ?? process.env.LOCAL_AI_MODEL ?? DEFAULT_MODEL
|
|
105
|
+
this.maxTokens = DEFAULT_MAX_TOKENS
|
|
106
|
+
this.onRateLimit = config.onRateLimit
|
|
107
|
+
this.baseUrl =
|
|
108
|
+
config.baseUrl ??
|
|
109
|
+
process.env.LOCAL_AI_BASE_URL ??
|
|
110
|
+
process.env.OLLAMA_BASE_URL ??
|
|
111
|
+
DEFAULT_BASE_URL
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Send a chat request and yield streamed `ChatEvent`s.
|
|
116
|
+
*
|
|
117
|
+
* @param params - Chat parameters.
|
|
118
|
+
* @yields {ChatEvent}
|
|
119
|
+
*/
|
|
120
|
+
async *chat(params: ChatParams): AsyncIterable<ChatEvent> {
|
|
121
|
+
const model = params.model ?? this.defaultModel
|
|
122
|
+
const maxTokens = params.maxTokens ?? this.maxTokens
|
|
123
|
+
|
|
124
|
+
const messages = this.formatMessages(params.messages, params.system)
|
|
125
|
+
|
|
126
|
+
const body: Record<string, unknown> = {
|
|
127
|
+
// Abuse attribution (see ChatParams.endUserId): OpenAI-compatible APIs
|
|
128
|
+
// scope enforcement by `user`, so an abusive tenant can be actioned
|
|
129
|
+
// individually instead of the org key that serves everyone. The value is
|
|
130
|
+
// the caller's opaque hash — never derived or logged here.
|
|
131
|
+
...(params.endUserId ? { user: params.endUserId } : {}),
|
|
132
|
+
model,
|
|
133
|
+
messages,
|
|
134
|
+
max_tokens: maxTokens,
|
|
135
|
+
}
|
|
136
|
+
if (params.temperature !== undefined) body.temperature = params.temperature
|
|
137
|
+
|
|
138
|
+
// Reasoning depth: the caller resolves the model's native reasoning_effort
|
|
139
|
+
// value from the model catalog and passes it as `thinking.effort`. Local
|
|
140
|
+
// servers that don't support it typically ignore an unknown field.
|
|
141
|
+
if (params.thinking?.effort) {
|
|
142
|
+
body.reasoning_effort = params.thinking.effort
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const tools = params.tools?.length ? this.formatTools(params.tools) : null
|
|
146
|
+
if (tools) {
|
|
147
|
+
body.tools = tools
|
|
148
|
+
if (params.toolChoice === 'required') {
|
|
149
|
+
body.tool_choice = 'required'
|
|
150
|
+
} else if (typeof params.toolChoice === 'object' && params.toolChoice?.type === 'tool') {
|
|
151
|
+
body.tool_choice = { type: 'function', function: { name: params.toolChoice.name } }
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const useStream = params.stream !== false
|
|
156
|
+
if (useStream) {
|
|
157
|
+
body.stream = true
|
|
158
|
+
body.stream_options = { include_usage: true }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Per-call correlation (see ChatParams.requestId): a header rather than the
|
|
162
|
+
// body's `user`, the stable per-account abuse-attribution value.
|
|
163
|
+
const requestId = params.requestId ?? randomUUID()
|
|
164
|
+
const call: LocalCallContext = {
|
|
165
|
+
meta: { requestId, endpoint: this.baseUrl },
|
|
166
|
+
endUserId: params.endUserId,
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const headers: Record<string, string> = {
|
|
170
|
+
'Content-Type': 'application/json',
|
|
171
|
+
'X-Mol-Request-Id': requestId,
|
|
172
|
+
}
|
|
173
|
+
// Only authenticate when a key is configured — local servers are keyless.
|
|
174
|
+
if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`
|
|
175
|
+
|
|
176
|
+
const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000
|
|
177
|
+
const signal = params.signal ?? AbortSignal.timeout(DEFAULT_TIMEOUT_MS)
|
|
178
|
+
|
|
179
|
+
const url = `${this.baseUrl}/chat/completions`
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
const MAX_RETRIES = 3
|
|
183
|
+
let response: Response | null = null
|
|
184
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
185
|
+
response = await fetch(url, {
|
|
186
|
+
method: 'POST',
|
|
187
|
+
headers,
|
|
188
|
+
body: JSON.stringify(body),
|
|
189
|
+
signal,
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
if (response.status === 429 || response.status === 503) {
|
|
193
|
+
const willRetry = attempt < MAX_RETRIES
|
|
194
|
+
// Retry-After is equally-valid as delta-seconds or an HTTP-date;
|
|
195
|
+
// parseInt on the date form yields NaN, degrading the backoff to
|
|
196
|
+
// a ~0ms retry against an already-busy local endpoint. Guard it.
|
|
197
|
+
const retryAfter = response.headers.get('retry-after')
|
|
198
|
+
const parsedRetryAfterSeconds = retryAfter ? parseInt(retryAfter, 10) : NaN
|
|
199
|
+
const hasRetryAfter =
|
|
200
|
+
Number.isFinite(parsedRetryAfterSeconds) && parsedRetryAfterSeconds >= 0
|
|
201
|
+
// Additive jitter (<500ms): concurrent callers rejected together must
|
|
202
|
+
// not sleep identical delays and re-arrive as the same burst.
|
|
203
|
+
const delayMs = willRetry
|
|
204
|
+
? (hasRetryAfter
|
|
205
|
+
? Math.min(parsedRetryAfterSeconds * 1000, 60_000)
|
|
206
|
+
: Math.min(1000 * 2 ** attempt, 30_000)) + Math.floor(Math.random() * 500)
|
|
207
|
+
: 0
|
|
208
|
+
try {
|
|
209
|
+
this.onRateLimit?.({
|
|
210
|
+
provider: this.name,
|
|
211
|
+
model,
|
|
212
|
+
status: response.status,
|
|
213
|
+
attempt: attempt + 1,
|
|
214
|
+
willRetry,
|
|
215
|
+
retryInMs: delayMs,
|
|
216
|
+
...(hasRetryAfter ? { retryAfterSeconds: parsedRetryAfterSeconds } : {}),
|
|
217
|
+
})
|
|
218
|
+
} catch (error) {
|
|
219
|
+
// Host-app telemetry; its failure must never break the request.
|
|
220
|
+
logger.warn('onRateLimit callback threw', { error })
|
|
221
|
+
}
|
|
222
|
+
if (willRetry) {
|
|
223
|
+
logger.warn('Local AI endpoint busy, retrying', {
|
|
224
|
+
status: response.status,
|
|
225
|
+
attempt: attempt + 1,
|
|
226
|
+
delayMs,
|
|
227
|
+
})
|
|
228
|
+
await new Promise<void>((resolve) => {
|
|
229
|
+
const timer = setTimeout(resolve, delayMs)
|
|
230
|
+
signal.addEventListener(
|
|
231
|
+
'abort',
|
|
232
|
+
() => {
|
|
233
|
+
clearTimeout(timer)
|
|
234
|
+
resolve()
|
|
235
|
+
},
|
|
236
|
+
{ once: true },
|
|
237
|
+
)
|
|
238
|
+
})
|
|
239
|
+
if (signal.aborted) break
|
|
240
|
+
continue
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
break
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (!response!.ok) {
|
|
247
|
+
const errorBody = await response!.text()
|
|
248
|
+
let detail = `HTTP ${response!.status}`
|
|
249
|
+
try {
|
|
250
|
+
const parsed = JSON.parse(errorBody) as { error?: { message?: string } }
|
|
251
|
+
if (parsed.error?.message) detail = parsed.error.message
|
|
252
|
+
} catch (_error) {
|
|
253
|
+
// Best-effort: detail already has an HTTP-status fallback; malformed body just stays as-is.
|
|
254
|
+
if (errorBody.length > 0 && errorBody.length < 200) detail = errorBody
|
|
255
|
+
}
|
|
256
|
+
logger.error('Local AI endpoint error', { status: response!.status, url, detail })
|
|
257
|
+
const clientMessage =
|
|
258
|
+
response!.status === 429
|
|
259
|
+
? 'AI rate limit exceeded. Please try again shortly.'
|
|
260
|
+
: response!.status === 401 || response!.status === 403
|
|
261
|
+
? 'AI service configuration error.'
|
|
262
|
+
: response!.status === 404
|
|
263
|
+
? 'Local AI endpoint or model not found. Is the server running and the model pulled?'
|
|
264
|
+
: response!.status === 400 &&
|
|
265
|
+
/context.*length|maximum context|too many tokens|prompt is too long/i.test(
|
|
266
|
+
detail,
|
|
267
|
+
)
|
|
268
|
+
? "Conversation too long for the model's context window."
|
|
269
|
+
: response!.status === 400
|
|
270
|
+
? 'AI request was invalid — check the model and request parameters.'
|
|
271
|
+
: response!.status === 503 || response!.status === 502
|
|
272
|
+
? 'AI service is temporarily overloaded. Please try again in a moment.'
|
|
273
|
+
: 'AI service error. Please try again.'
|
|
274
|
+
// Non-OK is a soft failure surfaced as an in-band error EVENT then a
|
|
275
|
+
// graceful return — matching the 8 sibling providers. molecule-dev's
|
|
276
|
+
// chat-handler consumes this via its `case 'error':` branch, which is a
|
|
277
|
+
// different path from its outer try/catch; throwing here would break
|
|
278
|
+
// that consumer contract.
|
|
279
|
+
yield { type: 'error', message: clientMessage, errorKey: 'ai.error.apiError' }
|
|
280
|
+
// … truncated — the full declaration is in node_modules/@molecule/api-ai-local/dist/provider.d.ts
|
|
281
|
+
```
|
|
282
|
+
|
|
90
283
|
### Functions
|
|
91
284
|
|
|
92
285
|
#### `createProvider(config)`
|
|
@@ -105,20 +298,20 @@ function createProvider(config?: LocalConfig): AIProvider
|
|
|
105
298
|
|
|
106
299
|
### Constants
|
|
107
300
|
|
|
108
|
-
#### `
|
|
301
|
+
#### `provider`
|
|
109
302
|
|
|
110
|
-
|
|
303
|
+
The provider implementation. Constructs keyless — no secret required.
|
|
111
304
|
|
|
112
305
|
```typescript
|
|
113
|
-
const
|
|
306
|
+
const provider: AIProvider
|
|
114
307
|
```
|
|
115
308
|
|
|
116
|
-
#### `
|
|
309
|
+
#### `aiLocalSecretDefinitions`
|
|
117
310
|
|
|
118
|
-
|
|
311
|
+
Optional secret/config overrides recognised by the local AI bond.
|
|
119
312
|
|
|
120
313
|
```typescript
|
|
121
|
-
const
|
|
314
|
+
const aiLocalSecretDefinitions: SecretDefinition[]
|
|
122
315
|
```
|
|
123
316
|
|
|
124
317
|
## Core Interface
|
package/dist/provider.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAOH,OAAO,cAAc,CAAA;AAErB,OAAO,KAAK,EACV,UAAU,EAGV,SAAS,EAET,UAAU,EAGX,MAAM,kBAAkB,CAAA;AAGzB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AA+B7C;;;;GAIG;AACH,qBAAa,eAAgB,YAAW,UAAU;IAChD,QAAQ,CAAC,IAAI,WAAU;IACvB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,YAAY,CAAQ;IAC5B,OAAO,CAAC,SAAS,CAAQ;IACzB,OAAO,CAAC,OAAO,CAAQ;IACvB,OAAO,CAAC,WAAW,CAAC,CAAqB;gBAE7B,MAAM,GAAE,WAAgB;IAepC;;;;;OAKG;IACI,IAAI,CAAC,MAAM,EAAE,UAAU,GAAG,aAAa,CAAC,SAAS,CAAC;IAkMzD;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,cAAc;IA+DtB;;;;OAIG;IACH,OAAO,CAAC,WAAW;IA6BnB,uEAAuE;IACvE,OAAO,CAAC,WAAW;IAWnB;;;;;OAKG;IACH,OAAO,CAAE,yBAAyB;IA8ClC;;;;;OAKG;YACY,sBAAsB;IA+ErC;;;;;;OAMG;IACH,OAAO,CAAE,eAAe;IAmGxB;;;;;;;;;;OAUG;IACH,OAAO,CAAE,qBAAqB;CAqC/B;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,UAAU,CAE/D"}
|
package/dist/provider.js
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
// Side-effect import: registers this bond's OPTIONAL secret definitions so the
|
|
14
14
|
// runtime registry is populated even when provider.js is imported directly
|
|
15
15
|
// (not through the package barrel).
|
|
16
|
+
import { randomUUID } from 'node:crypto';
|
|
16
17
|
import './secrets.js';
|
|
17
18
|
import { getLogger } from '@molecule/api-bond';
|
|
18
19
|
const logger = getLogger();
|
|
@@ -91,8 +92,16 @@ export class LocalAIProvider {
|
|
|
91
92
|
body.stream = true;
|
|
92
93
|
body.stream_options = { include_usage: true };
|
|
93
94
|
}
|
|
95
|
+
// Per-call correlation (see ChatParams.requestId): a header rather than the
|
|
96
|
+
// body's `user`, the stable per-account abuse-attribution value.
|
|
97
|
+
const requestId = params.requestId ?? randomUUID();
|
|
98
|
+
const call = {
|
|
99
|
+
meta: { requestId, endpoint: this.baseUrl },
|
|
100
|
+
endUserId: params.endUserId,
|
|
101
|
+
};
|
|
94
102
|
const headers = {
|
|
95
103
|
'Content-Type': 'application/json',
|
|
104
|
+
'X-Mol-Request-Id': requestId,
|
|
96
105
|
};
|
|
97
106
|
// Only authenticate when a key is configured — local servers are keyless.
|
|
98
107
|
if (this.apiKey)
|
|
@@ -201,7 +210,11 @@ export class LocalAIProvider {
|
|
|
201
210
|
yield* this.parseNonStreamingResponse(data);
|
|
202
211
|
return;
|
|
203
212
|
}
|
|
204
|
-
|
|
213
|
+
// Whatever the transport exposes about this call.
|
|
214
|
+
const traceId = response.headers.get('x-request-id') ?? response.headers.get('request-id') ?? undefined;
|
|
215
|
+
if (traceId)
|
|
216
|
+
call.meta.traceId = traceId;
|
|
217
|
+
yield* this.parseStreamingResponse(response, call);
|
|
205
218
|
}
|
|
206
219
|
catch (error) {
|
|
207
220
|
// A deliberate abort — client disconnect via `params.signal`, or the
|
|
@@ -392,7 +405,7 @@ export class LocalAIProvider {
|
|
|
392
405
|
* @param response - The fetch Response whose body is an SSE stream.
|
|
393
406
|
* @yields {ChatEvent} Incremental text, tool-use progress, keep-alive, and done events.
|
|
394
407
|
*/
|
|
395
|
-
async *parseStreamingResponse(response) {
|
|
408
|
+
async *parseStreamingResponse(response, call) {
|
|
396
409
|
const reader = response.body?.getReader();
|
|
397
410
|
if (!reader) {
|
|
398
411
|
yield {
|
|
@@ -419,7 +432,7 @@ export class LocalAIProvider {
|
|
|
419
432
|
const lines = buffer.split('\n');
|
|
420
433
|
buffer = lines.pop() ?? '';
|
|
421
434
|
let yielded = false;
|
|
422
|
-
for (const event of this.processSSELines(lines, state)) {
|
|
435
|
+
for (const event of this.processSSELines(lines, state, call)) {
|
|
423
436
|
yielded = true;
|
|
424
437
|
yield event;
|
|
425
438
|
// A mid-stream error (rate-limit/overload during high load, sent as a
|
|
@@ -437,7 +450,7 @@ export class LocalAIProvider {
|
|
|
437
450
|
yield { type: 'keep_alive' };
|
|
438
451
|
}
|
|
439
452
|
if (buffer.trim()) {
|
|
440
|
-
for (const event of this.processSSELines(buffer.split('\n'), state)) {
|
|
453
|
+
for (const event of this.processSSELines(buffer.split('\n'), state, call)) {
|
|
441
454
|
yield event;
|
|
442
455
|
if (event.type === 'error')
|
|
443
456
|
return;
|
|
@@ -466,6 +479,7 @@ export class LocalAIProvider {
|
|
|
466
479
|
outputTokens: state.outputTokens,
|
|
467
480
|
cacheReadInputTokens: state.cachedTokens,
|
|
468
481
|
},
|
|
482
|
+
provider: call.meta,
|
|
469
483
|
};
|
|
470
484
|
}
|
|
471
485
|
/**
|
|
@@ -475,7 +489,7 @@ export class LocalAIProvider {
|
|
|
475
489
|
* @param state - Mutable stream state tracking tokens and pending tool calls.
|
|
476
490
|
* @yields {ChatEvent} Text, tool-use progress, and usage events parsed from the SSE data lines.
|
|
477
491
|
*/
|
|
478
|
-
*processSSELines(lines, state) {
|
|
492
|
+
*processSSELines(lines, state, call) {
|
|
479
493
|
for (const line of lines) {
|
|
480
494
|
if (!line.startsWith('data: '))
|
|
481
495
|
continue;
|
|
@@ -484,6 +498,36 @@ export class LocalAIProvider {
|
|
|
484
498
|
continue;
|
|
485
499
|
try {
|
|
486
500
|
const event = JSON.parse(json);
|
|
501
|
+
// The reply's own identity, recorded for the caller: the completion id
|
|
502
|
+
// and the model the provider says answered. A reply carrying somebody
|
|
503
|
+
// else's identity is not ours to stream on.
|
|
504
|
+
if (typeof event.id === 'string')
|
|
505
|
+
call.meta.responseId = event.id;
|
|
506
|
+
if (typeof event.model === 'string')
|
|
507
|
+
call.meta.model = event.model;
|
|
508
|
+
const echoedUser = typeof event.user === 'string' ? event.user : undefined;
|
|
509
|
+
const echoedRequest = typeof event.request_id === 'string'
|
|
510
|
+
? event.request_id
|
|
511
|
+
: typeof event.requestId === 'string'
|
|
512
|
+
? event.requestId
|
|
513
|
+
: undefined;
|
|
514
|
+
const wrongUser = echoedUser !== undefined && call.endUserId !== undefined && echoedUser !== call.endUserId;
|
|
515
|
+
const wrongRequest = echoedRequest !== undefined && echoedRequest !== call.meta.requestId;
|
|
516
|
+
if (wrongUser || wrongRequest) {
|
|
517
|
+
logger.error('Provider echoed a different identity — this reply is not ours', {
|
|
518
|
+
requestId: call.meta.requestId,
|
|
519
|
+
echoedUser: wrongUser ? echoedUser : undefined,
|
|
520
|
+
echoedRequestId: wrongRequest ? echoedRequest : undefined,
|
|
521
|
+
responseId: call.meta.responseId,
|
|
522
|
+
traceId: call.meta.traceId,
|
|
523
|
+
});
|
|
524
|
+
yield {
|
|
525
|
+
type: 'error',
|
|
526
|
+
message: 'AI service error. Please try again.',
|
|
527
|
+
errorKey: 'ai.error.apiError',
|
|
528
|
+
};
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
487
531
|
// A mid-stream error arrives as a `data: {"error": {...}}` chunk (no
|
|
488
532
|
// `choices`) — most importantly rate-limit/overload when a shared local
|
|
489
533
|
// endpoint is under load. Without this it matches no branch below and is
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@molecule/api-ai-local",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.7",
|
|
4
4
|
"description": "AIProvider bond for any OpenAI-compatible local inference server (Ollama, LM Studio, llama.cpp, vLLM) — configurable base URL, keyless by default, streamed via raw fetch.",
|
|
5
5
|
"homepage": "https://www.molecule.dev/packages/api-ai-local",
|
|
6
6
|
"type": "module",
|
|
@@ -33,12 +33,12 @@
|
|
|
33
33
|
"directory": "packages/api/bonds/ai/local"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
|
-
"@molecule/api-ai": "1.3.
|
|
37
|
-
"@molecule/api-bond": "1.0.
|
|
36
|
+
"@molecule/api-ai": "1.3.5",
|
|
37
|
+
"@molecule/api-bond": "1.0.3",
|
|
38
38
|
"@molecule/api-secrets": "1.0.2",
|
|
39
|
-
"@types/node": "26.
|
|
39
|
+
"@types/node": "26.6.5",
|
|
40
40
|
"typescript": "6.0.3",
|
|
41
|
-
"vitest": "4.1.
|
|
41
|
+
"vitest": "4.1.12"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"@molecule/api-ai": "^1.0.1",
|