@huaweidevtools/aishell-dsh-llm 0.0.0-stage → 0.0.1-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +65 -2
- package/cordis.patch.yml +7 -0
- package/lib/index.js +423 -0
- package/lib/types/adapter.d.ts +48 -0
- package/lib/types/index.d.ts +29 -0
- package/lib/types/serialize.d.ts +13 -0
- package/lib/types/sse.d.ts +12 -0
- package/lib/types/translate.d.ts +15 -0
- package/lib/types/types.d.ts +128 -0
- package/package.json +47 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined in 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 derived from (or based upon) 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 2024 Huawei Cloud AI Shell
|
|
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
|
|
200
|
+
implied. See the License for the specific language governing
|
|
201
|
+
permissions and limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,66 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @huaweidevtools/aishell-dsh-llm
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
OpenAI-compatible LLM adapter for DSH. Registers the `aishell` provider route on `ctx.llm`, routing model calls through the aishell gateway with direct AK/SK signing.
|
|
4
|
+
|
|
5
|
+
## How it works
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
User selects aishell/<model>
|
|
9
|
+
→ GatewayAdapter.stream(options)
|
|
10
|
+
|
|
11
|
+
Every request is signed directly with AK/SK (SDK-HMAC-SHA256):
|
|
12
|
+
→ credential store reads HW_ACCESS_KEY + HW_SECRET_KEY (+ optional HW_SECURITY_TOKEN)
|
|
13
|
+
→ sign(POST, host, /chat/completions, query, body) → signed headers
|
|
14
|
+
→ POST {baseUrl}/chat/completions (signed headers, OpenAI wire format)
|
|
15
|
+
→ parseSse → translate → StreamChunks
|
|
16
|
+
|
|
17
|
+
Model listing:
|
|
18
|
+
→ GET {baseUrl}/models (AK/SK signed)
|
|
19
|
+
→ returns OpenAI-compatible model list
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
No intermediate API-key exchange or config fetch — every request is signed with the user's AK/SK. The credential store (OS keyring with fingerprint + memory fallback) holds the AK/SK; this adapter only reads them.
|
|
23
|
+
|
|
24
|
+
## What it does NOT touch
|
|
25
|
+
|
|
26
|
+
- `ctx.credentials` — DSH's own credential provider stays `dsh-credentials-local`. User-configured models and `.credentials.yaml` keep working.
|
|
27
|
+
- `llm-deepseek` / other adapters — user's existing providers are unchanged.
|
|
28
|
+
- No tools, commands, or session behavior is modified.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
# Standalone (LLM adapter only — no credentials UI):
|
|
34
|
+
dsh plugin --profile <name> add link:<repo>/packages/aishell-llm
|
|
35
|
+
|
|
36
|
+
# Or via the aishell-base bundle (full stack):
|
|
37
|
+
dsh plugin --profile <name> add @huaweidevtools/aishell-dsh-base
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Config
|
|
41
|
+
|
|
42
|
+
| Field | Type | Default | Description |
|
|
43
|
+
|---|---|---|---|
|
|
44
|
+
| `baseUrl` | `string?` | `https://api.aishell.openbuildlab.com` | Chat API base URL. `/chat/completions` and `/models` are appended. |
|
|
45
|
+
| `keyringService` | `string?` | `aishell-dsh` | Credential store service name. |
|
|
46
|
+
|
|
47
|
+
## Storing credentials
|
|
48
|
+
|
|
49
|
+
**Web UI (recommended):** Install `aishell-credentials` (or the `aishell-base` bundle) — the Settings page gets an "AI Shell" section with AK/SK/SecurityToken input fields. Values are transferred to the credential store.
|
|
50
|
+
|
|
51
|
+
**CLI fallback:**
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
node --input-type=module -e "
|
|
55
|
+
import { createCredentialsStore } from '@huaweidevtools/aishell-dsh-credentials-store';
|
|
56
|
+
const s = createCredentialsStore();
|
|
57
|
+
s.set('HW_ACCESS_KEY', 'your-ak');
|
|
58
|
+
s.set('HW_SECRET_KEY', 'your-sk');
|
|
59
|
+
// Optional: temporary security token (STS)
|
|
60
|
+
s.set('HW_SECURITY_TOKEN', 'your-token');
|
|
61
|
+
"
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## License
|
|
65
|
+
|
|
66
|
+
Apache License 2.0.
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# aishell-llm bundle patch: inserts the aishell LLM gateway adapter.
|
|
2
|
+
# Install standalone: `dsh plugin --profile <name> add link:<repo>/packages/aishell-llm`
|
|
3
|
+
# The single row mounts the host half (LLM adapter reading AK/SK from the
|
|
4
|
+
# credential store). Credentials are managed by aishell-credentials.
|
|
5
|
+
- insert:
|
|
6
|
+
- id: aishell-llm
|
|
7
|
+
name: '@huaweidevtools/aishell-dsh-llm'
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
import { createCredentialsStore } from "@huaweidevtools/aishell-dsh-credentials-store";
|
|
2
|
+
import { LlmAdapter, LlmError } from "@deepseek-ai/dsh-llm";
|
|
3
|
+
import { brandString } from "@deepseek-ai/dsh-brand";
|
|
4
|
+
import { EventSourceParserStream } from "eventsource-parser/stream";
|
|
5
|
+
import { sign } from "@huaweidevtools/aishell-dsh-credentials-store/signer";
|
|
6
|
+
|
|
7
|
+
//#region src/serialize.ts
|
|
8
|
+
/** Build the POST body for `/chat/completions`. */
|
|
9
|
+
function serializeRequest(options) {
|
|
10
|
+
const messages = [];
|
|
11
|
+
for (const message of options.messages) if (message.role === "user") {
|
|
12
|
+
const textBlocks = message.content.filter((block) => block.type === "text" || block.type === "reasoning");
|
|
13
|
+
messages.push({
|
|
14
|
+
role: "user",
|
|
15
|
+
content: textBlocks.length > 0 ? blocksToText(textBlocks) : ""
|
|
16
|
+
});
|
|
17
|
+
} else if (message.role === "tool") messages.push({
|
|
18
|
+
role: "tool",
|
|
19
|
+
tool_call_id: String(message.toolCallId),
|
|
20
|
+
content: blocksToText(message.content)
|
|
21
|
+
});
|
|
22
|
+
else if (message.role === "developer") {
|
|
23
|
+
const text = blocksToText(message.content);
|
|
24
|
+
if (text) messages.push({
|
|
25
|
+
role: "system",
|
|
26
|
+
content: text
|
|
27
|
+
});
|
|
28
|
+
} else if (message.role === "system") messages.push({
|
|
29
|
+
role: "system",
|
|
30
|
+
content: blocksToText(message.content)
|
|
31
|
+
});
|
|
32
|
+
else {
|
|
33
|
+
const toolCalls = message.content.filter(isToolCallBlock).map(serializeAssistantToolCall);
|
|
34
|
+
const assistantText = blocksToText(message.content.filter((block) => !isToolCallBlock(block)));
|
|
35
|
+
messages.push({
|
|
36
|
+
role: "assistant",
|
|
37
|
+
content: assistantText || null,
|
|
38
|
+
...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
model: options.model,
|
|
43
|
+
messages,
|
|
44
|
+
stream: true,
|
|
45
|
+
stream_options: { include_usage: true },
|
|
46
|
+
...options.tools && options.tools.length > 0 ? { tools: options.tools.map(serializeTool) } : {},
|
|
47
|
+
...options.temperature !== void 0 ? { temperature: options.temperature } : {},
|
|
48
|
+
...options.maxTokens !== void 0 ? { max_tokens: options.maxTokens } : {},
|
|
49
|
+
...options.stop !== void 0 ? { stop: options.stop } : {}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** Type guard for tool-call blocks. */
|
|
53
|
+
function isToolCallBlock(block) {
|
|
54
|
+
return block.type === "tool-call";
|
|
55
|
+
}
|
|
56
|
+
function blocksToText(blocks) {
|
|
57
|
+
return blocks.filter((block) => block.type === "text" || block.type === "reasoning").map((block) => block.text ?? "").join("");
|
|
58
|
+
}
|
|
59
|
+
function serializeAssistantToolCall(block) {
|
|
60
|
+
return {
|
|
61
|
+
id: String(block.id),
|
|
62
|
+
type: "function",
|
|
63
|
+
function: {
|
|
64
|
+
name: block.name,
|
|
65
|
+
arguments: block.arguments
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function serializeTool(tool) {
|
|
70
|
+
return {
|
|
71
|
+
type: "function",
|
|
72
|
+
function: {
|
|
73
|
+
name: tool.name,
|
|
74
|
+
description: tool.description,
|
|
75
|
+
parameters: tool.parameters
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/sse.ts
|
|
82
|
+
const DONE = "[DONE]";
|
|
83
|
+
async function* parseSse(stream) {
|
|
84
|
+
const events = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream());
|
|
85
|
+
for await (const { data } of events) {
|
|
86
|
+
yield data;
|
|
87
|
+
if (data === DONE) return;
|
|
88
|
+
}
|
|
89
|
+
throw new LlmError("SSE stream ended without [DONE]", "STREAM_CLOSED");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/translate.ts
|
|
94
|
+
/** Map the wire finish_reason vocabulary to the harness FinishReason. */
|
|
95
|
+
function mapFinishReason(reason) {
|
|
96
|
+
switch (reason) {
|
|
97
|
+
case "stop": return { kind: "stop" };
|
|
98
|
+
case "tool_calls": return { kind: "tool-calls" };
|
|
99
|
+
case "length": return { kind: "max-tokens" };
|
|
100
|
+
default: return {
|
|
101
|
+
kind: "error",
|
|
102
|
+
failure: {
|
|
103
|
+
message: `model stopped: ${reason ?? "unknown"}`,
|
|
104
|
+
code: (reason ?? "unknown").toUpperCase()
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** Map wire usage fields to disjoint harness counts. */
|
|
110
|
+
function mapUsage(usage) {
|
|
111
|
+
const cacheRead = usage.prompt_tokens_details?.cached_tokens;
|
|
112
|
+
const reasoning = usage.completion_tokens_details?.reasoning_tokens;
|
|
113
|
+
const combined = usage.prompt_tokens + usage.completion_tokens;
|
|
114
|
+
const hasExactTotal = Number.isSafeInteger(usage.prompt_tokens) && usage.prompt_tokens >= 0 && Number.isSafeInteger(usage.completion_tokens) && usage.completion_tokens >= 0 && Number.isSafeInteger(combined) && (usage.total_tokens === void 0 || usage.total_tokens === combined);
|
|
115
|
+
return {
|
|
116
|
+
inputTokens: usage.prompt_tokens - (cacheRead ?? 0),
|
|
117
|
+
outputTokens: usage.completion_tokens,
|
|
118
|
+
...hasExactTotal ? { totalTokens: combined } : {},
|
|
119
|
+
...cacheRead !== void 0 ? { cacheReadTokens: cacheRead } : {},
|
|
120
|
+
...reasoning !== void 0 ? { reasoningTokens: reasoning } : {}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/** Assemble the final ContentBlock for one open block. */
|
|
124
|
+
function closeBlock(block) {
|
|
125
|
+
switch (block.kind) {
|
|
126
|
+
case "text": return {
|
|
127
|
+
type: "text",
|
|
128
|
+
text: block.text
|
|
129
|
+
};
|
|
130
|
+
case "reasoning": return {
|
|
131
|
+
type: "reasoning",
|
|
132
|
+
text: block.text
|
|
133
|
+
};
|
|
134
|
+
case "tool-call": return {
|
|
135
|
+
type: "tool-call",
|
|
136
|
+
id: brandString(block.callId ?? ""),
|
|
137
|
+
name: block.name ?? "",
|
|
138
|
+
arguments: block.text
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** Accept one streamed identity field for a tool call. */
|
|
143
|
+
function acceptIdentity(current, incoming) {
|
|
144
|
+
return typeof incoming === "string" && incoming.length > 0 ? incoming : current;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Consume SSE data payloads (ending with `[DONE]`) and yield StreamChunks.
|
|
148
|
+
*/
|
|
149
|
+
async function* translate(payloads) {
|
|
150
|
+
let nextIndex = 0;
|
|
151
|
+
let textBlock;
|
|
152
|
+
let reasoningBlock;
|
|
153
|
+
const toolBlocks = new Map();
|
|
154
|
+
let pendingFinish;
|
|
155
|
+
let pendingUsage;
|
|
156
|
+
function open(kind) {
|
|
157
|
+
const block = {
|
|
158
|
+
index: nextIndex,
|
|
159
|
+
kind,
|
|
160
|
+
text: "",
|
|
161
|
+
callId: void 0,
|
|
162
|
+
name: void 0
|
|
163
|
+
};
|
|
164
|
+
nextIndex++;
|
|
165
|
+
return block;
|
|
166
|
+
}
|
|
167
|
+
for await (const payload of payloads) {
|
|
168
|
+
if (payload === DONE) break;
|
|
169
|
+
let chunk;
|
|
170
|
+
try {
|
|
171
|
+
chunk = JSON.parse(payload);
|
|
172
|
+
} catch {
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
if (chunk.usage) pendingUsage = mapUsage(chunk.usage);
|
|
176
|
+
const choice = chunk.choices?.[0];
|
|
177
|
+
if (!choice) continue;
|
|
178
|
+
const delta = choice.delta;
|
|
179
|
+
if (delta) {
|
|
180
|
+
if (delta.content && delta.content.length > 0) {
|
|
181
|
+
if (textBlock === void 0) {
|
|
182
|
+
textBlock = open("text");
|
|
183
|
+
yield {
|
|
184
|
+
type: "block-start",
|
|
185
|
+
index: textBlock.index,
|
|
186
|
+
blockType: "text"
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
textBlock.text += delta.content;
|
|
190
|
+
yield {
|
|
191
|
+
type: "text-delta",
|
|
192
|
+
index: textBlock.index,
|
|
193
|
+
text: delta.content
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
if (delta.reasoning_content && delta.reasoning_content.length > 0) {
|
|
197
|
+
if (reasoningBlock === void 0) {
|
|
198
|
+
reasoningBlock = open("reasoning");
|
|
199
|
+
yield {
|
|
200
|
+
type: "block-start",
|
|
201
|
+
index: reasoningBlock.index,
|
|
202
|
+
blockType: "reasoning"
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
reasoningBlock.text += delta.reasoning_content;
|
|
206
|
+
yield {
|
|
207
|
+
type: "reasoning-delta",
|
|
208
|
+
index: reasoningBlock.index,
|
|
209
|
+
text: delta.reasoning_content
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
if (delta.tool_calls) for (const tc of delta.tool_calls) {
|
|
213
|
+
let block = toolBlocks.get(tc.index);
|
|
214
|
+
if (block === void 0) {
|
|
215
|
+
block = open("tool-call");
|
|
216
|
+
toolBlocks.set(tc.index, block);
|
|
217
|
+
block.callId = acceptIdentity(void 0, tc.id);
|
|
218
|
+
block.name = acceptIdentity(void 0, tc.function?.name);
|
|
219
|
+
yield {
|
|
220
|
+
type: "block-start",
|
|
221
|
+
index: block.index,
|
|
222
|
+
blockType: "tool-call"
|
|
223
|
+
};
|
|
224
|
+
} else {
|
|
225
|
+
block.callId = acceptIdentity(block.callId, tc.id);
|
|
226
|
+
block.name = acceptIdentity(block.name, tc.function?.name);
|
|
227
|
+
}
|
|
228
|
+
const args = tc.function?.arguments;
|
|
229
|
+
if (args) {
|
|
230
|
+
block.text += args;
|
|
231
|
+
yield {
|
|
232
|
+
type: "tool-call-delta",
|
|
233
|
+
index: block.index,
|
|
234
|
+
id: brandString(block.callId ?? ""),
|
|
235
|
+
...block.name ? { name: block.name } : {},
|
|
236
|
+
argumentsDelta: args
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (choice.finish_reason) pendingFinish = mapFinishReason(choice.finish_reason);
|
|
242
|
+
}
|
|
243
|
+
const allBlocks = [
|
|
244
|
+
...textBlock !== void 0 ? [textBlock] : [],
|
|
245
|
+
...reasoningBlock !== void 0 ? [reasoningBlock] : [],
|
|
246
|
+
...toolBlocks.values()
|
|
247
|
+
].sort((a, b) => a.index - b.index);
|
|
248
|
+
for (const block of allBlocks) yield {
|
|
249
|
+
type: "block-end",
|
|
250
|
+
index: block.index,
|
|
251
|
+
block: closeBlock(block)
|
|
252
|
+
};
|
|
253
|
+
if (pendingUsage !== void 0) yield {
|
|
254
|
+
type: "usage",
|
|
255
|
+
usage: pendingUsage
|
|
256
|
+
};
|
|
257
|
+
yield {
|
|
258
|
+
type: "finish",
|
|
259
|
+
reason: pendingFinish ?? { kind: "stop" }
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
//#endregion
|
|
264
|
+
//#region src/adapter.ts
|
|
265
|
+
/** Credential store account names for Huawei Cloud credentials. */
|
|
266
|
+
const AK_ACCOUNT = "HW_ACCESS_KEY";
|
|
267
|
+
const SK_ACCOUNT = "HW_SECRET_KEY";
|
|
268
|
+
const TOKEN_ACCOUNT = "HW_SECURITY_TOKEN";
|
|
269
|
+
/**
|
|
270
|
+
* Map the gateway's `modalities` array (e.g. `["text","image"]`) to DSH's
|
|
271
|
+
* `ModelModality` vocabulary. DSH currently defines only `'text' | 'image'`;
|
|
272
|
+
* other modalities (audio, video) are dropped — the gateway still accepts
|
|
273
|
+
* them, but the harness catalog cannot advertise them.
|
|
274
|
+
*/
|
|
275
|
+
function mapModalities(modalities) {
|
|
276
|
+
if (modalities === void 0 || modalities.length === 0) return {};
|
|
277
|
+
const mapped = modalities.filter((m) => m === "text" || m === "image");
|
|
278
|
+
return mapped.length > 0 ? { inputModalities: mapped } : {};
|
|
279
|
+
}
|
|
280
|
+
var GatewayAdapter = class GatewayAdapter extends LlmAdapter {
|
|
281
|
+
constructor(opts) {
|
|
282
|
+
super();
|
|
283
|
+
this.opts = opts;
|
|
284
|
+
}
|
|
285
|
+
providerInfo(provider) {
|
|
286
|
+
return {
|
|
287
|
+
id: provider,
|
|
288
|
+
name: "AI Shell"
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Fetch the raw wire models from `/models`, cached for a short TTL so
|
|
293
|
+
* `listModels` and `resolveModel` don't each sign a separate request.
|
|
294
|
+
* Returns `[]` on any failure (missing credentials, network, non-ok) so
|
|
295
|
+
* the provider still registers — the user can type a model ID manually.
|
|
296
|
+
*/
|
|
297
|
+
async fetchWireModels() {
|
|
298
|
+
const now = Date.now();
|
|
299
|
+
if (this.modelsCache !== void 0 && this.modelsCache.expires > now) return this.modelsCache.promise;
|
|
300
|
+
const creds = this.readCredentials();
|
|
301
|
+
if (!creds?.ak) return [];
|
|
302
|
+
const promise = (async () => {
|
|
303
|
+
const response = await this.signedFetch("/models", "GET", void 0, void 0);
|
|
304
|
+
if (!response.ok) return [];
|
|
305
|
+
const json = await response.json();
|
|
306
|
+
return json.data ?? [];
|
|
307
|
+
})().catch(() => []);
|
|
308
|
+
this.modelsCache = {
|
|
309
|
+
promise,
|
|
310
|
+
expires: now + GatewayAdapter.MODELS_TTL_MS
|
|
311
|
+
};
|
|
312
|
+
return promise;
|
|
313
|
+
}
|
|
314
|
+
async listModels(provider) {
|
|
315
|
+
const wireModels = await this.fetchWireModels();
|
|
316
|
+
return wireModels.map((m) => ({
|
|
317
|
+
provider,
|
|
318
|
+
id: m.id,
|
|
319
|
+
name: m.id,
|
|
320
|
+
...mapModalities(m.modalities)
|
|
321
|
+
}));
|
|
322
|
+
}
|
|
323
|
+
async resolveModel(provider, model) {
|
|
324
|
+
const wireModels = await this.fetchWireModels();
|
|
325
|
+
const wire = wireModels.find((m) => m.id === model);
|
|
326
|
+
const base = {
|
|
327
|
+
provider,
|
|
328
|
+
id: model,
|
|
329
|
+
name: model,
|
|
330
|
+
...mapModalities(wire?.modalities)
|
|
331
|
+
};
|
|
332
|
+
if (wire === void 0) return base;
|
|
333
|
+
const contextWindow = wire.limits?.context_window;
|
|
334
|
+
const maxCompletion = wire.limits?.max_completion_tokens;
|
|
335
|
+
const efforts = wire.reasoning_effort;
|
|
336
|
+
return {
|
|
337
|
+
...base,
|
|
338
|
+
...typeof contextWindow === "number" && contextWindow > 0 ? { context: { contextWindow } } : {},
|
|
339
|
+
...typeof maxCompletion === "number" && maxCompletion > 0 ? { defaultMaxTokens: maxCompletion } : {},
|
|
340
|
+
...Array.isArray(efforts) && efforts.length > 0 ? { reasoning: { efforts: efforts.map((e) => ({
|
|
341
|
+
id: e,
|
|
342
|
+
name: e
|
|
343
|
+
})) } } : {}
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
/** Read AK/SK (and optional SecurityToken) from the credential store. */
|
|
347
|
+
readCredentials() {
|
|
348
|
+
const ak = this.opts.keyring.get(AK_ACCOUNT);
|
|
349
|
+
const sk = this.opts.keyring.get(SK_ACCOUNT);
|
|
350
|
+
if (!ak || !sk) return void 0;
|
|
351
|
+
const securityToken = this.opts.keyring.get(TOKEN_ACCOUNT);
|
|
352
|
+
return {
|
|
353
|
+
ak,
|
|
354
|
+
sk,
|
|
355
|
+
...securityToken ? { securityToken } : {}
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
/** Read credentials or throw MISSING_CREDENTIAL — every signing code path goes through here. */
|
|
359
|
+
requireCredentials() {
|
|
360
|
+
const creds = this.readCredentials();
|
|
361
|
+
if (!creds) throw new LlmError("aishell-llm: HW_ACCESS_KEY and HW_SECRET_KEY not found in credential store (service \"aishell-dsh\"); store them first", "MISSING_CREDENTIAL");
|
|
362
|
+
return creds;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Sign a request with AK/SK and fetch. Encapsulates the SDK-HMAC-SHA256
|
|
366
|
+
* signing flow: read credentials → sign → attach headers → fetch.
|
|
367
|
+
*/
|
|
368
|
+
async signedFetch(path, method, body, signal) {
|
|
369
|
+
const creds = this.requireCredentials();
|
|
370
|
+
const url = new URL(this.opts.baseUrl);
|
|
371
|
+
const headers = sign(method, url.host, path, {}, body ?? "", creds);
|
|
372
|
+
return fetch(`${this.opts.baseUrl}${path}`, {
|
|
373
|
+
method,
|
|
374
|
+
headers: {
|
|
375
|
+
host: headers.host,
|
|
376
|
+
"x-sdk-date": headers["x-sdk-date"],
|
|
377
|
+
Authorization: headers.Authorization,
|
|
378
|
+
...headers["x-security-token"] !== void 0 ? { "x-security-token": headers["x-security-token"] } : {},
|
|
379
|
+
...body !== void 0 ? { "content-type": "application/json" } : {}
|
|
380
|
+
},
|
|
381
|
+
...body !== void 0 ? { body } : {},
|
|
382
|
+
...signal ? { signal } : {}
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
async *stream(options) {
|
|
386
|
+
const body = JSON.stringify(serializeRequest(options));
|
|
387
|
+
let response;
|
|
388
|
+
try {
|
|
389
|
+
response = await this.signedFetch("/chat/completions", "POST", body, options.signal);
|
|
390
|
+
} catch (error) {
|
|
391
|
+
if (options.signal?.aborted) throw error;
|
|
392
|
+
throw new LlmError(`aishell-llm: request failed: ${error instanceof Error ? error.message : String(error)}`, "NETWORK_ERROR");
|
|
393
|
+
}
|
|
394
|
+
if (!response.ok) {
|
|
395
|
+
const text = await response.text().catch(() => "");
|
|
396
|
+
throw new LlmError(`aishell-llm: gateway returned ${response.status}: ${text}`, "PROVIDER_ERROR", { status: response.status });
|
|
397
|
+
}
|
|
398
|
+
if (!response.body) throw new LlmError("aishell-llm: gateway returned no body", "EMPTY_RESPONSE");
|
|
399
|
+
yield* translate(parseSse(response.body));
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
GatewayAdapter.MODELS_TTL_MS = 6e4;
|
|
403
|
+
|
|
404
|
+
//#endregion
|
|
405
|
+
//#region src/index.ts
|
|
406
|
+
/** Default chat API base URL. */
|
|
407
|
+
const DEFAULT_BASE_URL = "https://api.aishell.openbuildlab.com";
|
|
408
|
+
const name = "aishell-llm";
|
|
409
|
+
const inject = ["llm"];
|
|
410
|
+
/** The provider route this plugin owns. */
|
|
411
|
+
const PROVIDER = "aishell";
|
|
412
|
+
function apply(ctx, config = {}) {
|
|
413
|
+
const store = createCredentialsStore(config.keyringService ? { service: config.keyringService } : {});
|
|
414
|
+
const adapter = new GatewayAdapter({
|
|
415
|
+
baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
|
|
416
|
+
keyring: store
|
|
417
|
+
});
|
|
418
|
+
ctx.llm.registerAdapter([PROVIDER], adapter);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
//#endregion
|
|
422
|
+
export { PROVIDER, apply, inject, name };
|
|
423
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* aishell LLM gateway adapter for DSH.
|
|
3
|
+
*
|
|
4
|
+
* Routes model calls through the aishell gateway using direct
|
|
5
|
+
* AK/SK signing (SDK-HMAC-SHA256). No intermediate "config fetch" or API-key
|
|
6
|
+
* exchange — every request (chat + model listing) is signed with the user's
|
|
7
|
+
* AK/SK credentials read from the credential store.
|
|
8
|
+
*
|
|
9
|
+
* @module @huaweidevtools/aishell-dsh-llm/adapter
|
|
10
|
+
*/
|
|
11
|
+
import { LlmAdapter } from '@deepseek-ai/dsh-llm';
|
|
12
|
+
import type { GenerateOptions, LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo, StreamChunk } from '@deepseek-ai/dsh-llm';
|
|
13
|
+
import type { CredentialsStore } from '@huaweidevtools/aishell-dsh-credentials-store';
|
|
14
|
+
/** Adapter construction options. */
|
|
15
|
+
export interface GatewayAdapterOptions {
|
|
16
|
+
/** Chat API base URL (e.g. `https://api.aishell.openbuildlab.com`). */
|
|
17
|
+
readonly baseUrl: string;
|
|
18
|
+
/** Credential store for reading AK/SK. */
|
|
19
|
+
readonly keyring: CredentialsStore;
|
|
20
|
+
}
|
|
21
|
+
export declare class GatewayAdapter extends LlmAdapter {
|
|
22
|
+
private readonly opts;
|
|
23
|
+
/** Cached /models response (TTL-bounded so credential changes eventually refresh). */
|
|
24
|
+
private modelsCache;
|
|
25
|
+
private static readonly MODELS_TTL_MS;
|
|
26
|
+
constructor(opts: GatewayAdapterOptions);
|
|
27
|
+
providerInfo(provider: string): LlmProviderInfo;
|
|
28
|
+
/**
|
|
29
|
+
* Fetch the raw wire models from `/models`, cached for a short TTL so
|
|
30
|
+
* `listModels` and `resolveModel` don't each sign a separate request.
|
|
31
|
+
* Returns `[]` on any failure (missing credentials, network, non-ok) so
|
|
32
|
+
* the provider still registers — the user can type a model ID manually.
|
|
33
|
+
*/
|
|
34
|
+
private fetchWireModels;
|
|
35
|
+
listModels(provider: string): Promise<readonly LlmModelInfo[]>;
|
|
36
|
+
resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo>;
|
|
37
|
+
/** Read AK/SK (and optional SecurityToken) from the credential store. */
|
|
38
|
+
private readCredentials;
|
|
39
|
+
/** Read credentials or throw MISSING_CREDENTIAL — every signing code path goes through here. */
|
|
40
|
+
private requireCredentials;
|
|
41
|
+
/**
|
|
42
|
+
* Sign a request with AK/SK and fetch. Encapsulates the SDK-HMAC-SHA256
|
|
43
|
+
* signing flow: read credentials → sign → attach headers → fetch.
|
|
44
|
+
*/
|
|
45
|
+
private signedFetch;
|
|
46
|
+
stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=adapter.d.ts.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* aishell LLM gateway adapter plugin.
|
|
3
|
+
*
|
|
4
|
+
* Registers the `aishell` provider route on `ctx.llm`, routing model calls
|
|
5
|
+
* through the aishell gateway. Every request is signed directly with the
|
|
6
|
+
* user's AK/SK (SDK-HMAC-SHA256) — no intermediate API-key exchange. AK/SK
|
|
7
|
+
* are read from the credential store (OS keyring with memory fallback) via
|
|
8
|
+
* `createCredentialsStore`.
|
|
9
|
+
*
|
|
10
|
+
* Credential management (settings namespace + watch → store transfer) lives
|
|
11
|
+
* in `aishell-credentials`; this plugin only consumes the stored credentials.
|
|
12
|
+
*
|
|
13
|
+
* @module @huaweidevtools/aishell-dsh-llm
|
|
14
|
+
*/
|
|
15
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
16
|
+
export type { GatewayAdapter, GatewayAdapterOptions } from './adapter.ts';
|
|
17
|
+
/** Plugin config. */
|
|
18
|
+
export interface Config {
|
|
19
|
+
/** Chat API base URL. Default: the public aishell gateway. */
|
|
20
|
+
readonly baseUrl?: string;
|
|
21
|
+
/** Credential store service name; defaults to `'aishell-dsh'`. */
|
|
22
|
+
readonly keyringService?: string;
|
|
23
|
+
}
|
|
24
|
+
export declare const name = "aishell-llm";
|
|
25
|
+
export declare const inject: string[];
|
|
26
|
+
/** The provider route this plugin owns. */
|
|
27
|
+
export declare const PROVIDER = "aishell";
|
|
28
|
+
export declare function apply(ctx: Context, config?: Config): void;
|
|
29
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serialize harness {@link GenerateOptions} into an OpenAI-compatible wire request.
|
|
3
|
+
*
|
|
4
|
+
* Text-only: image blocks are not mapped (the gateway adapter is for text
|
|
5
|
+
* models; image support can be added later by extending `blocksToText`).
|
|
6
|
+
*
|
|
7
|
+
* @module @huaweidevtools/aishell-dsh-llm/serialize
|
|
8
|
+
*/
|
|
9
|
+
import type { GenerateOptions } from '@deepseek-ai/dsh-llm';
|
|
10
|
+
import type { WireRequest } from './types.ts';
|
|
11
|
+
/** Build the POST body for `/chat/completions`. */
|
|
12
|
+
export declare function serializeRequest(options: GenerateOptions): WireRequest;
|
|
13
|
+
//# sourceMappingURL=serialize.d.ts.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSE byte-stream parser for OpenAI-compatible chat-completions.
|
|
3
|
+
*
|
|
4
|
+
* Yields each event's `data` payload; the literal `[DONE]` is yielded as the
|
|
5
|
+
* final value so the caller owns final flushing. EOF before `[DONE]` raises
|
|
6
|
+
* `LlmError('STREAM_CLOSED')`.
|
|
7
|
+
*
|
|
8
|
+
* @module @huaweidevtools/aishell-dsh-llm/sse
|
|
9
|
+
*/
|
|
10
|
+
export declare const DONE = "[DONE]";
|
|
11
|
+
export declare function parseSse(stream: ReadableStream<BufferSource>): AsyncGenerator<string>;
|
|
12
|
+
//# sourceMappingURL=sse.d.ts.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Translate OpenAI-compatible SSE payloads into harness {@link StreamChunk}s.
|
|
3
|
+
*
|
|
4
|
+
* One stateful block per content, reasoning, or tool-call index. Finish reason
|
|
5
|
+
* and usage are deferred until `[DONE]`, covering both finish-attached and
|
|
6
|
+
* trailing usage-only shapes.
|
|
7
|
+
*
|
|
8
|
+
* @module @huaweidevtools/aishell-dsh-llm/translate
|
|
9
|
+
*/
|
|
10
|
+
import type { StreamChunk } from '@deepseek-ai/dsh-llm';
|
|
11
|
+
/**
|
|
12
|
+
* Consume SSE data payloads (ending with `[DONE]`) and yield StreamChunks.
|
|
13
|
+
*/
|
|
14
|
+
export declare function translate(payloads: AsyncIterable<string>): AsyncGenerator<StreamChunk>;
|
|
15
|
+
//# sourceMappingURL=translate.d.ts.map
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI-compatible chat-completions wire format (text-only).
|
|
3
|
+
*
|
|
4
|
+
* @module @huaweidevtools/aishell-dsh-llm/types
|
|
5
|
+
*/
|
|
6
|
+
/** Request body for `POST {baseURL}/chat/completions`. */
|
|
7
|
+
export interface WireRequest {
|
|
8
|
+
model: string;
|
|
9
|
+
messages: WireMessage[];
|
|
10
|
+
stream: true;
|
|
11
|
+
stream_options: {
|
|
12
|
+
include_usage: true;
|
|
13
|
+
};
|
|
14
|
+
tools?: WireTool[];
|
|
15
|
+
temperature?: number;
|
|
16
|
+
max_tokens?: number;
|
|
17
|
+
stop?: string[];
|
|
18
|
+
}
|
|
19
|
+
/** One wire message. */
|
|
20
|
+
export type WireMessage = WireSystemMessage | WireUserMessage | WireAssistantMessage | WireToolMessage;
|
|
21
|
+
export interface WireSystemMessage {
|
|
22
|
+
role: 'system';
|
|
23
|
+
content: string;
|
|
24
|
+
}
|
|
25
|
+
export interface WireUserMessage {
|
|
26
|
+
role: 'user';
|
|
27
|
+
content: string;
|
|
28
|
+
}
|
|
29
|
+
export interface WireAssistantMessage {
|
|
30
|
+
role: 'assistant';
|
|
31
|
+
content?: string | null;
|
|
32
|
+
tool_calls?: WireAssistantToolCall[];
|
|
33
|
+
}
|
|
34
|
+
export interface WireToolMessage {
|
|
35
|
+
role: 'tool';
|
|
36
|
+
tool_call_id: string;
|
|
37
|
+
content: string;
|
|
38
|
+
}
|
|
39
|
+
export interface WireAssistantToolCall {
|
|
40
|
+
id: string;
|
|
41
|
+
type: 'function';
|
|
42
|
+
function: {
|
|
43
|
+
name: string;
|
|
44
|
+
arguments: string;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export interface WireTool {
|
|
48
|
+
type: 'function';
|
|
49
|
+
function: {
|
|
50
|
+
name: string;
|
|
51
|
+
description: string;
|
|
52
|
+
parameters: Record<string, unknown>;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** One SSE chunk from the chat-completions stream. */
|
|
56
|
+
export interface WireChunk {
|
|
57
|
+
choices?: WireChoice[];
|
|
58
|
+
usage?: WireUsage;
|
|
59
|
+
}
|
|
60
|
+
/** One model entry from the GET /models response (OpenAI-compatible). */
|
|
61
|
+
export interface WireModel {
|
|
62
|
+
id: string;
|
|
63
|
+
object?: string;
|
|
64
|
+
owned_by?: string;
|
|
65
|
+
created?: number;
|
|
66
|
+
capabilities?: WireModelCapabilities;
|
|
67
|
+
modalities?: string[];
|
|
68
|
+
reasoning_effort?: string[];
|
|
69
|
+
limits?: WireModelLimits;
|
|
70
|
+
pricing?: WireModelPricing;
|
|
71
|
+
}
|
|
72
|
+
export interface WireModelCapabilities {
|
|
73
|
+
text?: boolean;
|
|
74
|
+
image?: boolean;
|
|
75
|
+
video?: boolean;
|
|
76
|
+
audio?: boolean;
|
|
77
|
+
streaming?: boolean;
|
|
78
|
+
thinking?: boolean;
|
|
79
|
+
tool_call?: boolean;
|
|
80
|
+
embedding?: boolean;
|
|
81
|
+
}
|
|
82
|
+
export interface WireModelLimits {
|
|
83
|
+
context_window?: number;
|
|
84
|
+
max_prompt_tokens?: number;
|
|
85
|
+
max_completion_tokens?: number;
|
|
86
|
+
}
|
|
87
|
+
export interface WireModelPricing {
|
|
88
|
+
currency?: string;
|
|
89
|
+
unit?: string;
|
|
90
|
+
input?: number;
|
|
91
|
+
cached_input?: number;
|
|
92
|
+
output?: number;
|
|
93
|
+
}
|
|
94
|
+
/** Response body from GET /models. */
|
|
95
|
+
export interface WireModelList {
|
|
96
|
+
data: WireModel[];
|
|
97
|
+
}
|
|
98
|
+
export interface WireChoice {
|
|
99
|
+
delta?: WireDelta;
|
|
100
|
+
finish_reason?: string | null;
|
|
101
|
+
}
|
|
102
|
+
export interface WireDelta {
|
|
103
|
+
role?: string;
|
|
104
|
+
content?: string;
|
|
105
|
+
reasoning_content?: string;
|
|
106
|
+
tool_calls?: WireDeltaToolCall[];
|
|
107
|
+
}
|
|
108
|
+
export interface WireDeltaToolCall {
|
|
109
|
+
index: number;
|
|
110
|
+
id?: string;
|
|
111
|
+
type?: 'function';
|
|
112
|
+
function?: {
|
|
113
|
+
name?: string;
|
|
114
|
+
arguments?: string;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
export interface WireUsage {
|
|
118
|
+
prompt_tokens: number;
|
|
119
|
+
completion_tokens: number;
|
|
120
|
+
total_tokens?: number;
|
|
121
|
+
prompt_tokens_details?: {
|
|
122
|
+
cached_tokens?: number;
|
|
123
|
+
};
|
|
124
|
+
completion_tokens_details?: {
|
|
125
|
+
reasoning_tokens?: number;
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=types.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@huaweidevtools/aishell-dsh-llm",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"description": "aishell LLM gateway adapter for DSH — OpenAI-compatible, Huawei Cloud AK/SK auth via credential store",
|
|
4
|
+
"version": "0.0.1-beta.0",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/yusheng-g/aishell-dsh-plugins.git",
|
|
11
|
+
"directory": "packages/aishell-llm"
|
|
12
|
+
},
|
|
13
|
+
"type": "module",
|
|
14
|
+
"main": "lib/index.js",
|
|
15
|
+
"types": "lib/types/index.d.ts",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./lib/types/index.d.ts",
|
|
19
|
+
"default": "./lib/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"lib/index.js",
|
|
24
|
+
"lib/types/**/*.d.ts",
|
|
25
|
+
"cordis.patch.yml"
|
|
26
|
+
],
|
|
27
|
+
"license": "Apache-2.0",
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"eventsource-parser": "^3.0.0",
|
|
30
|
+
"@huaweidevtools/aishell-dsh-credentials-store": "0.0.1-beta.0"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@deepseek-ai/cordis": "^4.0.4",
|
|
34
|
+
"@deepseek-ai/dsh-brand": "0.2.0-rc.1 || 0.2.1-alpha.1 || ^0.2.1",
|
|
35
|
+
"@deepseek-ai/dsh-llm": "0.2.0-rc.1 || 0.2.1-alpha.1 || ^0.2.1"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@deepseek-ai/cordis": "^4.0.4",
|
|
39
|
+
"@deepseek-ai/dsh-brand": "0.2.0-rc.1 || 0.2.1-alpha.1 || ^0.2.1",
|
|
40
|
+
"@deepseek-ai/dsh-llm": "0.2.0-rc.1 || 0.2.1-alpha.1 || ^0.2.1"
|
|
41
|
+
},
|
|
42
|
+
"dsh": {
|
|
43
|
+
"bundle": {
|
|
44
|
+
"patch": "./cordis.patch.yml"
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build:bundle": "tsdown"
|
|
49
|
+
}
|
|
6
50
|
}
|