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

files.ts

86 lines2.6 KB

1import { OpenAI, toFile } from 'openai'
2import {
3 BaseFilesAdapter,
4 normalizeFileUploadInput,
5} from '@tanstack/ai/adapters'
6import { getOpenAIApiKeyFromEnv } from '../utils/client'
7import type { FileHandle, FileUploadInput } from '@tanstack/ai/adapters'
8import type { FileObject, FilePurpose } from 'openai/resources/files'
9import type { OpenAIClientConfig } from '../utils/client'
10​
11export interface OpenAIFilesConfig extends OpenAIClientConfig {
12 /**
13 * Default `purpose` for uploads. Files uploaded for vision/document input to
14 * the Responses API use `'user_data'` (the flexible default). Override per
15 * upload need — e.g. `'vision'` — via this config.
16 * @default 'user_data'
17 */
18 purpose?: FilePurpose
20​
21/**
22 * OpenAI Files adapter — uploads media to the OpenAI Files API and references
23 * it by `file_id`. Pair with `openaiText()` (Responses API): reference the
24 * returned handle in a message via `fileSourceFromHandle(handle)`.
25 */
26export class OpenAIFilesAdapter extends BaseFilesAdapter<'openai'> {
27 readonly name = 'openai' as const
28 protected client: OpenAI
29 private readonly purpose: FilePurpose
30​
31 constructor(config: OpenAIFilesConfig) {
32 super()
33 const { purpose, ...clientOptions } = config
34 this.client = new OpenAI(clientOptions)
35 this.purpose = purpose ?? 'user_data'
36 }
37​
38 async upload(input: FileUploadInput): Promise<FileHandle<'openai'>> {
39 const { blob, mimeType, filename } = normalizeFileUploadInput(input)
40 const file = await toFile(blob, filename, {
41 ...(mimeType ? { type: mimeType } : {}),
42 })
43 const result = await this.client.files.create({
44 file,
45 purpose: this.purpose,
46 })
47 return toFileHandle(result)
48 }
49​
50 async get(id: string): Promise<FileHandle<'openai'>> {
51 return toFileHandle(await this.client.files.retrieve(id))
52 }
53​
54 async delete(id: string): Promise<void> {
55 await this.client.files.delete(id)
56 }
58​
59function toFileHandle(file: FileObject): FileHandle<'openai'> {
60 return {
61 id: file.id,
62 provider: 'openai',
63 sizeBytes: file.bytes,
64 filename: file.filename,
65 ...(file.expires_at ? { expiresAt: file.expires_at * 1000 } : {}),
66 }
68​
69/**
70 * Create an OpenAI Files adapter with an explicit API key.
71 */
72export function createOpenaiFiles(
73 apiKey: string,
74 config?: Omit<OpenAIFilesConfig, 'apiKey'>,
75): OpenAIFilesAdapter {
76 return new OpenAIFilesAdapter({ ...config, apiKey })
78​
79/**
80 * Create an OpenAI Files adapter, reading the API key from `OPENAI_API_KEY`.
81 */
82export function openaiFiles(
83 config?: Omit<OpenAIFilesConfig, 'apiKey'>,
84): OpenAIFilesAdapter {
85 return createOpenaiFiles(getOpenAIApiKeyFromEnv(), config)