@loomwork/llm 0.0.0-stage → 0.1.1
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 +202 -0
- package/NOTICE +8 -0
- package/README.md +80 -2
- package/dist/assembleStream.d.ts +95 -0
- package/dist/assembleStream.d.ts.map +1 -0
- package/dist/assembleStream.js +180 -0
- package/dist/assembleStream.js.map +1 -0
- package/dist/capabilities.d.ts +43 -0
- package/dist/capabilities.d.ts.map +1 -0
- package/dist/capabilities.js +77 -0
- package/dist/capabilities.js.map +1 -0
- package/dist/createLlmEffect.d.ts +110 -0
- package/dist/createLlmEffect.d.ts.map +1 -0
- package/dist/createLlmEffect.js +177 -0
- package/dist/createLlmEffect.js.map +1 -0
- package/dist/errors.d.ts +96 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +280 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +71 -0
- package/dist/index.js.map +1 -0
- package/dist/parts.d.ts +220 -0
- package/dist/parts.d.ts.map +1 -0
- package/dist/parts.js +231 -0
- package/dist/parts.js.map +1 -0
- package/dist/providers/AnthropicProvider.d.ts +53 -0
- package/dist/providers/AnthropicProvider.d.ts.map +1 -0
- package/dist/providers/AnthropicProvider.js +443 -0
- package/dist/providers/AnthropicProvider.js.map +1 -0
- package/dist/providers/GeminiProvider.d.ts +66 -0
- package/dist/providers/GeminiProvider.d.ts.map +1 -0
- package/dist/providers/GeminiProvider.js +281 -0
- package/dist/providers/GeminiProvider.js.map +1 -0
- package/dist/providers/OpenAiProvider.d.ts +56 -0
- package/dist/providers/OpenAiProvider.d.ts.map +1 -0
- package/dist/providers/OpenAiProvider.js +402 -0
- package/dist/providers/OpenAiProvider.js.map +1 -0
- package/dist/providers/extraHeaders.d.ts +7 -0
- package/dist/providers/extraHeaders.d.ts.map +1 -0
- package/dist/providers/extraHeaders.js +40 -0
- package/dist/providers/extraHeaders.js.map +1 -0
- package/dist/providers/systemPrompt.d.ts +10 -0
- package/dist/providers/systemPrompt.d.ts.map +1 -0
- package/dist/providers/systemPrompt.js +22 -0
- package/dist/providers/systemPrompt.js.map +1 -0
- package/dist/reasoning.d.ts +154 -0
- package/dist/reasoning.d.ts.map +1 -0
- package/dist/reasoning.js +256 -0
- package/dist/reasoning.js.map +1 -0
- package/dist/resolveContent.d.ts +74 -0
- package/dist/resolveContent.d.ts.map +1 -0
- package/dist/resolveContent.js +335 -0
- package/dist/resolveContent.js.map +1 -0
- package/dist/types.d.ts +152 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/untrusted.d.ts +91 -0
- package/dist/untrusted.d.ts.map +1 -0
- package/dist/untrusted.js +385 -0
- package/dist/untrusted.js.map +1 -0
- package/package.json +54 -3
- package/src/assembleStream.ts +219 -0
- package/src/capabilities.ts +96 -0
- package/src/createLlmEffect.ts +287 -0
- package/src/errors.ts +269 -0
- package/src/index.ts +137 -0
- package/src/parts.ts +409 -0
- package/src/providers/AnthropicProvider.ts +550 -0
- package/src/providers/GeminiProvider.ts +380 -0
- package/src/providers/OpenAiProvider.ts +511 -0
- package/src/providers/extraHeaders.ts +41 -0
- package/src/providers/systemPrompt.ts +19 -0
- package/src/reasoning.ts +386 -0
- package/src/resolveContent.ts +425 -0
- package/src/types.ts +175 -0
- package/src/untrusted.ts +440 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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 [yyyy] [name of copyright owner]
|
|
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.
|
|
202
|
+
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,81 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @loomwork/llm
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A provider-agnostic model interface (`LlmProvider`), three HTTP providers (Anthropic, OpenAI, Gemini),
|
|
4
|
+
and `createLlmEffect`, which wraps a provider as a journaled effect. Use it when a flow needs a model
|
|
5
|
+
call that is recorded in the log, replayed instead of re-called, and checked before it leaves the
|
|
6
|
+
process. The providers use `fetch` directly and add no vendor SDK. For tool-using loops see
|
|
7
|
+
`@loomwork/agent`; for routing across several models see `@loomwork/reasoning`.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { tainted } from "@loomwork/classify";
|
|
11
|
+
import { AnthropicProvider, UNTRUSTED_CONTENT_SYSTEM_NOTE, createLlmEffect } from "@loomwork/llm";
|
|
12
|
+
|
|
13
|
+
const provider = new AnthropicProvider({ model: "claude-opus-4-8" }); // key from ANTHROPIC_API_KEY
|
|
14
|
+
|
|
15
|
+
export const summarize = createLlmEffect<{ ticket: string }, string>({
|
|
16
|
+
provider,
|
|
17
|
+
buildRequest: ({ ticket }) => ({
|
|
18
|
+
system: `You summarize support tickets.\n${UNTRUSTED_CONTENT_SYSTEM_NOTE}`,
|
|
19
|
+
maxTokens: 300,
|
|
20
|
+
// Tainted text is fenced as data before it reaches the model.
|
|
21
|
+
messages: [{ role: "user", content: tainted(ticket, "customer-email") }],
|
|
22
|
+
}),
|
|
23
|
+
parseResponse: (response) => response.content, // the default
|
|
24
|
+
stream: true,
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Surface
|
|
29
|
+
|
|
30
|
+
- **Providers.** `AnthropicProvider`, `OpenAiProvider`, `GeminiProvider`, each taking
|
|
31
|
+
`{ apiKey?, model?, baseUrl?, capabilities?, headers? }`. Anything with `complete(request)` (and
|
|
32
|
+
optionally `stream`) is an `LlmProvider`, so a test double or another vendor needs no adapter.
|
|
33
|
+
- **The effect.** `createLlmEffect({ provider, buildRequest, parseResponse?, stream?, resolveContent?,
|
|
34
|
+
reasoning?, onDelta?, guard? })`.
|
|
35
|
+
- **Messages.** `content` is a string, a tainted string, or an array of parts: text, image, audio,
|
|
36
|
+
file (by `ref` address or inline base64), `tool_use`, `tool_result`. `textOf`, `toParts` and
|
|
37
|
+
`assistantMessageOf` read and build them.
|
|
38
|
+
- **Capabilities.** A provider declares which media types it takes; a request outside that throws
|
|
39
|
+
`UnsupportedModalityError` before any network call.
|
|
40
|
+
- **Reasoning capture.** `reasoning: { store }` keeps model reasoning text in a sidecar store, off the
|
|
41
|
+
step value; `readReasoning` reads it back (ADR 0133).
|
|
42
|
+
- **Streaming.** `collectStream`, `assembleStream`, `LLM_INTERRUPTED` (a cut-off generation keeps its
|
|
43
|
+
partial text as a typed failure).
|
|
44
|
+
- **Errors.** `LlmHttpError` (`status`, `kind: "auth"`), `LlmResponseLimitError`, `LlmStreamError`,
|
|
45
|
+
`InvalidLlmRequestError`, `OversizedInlinePartError`, `UntrustedContentError`.
|
|
46
|
+
|
|
47
|
+
## Behaviour that surprises people
|
|
48
|
+
|
|
49
|
+
- **Streaming is opt-in.** `stream` defaults to off; with it on, a provider that has no `stream`
|
|
50
|
+
falls back to `complete`. Deltas passed to `onDelta` are not journaled and are not replayed.
|
|
51
|
+
- **Tainted content may appear only in a `user` message.** Anywhere else `guardRequest` throws
|
|
52
|
+
`UntrustedContentError`. In a `user` message it is wrapped in an `<untrusted-input>` fence. The fence
|
|
53
|
+
is a label the model can still be talked across, and it only helps if your system prompt says what it
|
|
54
|
+
means: add `UNTRUSTED_CONTENT_SYSTEM_NOTE` yourself, the library does not write your prompt.
|
|
55
|
+
- **Media is claim-checked.** The journaled request holds a ref's address, not bytes. A `ref` needs a
|
|
56
|
+
`resolveContent` that authorizes the caller, or the call throws `UnresolvedContentError` before
|
|
57
|
+
any network call. Inline data is capped (64 KiB per part, 256 KiB per request by default).
|
|
58
|
+
- **Media capability is an allowlist by model id.** The shipped providers declare image/file support
|
|
59
|
+
only for model ids they recognise, and none when `baseUrl` is not the vendor default.
|
|
60
|
+
Pass `capabilities` to override.
|
|
61
|
+
- **Constructors do not check the key.** The Anthropic provider reads `ANTHROPIC_API_KEY` when no
|
|
62
|
+
`apiKey` is given and falls back to an empty string; the failure arrives as an `LlmHttpError` on
|
|
63
|
+
the first call.
|
|
64
|
+
- **Redirects are never followed**, since that would re-send the body and credentials. The response
|
|
65
|
+
body of a failed call is not put on the error, because it can echo the prompt. Response, stream and
|
|
66
|
+
line sizes are bounded (defaults 8 MiB, 128 MiB, 1 MiB, adjustable per provider).
|
|
67
|
+
- **`headers` cannot override** the headers a provider sets itself (`x-api-key`, `authorization`, and
|
|
68
|
+
similar); doing so throws at construction.
|
|
69
|
+
|
|
70
|
+
## See also
|
|
71
|
+
|
|
72
|
+
- API reference: section "`@loomwork/llm` — provider-agnostic models" in
|
|
73
|
+
[docs/api-reference.org](../../docs/api-reference.org).
|
|
74
|
+
- Guide: [isolation and untrusted content](../../docs/user-guide/isolation-and-untrusted-content.md).
|
|
75
|
+
- ADRs: [0085 untrusted content](../../docs/adr/0085-untrusted-content-integrity-axis.md),
|
|
76
|
+
[0120 content parts](../../docs/adr/0120-llm-content-parts-and-tool-threading.md),
|
|
77
|
+
[0060 typed failures](../../docs/adr/0060-typed-failure-channels.md).
|
|
78
|
+
|
|
79
|
+
## Install
|
|
80
|
+
|
|
81
|
+
Unpublished for now: inside this repo use `workspace:*`; from a sibling checkout use a `link:` override (see [AGENTS.md](../../AGENTS.md)).
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { LlmResponse, LlmStreamChunk } from "./types";
|
|
2
|
+
/** Thrown when a stream violates its shape contract (no terminal chunk, or more than one). */
|
|
3
|
+
export declare class MalformedStreamError extends Error {
|
|
4
|
+
constructor(message: string);
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Fold a completed stream into the `LlmResponse` it represents.
|
|
8
|
+
*
|
|
9
|
+
* `stopReason` defaults to `"end_turn"` when the provider does not report one —
|
|
10
|
+
* the same value `complete` yields for an unrecognised stop reason, so a
|
|
11
|
+
* text-only streaming provider assembles to the same shape it always would.
|
|
12
|
+
* `toolCalls` and `usage` stay ABSENT rather than becoming empty: `undefined`
|
|
13
|
+
* means "not reported", `[]` would mean "reported none", and metering must be
|
|
14
|
+
* able to tell a provider that omits usage from one that charged nothing.
|
|
15
|
+
*/
|
|
16
|
+
export declare function assembleStream(chunks: readonly LlmStreamChunk[]): LlmResponse;
|
|
17
|
+
/**
|
|
18
|
+
* The channel an interrupted generation fails on (ADR 0060). Its payload is
|
|
19
|
+
* {@link InterruptedGeneration} — the text produced before the abort, which is
|
|
20
|
+
* usually the most expensive artifact the turn made and was previously discarded:
|
|
21
|
+
* `complete` + abort throws with the response body unread, so there is nothing to
|
|
22
|
+
* keep. Only a call that has been accumulating deltas has a partial to hand back.
|
|
23
|
+
*
|
|
24
|
+
* Declare it in the owning contract's `errors:` map to get the ADR 0060 treatment
|
|
25
|
+
* (recorded as `STEP_FAILED { channel, payload }`, substituted on replay);
|
|
26
|
+
* undeclared, it degrades to an ordinary failure exactly as before.
|
|
27
|
+
*/
|
|
28
|
+
export declare const LLM_INTERRUPTED = "llmInterrupted";
|
|
29
|
+
export interface InterruptedGeneration {
|
|
30
|
+
/** Deltas received before the abort, concatenated. May be empty. */
|
|
31
|
+
content: string;
|
|
32
|
+
/** Usage, if the provider reported any before the interruption. */
|
|
33
|
+
usage?: {
|
|
34
|
+
inputTokens: number;
|
|
35
|
+
outputTokens: number;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** What a stream has produced so far, offered to {@link CollectStreamOptions.guard}. */
|
|
39
|
+
export interface StreamProgress {
|
|
40
|
+
/** Everything received so far, concatenated. */
|
|
41
|
+
text: string;
|
|
42
|
+
/** Number of deltas received. */
|
|
43
|
+
deltas: number;
|
|
44
|
+
/** Usage, if the provider has reported any yet. Most report only at the end. */
|
|
45
|
+
usage?: {
|
|
46
|
+
inputTokens: number;
|
|
47
|
+
outputTokens: number;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export interface CollectStreamOptions {
|
|
51
|
+
/** When this is aborted, the partial is captured instead of being thrown away. */
|
|
52
|
+
signal?: AbortSignal;
|
|
53
|
+
/** Transient sink for deltas as they arrive. Never journaled by this function. */
|
|
54
|
+
onDelta?: (delta: string) => void;
|
|
55
|
+
/**
|
|
56
|
+
* ADR 0133 D6 - transient sink for readable reasoning increments, a channel SEPARATE from
|
|
57
|
+
* `onDelta` (and never part of `guard`'s `text`, nor of the interrupted partial). Never journaled.
|
|
58
|
+
*/
|
|
59
|
+
onReasoningDelta?: (delta: string) => void;
|
|
60
|
+
/** R5 — transient sink for tool-call input fragments. Never journaled. */
|
|
61
|
+
onToolDelta?: (delta: {
|
|
62
|
+
id: string;
|
|
63
|
+
name?: string;
|
|
64
|
+
inputDelta: string;
|
|
65
|
+
}) => void;
|
|
66
|
+
/**
|
|
67
|
+
* Called after every delta. THROW to sever the generation mid-flight — the
|
|
68
|
+
* throw propagates, the `for await` exits, and the underlying HTTP call is
|
|
69
|
+
* released.
|
|
70
|
+
*
|
|
71
|
+
* This is the seam K8.4 needs and the only one a stream can offer: providers
|
|
72
|
+
* report usage once at the end, so the sole thing observable *while* a
|
|
73
|
+
* generation runs is its own output. A guard that throws here is the
|
|
74
|
+
* difference between paying for a runaway generation and stopping it.
|
|
75
|
+
*
|
|
76
|
+
* Deliberately generic — no budget vocabulary lives in this package.
|
|
77
|
+
* `@loomwork/middleware`'s `streamTokenBudget` builds the budget-shaped one.
|
|
78
|
+
*/
|
|
79
|
+
guard?: (progress: StreamProgress) => void;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* `assembleStream` over a live stream — drains it, feeds deltas out as they
|
|
83
|
+
* arrive, and folds what arrived.
|
|
84
|
+
*
|
|
85
|
+
* With a `signal`, an abort mid-generation is NOT a lost generation: what was
|
|
86
|
+
* produced is captured as an {@link LLM_INTERRUPTED} typed failure. Anything else
|
|
87
|
+
* propagates untyped, so a transport failure stays one — K9 retries the turn
|
|
88
|
+
* whole, and a network blip never reads as a user stop.
|
|
89
|
+
*
|
|
90
|
+
* Shared by `createLlmEffect` and `AgentRunner` deliberately: two copies of an
|
|
91
|
+
* accumulate-and-capture loop is two chances to differ about what "interrupted"
|
|
92
|
+
* means, and the whole point is that the partial survives identically either way.
|
|
93
|
+
*/
|
|
94
|
+
export declare function collectStream(stream: AsyncIterable<LlmStreamChunk>, options?: CollectStreamOptions): Promise<LlmResponse>;
|
|
95
|
+
//# sourceMappingURL=assembleStream.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assembleStream.d.ts","sourceRoot":"","sources":["../src/assembleStream.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAc3D,8FAA8F;AAC9F,qBAAa,oBAAqB,SAAQ,KAAK;gBACjC,OAAO,EAAE,MAAM;CAI5B;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,GAAG,WAAW,CAsB7E;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,eAAe,mBAAmB,CAAC;AAEhD,MAAM,WAAW,qBAAqB;IACpC,oEAAoE;IACpE,OAAO,EAAE,MAAM,CAAC;IAChB,mEAAmE;IACnE,KAAK,CAAC,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC;CACvD;AAED,wFAAwF;AACxF,MAAM,WAAW,cAAc;IAC7B,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,iCAAiC;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,gFAAgF;IAChF,KAAK,CAAC,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC;CACvD;AAED,MAAM,WAAW,oBAAoB;IACnC,kFAAkF;IAClF,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,kFAAkF;IAClF,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC;;;OAGG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3C,0EAA0E;IAC1E,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;IACjF;;;;;;;;;;;;OAYG;IACH,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,IAAI,CAAC;CAC5C;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,aAAa,CACjC,MAAM,EAAE,aAAa,CAAC,cAAc,CAAC,EACrC,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,WAAW,CAAC,CAuFtB"}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LLM_INTERRUPTED = exports.MalformedStreamError = void 0;
|
|
4
|
+
exports.assembleStream = assembleStream;
|
|
5
|
+
exports.collectStream = collectStream;
|
|
6
|
+
const core_1 = require("@loomwork/core");
|
|
7
|
+
// ── The streamed-≡-completed contract ─────────────────────────────────────────
|
|
8
|
+
//
|
|
9
|
+
// Two paths to one outcome need a rule saying they agree, or they drift and the
|
|
10
|
+
// drift shows up as an agent that behaves differently once streaming is switched
|
|
11
|
+
// on. ADR 0059 D1 set the precedent for content: a streamed address MUST equal
|
|
12
|
+
// the whole-buffer address. This is the same discipline for the model call —
|
|
13
|
+
// assembling a stream MUST produce what `complete` would have returned.
|
|
14
|
+
//
|
|
15
|
+
// Assembly is deliberately dumb: concatenate the deltas, take the outcome fields
|
|
16
|
+
// from the terminal chunk. Anything cleverer would be a place for the two paths
|
|
17
|
+
// to disagree.
|
|
18
|
+
/** Thrown when a stream violates its shape contract (no terminal chunk, or more than one). */
|
|
19
|
+
class MalformedStreamError extends Error {
|
|
20
|
+
constructor(message) {
|
|
21
|
+
super(`Malformed LLM stream: ${message}`);
|
|
22
|
+
this.name = "MalformedStreamError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
exports.MalformedStreamError = MalformedStreamError;
|
|
26
|
+
/**
|
|
27
|
+
* Fold a completed stream into the `LlmResponse` it represents.
|
|
28
|
+
*
|
|
29
|
+
* `stopReason` defaults to `"end_turn"` when the provider does not report one —
|
|
30
|
+
* the same value `complete` yields for an unrecognised stop reason, so a
|
|
31
|
+
* text-only streaming provider assembles to the same shape it always would.
|
|
32
|
+
* `toolCalls` and `usage` stay ABSENT rather than becoming empty: `undefined`
|
|
33
|
+
* means "not reported", `[]` would mean "reported none", and metering must be
|
|
34
|
+
* able to tell a provider that omits usage from one that charged nothing.
|
|
35
|
+
*/
|
|
36
|
+
function assembleStream(chunks) {
|
|
37
|
+
const terminals = chunks.filter((c) => c.done);
|
|
38
|
+
if (terminals.length === 0) {
|
|
39
|
+
throw new MalformedStreamError("no terminal chunk (none had done: true)");
|
|
40
|
+
}
|
|
41
|
+
if (terminals.length > 1) {
|
|
42
|
+
throw new MalformedStreamError(`${terminals.length} terminal chunks (exactly one is allowed)`);
|
|
43
|
+
}
|
|
44
|
+
const last = chunks[chunks.length - 1];
|
|
45
|
+
if (last?.done !== true) {
|
|
46
|
+
throw new MalformedStreamError("the terminal chunk is not last");
|
|
47
|
+
}
|
|
48
|
+
const content = chunks.map((c) => c.delta).join("");
|
|
49
|
+
return {
|
|
50
|
+
content,
|
|
51
|
+
...(last.toolCalls !== undefined && { toolCalls: last.toolCalls }),
|
|
52
|
+
stopReason: last.stopReason ?? "end_turn",
|
|
53
|
+
...(last.usage !== undefined && { usage: last.usage }),
|
|
54
|
+
...(last.reasoning !== undefined && { reasoning: last.reasoning }),
|
|
55
|
+
...(last.layout !== undefined && { layout: last.layout }),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The channel an interrupted generation fails on (ADR 0060). Its payload is
|
|
60
|
+
* {@link InterruptedGeneration} — the text produced before the abort, which is
|
|
61
|
+
* usually the most expensive artifact the turn made and was previously discarded:
|
|
62
|
+
* `complete` + abort throws with the response body unread, so there is nothing to
|
|
63
|
+
* keep. Only a call that has been accumulating deltas has a partial to hand back.
|
|
64
|
+
*
|
|
65
|
+
* Declare it in the owning contract's `errors:` map to get the ADR 0060 treatment
|
|
66
|
+
* (recorded as `STEP_FAILED { channel, payload }`, substituted on replay);
|
|
67
|
+
* undeclared, it degrades to an ordinary failure exactly as before.
|
|
68
|
+
*/
|
|
69
|
+
exports.LLM_INTERRUPTED = "llmInterrupted";
|
|
70
|
+
/**
|
|
71
|
+
* `assembleStream` over a live stream — drains it, feeds deltas out as they
|
|
72
|
+
* arrive, and folds what arrived.
|
|
73
|
+
*
|
|
74
|
+
* With a `signal`, an abort mid-generation is NOT a lost generation: what was
|
|
75
|
+
* produced is captured as an {@link LLM_INTERRUPTED} typed failure. Anything else
|
|
76
|
+
* propagates untyped, so a transport failure stays one — K9 retries the turn
|
|
77
|
+
* whole, and a network blip never reads as a user stop.
|
|
78
|
+
*
|
|
79
|
+
* Shared by `createLlmEffect` and `AgentRunner` deliberately: two copies of an
|
|
80
|
+
* accumulate-and-capture loop is two chances to differ about what "interrupted"
|
|
81
|
+
* means, and the whole point is that the partial survives identically either way.
|
|
82
|
+
*/
|
|
83
|
+
async function collectStream(stream, options = {}) {
|
|
84
|
+
// Only three facts about the stream survive the fold — the text, the terminal
|
|
85
|
+
// chunk's outcome, and the shape checks — so nothing retains the chunks
|
|
86
|
+
// themselves. A long generation would otherwise hold one small object per
|
|
87
|
+
// delta for its whole duration, times every concurrent stream.
|
|
88
|
+
let count = 0;
|
|
89
|
+
let terminals = 0;
|
|
90
|
+
let last;
|
|
91
|
+
// Running state, maintained per chunk rather than recomputed per chunk. The
|
|
92
|
+
// first cut rebuilt the text with `chunks.map(...).join("")` and rescanned for
|
|
93
|
+
// usage on EVERY delta, which is O(n²) over a generation: 4,000 deltas cost
|
|
94
|
+
// ~90ms of pure copying, and `streamTokenBudget`'s `checkEvery` could not help
|
|
95
|
+
// because the expensive part ran before the guard was ever consulted.
|
|
96
|
+
// Appending to a string is amortized O(1); tracking the last reported usage is
|
|
97
|
+
// O(1). The guard is now the only cost per delta.
|
|
98
|
+
let text = "";
|
|
99
|
+
let usage;
|
|
100
|
+
// A guard breach is NOT an interruption, and the two are easy to confuse: a
|
|
101
|
+
// guard that severs typically aborts the execution too, so by the time the
|
|
102
|
+
// catch below runs, `signal.aborted` is true and the budget error would be
|
|
103
|
+
// rewritten into "interrupted" — losing the reason the generation stopped.
|
|
104
|
+
// The caller has to be able to tell "a human stopped this" from "this cost too
|
|
105
|
+
// much", so the guard's own error is remembered and rethrown untouched.
|
|
106
|
+
let guardError;
|
|
107
|
+
try {
|
|
108
|
+
for await (const chunk of stream) {
|
|
109
|
+
count += 1;
|
|
110
|
+
last = chunk;
|
|
111
|
+
if (chunk.done)
|
|
112
|
+
terminals += 1;
|
|
113
|
+
text += chunk.delta;
|
|
114
|
+
// Providers report usage late; keep the most recent one seen.
|
|
115
|
+
if (chunk.usage !== undefined)
|
|
116
|
+
usage = chunk.usage;
|
|
117
|
+
// The guard runs BEFORE delivery: a delta that breaches it severs the stream
|
|
118
|
+
// and is never handed to a sink (ADR 0119 — a live tail must not see what the
|
|
119
|
+
// guard exists to stop).
|
|
120
|
+
if (options.guard !== undefined) {
|
|
121
|
+
try {
|
|
122
|
+
options.guard({
|
|
123
|
+
text,
|
|
124
|
+
deltas: count,
|
|
125
|
+
...(usage !== undefined && { usage }),
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
guardError = err;
|
|
130
|
+
throw err;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// A provider that ignores the signal keeps yielding after an abort; checking
|
|
134
|
+
// here severs it at the next chunk instead of delivering text to a caller who
|
|
135
|
+
// has gone (the catch below turns it into the LLM_INTERRUPTED partial).
|
|
136
|
+
if (options.signal?.aborted === true) {
|
|
137
|
+
throw options.signal.reason instanceof Error
|
|
138
|
+
? options.signal.reason
|
|
139
|
+
: new Error("generation aborted");
|
|
140
|
+
}
|
|
141
|
+
if (chunk.delta !== "")
|
|
142
|
+
options.onDelta?.(chunk.delta);
|
|
143
|
+
if (chunk.toolDelta !== undefined)
|
|
144
|
+
options.onToolDelta?.(chunk.toolDelta);
|
|
145
|
+
if (chunk.reasoningDelta !== undefined && chunk.reasoningDelta !== "") {
|
|
146
|
+
options.onReasoningDelta?.(chunk.reasoningDelta);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
catch (err) {
|
|
151
|
+
if (guardError !== undefined)
|
|
152
|
+
throw guardError;
|
|
153
|
+
if (options.signal?.aborted === true) {
|
|
154
|
+
const partial = {
|
|
155
|
+
content: text,
|
|
156
|
+
...(usage !== undefined && { usage }),
|
|
157
|
+
};
|
|
158
|
+
(0, core_1.fail)(exports.LLM_INTERRUPTED, partial, "generation interrupted");
|
|
159
|
+
}
|
|
160
|
+
throw err;
|
|
161
|
+
}
|
|
162
|
+
// Same contract as `assembleStream`, checked against the counters rather than
|
|
163
|
+
// a retained array.
|
|
164
|
+
if (terminals === 0)
|
|
165
|
+
throw new MalformedStreamError("no terminal chunk (none had done: true)");
|
|
166
|
+
if (terminals > 1) {
|
|
167
|
+
throw new MalformedStreamError(`${terminals} terminal chunks (exactly one is allowed)`);
|
|
168
|
+
}
|
|
169
|
+
if (last?.done !== true)
|
|
170
|
+
throw new MalformedStreamError("the terminal chunk is not last");
|
|
171
|
+
return {
|
|
172
|
+
content: text,
|
|
173
|
+
...(last.toolCalls !== undefined && { toolCalls: last.toolCalls }),
|
|
174
|
+
stopReason: last.stopReason ?? "end_turn",
|
|
175
|
+
...(last.usage !== undefined && { usage: last.usage }),
|
|
176
|
+
...(last.reasoning !== undefined && { reasoning: last.reasoning }),
|
|
177
|
+
...(last.layout !== undefined && { layout: last.layout }),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
//# sourceMappingURL=assembleStream.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assembleStream.js","sourceRoot":"","sources":["../src/assembleStream.ts"],"names":[],"mappings":";;;AAiCA,wCAsBC;AAyED,sCA0FC;AA1ND,yCAAsC;AAGtC,iFAAiF;AACjF,EAAE;AACF,gFAAgF;AAChF,iFAAiF;AACjF,+EAA+E;AAC/E,6EAA6E;AAC7E,wEAAwE;AACxE,EAAE;AACF,iFAAiF;AACjF,gFAAgF;AAChF,eAAe;AAEf,8FAA8F;AAC9F,MAAa,oBAAqB,SAAQ,KAAK;IAC7C,YAAY,OAAe;QACzB,KAAK,CAAC,yBAAyB,OAAO,EAAE,CAAC,CAAC;QAC1C,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;IACrC,CAAC;CACF;AALD,oDAKC;AAED;;;;;;;;;GASG;AACH,SAAgB,cAAc,CAAC,MAAiC;IAC9D,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAC/C,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,oBAAoB,CAAC,yCAAyC,CAAC,CAAC;IAC5E,CAAC;IACD,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,oBAAoB,CAAC,GAAG,SAAS,CAAC,MAAM,2CAA2C,CAAC,CAAC;IACjG,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;I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AG,CAAC,IAAI,CAAC,KAAK,KAAK,SAAS,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;QACtD,GAAG,CAAC,IAAI,CAAC,SAAS,KAAK,SAAS,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC;QAClE,GAAG,CAAC,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC;KAC1D,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { LlmMediaPart, LlmModality } from "./parts";
|
|
2
|
+
import type { LlmRequest } from "./types";
|
|
3
|
+
/**
|
|
4
|
+
* The media types a provider accepts for one modality: a list of exact types
|
|
5
|
+
* (`image/png`), type wildcards (`image/*`), or `"*"` for any.
|
|
6
|
+
*/
|
|
7
|
+
export type MediaTypeSet = readonly string[];
|
|
8
|
+
/** Text and tool calls are always supported; media is opt-in per modality. */
|
|
9
|
+
export interface LlmCapabilities {
|
|
10
|
+
image?: MediaTypeSet;
|
|
11
|
+
audio?: MediaTypeSet;
|
|
12
|
+
file?: MediaTypeSet;
|
|
13
|
+
/** ADR 0133 - the provider can return model reasoning. Drives the boot warning when no reasoning store is configured. */
|
|
14
|
+
reasoning?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/** Thrown, before any network call, when a request carries a modality the provider did not declare. */
|
|
17
|
+
export declare class UnsupportedModalityError extends Error {
|
|
18
|
+
readonly modality: LlmModality;
|
|
19
|
+
readonly mediaType: string;
|
|
20
|
+
readonly provider: string | undefined;
|
|
21
|
+
constructor(modality: LlmModality, mediaType: string, provider?: string);
|
|
22
|
+
}
|
|
23
|
+
export declare function mediaTypeAccepted(set: MediaTypeSet | undefined, mediaType: string): boolean;
|
|
24
|
+
/** Every media part in a request, in order (including those inside `tool_result`s). */
|
|
25
|
+
export declare function requestMediaParts(request: Pick<LlmRequest, "messages">): Generator<LlmMediaPart>;
|
|
26
|
+
/**
|
|
27
|
+
* Refuse a request that uses a modality / media type the provider has not declared.
|
|
28
|
+
* Pure and cheap (one walk); providers call it at the top of `complete` / `stream` and
|
|
29
|
+
* `createLlmEffect` calls it before resolving any content, so the refusal precedes
|
|
30
|
+
* every byte of I/O.
|
|
31
|
+
*/
|
|
32
|
+
export declare function assertRequestSupported(request: Pick<LlmRequest, "messages">, capabilities: LlmCapabilities | undefined, provider?: string): void;
|
|
33
|
+
/**
|
|
34
|
+
* The modalities a shipped provider declares for `model`: an ALLOWLIST. `base` only when the id
|
|
35
|
+
* matches a family known to take media (`allow`); every other id — unknown, older, a local alias —
|
|
36
|
+
* declares nothing, so a model that cannot take an image is refused locally instead of 400'd by the
|
|
37
|
+
* API, and a new family needs one line here before it is trusted with media. `config.capabilities`
|
|
38
|
+
* always wins (`capabilities: {}` = text-only). A provider on a non-default `baseUrl` (an
|
|
39
|
+
* OpenAI-compatible server) declares nothing either, since the model id says nothing about what is
|
|
40
|
+
* behind it; pass `capabilities` to turn media on.
|
|
41
|
+
*/
|
|
42
|
+
export declare function capabilitiesForModel(model: string, base: LlmCapabilities, allow: readonly RegExp[]): LlmCapabilities;
|
|
43
|
+
//# sourceMappingURL=capabilities.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"capabilities.d.ts","sourceRoot":"","sources":["../src/capabilities.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAkB,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACzE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAI1C;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,SAAS,MAAM,EAAE,CAAC;AAE7C,8EAA8E;AAC9E,MAAM,WAAW,eAAe;IAC9B,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB,IAAI,CAAC,EAAE,YAAY,CAAC;IACpB,yHAAyH;IACzH,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