@qilin-agent/llm 0.0.0-stage → 3.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.i18n.yaml +64 -0
- package/README.md +177 -2
- package/README.zh.md +178 -0
- package/lib/index.js +2388 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +626 -0
- package/lib/typert.remote-client.d.ts +26 -0
- package/lib/typert.remote-client.js +109 -0
- package/lib/types/adapter-failure.d.ts +14 -0
- package/lib/types/adapter-failure.js +108 -0
- package/lib/types/api-key.d.ts +28 -0
- package/lib/types/api-key.js +34 -0
- package/lib/types/assembler.d.ts +75 -0
- package/lib/types/assembler.js +191 -0
- package/lib/types/assistant-stream.d.ts +166 -0
- package/lib/types/assistant-stream.js +458 -0
- package/lib/types/attribution.d.ts +47 -0
- package/lib/types/attribution.js +46 -0
- package/lib/types/brand.d.ts +56 -0
- package/lib/types/brand.js +53 -0
- package/lib/types/call-config.d.ts +53 -0
- package/lib/types/call-config.js +46 -0
- package/lib/types/content.d.ts +149 -0
- package/lib/types/content.js +355 -0
- package/lib/types/error.d.ts +81 -0
- package/lib/types/error.js +153 -0
- package/lib/types/index.d.ts +416 -0
- package/lib/types/index.js +948 -0
- package/lib/types/message.d.ts +246 -0
- package/lib/types/message.js +101 -0
- package/lib/types/retry-policy.d.ts +66 -0
- package/lib/types/retry-policy.js +127 -0
- package/lib/types/types.d.ts +532 -0
- package/lib/types/types.js +7 -0
- package/package.json +74 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kkutysllb
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.i18n.yaml
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
|
|
2
|
+
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
|
3
|
+
# After editing either side, bring the other along and re-record with:
|
|
4
|
+
# pnpm run verify-translation-pairing --write packages/llm/llm/README.md
|
|
5
|
+
/:
|
|
6
|
+
en: 860509fb08c860f4
|
|
7
|
+
zh: b2c4448e8afc1f12
|
|
8
|
+
/qilin-llm:
|
|
9
|
+
en: 00910150bf3285c4
|
|
10
|
+
zh: 37d4d419b2454984
|
|
11
|
+
/qilin-llm/summary:
|
|
12
|
+
en: 001b5d6dbf487912
|
|
13
|
+
zh: d93167367af0bda9
|
|
14
|
+
/qilin-llm/table-of-contents:
|
|
15
|
+
en: d152484eb41ac6b4
|
|
16
|
+
zh: 09388d293f9be9cb
|
|
17
|
+
/qilin-llm/use-this-package:
|
|
18
|
+
en: 33738e61ce410ac0
|
|
19
|
+
zh: 363760460f4d4bed
|
|
20
|
+
/qilin-llm/use-this-package/when-to-choose-it:
|
|
21
|
+
en: 0403e67f55898820
|
|
22
|
+
zh: 1eacd064ea9740a1
|
|
23
|
+
/qilin-llm/use-this-package/minimal-composition:
|
|
24
|
+
en: 7550d716b90fcb09
|
|
25
|
+
zh: 77891a44ee623c7a
|
|
26
|
+
/qilin-llm/use-this-package/what-you-can-do:
|
|
27
|
+
en: b45d7a414141734e
|
|
28
|
+
zh: a641c8ea3827cee6
|
|
29
|
+
/qilin-llm/use-this-package/failures-and-recovery:
|
|
30
|
+
en: 4db9ebfa25dbadfd
|
|
31
|
+
zh: b2aebbd3215d50fc
|
|
32
|
+
/qilin-llm/understand-the-implementation:
|
|
33
|
+
en: 9630d7e26193a512
|
|
34
|
+
zh: 94222c2a487c4b8c
|
|
35
|
+
/qilin-llm/understand-the-implementation/design-philosophy:
|
|
36
|
+
en: 12d0444c18a397c7
|
|
37
|
+
zh: 9d4a5468b4bb7fcd
|
|
38
|
+
/qilin-llm/understand-the-implementation/source-map:
|
|
39
|
+
en: ae1618577f4e8364
|
|
40
|
+
zh: a6e8ab1563c08dfb
|
|
41
|
+
/qilin-llm/understand-the-implementation/main-flow:
|
|
42
|
+
en: b6a378ff4b7caf20
|
|
43
|
+
zh: 1453cd5e7f774575
|
|
44
|
+
/qilin-llm/understand-the-implementation/invariants:
|
|
45
|
+
en: 0163a050239248e5
|
|
46
|
+
zh: 885c95bedcbe2ff4
|
|
47
|
+
/qilin-llm/further-exploration:
|
|
48
|
+
en: e3f1f9cc4c5e35f2
|
|
49
|
+
zh: 89e86aa41cd1fe66
|
|
50
|
+
/qilin-llm/model-experience:
|
|
51
|
+
en: fa5677003ad6bc0a
|
|
52
|
+
zh: ba33cfc860d9c37c
|
|
53
|
+
/qilin-llm/model-experience/kv-cache-effect:
|
|
54
|
+
en: a81634136baef72f
|
|
55
|
+
zh: b92dda883986b0e1
|
|
56
|
+
/qilin-llm/known-limitations-and-deferred-work:
|
|
57
|
+
en: 8605bc10f1ad362f
|
|
58
|
+
zh: 3ca7e933071a513c
|
|
59
|
+
/qilin-llm/known-limitations-and-deferred-work/dev-note:
|
|
60
|
+
en: ecbc333b88e14d88
|
|
61
|
+
zh: 77c725d92efd8646
|
|
62
|
+
/qilin-llm/known-limitations-and-deferred-work/dev-note/open-items:
|
|
63
|
+
en: 3b64f4204c964ec8
|
|
64
|
+
zh: 27c2029a2f18a8b2
|
package/README.md
CHANGED
|
@@ -1,3 +1,178 @@
|
|
|
1
|
-
|
|
1
|
+
---
|
|
2
|
+
description: "The provider-neutral model-call service for users and maintainers streaming requests, registering provider adapters, or resolving model metadata."
|
|
3
|
+
kind: "package-reference"
|
|
4
|
+
---
|
|
2
5
|
|
|
3
|
-
|
|
6
|
+
# @qilin-agent/llm
|
|
7
|
+
|
|
8
|
+
English | [中文](README.zh.md)
|
|
9
|
+
|
|
10
|
+
## Summary
|
|
11
|
+
|
|
12
|
+
Use `@qilin-agent/llm` to stream model calls through configured provider adapters, discover models, and resolve model capabilities and call defaults. Callers must keep all model-visible input reconstructable from the session log. Loop-built requests arrive deep-frozen, so extensions and adapters cannot rewrite them. Each stream is one provider attempt: provider-specific translation stays with its adapter, while the optional `@qilin-agent/llm-retry` package re-runs failed requests. Streams always end with a terminal result, so callers can handle success, failure, and cancellation consistently.
|
|
13
|
+
|
|
14
|
+
## Table of Contents
|
|
15
|
+
|
|
16
|
+
- [Use this package](#use-this-package)
|
|
17
|
+
- [Understand the implementation](#understand-the-implementation)
|
|
18
|
+
- [Further Exploration](#further-exploration)
|
|
19
|
+
- [Model Experience](#model-experience)
|
|
20
|
+
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
|
|
21
|
+
- [Dev Note](#dev-note)
|
|
22
|
+
|
|
23
|
+
-----
|
|
24
|
+
|
|
25
|
+
<a id="use-this-package"></a>
|
|
26
|
+
## Use this package
|
|
27
|
+
|
|
28
|
+
`listModels` describes models offered by catalog-driven interfaces. Core resolution and streaming can still accept unlisted ids. The GUI requires catalog membership for selection and submission; adapters intended for GUI use must implement `listModels` and advertise their available models. The base implementation returns an empty list and therefore offers no GUI models.
|
|
29
|
+
|
|
30
|
+
Any composition that calls a model provider — an agent loop, a session-title generator, a compaction summarizer — streams its requests through this service. Mount it together with at least one provider adapter; the service itself has no configuration and no provider wire code.
|
|
31
|
+
|
|
32
|
+
### When to choose it
|
|
33
|
+
|
|
34
|
+
Choose this package whenever a plugin or composition needs to call a model: it is the only supported path into provider adapters, and it keeps one vocabulary across the loop, the session log, and every consumer. Do not reach for it when you need provider-specific wire behavior (that belongs in an adapter such as `qilin-llm-deepseek` or `qilin-llm-pi-ai`) or retry execution (that belongs in `qilin-llm-retry`).
|
|
35
|
+
|
|
36
|
+
### Minimal composition
|
|
37
|
+
|
|
38
|
+
Mount the service and at least one adapter, then select the provider by name in every request:
|
|
39
|
+
|
|
40
|
+
```yaml
|
|
41
|
+
- name: '@qilin-agent/llm'
|
|
42
|
+
- name: '@qilin-agent/llm-deepseek-api-key'
|
|
43
|
+
config:
|
|
44
|
+
apiKeyEnv: DEEPSEEK_API_KEY
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
A stream returns token-level chunks and always ends with one terminal `finish` chunk. `BlockAssembler` turns the chunks into content blocks and messages; `AssistantStreamAccumulator` preserves their exact timestamps and token boundaries in a compact representation that the loop embeds in one durable attempt settlement:
|
|
48
|
+
|
|
49
|
+
```text
|
|
50
|
+
for await (const chunk of ctx.llm.stream({
|
|
51
|
+
provider: 'deepseek-official',
|
|
52
|
+
model: 'deepseek-v4-flash',
|
|
53
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: 'Hello' }] }],
|
|
54
|
+
})) {
|
|
55
|
+
// chunks: block-start, text-delta, ..., usage, finish
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
After a successful mount, `ctx.llm.listProviders()` reports the registered routes in registration order.
|
|
60
|
+
|
|
61
|
+
`GenerateOptions.messages` accepts durable `Message` values and request-only `RequestUserInput` values. Request-only inputs carry user-role content with no `id` or `source`; Session writes and Agent delivery still require durable messages. Callers keep auxiliary inputs unchanged until the stream settles. A caller that records its exact request, such as session-title generation, must use durable messages.
|
|
62
|
+
|
|
63
|
+
### What you can do
|
|
64
|
+
|
|
65
|
+
- **Stream one model call** — `ctx.llm.stream(options)` yields raw chunks (token-level deltas) for any registered provider and model; consumers assemble them with `BlockAssembler`.
|
|
66
|
+
- **Register provider adapters** — an adapter owns one or more provider routes, and its registration captures that route's retry policy; registering the same route twice fails with `DUPLICATE_ADAPTER`.
|
|
67
|
+
- **Expose and activate providers through configuration** — adapters declare configurable-provider routes plus a settings namespace, so configuration surfaces can activate dormant providers and edit connection facts without a restart. `LlmConfigurableProvider.error` reports a configuration diagnostic for repair; unaffected models can remain serviceable.
|
|
68
|
+
- **Discover and resolve models** — List the models an adapter advertises, interrogate an endpoint for the models it serves (candidates carry optional `inputModalities`; absence means unknown), and resolve one exact model's context window, output default, reasoning efforts, input modalities, and system prompt update mode: `LlmResolvedModelInfo.systemPromptUpdate` is `'in-history'` when the model reads the latest `system` message at any position as the effective system prompt and absent when only a leading system message is read; `normalizeModelInfo` rejects any other value with `INVALID_MODEL_INFO`.
|
|
69
|
+
- **Validate call config** — an explicit or configured reasoning effort is checked against the exact model before any provider I/O, and an adapter-configured output cap is materialized when the request omits one.
|
|
70
|
+
- **Read an embedded Assistant stream without expanding it** — `assistantStreamFirstTokenTime` (first token), `assistantStreamHasVisibleContent` (any visible content), and `assistantStreamHasVisibleText` (any visible text) answer their questions from the compact records with early exit; `lastAssistantStreamChunk` scans backward to the last raw chunk of one type, `assistantStreamChunks` and `joinAssistantStreamText` scan the whole stream, and `assembleAssistantStream` feeds a `BlockAssembler` one joined delta per run with the same blocks, usage, and replay state as the per-member expansion. `runFirstTokenTime` and `runFirstVisibleTime` do the early-exit scan for one packed run, and `isTokenDelta`, `isVisibleChunk`, and `chunkHasVisibleText` define the token and visibility rules for a single chunk. `expandAssistantStream` remains the validating path for records read at a durable boundary; it is not memoized, because a retained expansion costs roughly ten times the compact stream for as long as the event lives.
|
|
71
|
+
|
|
72
|
+
### Failures and recovery
|
|
73
|
+
|
|
74
|
+
Every stream ends in exactly one terminal `finish` chunk: `{ kind: 'error', failure }` on failure, `{ kind: 'aborted', failure }` on cancellation. Failures carry stable codes such as `NO_ADAPTER`, `MISSING_CREDENTIAL`, `AUTH`, `RATE_LIMIT`, and `CONTEXT_WINDOW_EXCEEDED`; consumers route on the code, never on message text. `QUOTA` is provider-neutral exhaustion. QiLin's account surface is the own ui-account package (`/api/auth` gate); the upstream `deepseek-account` stack is not adopted, so no account-specific failure code exists. A request naming an unregistered provider fails with `NO_ADAPTER`, and a malformed credential fails with `INVALID_CREDENTIAL` instead of surfacing as an opaque fetch error. This service never re-runs a request: retrying is the job of `qilin-llm-retry` at the agent's failed-step extension point.
|
|
75
|
+
|
|
76
|
+
-----
|
|
77
|
+
|
|
78
|
+
<a id="understand-the-implementation"></a>
|
|
79
|
+
## Understand the implementation
|
|
80
|
+
|
|
81
|
+
<details>
|
|
82
|
+
<summary>Implementation internals — click to expand</summary>
|
|
83
|
+
|
|
84
|
+
This section explains the design behind the service; the observable behavior is fully covered in [Use this package](#use-this-package).
|
|
85
|
+
|
|
86
|
+
### Design philosophy
|
|
87
|
+
|
|
88
|
+
The service is built on one separation: **the logical contract is provider-neutral, adapters own the wire.** It defines the canonical message, content-block, and stream-chunk vocabulary once, and every provider adapter translates only its own wire format into that vocabulary. The registry is the topology owner — adapter routes, configurable-provider entries, and discovery offers all register here and are disposed with their fiber — while an agent-loop request stays a pure function of the session log: loop-built requests arrive deep-frozen, so listeners and adapters read them and never rewrite them.
|
|
89
|
+
|
|
90
|
+
### Source map
|
|
91
|
+
|
|
92
|
+
| File | Role |
|
|
93
|
+
|---|---|
|
|
94
|
+
| [`src/index.ts`](src/index.ts) | The `LlmRuntime` service: adapter registry, configurable-provider directory, model discovery, call preparation, and the streaming boundary |
|
|
95
|
+
| [`src/types.ts`](src/types.ts) | The `StreamChunk` protocol, content-block map, finish reasons, and shared vocabulary |
|
|
96
|
+
| [`src/message.ts`](src/message.ts) | Immutable message constructors shared by delivery, history, and requests |
|
|
97
|
+
| [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`: incremental chunk-to-block assembly |
|
|
98
|
+
| [`src/assistant-stream.ts`](src/assistant-stream.ts) | Compact timed Assistant stream accumulation, strict validation, exact expansion, and record-level readers |
|
|
99
|
+
| [`src/call-config.ts`](src/call-config.ts) | Call-config validation, adapter-default materialization, and request freezing |
|
|
100
|
+
| [`src/retry-policy.ts`](src/retry-policy.ts) | Provider-owned retry policy resolution (normal and always modes) |
|
|
101
|
+
| [`src/error.ts`](src/error.ts) | `HarnessError`/`LlmError` taxonomy and provider-neutral failure codes |
|
|
102
|
+
| [`src/content.ts`](src/content.ts) | Shared file and image helpers: content walks, file projection, image offload accounting, and offloaded-image projection |
|
|
103
|
+
| [`src/api-key.ts`](src/api-key.ts) | Credential format check shared by every adapter |
|
|
104
|
+
| [`src/adapter-failure.ts`](src/adapter-failure.ts) | Failure normalization into terminal finish chunks |
|
|
105
|
+
|
|
106
|
+
### Main flow
|
|
107
|
+
|
|
108
|
+
A request is validated against its exact model's capability — context window, output default, reasoning efforts, input modalities, and `systemPromptUpdate` mode — and any adapter-configured defaults are materialized. The runtime preserves freezing for already-frozen input; hand-built callers own input immutability. `prepareCall()` binds those facts, detached context, and retry policy to the exact adapter generation that performs terminal dispatch, so HMR or dynamic settings cannot combine one generation's image capability with another generation's endpoint. An image-capable adapter projects durable references into route-specific request versions; `resolveImageAttachmentAccess()` separately maps an attachment provider's optional host object into the current tool execution world without changing the request image or its `variantId`. A text-only route receives deterministic per-image placeholders, including tool-role result images, without rewriting append-only session history. Durable `FileBlock` references never reach any adapter: request assembly replaces each one, including tool-role result occurrences, with deterministic handle text naming the file and its saved read-only path, resolved through the mounted attachment and filesystem providers. `ctx.llm.fileRequestText(ref)` exposes that exact synchronous projection to request measurement. An image occurrence derived with `offloaded: true` reaches every route as placeholder text through `projectOffloadedImages()`. An image-capable route whose retained occurrences exceed its `LlmImageRequestBudget` at their exact bytes fails with `IMAGE_OFFLOAD_REQUIRED` naming the additional oldest occurrences (`requiredImageOffload()`), never with an unlogged projection; `qilin-compaction-image-offload` logs the selected occurrences in one `image/offload` event and retries. Adapters that charge visual tokens declare per-route `imageRequestPricing`, which `ctx.llm.imageRequestPricing(provider, model)` resolves synchronously for the token meter. Dispatch goes through the `llm/stream` waterfall, then chunks return as token-level deltas and every adapter outcome reaches the consumer as one terminal `finish` chunk.
|
|
109
|
+
|
|
110
|
+
File detection reads current content, including tool-role result content, on every request without caching message identities or freeze state. The [file-scan decision](../../../.agents/notes/implemented/simplification/2026-09-07-file-content-scan.md) records the measured traversal cost.
|
|
111
|
+
|
|
112
|
+
### Invariants
|
|
113
|
+
|
|
114
|
+
- **Model-visible ⟺ logged** — callers must keep every provider request's model-visible input reconstructable from the session log; loop-built requests arrive deep-frozen and cannot be rewritten.
|
|
115
|
+
- **Replay state travels only within one adapter** — assistant replay state rides along only when the same adapter instance owns the historical and target routes; otherwise it is dropped before dispatch.
|
|
116
|
+
- **Prepared calls are one-shot** — a prepared call can be dispatched exactly once, and its call-config fields must match the prepared config.
|
|
117
|
+
- **Image projection follows the captured route** — durable `ImageBlock` references become route-specific request versions only for image-capable models; text-only models receive stable placeholders.
|
|
118
|
+
- **File projection is unconditional** — no provider receives file bytes; every route gets one deterministic handle line per `FileBlock`, and the model reads the saved copy with its file tools on demand.
|
|
119
|
+
- **Protocol ordering** — `usage` precedes `finish`, tool arguments stay raw JSON strings, and nothing follows the terminal `finish`.
|
|
120
|
+
- **Registry mutations are atomic** — route and directory registration validates the whole candidate set before anything moves, so a refused change leaves the previous state serving.
|
|
121
|
+
|
|
122
|
+
</details>
|
|
123
|
+
|
|
124
|
+
-----
|
|
125
|
+
|
|
126
|
+
<a id="further-exploration"></a>
|
|
127
|
+
## Further Exploration
|
|
128
|
+
|
|
129
|
+
Read these pages when the package-level contract is not enough. They move from the shared types to the concrete adapters, the retry executor, and the measurement service.
|
|
130
|
+
|
|
131
|
+
- [LLM streaming subsystem](../../../docs/subsystems/llm-streaming.md) — the message and block types, compact Assistant stream records, the `StreamChunk` protocol, and the adapter contract.
|
|
132
|
+
- [llm-deepseek adapter](../llm-deepseek/README.md) — the direct DeepSeek Messages implementation.
|
|
133
|
+
- [llm-pi-ai adapter](../llm-pi-ai/README.md) — the pi-ai-backed multi-provider implementation.
|
|
134
|
+
- [llm-retry](../llm-retry/README.md) — the retry executor that re-runs failed model requests.
|
|
135
|
+
- [Token meter](../token-meter/README.md) — replay-aware request and context pressure measurement.
|
|
136
|
+
- [Twin LLM adapters](../../../.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.md) — why the DeepSeek route ships two structurally different adapters.
|
|
137
|
+
- [Terminal LLM stream failures](../../../.agents/notes/implemented/architecture/2026-07-29-terminal-llm-stream-failures.md) — the service boundary between model-request outcomes and plugin failures.
|
|
138
|
+
|
|
139
|
+
-----
|
|
140
|
+
|
|
141
|
+
<a id="model-experience"></a>
|
|
142
|
+
## Model Experience
|
|
143
|
+
|
|
144
|
+
None, as the LLM service adds no content; adapters choose when to add the shared image descriptors and per-image placeholders exported by this package.
|
|
145
|
+
|
|
146
|
+
#### KV Cache effect
|
|
147
|
+
|
|
148
|
+
Reasoning-effort materialization preserves the assembled request prefix. Image identity and request-preview text are deterministic, while an optional execution-world path is resolved for each request; a changed path or an offload decision can prevent reuse from that image.
|
|
149
|
+
|
|
150
|
+
## Known Limitations and Deferred Work
|
|
151
|
+
|
|
152
|
+
<a id="known-limitations-and-deferred-work"></a>
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
These limits define where this service stops and other packages or future work begin. They are current package constraints, not a task backlog.
|
|
156
|
+
|
|
157
|
+
- **No retry execution, caching, or rate limiting ships in this service** — provider registration stores the retry policy, but a stream remains a single provider attempt; `@qilin-agent/llm-retry` executes the policy at durable agent-step boundaries.
|
|
158
|
+
- **`GenerateOptions` sampling is `temperature`/`maxTokens`/`stop` only** — no `tool_choice`, `top_p`, or penalty fields; the vocabulary grows when a producer lands ([dropped inert knobs](../../../.agents/notes/archived/simplification/2026-07-04-drop-inert-request-knobs.md)).
|
|
159
|
+
- **Variants normally require a producer** — `prefill`, per-tool `strict`, block `cache` hints, and the `agent` message-source variant have no producer ([Agent Note](../../../.agents/notes/archived/simplification/2026-07-04-prune-producerless-vocabulary-variants.md)).
|
|
160
|
+
- **`BlockAssembler` handles core block kinds only** — a plugin-added block type whose stream is never closed by `block-end` makes `blocks()` throw.
|
|
161
|
+
- **`GenerateOptions.sessionId` is a locally-declared brand** — importing qilin-session's `SessionId` would create a dependency cycle.
|
|
162
|
+
- **Tool updates require session history** — `GenerateOptions.tools` contains active definitions. `toolHistory` supplies the initial declarations and historically resolved additions from `Session.toolHistory()`. At adapter dispatch, `projectToolUpdates` constructs deferred declarations and retains removed definitions for `in-history`; `addition-only` omits removed definitions and removal messages. Unsupported routes receive active tools without developer messages or `deferLoading`. Missing history or a request prefix omitting recorded updates falls back to current declarations without developer messages. Explicitly deferred baseline tools remain deferred until their first retained addition block; declaring a deferred tool does not activate it.
|
|
163
|
+
|
|
164
|
+
<a id="dev-note"></a>
|
|
165
|
+
### Dev Note
|
|
166
|
+
|
|
167
|
+
<details>
|
|
168
|
+
<summary>Working context for maintainers — click to expand</summary>
|
|
169
|
+
|
|
170
|
+
This Dev Note is non-authoritative working context: open questions and undecided directions. Shipped behavior and accepted rationale live in the sections above, the package code, and the linked Agent Notes.
|
|
171
|
+
|
|
172
|
+
#### Open items
|
|
173
|
+
|
|
174
|
+
- `GenerateOptions.sessionId` is a locally-declared brand because importing qilin-session's `SessionId` would create a dependency cycle; a future ids-owning package could dissolve the workaround.
|
|
175
|
+
- Reasoning-effort identifiers are adapter-owned opaque strings resolved only against each adapter's advertised set; a shared cross-adapter effort vocabulary is not decided.
|
|
176
|
+
- The `llm/adapters-updated` event is payload-free by design; consumers re-read the registries instead of receiving the new topology in the event.
|
|
177
|
+
|
|
178
|
+
</details>
|
package/README.zh.md
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: "面向用户与维护者的提供方无关模型调用服务说明:流式发起请求、注册提供方适配器或解析模型元数据。"
|
|
3
|
+
kind: "package-reference"
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# @qilin-agent/llm
|
|
7
|
+
|
|
8
|
+
[English](README.md) | 中文
|
|
9
|
+
|
|
10
|
+
## 概述
|
|
11
|
+
|
|
12
|
+
使用 `@qilin-agent/llm` 可通过已配置的提供方适配器流式调用模型、发现模型,并解析模型能力与调用默认值。调用方必须确保所有模型可见输入都可以从会话日志重建。Loop 构建的请求以深度冻结状态到达,因此扩展与适配器不能改写。每个流只尝试调用提供方一次:提供方特定的转换由对应适配器完成,可选包 `@qilin-agent/llm-retry` 负责重跑失败的请求。流始终以终止结果结束,因此调用方可以一致地处理成功、失败与取消。
|
|
13
|
+
|
|
14
|
+
## 目录
|
|
15
|
+
|
|
16
|
+
- [使用本包](#use-this-package)
|
|
17
|
+
- [理解实现](#understand-the-implementation)
|
|
18
|
+
- [进一步探索](#further-exploration)
|
|
19
|
+
- [模型体验](#model-experience)
|
|
20
|
+
- [已知限制与延期工作](#known-limitations-and-deferred-work)
|
|
21
|
+
- [开发备注](#dev-note)
|
|
22
|
+
|
|
23
|
+
-----
|
|
24
|
+
|
|
25
|
+
<a id="use-this-package"></a>
|
|
26
|
+
## 使用本包
|
|
27
|
+
|
|
28
|
+
`listModels` 描述目录驱动界面提供的模型。核心解析与流式调用仍可接受未列出的 ID。GUI 的模型选择与提交要求模型出现在目录中;供 GUI 使用的适配器必须实现 `listModels`,公布其可用模型。基类实现返回空列表,因此不向 GUI 提供模型。
|
|
29
|
+
|
|
30
|
+
任何调用模型提供方的组合——agent loop(智能体循环)、会话标题生成器、压缩(compaction)摘要器——都会通过本服务流式发起请求。与至少一个提供方适配器一起挂载它;服务本身没有任何配置,也不包含提供方协议代码。
|
|
31
|
+
|
|
32
|
+
### 何时选择
|
|
33
|
+
|
|
34
|
+
当插件或组合需要调用模型时选择本包:它是进入提供方适配器的唯一受支持路径,并在 loop、会话日志与每个消费方之间保持同一套词汇。当需要提供方特定的协议行为(那属于 `qilin-llm-deepseek` 或 `qilin-llm-pi-ai` 之类的适配器)或重试执行(那属于 `qilin-llm-retry`)时,不要选择它。
|
|
35
|
+
|
|
36
|
+
### 最小组合
|
|
37
|
+
|
|
38
|
+
挂载服务与至少一个适配器,然后在每个请求中按名称选择提供方:
|
|
39
|
+
|
|
40
|
+
```yaml
|
|
41
|
+
- name: '@qilin-agent/llm'
|
|
42
|
+
- name: '@qilin-agent/llm-deepseek-api-key'
|
|
43
|
+
config:
|
|
44
|
+
apiKeyEnv: DEEPSEEK_API_KEY
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
流会返回 token 级分片,并始终以一个终止 `finish` 分片结束。`BlockAssembler` 把分片组装为内容块与消息;`AssistantStreamAccumulator` 在紧凑表示中保留其精确时间戳与 token 边界,loop 再把它嵌入一个持久 attempt settlement:
|
|
48
|
+
|
|
49
|
+
```text
|
|
50
|
+
for await (const chunk of ctx.llm.stream({
|
|
51
|
+
provider: 'deepseek-official',
|
|
52
|
+
model: 'deepseek-v4-flash',
|
|
53
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: 'Hello' }] }],
|
|
54
|
+
})) {
|
|
55
|
+
// chunks: block-start, text-delta, ..., usage, finish
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
挂载成功后,`ctx.llm.listProviders()` 会按注册顺序报告已注册路由。
|
|
60
|
+
|
|
61
|
+
`GenerateOptions.messages` 接受持久 `Message` 值和仅供请求使用的 `RequestUserInput` 值。仅供请求使用的输入包含 user-role 内容,不含 `id` 或 `source`;Session 写入和 Agent 投递仍然要求持久消息。调用方必须在流结束前保持辅助输入不变。会记录完整请求的调用方(例如会话标题生成)必须使用持久消息。
|
|
62
|
+
|
|
63
|
+
### 你可以做什么
|
|
64
|
+
|
|
65
|
+
- **流式发起一次模型调用**——`ctx.llm.stream(options)` 为任何已注册提供方与模型产出原始分片(token 级增量);消费方用 `BlockAssembler` 组装。
|
|
66
|
+
- **注册提供方适配器**——一个适配器拥有一个或多个提供方路由,其注册会捕获该路由的重试策略;重复注册同一路由会以 `DUPLICATE_ADAPTER` 失败。
|
|
67
|
+
- **通过配置暴露并激活提供方**——适配器声明可配置提供方路由与 settings namespace,配置界面因此可以激活休眠提供方并编辑连接信息,无需重启。`LlmConfigurableProvider.error` 报告供修复的配置诊断;未受影响的模型仍可提供服务。
|
|
68
|
+
- **发现与解析模型**——列出适配器公布的模型、询问端点它提供哪些模型(候选携带可选的 `inputModalities`;缺省表示未知),并解析某个精确模型的上下文窗口、输出默认值、推理(reasoning)强度、输入模态与系统提示词更新模式:当模型把任意位置最新的 `system` 消息读作有效系统提示词时,`LlmResolvedModelInfo.systemPromptUpdate` 为 `'in-history'`;只读取开头 system 消息时该字段缺失;`normalizeModelInfo` 以 `INVALID_MODEL_INFO` 拒绝任何其他值。
|
|
69
|
+
- **校验调用配置**——显式或配置的推理强度会在任何提供方 I/O 之前对照精确模型校验;请求省略输出上限时,会填入适配器配置的输出上限。
|
|
70
|
+
- **不展开即读取内嵌 Assistant 流**——`assistantStreamFirstTokenTime`(首 token)、`assistantStreamHasVisibleContent`(任一可见内容)与 `assistantStreamHasVisibleText`(任一可见文本)通过可提前退出的扫描直接从紧凑记录得出结果;`lastAssistantStreamChunk` 反向扫描到某一类型的最后一个原始 chunk,`assistantStreamChunks` 与 `joinAssistantStreamText` 扫描整个流,`assembleAssistantStream` 向 `BlockAssembler` 每个 run 喂一段拼接 delta,blocks/usage/replayState 与逐成员展开相同。`runFirstTokenTime` 与 `runFirstVisibleTime` 对单个打包 run 做提前退出扫描,`isTokenDelta`、`isVisibleChunk` 与 `chunkHasVisibleText` 定义单个 chunk 的 token 与可见性规则。`expandAssistantStream` 仍是持久边界读取记录的校验路径;它不被记忆化,因为保留的展开在事件生命周期内约花费紧凑流的十倍内存。
|
|
71
|
+
|
|
72
|
+
### 失败与恢复
|
|
73
|
+
|
|
74
|
+
每个流都恰好以一个终止 `finish` 分片结束:失败为 `{ kind: 'error', failure }`,取消为 `{ kind: 'aborted', failure }`。失败携带稳定 code,如 `NO_ADAPTER`、`MISSING_CREDENTIAL`、`AUTH`、`RATE_LIMIT` 与 `CONTEXT_WINDOW_EXCEEDED`;消费方依据 code 路由,绝不解析消息文本。`QUOTA` 表示提供方中立的额度耗尽。QiLin 账号面为自有 ui-account 包(`/api/auth` gate),上游 `deepseek-account` 栈不采,因此不存在账号专属失败 code。点名未注册提供方的请求会以 `NO_ADAPTER` 失败,格式错误的凭据会以 `INVALID_CREDENTIAL` 失败,而不是表现为不透明的 fetch 错误。本服务从不自行重跑请求:重试是 `qilin-llm-retry` 在 agent 失败步骤扩展点上的职责。
|
|
75
|
+
|
|
76
|
+
-----
|
|
77
|
+
|
|
78
|
+
<a id="understand-the-implementation"></a>
|
|
79
|
+
## 理解实现
|
|
80
|
+
|
|
81
|
+
<details>
|
|
82
|
+
<summary>实现细节——点击展开</summary>
|
|
83
|
+
|
|
84
|
+
本节解释服务背后的设计;可观察行为已在[使用本包](#use-this-package)中完整说明。
|
|
85
|
+
|
|
86
|
+
### 设计理念
|
|
87
|
+
|
|
88
|
+
本服务基于一项职责分离原则:**逻辑约定是提供方无关的,适配器拥有协议。** 它一次性地定义规范消息、内容块与流式分片词汇,每个提供方适配器只把自己的协议格式翻译为该词汇。注册表是拓扑的拥有者——适配器路由、可配置提供方条目与发现 offer 都在这里注册,并随其 fiber 一起 dispose(资源释放)——而 agent loop 的请求始终是会话日志的纯函数:loop 构建的请求以深度冻结状态到达,因此监听器与适配器只能读取,绝不能改写。
|
|
89
|
+
|
|
90
|
+
### 源码地图
|
|
91
|
+
|
|
92
|
+
| 文件 | 职责 |
|
|
93
|
+
|---|---|
|
|
94
|
+
| [`src/index.ts`](src/index.ts) | `LlmRuntime` 服务:适配器注册表、可配置提供方目录、模型发现、调用准备与流式边界 |
|
|
95
|
+
| [`src/types.ts`](src/types.ts) | `StreamChunk` 协议、内容块映射、结束原因与共享词汇 |
|
|
96
|
+
| [`src/message.ts`](src/message.ts) | 投递、历史与请求共享的不可变消息构造函数 |
|
|
97
|
+
| [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`:分片到块的增量组装 |
|
|
98
|
+
| [`src/assistant-stream.ts`](src/assistant-stream.ts) | 带时间信息的紧凑 Assistant 流累积、严格校验、精确展开与记录级读取器 |
|
|
99
|
+
| [`src/call-config.ts`](src/call-config.ts) | 调用配置校验、适配器默认值填入与请求冻结 |
|
|
100
|
+
| [`src/retry-policy.ts`](src/retry-policy.ts) | 提供方自有重试策略解析(normal 与 always 模式) |
|
|
101
|
+
| [`src/error.ts`](src/error.ts) | `HarnessError`/`LlmError` 分类体系与提供方无关失败 code |
|
|
102
|
+
| [`src/content.ts`](src/content.ts) | 共享文件与图片辅助函数:内容遍历、文件投影、图片卸载计数与已卸载图片投影 |
|
|
103
|
+
| [`src/api-key.ts`](src/api-key.ts) | 每个适配器共享的凭据格式校验 |
|
|
104
|
+
| [`src/adapter-failure.ts`](src/adapter-failure.ts) | 把失败归一化为终止 finish 分片 |
|
|
105
|
+
|
|
106
|
+
### 主流程
|
|
107
|
+
|
|
108
|
+
请求会对照其精确模型的能力校验,包括上下文窗口、输出默认值、推理强度、输入模态与 `systemPromptUpdate` 模式,并填入任何适配器配置的默认值。运行时保留已冻结输入的冻结状态;手动构建请求的调用方负责保证输入不可变。`prepareCall()` 把这些事实、分离的上下文与重试策略绑定到执行最终分发的精确适配器代次,因此 HMR(热模块替换)或动态设置无法把一个代次的图片能力与另一代次的端点混用。支持图片的适配器把持久引用投影为路由专用请求版本;`resolveImageAttachmentAccess()` 会单独把附件提供方的可选宿主对象映射进当前工具执行世界,而不改变请求图片或其 `variantId`。纯文本路由接收确定性的逐图片占位符,包括 tool-role 结果图片,而不会改写仅追加会话历史。持久 `FileBlock` 引用永远不会到达任何适配器:请求组装把每个引用(包括 tool-role 结果中的出现)替换为确定性句柄文本,指出文件与其只读保存路径,路径经由挂载的附件与文件系统提供方解析。`ctx.llm.fileRequestText(ref)` 向请求计量公开相同的同步投影。派生后带有 `offloaded: true` 的图片出现位置,经 `projectOffloadedImages()` 以占位文本到达每条路由。支持图片的路由在保留的出现位置按精确字节超过其 `LlmImageRequestBudget` 时,以 `IMAGE_OFFLOAD_REQUIRED` 失败并说明还需省略多少最老的出现位置(`requiredImageOffload()`),绝不发送未记录的投影;`qilin-compaction-image-offload` 用一条 `image/offload` 事件记录所选位置并重试。对视觉 token 收费的适配器声明按路由的 `imageRequestPricing`,`ctx.llm.imageRequestPricing(provider, model)` 为 token meter 同步解析它。分发经过 `llm/stream` waterfall(瀑布式事件),随后分片以 token 级增量返回,每个适配器结果都以唯一一个终止 `finish` 分片到达消费方。
|
|
109
|
+
|
|
110
|
+
文件检测在每次请求时读取当前内容,包括 tool-role 结果内容,不缓存消息身份或冻结状态。[文件扫描决策](../../../.agents/notes/implemented/simplification/2026-09-07-file-content-scan.zh.md)记录了实测遍历成本。
|
|
111
|
+
|
|
112
|
+
### 不变式
|
|
113
|
+
|
|
114
|
+
- **模型可见 ⟺ 已记录**——调用方必须确保每个提供方请求中的模型可见输入都可以从会话日志重建;loop 构建的请求以深度冻结状态到达,不可改写。
|
|
115
|
+
- **回放状态只在同一适配器内流动**——仅当同一适配器实例同时拥有历史路由与目标路由时,assistant 回放状态才会随行;否则在分发前被丢弃。
|
|
116
|
+
- **已准备调用是一次性的**——已准备调用只能分发一次,且其调用配置字段必须与准备好的配置一致。
|
|
117
|
+
- **图片投影遵循捕获的路由**——只有支持图片的模型会把持久 `ImageBlock` 引用转换为路由专用请求版本;纯文本模型接收稳定占位符。
|
|
118
|
+
- **文件投影无条件进行**——没有任何提供方会收到文件字节;每条路由对每个 `FileBlock` 都得到一行确定性句柄文本,模型在需要时用文件工具读取保存的副本。
|
|
119
|
+
- **协议顺序**——`usage` 先于 `finish`,工具参数保持原始 JSON 字符串,终止 `finish` 之后不再有任何内容。
|
|
120
|
+
- **注册表变更具有原子性**——路由与目录注册会在任何变动前整体校验候选集合,因此被拒绝的变更会让此前状态继续服务。
|
|
121
|
+
|
|
122
|
+
</details>
|
|
123
|
+
|
|
124
|
+
-----
|
|
125
|
+
|
|
126
|
+
<a id="further-exploration"></a>
|
|
127
|
+
## 进一步探索
|
|
128
|
+
|
|
129
|
+
当包级约定不够用时阅读以下页面。它们从共享类型逐步进入具体适配器、重试执行器与计量服务。
|
|
130
|
+
|
|
131
|
+
- [LLM(大语言模型)流式子系统](../../../docs/subsystems/llm-streaming.zh.md)——消息与块类型、紧凑的 Assistant 流记录、`StreamChunk` 协议与适配器约定。
|
|
132
|
+
- [llm-deepseek 适配器](../llm-deepseek/README.zh.md)——DeepSeek Messages 直连实现。
|
|
133
|
+
- [llm-pi-ai 适配器](../llm-pi-ai/README.zh.md)——基于 pi-ai 的多提供方实现。
|
|
134
|
+
- [llm-retry](../llm-retry/README.zh.md)——重跑失败模型请求的重试执行器。
|
|
135
|
+
- [Token 计量](../token-meter/README.zh.md)——具备回放感知的请求与上下文压力测量。
|
|
136
|
+
- [孪生 LLM 适配器](../../../.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.zh.md)——为什么 DeepSeek 路由交付两个结构不同的适配器。
|
|
137
|
+
- [LLM 流终止失败](../../../.agents/notes/implemented/architecture/2026-07-29-terminal-llm-stream-failures.zh.md)——模型请求结果与插件失败之间的服务边界。
|
|
138
|
+
|
|
139
|
+
-----
|
|
140
|
+
|
|
141
|
+
<a id="model-experience"></a>
|
|
142
|
+
## 模型体验
|
|
143
|
+
|
|
144
|
+
没有直接影响,因为 LLM 服务不添加内容;适配器决定何时添加本包导出的共享图片描述符与逐图片占位符。
|
|
145
|
+
|
|
146
|
+
#### KV Cache 影响
|
|
147
|
+
|
|
148
|
+
推理强度的具体化会保留已组装请求前缀。图片身份与请求预览文本是确定性的,可选执行世界路径则按请求解析;路径变化或一次省略决策可能从该图片起阻止复用。
|
|
149
|
+
|
|
150
|
+
## 已知限制与延期工作
|
|
151
|
+
|
|
152
|
+
<a id="known-limitations-and-deferred-work"></a>
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
这些限制说明本服务在哪里停止、由其他包或未来工作接续。它们是当前包约束,不是任务积压。
|
|
156
|
+
|
|
157
|
+
- **本服务不提供重试执行、缓存或速率限制**——提供方注册会存储重试策略,但一次流仍是一次提供方尝试;`@qilin-agent/llm-retry` 在持久 agent 步骤边界上执行该策略。
|
|
158
|
+
- **`GenerateOptions` 采样只包含 `temperature`/`maxTokens`/`stop`**——没有 `tool_choice`、`top_p` 或 penalty 字段;有产生方落地时词汇才会增长(见[已删除惰性旋钮](../../../.agents/notes/archived/simplification/2026-07-04-drop-inert-request-knobs.md))。
|
|
159
|
+
- **变体通常要求实际产生方**——`prefill`、逐工具 `strict`、内容块 `cache` 提示和 `agent` 消息来源变体都没有产生方(见 [Agent Note](../../../.agents/notes/archived/simplification/2026-07-04-prune-producerless-vocabulary-variants.md))。
|
|
160
|
+
- **`BlockAssembler` 只处理核心块类型**——插件添加块类型的流若从未由 `block-end` 关闭,`blocks()` 会抛出异常。
|
|
161
|
+
- **`GenerateOptions.sessionId` 是本地声明的品牌类型**——导入 qilin-session 的 `SessionId` 会产生依赖循环。
|
|
162
|
+
- **工具更新需要会话历史** — `GenerateOptions.tools` 包含当前有效定义。`toolHistory` 提供 `Session.toolHistory()` 派生的初始声明及已解析历史定义的添加记录。适配器分发时,`projectToolUpdates` 构造延迟声明,并在 `in-history` 模式保留已移除定义;`addition-only` 省略已移除定义和移除消息。不支持更新的路由接收有效工具,不携带 developer 消息或 `deferLoading`。缺少历史或请求前缀遗漏已记录更新时,回退为当前声明且不发送 developer 消息。显式延迟加载的基线工具在其首个保留添加块之前保持延迟;声明延迟工具不会激活它。
|
|
163
|
+
|
|
164
|
+
<a id="dev-note"></a>
|
|
165
|
+
### 开发备注
|
|
166
|
+
|
|
167
|
+
<details>
|
|
168
|
+
<summary>维护者的工作上下文——点击展开</summary>
|
|
169
|
+
|
|
170
|
+
本开发备注是不具权威性的工作上下文:开放问题与尚未决定的探索方向。已交付的行为与既定理由以上文、包代码和相关 Agent Note 为准。
|
|
171
|
+
|
|
172
|
+
#### 开放事项
|
|
173
|
+
|
|
174
|
+
- `GenerateOptions.sessionId` 是本地声明的品牌类型,因为导入 qilin-session 的 `SessionId` 会造成依赖循环;未来拥有 id 的包可以消除该权宜之计。
|
|
175
|
+
- 推理强度标识符是由适配器定义的不透明字符串,只对照各适配器公布集合解析;跨适配器共享强度词汇尚未决定。
|
|
176
|
+
- `llm/adapters-updated` 事件按设计不携带载荷;消费方重新读取注册表,而不是在事件中接收新拓扑。
|
|
177
|
+
|
|
178
|
+
</details>
|