Open History to see the last commit
1import OpenAI from 'openai'
2import {
3 EventType,
4 isFileSource,
5 unsupportedFileSourceError,
6} from '@tanstack/ai'
7import { OpenAIBaseChatCompletionsTextAdapter } from '@tanstack/openai-base'
8import { generateId } from '@tanstack/ai-utils'
9import { resolveReasoning } from '@tanstack/ai/adapter-internals'
10import type { ResolvedReasoning } from '@tanstack/ai/adapter-internals'
11import {
12 BYTEPLUS_MODEL_INPUT_MODALITIES,
13 BYTEPLUS_MODEL_REASONING,
14 BYTEPLUS_STRUCTURED_OUTPUT_CHAT_MODELS,
15 emitsEncryptedContent,
16 supportsStructuredOutput,
17} from '../model-meta'
18import {
19 getBytePlusArkApiKeyFromEnv,
20 withBytePlusArkDefaults,
21} from '../utils/client'
22import type {
23 StructuredOutputOptions,
24 StructuredOutputResult,
25} from '@tanstack/ai/adapters'
26import type {
27 ContentPart,
28 ContentPartSource,
29 Modality,
30 ModelMessage,
31 AdapterYieldChunk,
32 TextOptions,
33} from '@tanstack/ai'
34import type {
35 ChatCompletionContentPart,
36 ChatCompletionMessageParam,
37} from 'openai/resources/chat/completions/completions'
38import type {
39 BYTEPLUS_CHAT_MODELS,
40 BytePlusChatModelToolCapabilitiesByName,
41 BytePlusModelReasoningByName,
42 ResolveInputModalities,
43 ResolveProviderOptions,
44} from '../model-meta'
45import type {
46 BytePlusAudioMetadata,
47 BytePlusChatContentPart,
48 BytePlusEncryptedContentFields,
49 BytePlusImageMetadata,
50 BytePlusInputAudioContentPart,
51 BytePlusMessageMetadataByModality,
52 BytePlusStreamDeltaExtras,
53 BytePlusVideoMetadata,
54} from '../message-types'
55import type { BytePlusArkConfig } from '../utils/client'
56import type { OpenAIBaseTextAdapterOptions } from '@tanstack/openai-base'
57
58type ResolveToolCapabilities<TModel extends string> =
59 TModel extends keyof BytePlusChatModelToolCapabilitiesByName
60 ? NonNullable<BytePlusChatModelToolCapabilitiesByName[TModel]>
61 : readonly []
62
63/**
64 * Configuration for the BytePlus text adapter.
65 */
66export interface BytePlusTextConfig
67 extends BytePlusArkConfig, OpenAIBaseTextAdapterOptions {}
68
69/**
70 * Re-export of the public provider options type.
71 */
72export type { BytePlusTextProviderOptions } from '../text/text-provider-options'
73
74/**
75 * BytePlus ModelArk Text (Chat) Adapter
76 *
77 * Tree-shakeable adapter for the Seed / GLM / DeepSeek / gpt-oss chat models
78 * on BytePlus ModelArk. Ark serves an OpenAI-compatible Chat Completions
79 * endpoint, so this drives the OpenAI SDK against Ark's `baseURL` — the same
80 * pattern as `ai-groq` and `ai-grok`.
81 *
82 * Three Ark behaviours are handled on top of the shared base:
83 *
84 * 1. **`reasoning_content` deltas** — Ark streams reasoning under
85 * `delta.reasoning_content` rather than the OpenAI `reasoning` field.
86 * 2. **`encrypted_content` round-trip** — thinking-summary models emit an
87 * opaque signature over the reasoning trace. See
88 * {@link BytePlusTextAdapter.processStreamChunks} and
89 * {@link BytePlusTextAdapter.convertMessage}.
90 * 3. **Per-model structured-output gating** — only 10 of the 18 shipped chat
91 * models honour `response_format: json_schema` (glm-4-7 accepts it and then
92 * ignores the schema), and Ark rejects `json_object` everywhere, so there
93 * is no JSON-mode fallback.
94 */
95/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */
96type ResolveReasoning<TModel extends string> =
97 TModel extends keyof BytePlusModelReasoningByName
98 ? BytePlusModelReasoningByName[TModel]
99 : never
100
101/**
102 * Ark's thinking fields for `chat({ reasoning })`: `thinking.type`, plus
103 * `reasoning_effort` when the level has an effort value. `off` sends only
104 * `disabled`, because Ark refuses an effort next to it.
105 */
106function arkThinking(resolved: ResolvedReasoning | undefined) {
107 if (!resolved) return {}
108 if (resolved.level === 'off') return { thinking: { type: 'disabled' } }
109 const effort = resolved.value
110 return effort === 'enabled'
111 ? { thinking: { type: 'enabled' } }
112 : { thinking: { type: 'enabled' }, reasoning_effort: effort }
113}
114
115export class BytePlusTextAdapter<
116 TModel extends (typeof BYTEPLUS_CHAT_MODELS)[number],
117 // `Record<string, any>` (not `unknown`) mirrors the OpenAI/Groq/Grok text
118 // adapters: the resolved provider options are an interface with no index
119 // signature, assignable to `Record<string, any>` but not to
120 // `Record<string, unknown>`. See issue #821.
121 TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,
122 TInputModalities extends ReadonlyArray<Modality> =
123 ResolveInputModalities<TModel>,
124 TToolCapabilities extends ReadonlyArray<string> =
125 ResolveToolCapabilities<TModel>,
126> extends OpenAIBaseChatCompletionsTextAdapter<
127 TModel,
128 TProviderOptions,
129 TInputModalities,
130 BytePlusMessageMetadataByModality,
131 TToolCapabilities,
132 ResolveReasoning<TModel>
133> {
134 override readonly kind = 'text' as const
135 override readonly name = 'byteplus' as const
136 override readonly inputModalities =
137 BYTEPLUS_MODEL_INPUT_MODALITIES[this.model]
138
139 constructor(config: BytePlusTextConfig, model: TModel) {
140 super(
141 model,
142 'byteplus',
143 new OpenAI(withBytePlusArkDefaults(config)),
144 config,
145 )
146 }
147
148 /**
149 * Ark has no error code for a context overflow. It answers
150 * `InvalidParameter` for every bad request, so the message text is the
151 * only signal.
152 */
153 protected override isContextOverflow(error: {
154 message: string
155 code: string | undefined
156 }): boolean {
157 return (
158 super.isContextOverflow(error) ||
159 (error.code === 'InvalidParameter' &&
160 error.message.includes('exceed max message tokens'))
161 )
162 }
163
164 /**
165 * Adds Ark's thinking fields for `chat({ reasoning })`. They are Ark
166 * fields that the OpenAI SDK type does not list, so they go on with
167 * Object.assign.
168 */
169 protected override mapOptionsToRequest(options: TextOptions) {
170 return Object.assign(
171 super.mapOptionsToRequest(options),
172 arkThinking(
173 resolveReasoning(
174 options.reasoning,
175 BYTEPLUS_MODEL_REASONING[options.model],
176 ),
177 ),
178 )
179 }
180
181 /**
182 * Surfaces Ark's reasoning deltas. Thinking-enabled models stream the
183 * reasoning trace as `delta.reasoning_content` (the OpenAI chunk shape has
184 * no reasoning field); the base routes this hook through both `chatStream`
185 * and `structuredOutputStream`.
186 */
187 protected override extractReasoning(
188 chunk: OpenAI.Chat.Completions.ChatCompletionChunk,
189 ): { text: string } | undefined {
190 const delta = chunk.choices?.[0]?.delta as
191 | BytePlusStreamDeltaExtras
192 | undefined
193 const raw = delta?.reasoning_content
194 if (typeof raw === 'string' && raw.length > 0) {
195 return { text: raw }
196 }
197 return undefined
198 }
199
200 /**
201 * Captures Ark's `encrypted_content` and sends it as a
202 * `REASONING_ENCRYPTED_VALUE` for the reasoning message, right after the
203 * reasoning step's `STEP_FINISHED`. Its `entityId` is the reasoning
204 * message id, so an AG-UI client finds that message.
205 *
206 * On a thinking-summary model Ark streams the whole blob as one dedicated
207 * chunk (empty `content` and `reasoning_content`) sitting between the
208 * reasoning deltas and the content deltas — so it is always captured before
209 * the base closes the reasoning lifecycle at the first content delta.
210 *
211 * The encrypted value is the framework's provider-signature seam: the chat
212 * engine stores it on the `ThinkingPart`, which
213 * `buildAssistantMessages` carries into `ModelMessage.thinking[].signature`,
214 * which {@link BytePlusTextAdapter.convertMessage} echoes back to Ark on the
215 * next turn. No base-class change is needed — this is the same round-trip
216 * Anthropic's thinking signatures use.
217 *
218 * Only `chatStream` is covered: `structuredOutputStream` drives the SDK
219 * directly in the base with no per-chunk seam, so a structured-output turn
220 * does not capture the blob. Ark accepts a following turn without it, so the
221 * consequence is a lost reasoning-cache hit, not a failed request.
222 */
223 protected override async *processStreamChunks(
224 stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>,
225 options: TextOptions,
226 aguiState: {
227 runId: string
228 threadId: string
229 messageId: string
230 hasEmittedRunStarted: boolean
231 },
232 ): AsyncIterable<AdapterYieldChunk> {
233 const captured: { encryptedContent?: string } = {}
234 let reasoningMessageId: string | undefined
235
236 for await (const event of super.processStreamChunks(
237 captureEncryptedContent(stream, captured),
238 options,
239 aguiState,
240 )) {
241 if (event.type === EventType.REASONING_MESSAGE_START) {
242 reasoningMessageId = event.messageId
243 }
244 if (
245 event.type === EventType.STEP_FINISHED &&
246 captured.encryptedContent !== undefined &&
247 event.signature === undefined &&
248 reasoningMessageId !== undefined
249 ) {
250 yield event
251 yield {
252 type: EventType.REASONING_ENCRYPTED_VALUE,
253 subtype: 'message' as const,
254 entityId: reasoningMessageId,
255 encryptedValue: captured.encryptedContent,
256 model: event.model,
257 timestamp: event.timestamp,
258 }
259 continue
260 }
261 yield event
262 }
263 }
264
265 /**
266 * Echoes a captured `encrypted_content` blob back on outgoing assistant
267 * messages so multi-turn conversations replay it verbatim, as Ark's
268 * thinking-summary docs require.
269 *
270 * The gate is `emitsEncryptedContent(this.model)` — the model being called
271 * now, not the provenance of the history. That guarantees a signature is
272 * never sent to a model that has no `encrypted_content` concept. It does
273 * NOT identify who produced the signature: `ModelMessage` carries no
274 * provider field, so a foreign signature (e.g. an Anthropic thinking
275 * signature in replayed cross-provider history) WILL be forwarded when the
276 * current model is a thinking-summary model. No shape guard is attempted —
277 * the blob is opaque and Ark is the only party that can validate it.
278 *
279 * Absence is never an error: a live probe confirmed Ark accepts a turn whose
280 * assistant message omits `encrypted_content`.
281 */
282 protected override convertMessage(
283 message: ModelMessage,
284 ): ChatCompletionMessageParam {
285 const converted = super.convertMessage(message)
286 if (converted.role !== 'assistant' || !emitsEncryptedContent(this.model)) {
287 return converted
288 }
289
290 const encryptedContent = lastThinkingSignature(message)
291 if (encryptedContent === undefined) return converted
292
293 // Intersection rather than a cast: `encrypted_content` is an Ark-only
294 // field with no slot on the OpenAI message param, and the intersection is
295 // still assignable to `ChatCompletionMessageParam`.
296 const withEncrypted: typeof converted & BytePlusEncryptedContentFields = {
297 ...converted,
298 encrypted_content: encryptedContent,
299 }
300 return withEncrypted
301 }
302
303 /**
304 * Adds the Ark-only content parts on top of the base's text/image handling:
305 * `video_url`, URL-addressed `input_audio`, and the extra `image_url`
306 * fields (`detail: 'xhigh'`, `image_pixel_limit`).
307 */
308 protected override convertContentPart(
309 part: ContentPart,
310 ): ChatCompletionContentPart | null {
311 if (part.type === 'image') {
312 const metadata = part.metadata as BytePlusImageMetadata | undefined
313 return asChatContentPart({
314 type: 'image_url',
315 image_url: {
316 url: toUrlOrDataUri(part.source),
317 detail: metadata?.detail ?? 'auto',
318 ...(metadata?.image_pixel_limit && {
319 image_pixel_limit: metadata.image_pixel_limit,
320 }),
321 },
322 })
323 }
324
325 if (part.type === 'video') {
326 const metadata = part.metadata as BytePlusVideoMetadata | undefined
327 return asChatContentPart({
328 type: 'video_url',
329 video_url: {
330 url: toUrlOrDataUri(part.source),
331 ...(metadata?.fps !== undefined && { fps: metadata.fps }),
332 },
333 })
334 }
335
336 if (part.type === 'audio') {
337 const metadata = part.metadata as BytePlusAudioMetadata | undefined
338 if (isFileSource(part.source)) {
339 throw unsupportedFileSourceError('byteplus')
340 }
341 // Ark takes audio either by URL or as inline base64 with an explicit
342 // container format; unlike images there is no data-URI form.
343 if (part.source.type === 'url') {
344 return asChatContentPart({
345 type: 'input_audio',
346 input_audio: { url: part.source.value },
347 })
348 }
349 const format = metadata?.format ?? audioFormatFromMimeType(part.source)
350 if (format === undefined) {
351 throw new Error(
352 `Audio content part for ${this.name} has an unrecognised mimeType ` +
353 `(${part.source.mimeType || 'none'}). Set the container format ` +
354 `explicitly via the part's metadata.format, or supply a URL source.`,
355 )
356 }
357 return asChatContentPart({
358 type: 'input_audio',
359 input_audio: { data: stripDataUriPrefix(part.source.value), format },
360 })
361 }
362
363 return super.convertContentPart(part)
364 }
365
366 /**
367 * Only the models in {@link BYTEPLUS_STRUCTURED_OUTPUT_CHAT_MODELS} accept
368 * `response_format: json_schema`; the rest reject it with a 400.
369 *
370 * Returning `false` for a rejecting model does not make structured output
371 * work — Ark has no `json_object` fallback to downgrade to. What it buys is
372 * keeping `response_format` out of the request the engine would otherwise
373 * build: with the hook false the engine takes its separate finalization
374 * path, and the guard in {@link BytePlusTextAdapter.structuredOutput} /
375 * {@link BytePlusTextAdapter.structuredOutputStream} stops that *before*
376 * any HTTP call. So a `chat({ outputSchema })` on a rejecting model fails
377 * loudly, named, without a schema Ark would 400 on ever leaving the
378 * process — rather than 400-ing on every turn, or (worse) parsing prose as
379 * if it were JSON.
380 *
381 * Tools without a schema are unaffected: `tools` alone never involves
382 * `response_format`.
383 */
384 override supportsCombinedToolsAndSchema(): boolean {
385 return supportsStructuredOutput(this.model)
386 }
387
388 override async structuredOutput(
389 options: StructuredOutputOptions<TProviderOptions>,
390 ): Promise<StructuredOutputResult<unknown>> {
391 const unsupported = this.structuredOutputUnsupportedMessage()
392 if (unsupported) {
393 options.chatOptions.logger.errors(
394 `${this.name}.structuredOutput unsupported model`,
395 {
396 error: { message: unsupported },
397 source: `${this.name}.structuredOutput`,
398 },
399 )
400 throw new Error(unsupported)
401 }
402 return await super.structuredOutput(options)
403 }
404
405 override async *structuredOutputStream(
406 options: StructuredOutputOptions<TProviderOptions>,
407 ): AsyncIterable<AdapterYieldChunk> {
408 const unsupported = this.structuredOutputUnsupportedMessage()
409 if (unsupported) {
410 // Mirror the base's contract: failures inside structuredOutputStream
411 // surface as a RUN_STARTED → RUN_ERROR pair rather than a throw, so
412 // consumers keep a single error-handling path.
413 const runId = generateId(this.name)
414 yield {
415 type: EventType.RUN_STARTED,
416 runId,
417 threadId: options.chatOptions.threadId ?? generateId(this.name),
418 model: options.chatOptions.model,
419 timestamp: Date.now(),
420 parentRunId: options.chatOptions.parentRunId,
421 }
422 yield {
423 type: EventType.RUN_ERROR,
424 runId,
425 model: options.chatOptions.model,
426 timestamp: Date.now(),
427 message: unsupported,
428 code: 'unsupported-structured-output',
429 error: { message: unsupported, code: 'unsupported-structured-output' },
430 }
431 options.chatOptions.logger.errors(
432 `${this.name}.structuredOutputStream unsupported model`,
433 {
434 error: { message: unsupported },
435 source: `${this.name}.structuredOutputStream`,
436 },
437 )
438 return
439 }
440 yield* super.structuredOutputStream(options)
441 }
442
443 /**
444 * Explains why structured output is unavailable, or `undefined` when the
445 * model supports it. Ark rejects `response_format: json_object` on every
446 * model, so there is no JSON-mode fallback to degrade to — failing loud
447 * here beats a raw upstream 400.
448 */
449 private structuredOutputUnsupportedMessage(): string | undefined {
450 if (supportsStructuredOutput(this.model)) return undefined
451 return (
452 `BytePlus model ${this.model} does not support structured output — Ark ` +
453 `rejects both response_format json_schema and json_object on it. Use ` +
454 `one of: ${BYTEPLUS_STRUCTURED_OUTPUT_CHAT_MODELS.join(', ')}.`
455 )
456 }
457}
458
459/**
460 * Passes Ark's chunks through untouched while recording the single
461 * `encrypted_content` blob a thinking-summary model emits.
462 */
463async function* captureEncryptedContent(
464 stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>,
465 captured: { encryptedContent?: string },
466): AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk> {
467 for await (const chunk of stream) {
468 const delta = chunk.choices?.[0]?.delta as
469 | BytePlusStreamDeltaExtras
470 | undefined
471 const blob = delta?.encrypted_content
472 if (typeof blob === 'string' && blob.length > 0) {
473 captured.encryptedContent = blob
474 }
475 yield chunk
476 }
477}
478
479/**
480 * The blob to echo back for an assistant message: the last thinking step that
481 * carries a signature.
482 */
483function lastThinkingSignature(message: ModelMessage): string | undefined {
484 const thinking = message.thinking
485 if (!thinking) return undefined
486 for (let i = thinking.length - 1; i >= 0; i--) {
487 const signature = thinking[i]?.signature
488 if (signature) return signature
489 }
490 return undefined
491}
492
493/**
494 * The one place the Ark content-part dialect meets the OpenAI SDK's request
495 * types.
496 *
497 * Ark's union is a superset of OpenAI's: `video_url` has no OpenAI arm at all,
498 * `input_audio` additionally accepts a `url`, and `image_url` carries
499 * `detail: 'xhigh'` and `image_pixel_limit`. `ChatCompletionContentPart` is a
500 * closed type alias in the SDK, so no interface augmentation can admit those
501 * arms and no narrowing can produce them — widening to `object` keeps this to
502 * a single downcast rather than spreading one through each branch of
503 * {@link BytePlusTextAdapter.convertContentPart}.
504 */
505function asChatContentPart(
506 part: BytePlusChatContentPart,
507): ChatCompletionContentPart {
508 const arkPart: object = part
509 return arkPart as ChatCompletionContentPart
510}
511
512/**
513 * Renders a content source as the URL string Ark expects: URLs pass through,
514 * inline base64 becomes a `data:` URI.
515 */
516function toUrlOrDataUri(source: ContentPartSource): string {
517 if (isFileSource(source)) throw unsupportedFileSourceError('byteplus')
518 if (source.type !== 'data' || source.value.startsWith('data:')) {
519 return source.value
520 }
521 // A missing mimeType would interpolate as "data:undefined;base64,…" and be
522 // rejected, so fall back the same way the OpenAI base does.
523 return `data:${source.mimeType || 'application/octet-stream'};base64,${source.value}`
524}
525
526/**
527 * Strips a `data:` prefix so inline audio is sent as bare base64.
528 */
529function stripDataUriPrefix(value: string): string {
530 const comma = value.startsWith('data:') ? value.indexOf(',') : -1
531 return comma === -1 ? value : value.slice(comma + 1)
532}
533
534const AUDIO_FORMAT_BY_MIME_SUBTYPE: Record<
535 string,
536 NonNullable<BytePlusInputAudioContentPart['input_audio']['format']>
537> = {
538 mpeg: 'mp3',
539 mp3: 'mp3',
540 wav: 'wav',
541 'x-wav': 'wav',
542 wave: 'wav',
543 ogg: 'ogg',
544 flac: 'flac',
545 'x-flac': 'flac',
546 mp4: 'm4a',
547 m4a: 'm4a',
548 'x-m4a': 'm4a',
549 aac: 'aac',
550 pcm: 'pcm',
551 l16: 'pcm',
552}
553
554/**
555 * Maps an audio part's mimeType to Ark's container format token.
556 */
557function audioFormatFromMimeType(
558 source: ContentPartSource,
559):
560 | NonNullable<BytePlusInputAudioContentPart['input_audio']['format']>
561 | undefined {
562 const mimeType = source.mimeType
563 if (!mimeType) return undefined
564 const subtype = mimeType.split(';')[0]?.split('/')[1]?.toLowerCase()
565 return subtype ? AUDIO_FORMAT_BY_MIME_SUBTYPE[subtype] : undefined
566}
567
568/**
569 * Creates a BytePlus text adapter with an explicit API key.
570 *
571 * @param model - The chat model id (e.g., `'seed-2-0-lite-260428'`)
572 * @param apiKey - Your BytePlus Ark API key
573 * @param config - Optional additional configuration
574 *
575 * @example
576 * ```typescript
577 * const adapter = createBytePlusText('seed-2-0-lite-260428', 'ark-...')
578 * ```
579 */
580export function createBytePlusText<
581 TModel extends (typeof BYTEPLUS_CHAT_MODELS)[number],
582>(
583 model: TModel,
584 apiKey: string,
585 config?: Omit<BytePlusTextConfig, 'apiKey'>,
586): BytePlusTextAdapter<TModel> {
587 return new BytePlusTextAdapter({ apiKey, ...config }, model)
588}
589
590/**
591 * Creates a BytePlus text adapter with the API key read from `ARK_API_KEY`.
592 *
593 * @param model - The chat model id (e.g., `'seed-2-0-lite-260428'`)
594 * @param config - Optional configuration (excluding `apiKey`)
595 * @throws Error if `ARK_API_KEY` is not set
596 *
597 * @example
598 * ```typescript
599 * const adapter = byteplusText('seed-2-0-lite-260428')
600 *
601 * const stream = chat({
602 * adapter,
603 * messages: [{ role: 'user', content: 'Hello!' }],
604 * })
605 * ```
606 */
607export function byteplusText<
608 TModel extends (typeof BYTEPLUS_CHAT_MODELS)[number],
609>(
610 model: TModel,
611 config?: Omit<BytePlusTextConfig, 'apiKey'>,
612): BytePlusTextAdapter<TModel> {
613 const apiKey = getBytePlusArkApiKeyFromEnv()
614 return createBytePlusText(model, apiKey, config)
615}