@baishuyun/coze-provider 0.0.16 → 0.1.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/dist/index.mjs CHANGED
@@ -12,8 +12,8 @@ import {
12
12
  var VERSION = "0.0.1";
13
13
 
14
14
  // src/coze-language-model.ts
15
- import { ServerSentEventTransformStream } from "parse-sse";
16
- import { TextDecoderStream } from "stream/web";
15
+ import { ServerSentEventTransformStream as ServerSentEventTransformStream2 } from "parse-sse";
16
+ import { TextDecoderStream as TextDecoderStream2 } from "stream/web";
17
17
 
18
18
  // src/utils/prompt-to-model-msg.ts
19
19
  import { RoleType } from "@coze/api";
@@ -107,6 +107,62 @@ var convertPromptToMessages = (messages) => {
107
107
  });
108
108
  };
109
109
 
110
+ // src/utils/accumulate-sse-response.ts
111
+ import { ServerSentEventTransformStream } from "parse-sse";
112
+ import { TextDecoderStream } from "stream/web";
113
+ async function accumulateSSEResponse(body) {
114
+ const sseStream = body.pipeThrough(
115
+ new TextDecoderStream()
116
+ ).pipeThrough(new ServerSentEventTransformStream());
117
+ let textContent = "";
118
+ let reasoningContent = "";
119
+ let finishReason = "stop";
120
+ let usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
121
+ const reader = sseStream.getReader();
122
+ try {
123
+ while (true) {
124
+ const { done, value: evt } = await reader.read();
125
+ if (done) break;
126
+ if (!evt) continue;
127
+ let evtData;
128
+ try {
129
+ evtData = JSON.parse(evt.data);
130
+ } catch {
131
+ continue;
132
+ }
133
+ const event = evt.type;
134
+ if (event === "conversation.message.delta") {
135
+ if (evtData.reasoning_content) {
136
+ reasoningContent += evtData.reasoning_content;
137
+ } else if (evtData.content) {
138
+ textContent += evtData.content;
139
+ }
140
+ } else if (event === "conversation.chat.completed" || event === "done") {
141
+ finishReason = "stop";
142
+ if (evtData.usage) {
143
+ usage = {
144
+ inputTokens: evtData.usage.input_count || 0,
145
+ outputTokens: evtData.usage.output_count || 0,
146
+ totalTokens: evtData.usage.total_count || 0
147
+ };
148
+ }
149
+ } else if (event === "error") {
150
+ finishReason = "error";
151
+ }
152
+ }
153
+ } finally {
154
+ reader.releaseLock();
155
+ }
156
+ const content = [];
157
+ if (reasoningContent) {
158
+ content.push({ type: "reasoning", text: reasoningContent });
159
+ }
160
+ if (textContent) {
161
+ content.push({ type: "text", text: textContent });
162
+ }
163
+ return { content, finishReason, usage };
164
+ }
165
+
110
166
  // src/utils/create-error-stream.ts
111
167
  import { generateId } from "@ai-sdk/provider-utils";
112
168
  var createErrorStream = (error) => {
@@ -333,6 +389,31 @@ var LLMPartTrasnformStream = class extends TransformStream {
333
389
  }
334
390
  };
335
391
 
392
+ // src/utils/build-generate-result-by-chat-res.ts
393
+ var BuildWarningGenerateResult = (message) => {
394
+ return {
395
+ content: [],
396
+ finishReason: "error",
397
+ request: {
398
+ body: null
399
+ },
400
+ usage: {
401
+ inputTokens: 0,
402
+ outputTokens: 0,
403
+ totalTokens: 0
404
+ },
405
+ response: {
406
+ body: null
407
+ },
408
+ warnings: [
409
+ {
410
+ type: "other",
411
+ message
412
+ }
413
+ ]
414
+ };
415
+ };
416
+
336
417
  // src/coze-language-model.ts
