@xsai/text-chat 0.0.0-stage → 1.0.0-beta.2

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.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Moeru AI
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.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # @xsai/text-chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <!-- automd:file src="/docs/snippets/text-chat.md" -->
4
+
5
+ ```sh
6
+ pnpm add @xsai/text @xsai/text-chat
7
+ ```
8
+
9
+ ```ts
10
+ import { generateText } from '@xsai/text'
11
+ import { chat } from '@xsai/text-chat'
12
+
13
+ const model = chat({
14
+ apiKey: process.env.OPENAI_API_KEY,
15
+ baseURL: 'https://api.openai.com/v1/',
16
+ model: 'gpt-6-luna',
17
+ })
18
+
19
+ const { text } = await generateText(model, { input: 'Say hello.' })
20
+ console.log(text)
21
+ ```
22
+
23
+ <!-- /automd -->
24
+
25
+ Read the [documentation](https://xsai.js.org/text/adapters).
@@ -0,0 +1,29 @@
1
+ import { HttpOptions } from '@xsai/shared';
2
+ import { LanguageModel } from '@xsai/text';
3
+
4
+ interface ChatPartMetadata {
5
+ /** Which assistant-message field carried reasoning on this wire. */
6
+ reasoning_field?: 'reasoning' | 'reasoning_content';
7
+ }
8
+
9
+ interface ChatProviderOptions {
10
+ frequencyPenalty?: number;
11
+ parallelToolCalls?: boolean;
12
+ presencePenalty?: number;
13
+ seed?: number;
14
+ stopSequences?: readonly string[];
15
+ topK?: number;
16
+ }
17
+
18
+ declare module '@xsai/text' {
19
+ interface LanguageModelProviderOptions {
20
+ chat?: ChatProviderOptions;
21
+ }
22
+ interface PartProviderMetadata {
23
+ chat?: ChatPartMetadata;
24
+ }
25
+ }
26
+ declare const chat: (options: HttpOptions) => LanguageModel;
27
+
28
+ export { chat };
29
+ export type { ChatPartMetadata, ChatProviderOptions };
package/dist/index.js ADDED
@@ -0,0 +1,322 @@
1
+ import { WireEventStream, resolveSchema, wireRequest } from '@xsai/text/internal';
2
+ import { XSAIError } from '@xsai/shared';
3
+
4
+ const mapFinish = (reason, refusal) => {
5
+ switch (reason) {
6
+ case "content_filter":
7
+ return { reason: "content-filter", status: "incomplete" };
8
+ case "length":
9
+ case "max_output_tokens":
10
+ case "max_tokens":
11
+ return { reason: "length", status: "incomplete" };
12
+ case null:
13
+ case void 0:
14
+ return { status: "completed" };
15
+ case "stop":
16
+ return { reason: refusal ? "refusal" : "stop", status: "completed" };
17
+ case "tool_calls":
18
+ return { reason: "tool-calls", status: "completed" };
19
+ default:
20
+ return { reason, status: "completed" };
21
+ }
22
+ };
23
+ const normalizeUsage = (usage) => {
24
+ const input = usage.prompt_tokens ?? 0;
25
+ const output = usage.completion_tokens ?? 0;
26
+ return {
27
+ cacheReadInputTokens: usage.prompt_tokens_details?.cached_tokens ?? usage.prompt_cache_hit_tokens,
28
+ inputTokens: input,
29
+ outputTokens: output,
30
+ reasoningTokens: usage.completion_tokens_details?.reasoning_tokens,
31
+ totalTokens: usage.total_tokens ?? input + output
32
+ };
33
+ };
34
+ class ChatEventStream extends WireEventStream {
35
+ // Preserve the wire field for assistant-message replay.
36
+ hasRefusal = false;
37
+ reasoningField;
38
+ constructor(includeRawEvents = false) {
39
+ super((chunk, builder) => {
40
+ if (chunk.error != null) {
41
+ builder.fail(new XSAIError("model-error", chunk.error.message, {
42
+ cause: chunk.error
43
+ }));
44
+ return;
45
+ }
46
+ if (chunk.usage != null)
47
+ builder.meta({ usage: normalizeUsage(chunk.usage) });
48
+ for (const choice of chunk.choices ?? []) {
49
+ if (choice.index !== 0)
50
+ continue;
51
+ if (choice.delta != null)
52
+ this.onDelta(builder, choice.delta);
53
+ if (choice.finish_reason != null) {
54
+ if (this.reasoningField != null)
55
+ builder.end("reasoning", { providerMetadata: { chat: { reasoning_field: this.reasoningField } } });
56
+ const finish = mapFinish(choice.finish_reason, this.hasRefusal);
57
+ builder.done(finish.status, finish.reason);
58
+ }
59
+ }
60
+ }, includeRawEvents);
61
+ }
62
+ onDelta(builder, delta) {
63
+ const reasoning = delta.reasoning_content ?? delta.reasoning;
64
+ if (reasoning != null && reasoning !== "") {
65
+ this.reasoningField ??= delta.reasoning_content != null ? "reasoning_content" : "reasoning";
66
+ builder.start("reasoning", "reasoning");
67
+ builder.delta("reasoning", reasoning);
68
+ }
69
+ const content = delta.content ?? "";
70
+ if (content !== "") {
71
+ builder.start("text", "text");
72
+ builder.delta("text", content);
73
+ }
74
+ const refusal = delta.refusal ?? "";
75
+ if (refusal !== "") {
76
+ this.hasRefusal = true;
77
+ builder.start("refusal", "refusal");
78
+ builder.delta("refusal", refusal);
79
+ }
80
+ for (const call of delta.tool_calls ?? []) {
81
+ const key = `tool:${call.index}`;
82
+ builder.start(key, "tool-call", { fallbackId: `call_${call.index}` });
83
+ builder.delta(key, call.function?.arguments ?? "", { callId: call.id, name: call.function?.name });
84
+ }
85
+ }
86
+ }
87
+
88
+ const SUPPORTED_FORMATS = /* @__PURE__ */ new Set([
89
+ "date",
90
+ "date-time",
91
+ "duration",
92
+ "email",
93
+ "hostname",
94
+ "ipv4",
95
+ "ipv6",
96
+ "time",
97
+ "uuid"
98
+ ]);
99
+ const normalizeSchema = (schema) => {
100
+ const normalized = { ...schema };
101
+ const normalize = (schema2) => typeof schema2 === "boolean" ? schema2 : normalizeSchema(schema2);
102
+ if (normalized.$ref != null)
103
+ return { $ref: normalized.$ref };
104
+ if (normalized.type === "object" || normalized.properties != null) {
105
+ normalized.properties ??= {};
106
+ normalized.properties = Object.fromEntries(Object.entries(normalized.properties).map(([name, property]) => [name, normalize(property)]));
107
+ normalized.additionalProperties = false;
108
+ normalized.required = Object.keys(normalized.properties);
109
+ }
110
+ if (normalized.$defs != null)
111
+ normalized.$defs = Object.fromEntries(Object.entries(normalized.$defs).map(([name, definition]) => [name, normalize(definition)]));
112
+ if (normalized.definitions != null)
113
+ normalized.definitions = Object.fromEntries(Object.entries(normalized.definitions).map(([name, definition]) => [name, normalize(definition)]));
114
+ if (normalized.items != null) {
115
+ normalized.items = Array.isArray(normalized.items) ? normalized.items.map(normalize) : normalize(normalized.items);
116
+ }
117
+ if (normalized.oneOf != null) {
118
+ const oneOf = normalized.oneOf;
119
+ delete normalized.oneOf;
120
+ normalized.anyOf = normalized.anyOf == null ? oneOf : normalized.anyOf.concat(oneOf);
121
+ }
122
+ if (normalized.anyOf != null)
123
+ normalized.anyOf = normalized.anyOf.map(normalize);
124
+ delete normalized.allOf;
125
+ delete normalized.not;
126
+ delete normalized.if;
127
+ delete normalized.then;
128
+ delete normalized.else;
129
+ if (normalized.format != null && !SUPPORTED_FORMATS.has(normalized.format))
130
+ delete normalized.format;
131
+ return normalized;
132
+ };
133
+
134
+ const normalizeSchemaName = (title) => title == null || title === "" ? "output" : title.replace(/[^\w-]/g, "_").slice(0, 64);
135
+ const normalizeFormat = (outputFormat) => {
136
+ if (outputFormat == null)
137
+ return void 0;
138
+ const { schema } = resolveSchema(outputFormat);
139
+ const normalized = normalizeSchema(schema);
140
+ return {
141
+ json_schema: {
142
+ description: normalized.description,
143
+ name: normalizeSchemaName(normalized.title),
144
+ schema: normalized,
145
+ strict: true
146
+ },
147
+ type: "json_schema"
148
+ };
149
+ };
150
+
151
+ const normalizeInputTextPart = (part) => ({
152
+ text: part.text,
153
+ type: "text"
154
+ });
155
+ const normalizeImagePart = (part) => {
156
+ const data = part.data.toString();
157
+ if (URL.canParse(data))
158
+ return { image_url: { detail: part.detail, url: data }, type: "image_url" };
159
+ throw new XSAIError("invalid-input", "Image part data must be a URL or a base64 data: URL");
160
+ };
161
+ const normalizeFilePart = (part) => {
162
+ const data = part.data.toString();
163
+ if (data.startsWith("data:"))
164
+ return { file: { file_data: data }, type: "file" };
165
+ throw new XSAIError("invalid-input", "File part data must be a base64 data: URL");
166
+ };
167
+ const normalizeToolResultPart = (part) => {
168
+ const output = typeof part.output === "string" ? part.output : part.output.map((content) => {
169
+ if (content.type !== "text")
170
+ throw new XSAIError("invalid-input", "Image tool results are not supported on the Chat Completions API");
171
+ return normalizeInputTextPart(content);
172
+ });
173
+ return {
174
+ // Some gateways reject empty tool content.
175
+ content: output === "" || Array.isArray(output) && output.length === 0 ? "(no output)" : output,
176
+ role: "tool",
177
+ tool_call_id: part.callId
178
+ };
179
+ };
180
+ const reasoningText = (part) => part.content.filter((content) => content.type === "text").map((content) => content.text).join("");
181
+ const normalizeToolCallPart = (part) => ({
182
+ function: {
183
+ arguments: part.arguments,
184
+ name: part.name
185
+ },
186
+ id: part.callId,
187
+ type: "function"
188
+ });
189
+ const normalizeAssistantMessage = (message) => {
190
+ if (typeof message.content === "string")
191
+ return { content: message.content, role: "assistant" };
192
+ const content = [];
193
+ const reasoning = [];
194
+ let reasoningField = "reasoning_content";
195
+ const refusal = [];
196
+ const toolCalls = [];
197
+ for (const part of message.content) {
198
+ switch (part.type) {
199
+ case "provider":
200
+ break;
201
+ case "reasoning":
202
+ reasoning.push(reasoningText(part));
203
+ reasoningField = part.providerMetadata?.chat?.reasoning_field ?? reasoningField;
204
+ break;
205
+ case "refusal":
206
+ refusal.push(part.refusal);
207
+ break;
208
+ case "text":
209
+ content.push(normalizeInputTextPart(part));
210
+ break;
211
+ case "tool-call":
212
+ toolCalls.push(normalizeToolCallPart(part));
213
+ break;
214
+ }
215
+ }
216
+ if (content.length === 0 && reasoning.length === 0 && refusal.length === 0 && toolCalls.length === 0)
217
+ return void 0;
218
+ return {
219
+ // Some gateways reject `content: null` even when tool_calls is set.
220
+ content: content.length === 0 ? "" : content,
221
+ [reasoningField]: reasoning.length === 0 ? void 0 : reasoning.join(""),
222
+ refusal: refusal.length === 0 ? void 0 : refusal.join(""),
223
+ role: "assistant",
224
+ tool_calls: toolCalls.length === 0 ? void 0 : toolCalls
225
+ };
226
+ };
227
+ const normalizeUserPart = (part) => {
228
+ switch (part.type) {
229
+ case "file":
230
+ return normalizeFilePart(part);
231
+ case "image":
232
+ return normalizeImagePart(part);
233
+ case "text":
234
+ return normalizeInputTextPart(part);
235
+ }
236
+ };
237
+ const normalizeUserMessage = (message, messages) => {
238
+ if (typeof message.content === "string") {
239
+ messages.push({ content: message.content, role: "user" });
240
+ return;
241
+ }
242
+ let content = [];
243
+ const flush = () => {
244
+ if (content.length === 0)
245
+ return;
246
+ messages.push({ content, role: "user" });
247
+ content = [];
248
+ };
249
+ for (const part of message.content) {
250
+ if (part.type === "tool-result") {
251
+ flush();
252
+ messages.push(normalizeToolResultPart(part));
253
+ continue;
254
+ }
255
+ content.push(normalizeUserPart(part));
256
+ }
257
+ flush();
258
+ };
259
+ const joinText = (content) => typeof content === "string" ? content : content.map((part) => part.text).join("");
260
+ const normalizeInput = (options) => {
261
+ const messages = [];
262
+ if (options.instructions != null)
263
+ messages.push({ content: options.instructions, role: "system" });
264
+ for (const message of typeof options.input === "string" ? [{ content: options.input, role: "user" }] : options.input) {
265
+ switch (message.role) {
266
+ case "assistant":
267
+ {
268
+ const assistant = normalizeAssistantMessage(message);
269
+ if (assistant != null)
270
+ messages.push(assistant);
271
+ }
272
+ break;
273
+ case "developer":
274
+ case "system":
275
+ messages.push({ content: joinText(message.content), role: message.role });
276
+ break;
277
+ case "user":
278
+ normalizeUserMessage(message, messages);
279
+ break;
280
+ }
281
+ }
282
+ return messages;
283
+ };
284
+
285
+ const normalizeTools = (tools) => tools?.map((tool) => ({
286
+ function: {
287
+ description: tool.description,
288
+ name: tool.name,
289
+ parameters: normalizeSchema(tool.inputSchema.schema),
290
+ strict: true
291
+ },
292
+ type: "function"
293
+ }));
294
+ const normalizeToolChoice = (toolChoice) => toolChoice == null ? void 0 : typeof toolChoice === "string" ? toolChoice : { function: { name: toolChoice.name }, type: "function" };
295
+
296
+ const chat = (options) => async (modelOptions) => {
297
+ const providerOptions = modelOptions.providerOptions?.chat;
298
+ return wireRequest({
299
+ body: {
300
+ frequency_penalty: providerOptions?.frequencyPenalty,
301
+ max_tokens: modelOptions.maxOutputTokens,
302
+ messages: normalizeInput(modelOptions),
303
+ model: options.model,
304
+ parallel_tool_calls: providerOptions?.parallelToolCalls,
305
+ presence_penalty: providerOptions?.presencePenalty,
306
+ reasoning_effort: modelOptions.reasoningEffort,
307
+ response_format: normalizeFormat(modelOptions.outputFormat),
308
+ seed: providerOptions?.seed,
309
+ stop: providerOptions?.stopSequences,
310
+ stream: true,
311
+ stream_options: { include_usage: true },
312
+ temperature: modelOptions.temperature,
313
+ tool_choice: normalizeToolChoice(modelOptions.toolChoice),
314
+ tools: normalizeTools(modelOptions.tools),
315
+ top_k: providerOptions?.topK,
316
+ top_p: modelOptions.topP
317
+ },
318
+ path: "chat/completions"
319
+ }, options, modelOptions, new ChatEventStream(modelOptions.includeRawEvents));
320
+ };
321
+
322
+ export { chat };
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@xsai/text-chat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "1.0.0-beta.2",
5
+ "description": "extra-small AI SDK: OpenAI Chat Completions API model for @xsai/text.",
6
+ "author": "Moeru AI",
7
+ "license": "MIT",
8
+ "homepage": "https://xsai.js.org",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/moeru-ai/xsai.git",
12
+ "directory": "packages/text-chat"
13
+ },
14
+ "bugs": "https://github.com/moeru-ai/xsai/issues",
15
+ "keywords": [
16
+ "xsai",
17
+ "ai",
18
+ "openai",
19
+ "chat",
20
+ "chat-completions"
21
+ ],
22
+ "sideEffects": false,
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "engines": {
34
+ "node": ">=26"
35
+ },
36
+ "peerDependencies": {
37
+ "@xsai/text": "1.0.0-beta.2"
38
+ },
39
+ "dependencies": {
40
+ "@xsai/shared": "1.0.0-beta.2"
41
+ },
42
+ "devDependencies": {
43
+ "@xsai/text": "1.0.0-beta.2",
44
+ "zod": "^4.3.6"
45
+ },
46
+ "scripts": {
47
+ "build": "pkgroll --clean-dist",
48
+ "test": "vitest run --exclude e2e/**",
49
+ "test:watch": "vitest"
50
+ },
51
+ "main": "./dist/index.js",
52
+ "types": "./dist/index.d.ts"
6
53
  }