feat: extract @tanstack/openai-base and @tanstack/ai-utils packages #409
MergedAlemTuzlakmerged 31 commits into
main fromrefs/pull/409/headmerged by AlemTuzlak View on GitHub- packages/typescript/ai-groq/src/utils/schema-converter.ts lines 18 to 37Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -28,3 +18,20 @@18+ if (result.properties && typeof result.properties === 'object') {19+ const properties: Record<string, any> = {}20+ for (const [key, value] of Object.entries(21+ result.properties as Record<string, any>,22+ )) {23+ properties[key] =24+ typeof value === 'object' && value !== null && !Array.isArray(value)25+ ? removeEmptyRequired(value)26+ : value2827 }29- return result as T28+ result.properties = properties29+ }30+31+ if (32+ result.items &&33+ typeof result.items === 'object' &&34+ !Array.isArray(result.items)35+ ) {36+ result.items = removeEmptyRequired(result.items)3037 }packages/typescript/openai-base/src/adapters/chat-completions-text.ts lines 84 to 98Resolvedby tombeckenham@@ -0,0 +61,21 @@61+ async *chatStream(62+ options: TextOptions<TProviderOptions>,63+ ): AsyncIterable<StreamChunk> {64+ const requestParams = this.mapOptionsToRequest(options)65+ const timestamp = Date.now()66+67+ // AG-UI lifecycle tracking (mutable state object for ESLint compatibility)68+ const aguiState = {69+ runId: generateId(this.name),70+ messageId: generateId(this.name),71+ timestamp,72+ hasEmittedRunStarted: false,73+ }74+75+ try {76+ const stream = await this.client.chat.completions.create({77+ ...requestParams,78+ stream: true,79+ })80+81+ yield* this.processStreamChunks(stream, options, aguiState)packages/typescript/openai-base/src/adapters/chat-completions-text.ts lines 141 to 152OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +132,21 @@132+ const { chatOptions, outputSchema } = options133+ const requestParams = this.mapOptionsToRequest(chatOptions)134+135+ const jsonSchema = this.makeStructuredOutputCompatible(136+ outputSchema,137+ outputSchema.required || [],138+ )139+140+ try {141+ const response = await this.client.chat.completions.create({142+ ...requestParams,143+ stream: false,144+ response_format: {145+ type: 'json_schema',146+ json_schema: {147+ name: 'structured_output',148+ schema: jsonSchema,149+ strict: true,150+ },151+ },152+ })packages/typescript/openai-base/src/adapters/chat-completions-text.ts lines 585 to 637Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +428,21 @@428+ messages.push({429+ role: 'system',430+ content: options.systemPrompts.join('\n'),431+ })432+ }433+434+ // Convert messages435+ for (const message of options.messages) {436+ messages.push(this.convertMessage(message))437+ }438+439+ return {440+ model: options.model,441+ messages,442+ temperature: options.temperature,443+ max_tokens: options.maxTokens,444+ top_p: options.topP,445+ tools: tools as Array<OpenAI_SDK.Chat.Completions.ChatCompletionTool>,446+ stream: true,447+ stream_options: { include_usage: true },448+ }packages/typescript/openai-base/src/adapters/responses-text.ts lines 88 to 91Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +62,21 @@62+ constructor(63+ config: OpenAICompatibleClientConfig,64+ model: TModel,65+ name: string = 'openai-compatible-responses',66+ ) {67+ super({}, model)68+ this.name = name69+ this.client = createOpenAICompatibleClient(config)70+ }71+72+ async *chatStream(73+ options: TextOptions<TProviderOptions>,74+ ): AsyncIterable<StreamChunk> {75+ // Track tool call metadata by unique ID76+ // Responses API streams tool calls with deltas — first chunk has ID/name,77+ // subsequent chunks only have args.78+ // We assign our own indices as we encounter unique tool call IDs.79+ const toolCallMetadata = new Map<80+ string,81+ { index: number; name: string; started: boolean }82+ >()packages/typescript/openai-base/src/adapters/transcription.ts lines 62 to 66Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +45,21 @@45+ const { model, audio, language, prompt, responseFormat, modelOptions } =46+ options47+48+ // Convert audio input to File object49+ const file = this.prepareAudioFile(audio)50+51+ // Build request52+ const request: OpenAI_SDK.Audio.TranscriptionCreateParams = {53+ model,54+ file,55+ language,56+ prompt,57+ response_format: this.mapResponseFormat(responseFormat),58+ ...modelOptions,59+ }60+61+ // Call API - use verbose_json to get timestamps when available62+ const useVerbose =63+ responseFormat === 'verbose_json' ||64+ (!responseFormat && model !== 'whisper-1')65+packages/typescript/openai-base/src/adapters/transcription.ts lines 123 to 161OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +127,21 @@127+ const parts = audio.split(',')128+ const header = parts[0]129+ const base64Data = parts[1] || ''130+ const mimeMatch = header?.match(/data:([^;]+)/)131+ const mimeType = mimeMatch?.[1] || 'audio/mpeg'132+ const binaryStr = atob(base64Data)133+ const bytes = new Uint8Array(binaryStr.length)134+ for (let i = 0; i < binaryStr.length; i++) {135+ bytes[i] = binaryStr.charCodeAt(i)136+ }137+ const extension = mimeType.split('/')[1] || 'mp3'138+ return new File([bytes], `audio.${extension}`, { type: mimeType })139+ }140+141+ // Assume raw base64142+ const binaryStr = atob(audio)143+ const bytes = new Uint8Array(binaryStr.length)144+ for (let i = 0; i < binaryStr.length; i++) {145+ bytes[i] = binaryStr.charCodeAt(i)146+ }147+ return new File([bytes], 'audio.mp3', { type: 'audio/mpeg' })packages/typescript/openai-base/src/adapters/tts.ts lines 50 to 57Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +36,21 @@36+ }37+38+ async generateSpeech(39+ options: TTSOptions<TProviderOptions>,40+ ): Promise<TTSResult> {41+ const { model, text, voice, format, speed, modelOptions } = options42+43+ // Validate inputs44+ this.validateAudioInput(text)45+ this.validateSpeed(speed)46+ this.validateInstructions(model, modelOptions)47+48+ // Build request49+ const request: OpenAI_SDK.Audio.SpeechCreateParams = {50+ model,51+ input: text,52+ voice: (voice || 'alloy') as OpenAI_SDK.Audio.SpeechCreateParams['voice'],53+ response_format: format,54+ speed,55+ ...modelOptions,56+ }packages/typescript/openai-base/src/adapters/video.ts lines 131 to 139OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +119,21 @@119+120+ /**121+ * Get the URL to download/view the generated video.122+ *123+ * @experimental Video generation is an experimental feature and may change.124+ */125+ async getVideoUrl(jobId: string): Promise<VideoUrlResult> {126+ try {127+ const client = this.client as any128+129+ let response: any130+131+ if (typeof client.videos?.content === 'function') {132+ response = await client.videos.content(jobId)133+ } else if (typeof client.videos?.getContent === 'function') {134+ response = await client.videos.getContent(jobId)135+ } else if (typeof client.videos?.download === 'function') {136+ response = await client.videos.download(jobId)137+ } else {138+ // Fallback: check if retrieve returns the URL directly139+ const videoInfo = await client.videos.retrieve(jobId)packages/typescript/openai-base/src/adapters/video.ts lines 140 to 146OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +126,21 @@126+ try {127+ const client = this.client as any128+129+ let response: any130+131+ if (typeof client.videos?.content === 'function') {132+ response = await client.videos.content(jobId)133+ } else if (typeof client.videos?.getContent === 'function') {134+ response = await client.videos.getContent(jobId)135+ } else if (typeof client.videos?.download === 'function') {136+ response = await client.videos.download(jobId)137+ } else {138+ // Fallback: check if retrieve returns the URL directly139+ const videoInfo = await client.videos.retrieve(jobId)140+ if (videoInfo.url) {141+ return {142+ jobId,143+ url: videoInfo.url,144+ expiresAt: videoInfo.expires_at145+ ? new Date(videoInfo.expires_at)146+ : undefined,packages/typescript/openai-base/src/tools/mcp-tool.ts lines 18 to 24OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +4,21 @@4+export type MCPTool = OpenAI.Responses.Tool.Mcp5+6+export function validateMCPtool(tool: MCPTool) {7+ if (!tool.server_url && !tool.connector_id) {8+ throw new Error('Either server_url or connector_id must be provided.')9+ }10+ if (tool.connector_id && tool.server_url) {11+ throw new Error('Only one of server_url or connector_id can be provided.')12+ }13+}14+15+/**16+ * Converts a standard Tool to OpenAI MCPTool format17+ */18+export function convertMCPToolToAdapterFormat(tool: Tool): MCPTool {19+ const metadata = tool.metadata as Omit<MCPTool, 'type'>20+21+ const mcpTool: MCPTool = {22+ type: 'mcp',23+ ...metadata,24+ }packages/typescript/openai-base/src/utils/schema-converter.ts lines 12 to 24OutdatedResolvedby tombeckenham@@ -0,0 +4,21 @@4+ * - All properties must be in the `required` array5+ * - Optional fields should have null added to their type union6+ * - additionalProperties must be false for objects7+ *8+ * @param schema - JSON schema to transform9+ * @param originalRequired - Original required array (to know which fields were optional)10+ * @returns Transformed schema compatible with OpenAI structured output11+ */12+export function makeStructuredOutputCompatible(13+ schema: Record<string, any>,14+ originalRequired: Array<string> = [],15+): Record<string, any> {16+ const result = { ...schema }17+18+ if (result.type === 'object' && result.properties) {19+ const properties = { ...result.properties }20+ const allPropertyNames = Object.keys(properties)21+22+ for (const propName of allPropertyNames) {23+ const prop = properties[propName]24+ const wasOptional = !originalRequired.includes(propName)packages/typescript/openai-base/src/utils/schema-converter.ts lines 29 to 66Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +46,21 @@46+ 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',47+ )48+ } else if (wasOptional) {49+ // Optional fields must be nullable because OpenAI requires all properties in `required`50+ if (prop.type && !Array.isArray(prop.type)) {51+ properties[propName] = {52+ ...prop,53+ type: [prop.type, 'null'],54+ }55+ } else if (Array.isArray(prop.type) && !prop.type.includes('null')) {56+ properties[propName] = {57+ ...prop,58+ type: [...prop.type, 'null'],59+ }60+ }61+ }62+ }63+64+ result.properties = properties65+ result.required = allPropertyNames66+ result.additionalProperties = false
- packages/typescript/ai-groq/src/utils/client.ts line 3OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1,2 +1,3 @@11 import Groq_SDK from 'groq-sdk'22 import type { ClientOptions } from 'groq-sdk'3+import { generateId as _generateId, getApiKeyFromEnv } from '@tanstack/ai-utils'packages/typescript/ai-groq/tests/schema-converter.test.ts lines 32 to 64OutdatedResolvedby tombeckenham@@ -0,0 +44,21 @@44+ required: ['data'],45+ }46+47+ // First create a schema that would produce empty required after processing48+ const result = makeGroqStructuredOutputCompatible(schema, ['data'])49+50+ // Should not have empty required arrays anywhere51+ const checkNoEmptyRequired = (obj: any): void => {52+ if (obj && typeof obj === 'object') {53+ if (Array.isArray(obj.required)) {54+ expect(obj.required.length).toBeGreaterThan(0)55+ }56+ for (const value of Object.values(obj)) {57+ if (typeof value === 'object' && value !== null) {58+ checkNoEmptyRequired(value)59+ }60+ }61+ }62+ }63+ checkNoEmptyRequired(result)64+ })@@ -0,0 +1,16 @@1+import { describe, it, expect, vi, afterEach } from 'vitest'2+import { getApiKeyFromEnv } from '../src/env'3+4+describe('getApiKeyFromEnv', () => {5+ afterEach(() => {6+ vi.unstubAllEnvs()7+ })8+9+ it('should return the API key from process.env', () => {10+ vi.stubEnv('TEST_API_KEY', 'sk-test-123')11+ expect(getApiKeyFromEnv('TEST_API_KEY')).toBe('sk-test-123')12+ })13+14+ it('should throw if the env var is not set', () => {15+ expect(() => getApiKeyFromEnv('NONEXISTENT_KEY')).toThrow('NONEXISTENT_KEY')16+ })
- packages/typescript/ai-groq/src/utils/schema-converter.ts lines 82 to 93OutdatedResolvedby tombeckenham@@ -92,18 +90,4 @@92- result.properties = properties93- // Groq rejects `required` when there are no properties, even if it's an empty array94- if (allPropertyNames.length > 0) {95- result.required = allPropertyNames96- } else {97- delete result.required98- }99- result.additionalProperties = false100- }90+ const result = makeStructuredOutputCompatible(normalised, originalRequired)10191102- if (result.type === 'array' && result.items) {103- result.items = makeGroqStructuredOutputCompatible(104- result.items,105- result.items.required || [],106- )107- }108-109- return result92+ // Groq rejects `required` when it is an empty array93+ return removeEmptyRequired(result)
- packages/typescript/openai-base/src/adapters/chat-completions-text.ts lines 89 to 93Resolvedby tombeckenham@@ -0,0 +60,21 @@60+61+ async *chatStream(62+ options: TextOptions<TProviderOptions>,63+ ): AsyncIterable<StreamChunk> {64+ const requestParams = this.mapOptionsToRequest(options)65+ const timestamp = Date.now()66+67+ // AG-UI lifecycle tracking (mutable state object for ESLint compatibility)68+ const aguiState = {69+ runId: generateId(this.name),70+ messageId: generateId(this.name),71+ timestamp,72+ hasEmittedRunStarted: false,73+ }74+75+ try {76+ const stream = await this.client.chat.completions.create(77+ {78+ ...requestParams,79+ stream: true,80+ stream_options: { include_usage: true },packages/typescript/openai-base/src/adapters/chat-completions-text.ts lines 714 to 722Resolvedby tombeckenham@@ -0,0 +514,21 @@514+ }515+516+ // Handle user messages - support multimodal content517+ const contentParts = this.normalizeContent(message.content)518+519+ // If only text, use simple string format520+ if (contentParts.length === 1 && contentParts[0]?.type === 'text') {521+ return {522+ role: 'user',523+ content: contentParts[0].content,524+ }525+ }526+527+ // Otherwise, use array format for multimodal528+ const parts: Array<OpenAI_SDK.Chat.Completions.ChatCompletionContentPart> =529+ []530+ for (const part of contentParts) {531+ const converted = this.convertContentPart(part)532+ if (converted) {533+ parts.push(converted)534+ }
tombeckenham requested changes
@@ -0,0 +1,5 @@1+export function getApiKeyFromEnv(envVarName: string): string {2+ const env =3+ typeof globalThis !== 'undefined' && (globalThis as any).window?.env4+ ? (globalThis as any).window.env5+ : typeof process !== 'undefined'@@ -0,0 +38,21 @@38+ readonly name: string39+40+ protected client: OpenAI_SDK41+42+ constructor(43+ config: OpenAICompatibleClientConfig,44+ model: TModel,45+ name: string = 'openai-compatible',46+ ) {47+ super(model, {})48+ this.name = name49+ this.client = createOpenAICompatibleClient(config)50+ }51+52+ async generateImages(53+ options: ImageGenerationOptions<TProviderOptions>,54+ ): Promise<ImageGenerationResult> {55+ const { model, prompt, numberOfImages, size } = options56+57+ // Validate inputs58+ this.validatePrompt({ prompt, model })@@ -0,0 +124,21 @@124+ : undefined,125+ }126+ }127+128+ protected validatePrompt(options: { prompt: string; model: string }): void {129+ if (options.prompt.length === 0) {130+ throw new Error('Prompt cannot be empty.')131+ }132+ }133+134+ protected validateImageSize(_model: string, _size: string | undefined): void {135+ // Default: no size validation — subclasses can override136+ }137+138+ protected validateNumberOfImages(139+ _model: string,140+ numberOfImages: number | undefined,141+ ): void {142+ if (numberOfImages === undefined) return143+144+ if (numberOfImages < 1 || numberOfImages > 10) {@@ -140,14 +39,7 @@140- break141- default:142- prompt += 'Provide a clear and concise summary. '143- }144-145- if (options.focus && options.focus.length > 0) {146- prompt += `Focus on the following aspects: ${options.focus.join(', ')}. `147- }148-149- if (options.maxLength) {150- prompt += `Keep the summary under ${options.maxLength} tokens. `151- }152-153- return prompt39+ // The text adapter accepts richer provider options than the summarize adapter needs,40+ // but we only pass basic options (model, messages, systemPrompts, etc.) at call time.41+ super(42+ new OpenAITextAdapter(43+ config,44+ model,45+ ) as unknown as ChatStreamCapable<OpenAISummarizeProviderOptions>,@@ -0,0 +31,21 @@31+export class OpenAICompatibleSummarizeAdapter<32+ TModel extends string,33+ TProviderOptions extends object = Record<string, any>,34+> extends BaseSummarizeAdapter<TModel, TProviderOptions> {35+ readonly name: string36+37+ private textAdapter: ChatStreamCapable<TProviderOptions>38+39+ constructor(40+ textAdapter: ChatStreamCapable<TProviderOptions>,41+ model: TModel,42+ name: string = 'openai-compatible',43+ ) {44+ super({}, model)45+ this.name = name46+ this.textAdapter = textAdapter47+ }48+49+ async summarize(options: SummarizationOptions): Promise<SummarizationResult> {50+ const systemPrompt = this.buildSummarizationPrompt(options)51+@@ -0,0 +44,21 @@44+ super({}, model)45+ this.name = name46+ this.textAdapter = textAdapter47+ }48+49+ async summarize(options: SummarizationOptions): Promise<SummarizationResult> {50+ const systemPrompt = this.buildSummarizationPrompt(options)51+52+ let summary = ''53+ const id = generateId(this.name)54+ let model = options.model55+ let usage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 }56+57+ for await (const chunk of this.textAdapter.chatStream({58+ model: options.model as TModel,59+ messages: [{ role: 'user', content: options.text }],60+ systemPrompts: [systemPrompt],61+ maxTokens: options.maxLength,62+ temperature: 0.3,63+ logger: options.logger,64+ } as TextOptions<TProviderOptions>)) {@@ -0,0 +34,21 @@34+> extends BaseSummarizeAdapter<TModel, TProviderOptions> {35+ readonly name: string36+37+ private textAdapter: ChatStreamCapable<TProviderOptions>38+39+ constructor(40+ textAdapter: ChatStreamCapable<TProviderOptions>,41+ model: TModel,42+ name: string = 'openai-compatible',43+ ) {44+ super({}, model)45+ this.name = name46+ this.textAdapter = textAdapter47+ }48+49+ async summarize(options: SummarizationOptions): Promise<SummarizationResult> {50+ const systemPrompt = this.buildSummarizationPrompt(options)51+52+ let summary = ''53+ const id = generateId(this.name)54+ let model = options.model@@ -0,0 +63,21 @@63+ logger: options.logger,64+ } as TextOptions<TProviderOptions>)) {65+ if (chunk.type === 'TEXT_MESSAGE_CONTENT') {66+ if (chunk.content) {67+ summary = chunk.content68+ } else if (chunk.delta) {69+ // Append delta only when present — a content-less chunk with no70+ // delta would otherwise concat literal `'undefined'`.71+ summary += chunk.delta72+ }73+ model = chunk.model || model74+ }75+ if (chunk.type === 'RUN_FINISHED') {76+ if (chunk.usage) {77+ usage = chunk.usage78+ }79+ }80+ // Surface failures: the underlying chatStream emits RUN_ERROR instead of81+ // throwing, so without this branch summarize() would return an empty82+ // summary and pretend a failed run succeeded.83+ if (chunk.type === 'RUN_ERROR') {@@ -0,0 +88,21 @@88+ const code =89+ chunk.error && typeof chunk.error.code === 'string'90+ ? chunk.error.code91+ : undefined92+ const err = new Error(message)93+ if (code) {94+ ;(err as Error & { code?: string }).code = code95+ }96+ throw err97+ }98+ }99+100+ return { id, model, summary, usage }101+ }102+103+ async *summarizeStream(104+ options: SummarizationOptions,105+ ): AsyncIterable<StreamChunk> {106+ const systemPrompt = this.buildSummarizationPrompt(options)107+108+ yield* this.textAdapter.chatStream({@@ -0,0 +83,21 @@83+ // Track tool call metadata by unique ID84+ // Responses API streams tool calls with deltas — first chunk has ID/name,85+ // subsequent chunks only have args.86+ // We assign our own indices as we encounter unique tool call IDs.87+ const toolCallMetadata = new Map<88+ string,89+ { index: number; name: string; started: boolean }90+ >()91+ const requestParams = this.mapOptionsToRequest(options)92+ const timestamp = Date.now()93+94+ // AG-UI lifecycle tracking95+ const aguiState = {96+ runId: generateId(this.name),97+ messageId: generateId(this.name),98+ timestamp,99+ hasEmittedRunStarted: false,100+ }101+102+ try {103+ const response = await this.client.responses.create(@@ -0,0 +163,21 @@163+ *164+ * The outputSchema is already JSON Schema (converted in the ai layer).165+ * We apply provider-specific transformations for structured output compatibility.166+ */167+ async structuredOutput(168+ options: StructuredOutputOptions<TProviderOptions>,169+ ): Promise<StructuredOutputResult<unknown>> {170+ const { chatOptions, outputSchema } = options171+ const requestParams = this.mapOptionsToRequest(chatOptions)172+173+ // Apply provider-specific transformations for structured output compatibility174+ const jsonSchema = this.makeStructuredOutputCompatible(175+ outputSchema,176+ outputSchema.required || [],177+ )178+179+ try {180+ // Strip streaming-only fields a subclass override of mapOptionsToRequest181+ // might have returned (parallel to chat-completions's structuredOutput182+ // cleanup) — sending stream_options to a non-streaming call is a 4xx.183+ const {packages/typescript/openai-base/src/adapters/responses-text.ts line 215OutdatedResolvedby tombeckenham@@ -0,0 +195,21 @@195+ >),196+ stream: false,197+ // Configure structured output via text.format198+ text: {199+ format: {200+ type: 'json_schema',201+ name: 'structured_output',202+ schema: jsonSchema,203+ strict: true,204+ },205+ },206+ },207+ {208+ headers: chatOptions.request?.headers,209+ signal: chatOptions.request?.signal,210+ },211+ )212+213+ // Extract text content from the response214+ const rawText = this.extractTextFromResponse(215+ response as OpenAI_SDK.Responses.Response,@@ -0,0 +327,21 @@327+328+ // Track if we've been streaming deltas to avoid duplicating content from done events329+ let hasStreamedContentDeltas = false330+ let hasStreamedReasoningDeltas = false331+332+ // Preserve response metadata across events333+ let model: string = options.model334+335+ // AG-UI lifecycle tracking336+ let stepId: string | null = null337+ let hasEmittedTextMessageStart = false338+ let hasEmittedStepStarted = false339+ // Track whether we've emitted a terminal RUN_FINISHED so the340+ // end-of-stream fallback below knows to synthesise one when the upstream341+ // cuts off without a response.completed event.342+ let runFinishedEmitted = false343+344+ try {345+ for await (const chunk of stream) {346+ // Emit RUN_STARTED on first chunk347+ if (!aguiState.hasEmittedRunStarted) {@@ -0,0 +338,21 @@338+ let hasEmittedStepStarted = false339+ // Track whether we've emitted a terminal RUN_FINISHED so the340+ // end-of-stream fallback below knows to synthesise one when the upstream341+ // cuts off without a response.completed event.342+ let runFinishedEmitted = false343+344+ try {345+ for await (const chunk of stream) {346+ // Emit RUN_STARTED on first chunk347+ if (!aguiState.hasEmittedRunStarted) {348+ aguiState.hasEmittedRunStarted = true349+ yield asChunk({350+ type: 'RUN_STARTED',351+ runId: aguiState.runId,352+ model: model || options.model,353+ timestamp,354+ })355+ }356+357+ const handleContentPart = (contentPart: {358+ type: string@@ -872,14 +125,13 @@872125 ? convertToolsToProviderFormat(options.tools)873126 : undefined874127128+ // Mirror the base adapter's precedence: spread `modelOptions` first, then129+ // conditionally add explicit top-level options only when defined. The130+ // previous override spread `...modelOptions` LAST and wrote131+ // `temperature: options.temperature` unconditionally — re-introducing the132+ // exact regression the base class's nullish-aware merge fixes.875133 const requestParams: Omit<876134 OpenAI_SDK.Responses.ResponseCreateParams,877135 'stream'878136 > = {879- model: options.model,880- temperature: options.temperature,881- max_output_tokens: options.maxTokens,882- top_p: options.topP,883- metadata: options.metadata,884- instructions: options.systemPrompts?.join('\n'),885137 ...modelOptions,@@ -0,0 +1024,21 @@1024+ protected convertContentPartToInput(1025+ part: ContentPart,1026+ ): Responses.ResponseInputContent {1027+ switch (part.type) {1028+ case 'text':1029+ return {1030+ type: 'input_text',1031+ text: part.content,1032+ }1033+ case 'image': {1034+ const imageMetadata = part.metadata as1035+ | { detail?: 'auto' | 'low' | 'high' }1036+ | undefined1037+ if (part.source.type === 'url') {1038+ return {1039+ type: 'input_image',1040+ image_url: part.source.value,1041+ detail: imageMetadata?.detail || 'auto',1042+ }1043+ }1044+ // For base64 data, construct a data URI using the mimeType from@@ -0,0 +30,21 @@30+31+ protected client: OpenAI_SDK32+33+ constructor(34+ config: OpenAICompatibleClientConfig,35+ model: TModel,36+ name: string = 'openai-compatible',37+ ) {38+ super(model, {})39+ this.name = name40+ this.client = createOpenAICompatibleClient(config)41+ }42+43+ async transcribe(44+ options: TranscriptionOptions<TProviderOptions>,45+ ): Promise<TranscriptionResult> {46+ const { model, audio, language, prompt, responseFormat, modelOptions } =47+ options48+49+ // Convert audio input to File object50+ const file = this.prepareAudioFile(audio)packages/typescript/openai-base/src/adapters/transcription.ts line 181OutdatedResolvedby tombeckenham@@ -0,0 +161,21 @@161+ }162+163+ /**164+ * Checks that the global `File` constructor is available.165+ * Throws a descriptive error in environments that lack it (e.g. Node < 20).166+ */167+ private ensureFileSupport(): void {168+ if (typeof File === 'undefined') {169+ throw new Error(170+ '`File` is not available in this environment. ' +171+ 'Use Node.js 20 or newer, or pass a File object directly.',172+ )173+ }174+ }175+176+ /**177+ * Decodes a base64 string to an ArrayBuffer.178+ * Uses `atob` when available, falling back to `Buffer.from` in Node.js.179+ */180+ private decodeBase64(base64: string): ArrayBuffer {181+ if (typeof atob === 'function') {@@ -0,0 +117,21 @@117+ }118+ return contentTypes[format] || 'audio/mpeg'119+ }120+}121+122+/**123+ * Cross-runtime ArrayBuffer → base64 helper. Prefers Node's `Buffer` when124+ * available; otherwise walks the byte array via `atob`/`btoa` for browser /125+ * edge runtimes that ship a fetch/`Response` but no Buffer global.126+ */127+function arrayBufferToBase64(buffer: ArrayBuffer): string {128+ if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {129+ return Buffer.from(buffer).toString('base64')130+ }131+ const view = new Uint8Array(buffer)132+ let binary = ''133+ for (let i = 0; i < view.byteLength; i += 1) {134+ binary += String.fromCharCode(view[i]!)135+ }136+ return btoa(binary)137+}@@ -0,0 +62,21 @@62+ ): Promise<VideoJobResult> {63+ const { model, size, duration, modelOptions } = options64+65+ // Validate inputs66+ this.validateVideoSize(model, size)67+ const seconds = duration ?? (modelOptions as any)?.seconds68+ this.validateVideoSeconds(model, seconds)69+70+ // Build request71+ const request = this.buildRequest(options)72+73+ try {74+ const client = this.client as any75+ const response = await client.videos.create(request)76+77+ return {78+ jobId: response.id,79+ model,80+ }81+ } catch (error: any) {82+ if (error?.message?.includes('videos') || error?.code === 'invalid_api') {@@ -0,0 +46,21 @@46+ model: TModel,47+ name: string = 'openai-compatible',48+ ) {49+ super(config, model)50+ this.name = name51+ this.clientConfig = config52+ this.client = createOpenAICompatibleClient(config)53+ }54+55+ /**56+ * Create a new video generation job.57+ *58+ * @experimental Video generation is an experimental feature and may change.59+ */60+ async createVideoJob(61+ options: VideoGenerationOptions<TProviderOptions>,62+ ): Promise<VideoJobResult> {63+ const { model, size, duration, modelOptions } = options64+65+ // Validate inputs66+ this.validateVideoSize(model, size)@@ -0,0 +48,21 @@48+ ) {49+ super(config, model)50+ this.name = name51+ this.clientConfig = config52+ this.client = createOpenAICompatibleClient(config)53+ }54+55+ /**56+ * Create a new video generation job.57+ *58+ * @experimental Video generation is an experimental feature and may change.59+ */60+ async createVideoJob(61+ options: VideoGenerationOptions<TProviderOptions>,62+ ): Promise<VideoJobResult> {63+ const { model, size, duration, modelOptions } = options64+65+ // Validate inputs66+ this.validateVideoSize(model, size)67+ const seconds = duration ?? (modelOptions as any)?.seconds68+ this.validateVideoSeconds(model, seconds)@@ -0,0 +107,21 @@107+ }108+ } catch (error: any) {109+ if (error.status === 404) {110+ return {111+ jobId,112+ status: 'failed',113+ error: 'Job not found',114+ }115+ }116+ throw error117+ }118+ }119+120+ /**121+ * Get the URL to download/view the generated video.122+ *123+ * @experimental Video generation is an experimental feature and may change.124+ */125+ async getVideoUrl(jobId: string): Promise<VideoUrlResult> {126+ try {127+ const client = this.client as any@@ -0,0 +128,21 @@128+129+ // Prefer retrieve() because many openai-compatible backends (and the130+ // aimock test harness) return the URL directly on the video resource131+ // and do not implement a separate /content endpoint. Subclasses can132+ // override this method if they need to download raw bytes via133+ // downloadContent()/content().134+ const videoInfo = await client.videos.retrieve(jobId)135+ if (videoInfo.url) {136+ return {137+ jobId,138+ url: videoInfo.url,139+ expiresAt: videoInfo.expires_at140+ ? new Date(videoInfo.expires_at)141+ : undefined,142+ }143+ }144+145+ // SDK download fall-through: try the various possible method names in146+ // decreasing order of modernity.147+ if (typeof client.videos?.downloadContent === 'function') {148+ const contentResponse = await client.videos.downloadContent(jobId)@@ -0,0 +145,21 @@145+ // SDK download fall-through: try the various possible method names in146+ // decreasing order of modernity.147+ if (typeof client.videos?.downloadContent === 'function') {148+ const contentResponse = await client.videos.downloadContent(jobId)149+ const videoBlob = await contentResponse.blob()150+ const buffer = await videoBlob.arrayBuffer()151+ const base64 = arrayBufferToBase64(buffer)152+ const mimeType =153+ contentResponse.headers.get('content-type') || 'video/mp4'154+ return {155+ jobId,156+ url: `data:${mimeType};base64,${base64}`,157+ expiresAt: undefined,158+ }159+ }160+161+ // The remaining SDK fall-throughs all return a binary payload162+ // (Blob/Response/ArrayBuffer-shaped), NOT an `{ url, expires_at }`163+ // object the way the bottom return assumed. Convert to a data URL164+ // here so the caller actually receives a usable URL.165+ let response: any@@ -0,0 +11,21 @@11+ */12+export function convertCodeInterpreterToolToAdapterFormat(13+ tool: Tool,14+): CodeInterpreterToolConfig {15+ const metadata = tool.metadata as CodeInterpreterToolConfig16+ return {17+ type: 'code_interpreter',18+ container: metadata.container,19+ }20+}21+22+/**23+ * Creates a standard Tool from CodeInterpreterTool parameters.24+ *25+ * Base (non-branded) factory. Providers that need branded return types should26+ * re-wrap this in their own package.27+ */28+export function codeInterpreterTool(29+ container: CodeInterpreterToolConfig,30+): Tool {31+ return {@@ -37,3 +31,3 @@3731 */3832 export class GrokImageAdapter<3933 TModel extends GrokImageModel,@@ -34,12 +18,16 @@3418 'XAI_API_KEY is required. Please set it in your environment variables or use the factory function with an explicit API key.',3519 )3620 }37-38- return key3921 }40224123 /**42- * Generates a unique ID with a prefix24+ * Converts a GrokClientConfig to OpenAICompatibleClientConfig.25+ * Sets the default xAI base URL if not already set.4326 */44-export function generateId(prefix: string): string {45- return `${prefix}-${Date.now()}-${Math.random().toString(36).substring(7)}`27+export function toCompatibleConfig(28+ config: GrokClientConfig,29+): OpenAICompatibleClientConfig {30+ return {31+ ...config,32+ baseURL: config.baseURL || 'https://api.x.ai/v1',33+ } as unknown as OpenAICompatibleClientConfig@@ -1,4 +1,5 @@1-import OpenAI_SDK from 'openai'1+import { getApiKeyFromEnv } from '@tanstack/ai-utils'2+import type { OpenAICompatibleClientConfig } from '@tanstack/openai-base'23 import type { ClientOptions } from 'openai'3445 export interface GrokClientConfig extends ClientOptions {@@ -1,4 +1,5 @@1-import OpenAI_SDK from 'openai'1+import { getApiKeyFromEnv } from '@tanstack/ai-utils'2+import type { OpenAICompatibleClientConfig } from '@tanstack/openai-base'23 import type { ClientOptions } from 'openai'3445 export interface OpenAIClientConfig extends ClientOptions {@@ -30,12 +14,13 @@30- 'OPENAI_API_KEY is required. Please set it in your environment variables or use the factory function with an explicit API key.',31- )32- }33-34- return key14+ return getApiKeyFromEnv('OPENAI_API_KEY')3515 }36163717 /**38- * Generates a unique ID with a prefix18+ * Converts an OpenAIClientConfig to OpenAICompatibleClientConfig.19+ * This bridges the type gap between the local config type (which extends20+ * the local copy of ClientOptions) and the base package's config type21+ * (which extends its own copy of ClientOptions).3922 */40-export function generateId(prefix: string): string {41- return `${prefix}-${Date.now()}-${Math.random().toString(36).substring(7)}`23+export function toCompatibleConfig(24+ config: OpenAIClientConfig,25+): OpenAICompatibleClientConfig {26+ return config as unknown as OpenAICompatibleClientConfigpackages/typescript/openai-base/src/adapters/chat-completions-text.ts line 457OutdatedResolvedby tombeckenham@@ -0,0 +437,21 @@437+ }438+ }439+440+ // Emit AG-UI TOOL_CALL_END441+ yield asChunk({442+ type: 'TOOL_CALL_END',443+ toolCallId: toolCall.id,444+ toolCallName: toolCall.name,445+ toolName: toolCall.name,446+ model: chunk.model || options.model,447+ timestamp,448+ input: parsedInput,449+ })450+ emittedAnyToolCallEnd = true451+ }452+ // Clear tool-call state after emission so a subsequent453+ // `finish_reason: 'stop'` chunk (or the post-loop synthetic454+ // block) doesn't see lingering entries and misreport the finish.455+ toolCallsInProgress.clear()456+ }457+ void emittedAnyToolCallEndpackages/typescript/openai-base/src/adapters/chat-completions-text.ts line 543Resolvedby tombeckenham@@ -0,0 +514,21 @@514+ yield asChunk({515+ type: 'TEXT_MESSAGE_END',516+ messageId: aguiState.messageId,517+ model: lastModel || options.model,518+ timestamp,519+ })520+ }521+522+ // Map upstream finish_reason to AG-UI's narrower vocabulary while523+ // preserving the upstream value when it falls outside the AG-UI set.524+ // Collapsing length / content_filter to 'stop' would hide why the525+ // run terminated — surface it instead. Use `tool_calls` only when526+ // the upstream actually said so OR when we just closed pending tool527+ // calls (truncated stream); a clean `stop` with no started tool528+ // calls must NOT be remapped to `tool_calls`.529+ const finishReason: string =530+ pendingFinishReason === 'tool_calls' || pendingToolCount > 0531+ ? 'tool_calls'532+ : (pendingFinishReason ?? 'stop')533+534+ yield asChunk({@@ -0,0 +686,21 @@686+ type: 'TOOL_CALL_START',687+ toolCallId: item.id,688+ toolCallName: item.name || '',689+ toolName: item.name || '',690+ model: model || options.model,691+ timestamp,692+ index: chunk.output_index,693+ })694+ toolCallMetadata.get(item.id)!.started = true695+ }696+ }697+ }698+699+ // Handle function call arguments delta (streaming). Drop the700+ // previously-emitted `args` field — it had inverted polarity701+ // (populated only when metadata was MISSING, i.e. when the702+ // matching TOOL_CALL_START hadn't fired) and the chat-completions703+ // adapter never emitted it, so it leaked partial deltas as704+ // pseudo-args only on the orphan path. Consumers should accumulate705+ // `delta` themselves.706+ if (packages/typescript/openai-base/src/types/message-metadata.ts line 13OutdatedResolvedby tombeckenham@@ -0,0 +1,13 @@1+export interface OpenAICompatibleImageMetadata {2+ detail?: 'auto' | 'low' | 'high'3+}4+5+export interface OpenAICompatibleAudioMetadata {6+ format?: 'mp3' | 'wav' | 'flac' | 'ogg' | 'webm' | 'aac'7+}8+9+export interface OpenAICompatibleVideoMetadata {}10+export interface OpenAICompatibleDocumentMetadata {}11+export interface OpenAICompatibleTextMetadata {}12+13+export interface OpenAICompatibleMessageMetadataByModality {@@ -0,0 +1 @@1+export interface OpenAICompatibleBaseOptions {@@ -0,0 +1,5 @@1+import { describe, it, expect } from 'vitest'2+import { defineModelMeta } from '../src/model-meta/define'3+import type { ModelMeta, Modality } from '../src/model-meta/types'4+5+describe('defineModelMeta', () => {packages/typescript/openai-base/src/adapters/responses-text.ts line 316OutdatedResolvedby tombeckenham@@ -0,0 +296,21 @@296+ * Processes streamed chunks from the Responses API and yields AG-UI events.297+ * Override this in subclasses to handle provider-specific stream behavior.298+ *299+ * Handles the following event types:300+ * - response.created / response.incomplete / response.failed301+ * - response.output_text.delta302+ * - response.reasoning_text.delta303+ * - response.reasoning_summary_text.delta304+ * - response.content_part.added / response.content_part.done305+ * - response.output_item.added306+ * - response.function_call_arguments.delta / response.function_call_arguments.done307+ * - response.completed308+ * - error309+ */310+ protected async *processStreamChunks(311+ stream: AsyncIterable<OpenAI_SDK.Responses.ResponseStreamEvent>,312+ toolCallMetadata: Map<313+ string,314+ { index: number; name: string; started: boolean }315+ >,316+ options: TextOptions,packages/typescript/openai-base/src/adapters/responses-text.ts line 882OutdatedResolvedby tombeckenham@@ -0,0 +862,21 @@862+ )863+ options.logger.errors(`${this.name}.processStreamChunks fatal`, {864+ error: errorPayload,865+ source: `${this.name}.processStreamChunks`,866+ })867+ yield asChunk({868+ type: 'RUN_ERROR',869+ runId: aguiState.runId,870+ model: options.model,871+ timestamp,872+ error: errorPayload,873+ })874+ }875+ }876+877+ /**878+ * Maps common TextOptions to Responses API request format.879+ * Override this in subclasses to add provider-specific options.880+ */881+ protected mapOptionsToRequest(882+ options: TextOptions,@@ -262,20 +101,2 @@262- for (const item of response.output) {263- if (item.type === 'message') {264- for (const part of item.content) {265- if (part.type === 'output_text') {266- textContent += part.text267- }268- }269- }270- }271-272- return textContent273- }274-275- private async *processOpenAIStreamChunks(276- stream: AsyncIterable<OpenAI_SDK.Responses.ResponseStreamEvent>,277- toolCallMetadata: Map<278- string,279- { index: number; name: string; started: boolean }280- >,101+ protected override mapOptionsToRequest(281102 options: TextOptions,@@ -832,20 +103,2 @@832- type: 'RUN_ERROR',833- runId,834- message: err.message || 'Unknown error occurred',835- code: err.code,836- model: options.model,837- timestamp,838- error: {839- message: err.message || 'Unknown error occurred',840- code: err.code,841- },842- })843- }844- }845-846- /**847- * Maps common options to OpenAI-specific format848- * Handles translation of normalized options to OpenAI's API format849- */850- private mapTextOptionsToOpenAI(options: TextOptions) {103+ ): Omit<OpenAI_SDK.Responses.ResponseCreateParams, 'stream'> {851104 const modelOptions = options.modelOptions as@@ -0,0 +1 @@1+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'tombeckenham approved these changes
AlemTuzlak merged this27c9aeb
AlemTuzlak closed this
Sign in to join this conversation.
🚀 Changeset Version Preview#
11 package(s) bumped directly, 3 bumped as dependents.
🟨 Minor bumps#
@tanstack/ai-utils@tanstack/openai-base🟩 Patch bumps#
@tanstack/ai-anthropic@tanstack/ai-elevenlabs@tanstack/ai-fal@tanstack/ai-gemini@tanstack/ai-grok@tanstack/ai-groq@tanstack/ai-ollama@tanstack/ai-openai@tanstack/ai-openrouter@tanstack/ai-code-mode-models-evalts-svelte-chatts-vue-chat