337
418
  var CozeLanguageModel = class {
338
419
  specificationVersion = "v2";
@@ -346,8 +427,59 @@ var CozeLanguageModel = class {
346
427
  this.supportedUrls = config.supportedUrls?.() || {};
347
428
  this.config = config;
348
429
  }
349
- doGenerate(options) {
350
- throw new Error("Method not implemented.");
430
+ async doGenerate(options) {
431
+ const messages = convertPromptToMessages(options.prompt);
432
+ const warnings = [];
433
+ const url = this.config.url({ path: "/chat" });
434
+ const user_id = options.headers ? options.headers["x-user-id"] : "";
435
+ const user_var = options.headers ? options.headers["x-user-var"] : "";
436
+ let customVar;
437
+ if (user_var) {
438
+ try {
439
+ customVar = JSON.parse(user_var);
440
+ } catch (e) {
441
+ console.warn("x-user-var parse error", e);
442
+ }
443
+ }
444
+ const body = {
445
+ bot_id: this.config.botId,
446
+ auto_save_history: false,
447
+ user_id: user_id || "7543191937730215936",
448
+ stream: true,
449
+ additional_messages: messages
450
+ };
451
+ if (customVar) {
452
+ body.custom_variables = customVar;
453
+ }
454
+ const headers = this.config.headers();
455
+ const abortSignal = options.abortSignal;
456
+ const response = await fetch(url, {
457
+ method: "POST",
458
+ headers,
459
+ credentials: "include",
460
+ body: JSON.stringify(body),
461
+ signal: abortSignal
462
+ });
463
+ if (!response.ok || !response.body) {
464
+ const rawError = await response.text();
465
+ let errorDetail;
466
+ try {
467
+ errorDetail = JSON.parse(rawError);
468
+ } catch {
469
+ errorDetail = rawError;
470
+ }
471
+ const errorMessage = typeof errorDetail === "object" && errorDetail?.msg ? errorDetail.msg : `Coze API error: ${response.status} ${response.statusText}`;
472
+ return BuildWarningGenerateResult(errorMessage);
473
+ }
474
+ const { content, finishReason, usage } = await accumulateSSEResponse(response.body);
475
+ return {
476
+ content,
477
+ finishReason,
478
+ usage,
479
+ request: { body },
480
+ response: { body: null },
481
+ warnings
482
+ };
351
483
  }
352
484
  isVisibleMsgPart(evtData) {
353
485
  if (evtData.type === "knowledge" && evtData.role === "assistant") {
@@ -361,7 +493,7 @@ var CozeLanguageModel = class {
361
493
  const url = this.config.url({
362
494
  path: "/chat"
363
495
  });
364
- const user_id = (options.headers ? options.headers["x-user-id"] : "") || Date.now().toString();
496
+ const user_id = options.headers ? options.headers["x-user-id"] : "";
365
497
  const user_var = options.headers ? options.headers["x-user-var"] : "";
366
498
  let customVar;
367
499
  if (user_var) {
@@ -374,14 +506,12 @@ var CozeLanguageModel = class {
374
506
  const body = {
375
507
  bot_id: this.config.botId,
376
508
  auto_save_history: false,
377
- user_id: "7543191937730215936",
378
- // user_id,
509
+ user_id: user_id || "7543191937730215936",
379
510
  stream: true,
380
511
  additional_messages: messages
381
512
  };
382
- console.log("Request body for Coze API:", JSON.stringify(body));
383
513
  if (customVar) {
384
- body.custom_var = customVar;
514
+ body.custom_variables = customVar;
385
515
  }
386
516
  const headers = this.config.headers();
387
517
  const abortSignal = options.abortSignal;
@@ -413,8 +543,8 @@ var CozeLanguageModel = class {
413
543
  const isBuildStage = stage === "build";
414
544
  const isFillStage = stage === "fill";
415
545
  const result = response.body.pipeThrough(
416
- new TextDecoderStream()
417
- ).pipeThrough(new ServerSentEventTransformStream()).pipeThrough(new MCPChunkFilterTransformStream(isBuildStage || isFillStage)).pipeThrough(new LLMChunkInjectorTransformStream()).pipeThrough(new LLMPartTrasnformStream());
546
+ new TextDecoderStream2()
547
+ ).pipeThrough(new ServerSentEventTransformStream2()).pipeThrough(new MCPChunkFilterTransformStream(isBuildStage || isFillStage)).pipeThrough(new LLMChunkInjectorTransformStream()).pipeThrough(new LLMPartTrasnformStream());
418
548
  let finalResult = result;
419
549
  if (externalTransformers.length > 0) {
420
550
  finalResult = externalTransformers.reduce(
@@ -1659,6 +1789,9 @@ var RebuilderMap = {
1659
1789
  dept: rebuildDept,
1660
1790
  sn: rebuildSn,
1661
1791
  deptgroup: rebuildDeptGroup,
1792
+ flowState: defaultBuilder,
1793
+ flowstate: defaultBuilder,
1794
+ formula: defaultBuilder,
1662
1795
  unknown: defaultBuilder
1663
1796
  };
1664
1797
  var rebuildFieldsJsonStructure = (truncatedJson, subItemsOnly = false) => {
@@ -1676,9 +1809,12 @@ var rebuildFieldsJsonStructure = (truncatedJson, subItemsOnly = false) => {
1676
1809
  // src/stream-trasnformer/fields-json-transform-stream.ts
1677
1810
  var createFieldsJsonTransformStream = (enableJsonParser) => {
1678
1811
  let parser;
1812
+ let enqueueTextDelta;
1679
1813
  let id;
1814
+ let isFirstChunk = true;
1815
+ let passthroughMode = false;
1680
1816
  const chunkGuard = (chunk) => {
1681
- if (!enableJsonParser) {
1817
+ if (!enableJsonParser || passthroughMode) {
1682
1818
  return false;
1683
1819
  }
1684
1820
  if (chunk.type !== "text-delta" || !("delta" in chunk)) {
@@ -1695,19 +1831,28 @@ var createFieldsJsonTransformStream = (enableJsonParser) => {
1695
1831
  }
1696
1832
  },
1697
1833
  transform: (chunk, controller) => {
1698
- if (!parser) {
1834
+ if (!parser && !passthroughMode) {
1699
1835
  return;
1700
1836
  }
1701
1837
  try {
1702
1838
  if (chunkGuard(chunk)) {
1703
1839
  if ("id" in chunk && "delta" in chunk) {
1704
1840
  id = chunk.id;
1705
- parser.write(chunk.delta);
1841
+ let delta = chunk.delta;
1842
+ if (isFirstChunk) {
1843
+ delta = delta.replace(/^\uFEFF/, "");
1844
+ isFirstChunk = false;
1845
+ }
1846
+ parser.write(delta);
1847
+ } else {
1848
+ console.warn("Unexpected chunk format for JSON parsing:", chunk);
1849
+ controller.enqueue(chunk);
1706
1850
  }
1707
1851
  } else {
1708
1852
  controller.enqueue(chunk);
1709
1853
  }
1710
1854
  } catch (e) {
1855
+ console.log("write or enqueue error", e);
1711
1856
  controller.error(e);
1712
1857
  }
1713
1858
  },
@@ -1715,7 +1860,7 @@ var createFieldsJsonTransformStream = (enableJsonParser) => {
1715
1860
  parser = new JSONParser({
1716
1861
  paths: ["$.*"]
1717
1862
  });
1718
- const enqueueTextDelta = enableJsonParser ? createTextInfoEnqueuer(controller) : (content) => {
1863
+ enqueueTextDelta = enableJsonParser ? createTextInfoEnqueuer(controller) : (content) => {
1719
1864
  };
1720
1865
  parser.onValue = (parsedInfo) => {
1721
1866
  const value = parsedInfo.value;
@@ -1731,12 +1876,9 @@ var createFieldsJsonTransformStream = (enableJsonParser) => {
1731
1876
  id
1732
1877
  );
1733
1878
  };
1734
- let errorLogged = false;
1735
1879
  parser.onError = (err) => {
1736
- if (!errorLogged) {
1737
- console.error("JsonWidgetStream: JSON Parsing Error:", err);
1738
- errorLogged = true;
1739
- }
1880
+ console.error("JsonWidgetStream: JSON Parsing Error:", err);
1881
+ passthroughMode = true;
1740
1882
  };
1741
1883
  parser.onEnd = () => {
1742
1884
  enqueueTextDelta(