How to upload files to OpenAI API
Quick answer
Use the
OpenAI Python SDK's client.files.create() method to upload files to the OpenAI API. Provide the file path and purpose (e.g., fine-tune) as parameters to upload your file successfully.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official openai Python SDK and set your API key as an environment variable.
- Install SDK:
pip install openai>=1.0 - Set environment variable:
export OPENAI_API_KEY='your_api_key'(Linux/macOS) orsetx OPENAI_API_KEY "your_api_key"(Windows)
pip install openai>=1.0 Step by step
This example uploads a local JSONL file for fine-tuning using the client.files.create() method. Replace path/to/yourfile.jsonl with your actual file path.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.files.create(
file=open("path/to/yourfile.jsonl", "rb"),
purpose="fine-tune"
)
print("File ID:", response.id)
print("Filename:", response.filename)
print("Status:", response.status) output
File ID: file-abc123xyz Filename: yourfile.jsonl Status: uploaded
Common variations
You can upload files for different purposes such as fine-tune, answers, or search. The file parameter accepts any binary file object.
- Use async upload with
asyncioandawait client.files.create(...)in async context. - Use different models with uploaded files for fine-tuning or embeddings.
import asyncio
import os
from openai import OpenAI
async def upload_file_async():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = await client.files.create(
file=open("path/to/yourfile.jsonl", "rb"),
purpose="fine-tune"
)
print("Async File ID:", response.id)
asyncio.run(upload_file_async()) output
Async File ID: file-abc123xyz
Troubleshooting
- If you get a
FileNotFoundError, verify the file path is correct and accessible. - If you see
401 Unauthorized, check yourOPENAI_API_KEYenvironment variable. - For
400 Bad Request, ensure the file format matches thepurpose(e.g., JSONL for fine-tuning).
Key Takeaways
- Use
client.files.create()with a binary file object and a purpose to upload files. - Set your API key securely in
os.environ["OPENAI_API_KEY"]before running code. - File format must match the intended
purpose(e.g., JSONL for fine-tuning). - Async uploads are supported with
await client.files.create()in async functions. - Check file path and API key environment variable if upload fails.