Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions examples/file-content-retrieval.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/usr/bin/env -S npm run tsn -T

/**
* Demonstrates how to retrieve and consume file content from OpenAI.
*
* The files.content() method returns a Response object, which can be
* consumed in different formats depending on the file type.
*/

import OpenAI from 'openai';

const client = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'],
});

async function main() {
// Example 1: Retrieve text file content (e.g., JSONL for fine-tuning)
{
console.log('Fetching text file content...');
const response = await client.files.content('file-abc123');
const textContent = await response.text();
console.log('File content as text:', textContent);
}

// Example 2: Retrieve binary file content (e.g., images)
{
console.log('Fetching binary file content...');
const response = await client.files.content('file-xyz789');
const blobContent = await response.blob();
console.log('File content as blob:', blobContent);
}

// Example 3: Retrieve as ArrayBuffer for low-level operations
{
console.log('Fetching file as ArrayBuffer...');
const response = await client.files.content('file-def456');
const buffer = await response.arrayBuffer();
console.log('File size in bytes:', buffer.byteLength);
}
}

main().catch((err) => {
console.error(err);
process.exit(1);
});
19 changes: 18 additions & 1 deletion src/resources/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,24 @@ export class Files extends APIResource {
}

/**
* Returns the contents of the specified file.
* Returns the contents of the specified file as a Response object.
*
* The Response object provides methods to consume the file content in different formats:
* - `.text()` - Returns file content as a string
* - `.blob()` - Returns file content as a Blob
* - `.arrayBuffer()` - Returns file content as an ArrayBuffer
*
* @example
* ```ts
* // Get file content as text (e.g., for JSONL files)
* const response = await client.files.content('file-abc123');
* const text = await response.text();
* console.log(text);
*
* // Get file content as blob (e.g., for images)
* const response = await client.files.content('file-abc123');
* const blob = await response.blob();
* ```
*/
content(fileID: string, options?: RequestOptions): APIPromise<Response> {
return this._client.get(path`/files/${fileID}/content`, {
Expand Down