Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

text.ts

612 lines21.0 KB

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 }
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 before its
203 * `REASONING_MESSAGE_END`. Its `entityId` is the reasoning message id, so an
204 * 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.REASONING_MESSAGE_END &&
246 captured.encryptedContent !== undefined &&
247 event.messageId === reasoningMessageId
248 ) {
249 yield {
250 type: EventType.REASONING_ENCRYPTED_VALUE,
251 subtype: 'message' as const,
252 entityId: reasoningMessageId,
253 encryptedValue: captured.encryptedContent,
254 model: event.model,
255 timestamp: event.timestamp,
256 }
257 }
258 yield event
259 }
260 }
261​
262 /**
263 * Echoes a captured `encrypted_content` blob back on outgoing assistant
264 * messages so multi-turn conversations replay it verbatim, as Ark's
265 * thinking-summary docs require.
266 *
267 * The gate is `emitsEncryptedContent(this.model)` — the model being called
268 * now, not the provenance of the history. That guarantees a signature is
269 * never sent to a model that has no `encrypted_content` concept. It does
270 * NOT identify who produced the signature: `ModelMessage` carries no
271 * provider field, so a foreign signature (e.g. an Anthropic thinking
272 * signature in replayed cross-provider history) WILL be forwarded when the
273 * current model is a thinking-summary model. No shape guard is attempted —
274 * the blob is opaque and Ark is the only party that can validate it.
275 *
276 * Absence is never an error: a live probe confirmed Ark accepts a turn whose
277 * assistant message omits `encrypted_content`.
278 */
279 protected override convertMessage(
280 message: ModelMessage,
281 ): ChatCompletionMessageParam {
282 const converted = super.convertMessage(message)
283 if (converted.role !== 'assistant' || !emitsEncryptedContent(this.model)) {
284 return converted
285 }
286​
287 const encryptedContent = lastThinkingSignature(message)
288 if (encryptedContent === undefined) return converted
289​
290 // Intersection rather than a cast: `encrypted_content` is an Ark-only
291 // field with no slot on the OpenAI message param, and the intersection is
292 // still assignable to `ChatCompletionMessageParam`.
293 const withEncrypted: typeof converted & BytePlusEncryptedContentFields = {
294 ...converted,
295 encrypted_content: encryptedContent,
296 }
297 return withEncrypted
298 }
299​
300 /**
301 * Adds the Ark-only content parts on top of the base's text/image handling:
302 * `video_url`, URL-addressed `input_audio`, and the extra `image_url`
303 * fields (`detail: 'xhigh'`, `image_pixel_limit`).
304 */
305 protected override convertContentPart(
306 part: ContentPart,
307 ): ChatCompletionContentPart | null {
308 if (part.type === 'image') {
309 const metadata = part.metadata as BytePlusImageMetadata | undefined
310 return asChatContentPart({
311 type: 'image_url',
312 image_url: {
313 url: toUrlOrDataUri(part.source),
314 detail: metadata?.detail ?? 'auto',
315 ...(metadata?.image_pixel_limit && {
316 image_pixel_limit: metadata.image_pixel_limit,
317 }),
318 },
319 })
320 }
321​
322 if (part.type === 'video') {
323 const metadata = part.metadata as BytePlusVideoMetadata | undefined
324 return asChatContentPart({
325 type: 'video_url',
326 video_url: {
327 url: toUrlOrDataUri(part.source),
328 ...(metadata?.fps !== undefined && { fps: metadata.fps }),
329 },
330 })
331 }
332​
333 if (part.type === 'audio') {
334 const metadata = part.metadata as BytePlusAudioMetadata | undefined
335 if (isFileSource(part.source)) {
336 throw unsupportedFileSourceError('byteplus')
337 }
338 // Ark takes audio either by URL or as inline base64 with an explicit
339 // container format; unlike images there is no data-URI form.
340 if (part.source.type === 'url') {
341 return asChatContentPart({
342 type: 'input_audio',
343 input_audio: { url: part.source.value },
344 })
345 }
346 const format = metadata?.format ?? audioFormatFromMimeType(part.source)
347 if (format === undefined) {
348 throw new Error(
349 `Audio content part for ${this.name} has an unrecognised mimeType ` +
350 `(${part.source.mimeType || 'none'}). Set the container format ` +
351 `explicitly via the part's metadata.format, or supply a URL source.`,
352 )
353 }
354 return asChatContentPart({
355 type: 'input_audio',
356 input_audio: { data: stripDataUriPrefix(part.source.value), format },
357 })
358 }
359​
360 return super.convertContentPart(part)
361 }
362​
363 /**
364 * Only the models in {@link BYTEPLUS_STRUCTURED_OUTPUT_CHAT_MODELS} accept
365 * `response_format: json_schema`; the rest reject it with a 400.
366 *
367 * Returning `false` for a rejecting model does not make structured output
368 * work — Ark has no `json_object` fallback to downgrade to. What it buys is
369 * keeping `response_format` out of the request the engine would otherwise
370 * build: with the hook false the engine takes its separate finalization
371 * path, and the guard in {@link BytePlusTextAdapter.structuredOutput} /
372 * {@link BytePlusTextAdapter.structuredOutputStream} stops that *before*
373 * any HTTP call. So a `chat({ outputSchema })` on a rejecting model fails
374 * loudly, named, without a schema Ark would 400 on ever leaving the
375 * process — rather than 400-ing on every turn, or (worse) parsing prose as
376 * if it were JSON.
377 *
378 * Tools without a schema are unaffected: `tools` alone never involves
379 * `response_format`.
380 */
381 override supportsCombinedToolsAndSchema(): boolean {
382 return supportsStructuredOutput(this.model)
383 }
384​
385 override async structuredOutput(
386 options: StructuredOutputOptions<TProviderOptions>,
387 ): Promise<StructuredOutputResult<unknown>> {
388 const unsupported = this.structuredOutputUnsupportedMessage()
389 if (unsupported) {
390 options.chatOptions.logger.errors(
391 `${this.name}.structuredOutput unsupported model`,
392 {
393 error: { message: unsupported },
394 source: `${this.name}.structuredOutput`,
395 },
396 )
397 throw new Error(unsupported)
398 }
399 return await super.structuredOutput(options)
400 }
401​
402 override async *structuredOutputStream(
403 options: StructuredOutputOptions<TProviderOptions>,
404 ): AsyncIterable<AdapterYieldChunk> {
405 const unsupported = this.structuredOutputUnsupportedMessage()
406 if (unsupported) {
407 // Mirror the base's contract: failures inside structuredOutputStream
408 // surface as a RUN_STARTED → RUN_ERROR pair rather than a throw, so
409 // consumers keep a single error-handling path.
410 const runId = generateId(this.name)
411 yield {
412 type: EventType.RUN_STARTED,
413 runId,
414 threadId: options.chatOptions.threadId,
415 model: options.chatOptions.model,
416 timestamp: Date.now(),
417 parentRunId: options.chatOptions.parentRunId,
418 }
419 yield {
420 type: EventType.RUN_ERROR,
421 runId,
422 model: options.chatOptions.model,
423 timestamp: Date.now(),
424 message: unsupported,
425 code: 'unsupported-structured-output',
426 error: { message: unsupported, code: 'unsupported-structured-output' },
427 }
428 options.chatOptions.logger.errors(
429 `${this.name}.structuredOutputStream unsupported model`,
430 {
431 error: { message: unsupported },
432 source: `${this.name}.structuredOutputStream`,
433 },
434 )
435 return
436 }
437 yield* super.structuredOutputStream(options)
438 }
439​
440 /**
441 * Explains why structured output is unavailable, or `undefined` when the
442 * model supports it. Ark rejects `response_format: json_object` on every
443 * model, so there is no JSON-mode fallback to degrade to — failing loud
444 * here beats a raw upstream 400.
445 */
446 private structuredOutputUnsupportedMessage(): string | undefined {
447 if (supportsStructuredOutput(this.model)) return undefined
448 return (
449 `BytePlus model ${this.model} does not support structured output — Ark ` +
450 `rejects both response_format json_schema and json_object on it. Use ` +
451 `one of: ${BYTEPLUS_STRUCTURED_OUTPUT_CHAT_MODELS.join(', ')}.`
452 )
453 }
455​
456/**
457 * Passes Ark's chunks through untouched while recording the single
458 * `encrypted_content` blob a thinking-summary model emits.
459 */
460async function* captureEncryptedContent(
461 stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>,
462 captured: { encryptedContent?: string },
463): AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk> {
464 for await (const chunk of stream) {
465 const delta = chunk.choices?.[0]?.delta as
466 | BytePlusStreamDeltaExtras
467 | undefined
468 const blob = delta?.encrypted_content
469 if (typeof blob === 'string' && blob.length > 0) {
470 captured.encryptedContent = blob
471 }
472 yield chunk
473 }
475​
476/**
477 * The blob to echo back for an assistant message: the last thinking step that
478 * carries a signature.
479 */
480function lastThinkingSignature(message: ModelMessage): string | undefined {
481 const thinking = message.thinking
482 if (!thinking) return undefined
483 for (let i = thinking.length - 1; i >= 0; i--) {
484 const signature = thinking[i]?.signature
485 if (signature) return signature
486 }
487 return undefined
489​
490/**
491 * The one place the Ark content-part dialect meets the OpenAI SDK's request
492 * types.
493 *
494 * Ark's union is a superset of OpenAI's: `video_url` has no OpenAI arm at all,
495 * `input_audio` additionally accepts a `url`, and `image_url` carries
496 * `detail: 'xhigh'` and `image_pixel_limit`. `ChatCompletionContentPart` is a
497 * closed type alias in the SDK, so no interface augmentation can admit those
498 * arms and no narrowing can produce them — widening to `object` keeps this to
499 * a single downcast rather than spreading one through each branch of
500 * {@link BytePlusTextAdapter.convertContentPart}.
501 */
502function asChatContentPart(
503 part: BytePlusChatContentPart,
504): ChatCompletionContentPart {
505 const arkPart: object = part
506 return arkPart as ChatCompletionContentPart
508​
509/**
510 * Renders a content source as the URL string Ark expects: URLs pass through,
511 * inline base64 becomes a `data:` URI.
512 */
513function toUrlOrDataUri(source: ContentPartSource): string {
514 if (isFileSource(source)) throw unsupportedFileSourceError('byteplus')
515 if (source.type !== 'data' || source.value.startsWith('data:')) {
516 return source.value
517 }
518 // A missing mimeType would interpolate as "data:undefined;base64,…" and be
519 // rejected, so fall back the same way the OpenAI base does.
520 return `data:${source.mimeType || 'application/octet-stream'};base64,${source.value}`
522​
523/**
524 * Strips a `data:` prefix so inline audio is sent as bare base64.
525 */
526function stripDataUriPrefix(value: string): string {
527 const comma = value.startsWith('data:') ? value.indexOf(',') : -1
528 return comma === -1 ? value : value.slice(comma + 1)
530​
531const AUDIO_FORMAT_BY_MIME_SUBTYPE: Record<
532 string,
533 NonNullable<BytePlusInputAudioContentPart['input_audio']['format']>
534> = {
535 mpeg: 'mp3',
536 mp3: 'mp3',
537 wav: 'wav',
538 'x-wav': 'wav',
539 wave: 'wav',
540 ogg: 'ogg',
541 flac: 'flac',
542 'x-flac': 'flac',
543 mp4: 'm4a',
544 m4a: 'm4a',
545 'x-m4a': 'm4a',
546 aac: 'aac',
547 pcm: 'pcm',
548 l16: 'pcm',
550​
551/**
552 * Maps an audio part's mimeType to Ark's container format token.
553 */
554function audioFormatFromMimeType(
555 source: ContentPartSource,
556):
557 | NonNullable<BytePlusInputAudioContentPart['input_audio']['format']>
558 | undefined {
559 const mimeType = source.mimeType
560 if (!mimeType) return undefined
561 const subtype = mimeType.split(';')[0]?.split('/')[1]?.toLowerCase()
562 return subtype ? AUDIO_FORMAT_BY_MIME_SUBTYPE[subtype] : undefined
564​
565/**
566 * Creates a BytePlus text adapter with an explicit API key.
567 *
568 * @param model - The chat model id (e.g., `'seed-2-0-lite-260428'`)
569 * @param apiKey - Your BytePlus Ark API key
570 * @param config - Optional additional configuration
571 *
572 * @example
573 * ```typescript
574 * const adapter = createBytePlusText('seed-2-0-lite-260428', 'ark-...')
575 * ```
576 */
577export function createBytePlusText<
578 TModel extends (typeof BYTEPLUS_CHAT_MODELS)[number],
579>(
580 model: TModel,
581 apiKey: string,
582 config?: Omit<BytePlusTextConfig, 'apiKey'>,
583): BytePlusTextAdapter<TModel> {
584 return new BytePlusTextAdapter({ apiKey, ...config }, model)
586​
587/**
588 * Creates a BytePlus text adapter with the API key read from `ARK_API_KEY`.
589 *
590 * @param model - The chat model id (e.g., `'seed-2-0-lite-260428'`)
591 * @param config - Optional configuration (excluding `apiKey`)
592 * @throws Error if `ARK_API_KEY` is not set
593 *
594 * @example
595 * ```typescript
596 * const adapter = byteplusText('seed-2-0-lite-260428')
597 *
598 * const stream = chat({
599 * adapter,
600 * messages: [{ role: 'user', content: 'Hello!' }],
601 * })
602 * ```
603 */
604export function byteplusText<
605 TModel extends (typeof BYTEPLUS_CHAT_MODELS)[number],
606>(
607 model: TModel,
608 config?: Omit<BytePlusTextConfig, 'apiKey'>,
609): BytePlusTextAdapter<TModel> {
610 const apiKey = getBytePlusArkApiKeyFromEnv()
611 return createBytePlusText(model, apiKey, config)