API Reference

The OpenAI API can be applied to virtually any task. We offer a spectrum of models with different levels of power suitable for different tasks, as well as the ability to fine-tune custom models.

Introduction

The OpenAI API provides programmatic access to OpenAI models including GPT-4o, GPT-4o mini, o1, DALL·E 3, Whisper, TTS, and embedding models. You can interact with the API through HTTP requests from any language, via our official Python or Node.js libraries, or through a growing list of community-maintained libraries. Base URL https://api.openai.com/v1

Authentication

The OpenAI API uses API keys for authentication. You can create API keys at the API keys page in your account settings. All API requests must include your API key in an Authorization HTTP header:
Authorization: Bearer OPENAI_API_KEY
Organization (optional) For users who belong to multiple organizations, you can pass a header to specify which organization is used. Usage from these API requests will count against the specified organization's quota.
OpenAI-Organization: org-xxxxxxx

Making requests

You can paste the command below into your terminal to run your first API request. Make sure to replace $OPENAI_API_KEY with your secret API key.
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
This request queries the gpt-4o model to complete the text starting with "Hello!". You should get a response back that resembles the following:
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1677858242,
  "model": "gpt-4o-2024-08-06",
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "Hello! How can I assist you today?"
    },
    "finish_reason": "stop",
    "index": 0
  }],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21
  }
}

Streaming

The OpenAI API supports streaming responses back to the client using Server-Sent Events (SSE). Streaming is supported for both the Chat Completions and Assistants APIs. To enable streaming, set stream: true in your request body. Partial message deltas will be sent as data: [JSON] events, with the stream terminated by a data: [DONE] message.
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "stream": true,
    "messages": [{"role": "user", "content": "Hello!"}]
  }'

Chat

Given a list of messages comprising a conversation, the model will return a response. Related guide: Chat Completions.

Create chat completion

POST/v1/chat/completions

Creates a model response for the given chat conversation. See the text generation guide and the code generation guide for more information.

Request body

NameTypeDescription
modelstringRequiredID of the model to use. See the model endpoint compatibility table for details on which models work with the Chat API.
messagesarrayRequiredA list of messages comprising the conversation so far. Each message is an object with a role (system, user, assistant) and content.
temperaturenumberOptionalWhat sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. Defaults to 1.
top_pnumberOptionalAn alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. Defaults to 1.
nintegerOptionalHow many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all choices. Defaults to 1.
streambooleanOptionalIf set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only server-sent events as they become available. Defaults to false.
max_tokensinteger | nullOptionalThe maximum number of tokens that can be generated in the chat completion. The total length of input tokens and generated tokens is limited by the model's context length.
response_formatobjectOptionalAn object specifying the format that the model must output. Setting to { "type": "json_object" } enables JSON mode.
toolsarrayOptionalA list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for.
tool_choicestring | objectOptionalControls which (if any) tool is called by the model. "none" means the model will not call any tool. "auto" means the model can pick between generating a message or calling one or more tools.
Example request
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "Hello!"
      }
    ]
  }'
Response
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1709123456,
  "model": "gpt-4o-2024-08-06",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I assist you today?"
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 19,
    "completion_tokens": 10,
    "total_tokens": 29
  },
  "system_fingerprint": "fp_44709d6fcb"
}

Embeddings

Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. Related guide: Embeddings.

Create embeddings

POST/v1/embeddings

Creates an embedding vector representing the input text.

Request body

NameTypeDescription
inputstring | arrayRequiredInput text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays.
modelstringRequiredID of the model to use. You can use the List models API to see all available models, or see our Model overview for descriptions of them.
encoding_formatstringOptionalThe format to return the embeddings in. Can be either "float" or "base64". Defaults to "float".
dimensionsintegerOptionalThe number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models.
Example request
curl https://api.openai.com/v1/embeddings \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "input": "The food was delicious and the waiter...",
    "model": "text-embedding-3-small"
  }'
Response
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "embedding": [
        0.0023064255,
        -0.009327292,
        -0.0028842222,
        ...
      ],
      "index": 0
    }
  ],
  "model": "text-embedding-3-small",
  "usage": {
    "prompt_tokens": 8,
    "total_tokens": 8
  }
}

Images

Given a prompt and/or an input image, the model will generate a new image. Related guide: Image generation.

Create image

POST/v1/images/generations

Creates an image given a prompt.

Request body

NameTypeDescription
promptstringRequiredA text description of the desired image(s). The maximum length is 4000 characters for dall-e-3.
modelstringOptionalThe model to use for image generation. Defaults to "dall-e-3".
ninteger | nullOptionalThe number of images to generate. Must be between 1 and 10. For dall-e-3, only n=1 is supported. Defaults to 1.
qualitystringOptionalThe quality of the image that will be generated. "hd" creates images with finer details and greater consistency. Defaults to "standard".
response_formatstring | nullOptionalThe format in which the generated images are returned. Must be one of "url" or "b64_json". Defaults to "url".
sizestring | nullOptionalThe size of the generated images. Must be one of "1024x1024", "1792x1024", or "1024x1792" for dall-e-3. Defaults to "1024x1024".
stylestring | nullOptionalThe style of the generated images. Must be one of "vivid" or "natural". Vivid causes the model to lean towards generating hyper-real and dramatic images. Defaults to "vivid".
Example request
curl https://api.openai.com/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "dall-e-3",
    "prompt": "A white siamese cat",
    "n": 1,
    "size": "1024x1024"
  }'
Response
{
  "created": 1709375436,
  "data": [
    {
      "revised_prompt": "A serene white Siamese cat with striking blue almond-shaped eyes...",
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/..."
    }
  ]
}

Audio

Learn how to turn audio into text or text into audio. Related guide: Speech to text.

Create speech

POST/v1/audio/speech

Generates audio from the input text.

Request body

NameTypeDescription
modelstringRequiredOne of the available TTS models: tts-1 or tts-1-hd.
inputstringRequiredThe text to generate audio for. The maximum length is 4096 characters.
voicestringRequiredThe voice to use when generating the audio. Supported voices are alloy, echo, fable, onyx, nova, and shimmer.
response_formatstringOptionalThe format to return audio in. Supported formats are mp3, opus, aac, flac, wav, and pcm. Defaults to "mp3".
speednumberOptionalThe speed of the generated audio. Select a value from 0.25 to 4.0. Defaults to 1.0.
Example request
curl https://api.openai.com/v1/audio/speech \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "tts-1",
    "input": "The quick brown fox jumped over the lazy dog.",
    "voice": "alloy"
  }' \
  --output speech.mp3
Response
# The response is the audio file content.
# The response headers include:
Content-Type: audio/mpeg
Transfer-Encoding: chunked

Create transcription

POST/v1/audio/transcriptions

Transcribes audio into the input language.

Request body

NameTypeDescription
filefileRequiredThe audio file object to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.
modelstringRequiredID of the model to use. Only whisper-1 is currently available.
languagestringOptionalThe language of the input audio. Supplying the input language in ISO-639-1 format will improve accuracy and latency.
promptstringOptionalAn optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language.
response_formatstringOptionalThe format of the transcript output. Options are json, text, srt, verbose_json, or vtt. Defaults to "json".
temperaturenumberOptionalThe sampling temperature, between 0 and 1. Defaults to 0.
Example request
curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F file="@/path/to/file/audio.mp3" \
  -F model="whisper-1"
Response
{
  "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger."
}

Moderations

Given text and/or image inputs, classifies if those inputs are potentially harmful across several categories. Related guide: Moderations.

Create moderation

POST/v1/moderations

Classifies if text and/or image inputs are potentially harmful. Use this to check whether content complies with OpenAI's usage policies.

Request body

NameTypeDescription
inputstring | arrayRequiredInput (or inputs) to classify. Can be a single string, an array of strings, or an array of multi-modal input objects.
modelstringOptionalThe content moderation model you would like to use. Defaults to "omni-moderation-latest".
Example request
curl https://api.openai.com/v1/moderations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "input": "I want to kill them."
  }'
Response
{
  "id": "modr-abc123",
  "model": "omni-moderation-latest",
  "results": [
    {
      "flagged": true,
      "categories": {
        "sexual": false,
        "hate": false,
        "harassment": false,
        "self-harm": false,
        "sexual/minors": false,
        "hate/threatening": false,
        "violence/graphic": false,
        "self-harm/intent": false,
        "self-harm/instructions": false,
        "harassment/threatening": true,
        "violence": true
      },
      "category_scores": {
        "sexual": 1.2282071e-06,
        "hate": 0.010696256,
        "harassment": 0.29842457,
        "self-harm": 1.5236925e-08,
        "violence": 0.99011886,
        "harassment/threatening": 0.63055265,
        "violence/graphic": 1.0209e-05
      }
    }
  ]
}

Fine-tuning

Manage fine-tuning jobs to tailor a model to your specific training data. Related guide: Fine-tuning models.

Create fine-tuning job

POST/v1/fine_tuning/jobs

Creates a fine-tuning job which begins the process of creating a new model from a given dataset.

Request body

NameTypeDescription
training_filestringRequiredThe ID of an uploaded file that contains training data. Your dataset must be formatted as a JSONL file. You can upload files with the Files API.
modelstringRequiredThe name of the model to fine-tune. You can select one of the supported models.
hyperparametersobjectOptionalThe hyperparameters used for the fine-tuning job.
suffixstring | nullOptionalA string of up to 18 characters that will be added to your fine-tuned model name.
validation_filestring | nullOptionalThe ID of an uploaded file that contains validation data.
Example request
curl https://api.openai.com/v1/fine_tuning/jobs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "training_file": "file-BK7bzQj3FfZFXr7DbL6xJwfo",
    "model": "gpt-4o-mini-2024-07-18"
  }'
Response
{
  "object": "fine_tuning.job",
  "id": "ftjob-abc123",
  "model": "gpt-4o-mini-2024-07-18",
  "created_at": 1692661014,
  "finished_at": null,
  "fine_tuned_model": null,
  "organization_id": "org-abc123",
  "result_files": [],
  "status": "validating_files",
  "validation_file": null,
  "training_file": "file-BK7bzQj3FfZFXr7DbL6xJwfo",
  "hyperparameters": {
    "n_epochs": "auto"
  },
  "trained_tokens": null,
  "error": {}
}

List fine-tuning jobs

GET/v1/fine_tuning/jobs

List your organization's fine-tuning jobs.

Request body

NameTypeDescription
afterstringOptionalIdentifier for the last job from the previous pagination request.
limitintegerOptionalNumber of fine-tuning jobs to retrieve. Defaults to 20.
Example request
curl https://api.openai.com/v1/fine_tuning/jobs?limit=2 \
  -H "Authorization: Bearer $OPENAI_API_KEY"
Response
{
  "object": "list",
  "data": [
    {
      "object": "fine_tuning.job",
      "id": "ftjob-abc123",
      "model": "gpt-4o-mini-2024-07-18",
      "created_at": 1692661014,
      "finished_at": 1692661190,
      "fine_tuned_model": "ft:gpt-4o-mini-2024-07-18:my-org::7q8XXYZY",
      "status": "succeeded",
      "trained_tokens": 5768
    }
  ],
  "has_more": true
}

Files

Files are used to upload documents that can be used with features like Assistants, Fine-tuning, and Batch API.

Upload file

POST/v1/files

Upload a file that can be used across various endpoints. Individual files can be up to 512 MB, and the size of all files uploaded by one organization can be up to 100 GB.

Request body

NameTypeDescription
filefileRequiredThe File object to be uploaded.
purposestringRequiredThe intended purpose of the uploaded file. Use "assistants" for Assistants and Message files, "fine-tune" for Fine-tuning, "vision" for Assistants image file inputs, and "batch" for Batch API.
Example request
curl https://api.openai.com/v1/files \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F purpose="fine-tune" \
  -F file="@mydata.jsonl"
Response
{
  "id": "file-BK7bzQj3FfZFXr7DbL6xJwfo",
  "object": "file",
  "bytes": 120000,
  "created_at": 1677610602,
  "filename": "mydata.jsonl",
  "purpose": "fine-tune"
}

List files

GET/v1/files

Returns a list of files that belong to the user's organization.

Request body

NameTypeDescription
purposestringOptionalOnly return files with the given purpose.
Example request
curl https://api.openai.com/v1/files \
  -H "Authorization: Bearer $OPENAI_API_KEY"
Response
{
  "data": [
    {
      "id": "file-abc123",
      "object": "file",
      "bytes": 175,
      "created_at": 1613677385,
      "filename": "train.jsonl",
      "purpose": "fine-tune"
    },
    {
      "id": "file-def456",
      "object": "file",
      "bytes": 140,
      "created_at": 1613779121,
      "filename": "puppy.jsonl",
      "purpose": "fine-tune"
    }
  ],
  "object": "list"
}

Delete file

DELETE/v1/files/{file_id}

Delete a file.

Request body

NameTypeDescription
file_idstringRequiredThe ID of the file to use for this request.
Example request
curl https://api.openai.com/v1/files/file-abc123 \
  -X DELETE \
  -H "Authorization: Bearer $OPENAI_API_KEY"
Response
{
  "id": "file-abc123",
  "object": "file",
  "deleted": true
}

Models

List and describe the various models available in the API. You can refer to the Models documentation to understand which models are available and the differences between them.

List models

GET/v1/models

Lists the currently available models, and provides basic information about each one such as the owner and availability.

Example request
curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"
Response
{
  "object": "list",
  "data": [
    {
      "id": "gpt-4o",
      "object": "model",
      "created": 1686935002,
      "owned_by": "system"
    },
    {
      "id": "gpt-4o-mini",
      "object": "model",
      "created": 1721172741,
      "owned_by": "system"
    },
    {
      "id": "dall-e-3",
      "object": "model",
      "created": 1698785189,
      "owned_by": "system"
    }
  ]
}

Retrieve model

GET/v1/models/{model}

Retrieves a model instance, providing basic information about the model such as the owner and permissioning.

Request body

NameTypeDescription
modelstringRequiredThe ID of the model to use for this request.
Example request
curl https://api.openai.com/v1/models/gpt-4o \
  -H "Authorization: Bearer $OPENAI_API_KEY"
Response
{
  "id": "gpt-4o",
  "object": "model",
  "created": 1686935002,
  "owned_by": "system"
}

Delete a fine-tuned model

DELETE/v1/models/{model}

Delete a fine-tuned model. You must have the Owner role in your organization to delete a model.

Request body

NameTypeDescription
modelstringRequiredThe model to delete.
Example request
curl https://api.openai.com/v1/models/ft:gpt-4o-mini:acemeco:suffix:abc123 \
  -X DELETE \
  -H "Authorization: Bearer $OPENAI_API_KEY"
Response
{
  "id": "ft:gpt-4o-mini:acemeco:suffix:abc123",
  "object": "model",
  "deleted": true
}

Assistants

Build assistants that can call models and use tools to perform tasks. Related guide: Assistants overview.

Create assistant

POST/v1/assistants

Create an assistant with a model and instructions.

Request body

NameTypeDescription
modelstringRequiredID of the model to use.
namestring | nullOptionalThe name of the assistant. The maximum length is 256 characters.
descriptionstring | nullOptionalThe description of the assistant. The maximum length is 512 characters.
instructionsstring | nullOptionalThe system instructions that the assistant uses. The maximum length is 256,000 characters.
toolsarrayOptionalA list of tools enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types code_interpreter, file_search, or function.
metadataobject | nullOptionalSet of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format.
Example request
curl https://api.openai.com/v1/assistants \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "instructions": "You are a personal math tutor.",
    "name": "Math Tutor",
    "tools": [{"type": "code_interpreter"}],
    "model": "gpt-4o"
  }'
Response
{
  "id": "asst_abc123",
  "object": "assistant",
  "created_at": 1698984975,
  "name": "Math Tutor",
  "description": null,
  "model": "gpt-4o",
  "instructions": "You are a personal math tutor.",
  "tools": [
    { "type": "code_interpreter" }
  ],
  "metadata": {},
  "top_p": 1.0,
  "temperature": 1.0,
  "response_format": "auto"
}

List assistants

GET/v1/assistants

Returns a list of assistants.

Request body

NameTypeDescription
limitintegerOptionalA limit on the number of objects to be returned. Limit can range between 1 and 100. Defaults to 20.
orderstringOptionalSort order by the created_at timestamp of the objects. "asc" for ascending order and "desc" for descending order. Defaults to "desc".
afterstringOptionalA cursor for use in pagination. after is an object ID that defines your place in the list.
beforestringOptionalA cursor for use in pagination. before is an object ID that defines your place in the list.
Example request
curl https://api.openai.com/v1/assistants?order=desc&limit=20 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2"
Response
{
  "object": "list",
  "data": [
    {
      "id": "asst_abc123",
      "object": "assistant",
      "created_at": 1698982736,
      "name": "Coding Helper",
      "description": null,
      "model": "gpt-4o",
      "instructions": "You are a helpful coding assistant.",
      "tools": [],
      "metadata": {}
    },
    {
      "id": "asst_abc456",
      "object": "assistant",
      "created_at": 1698982718,
      "name": "My Assistant",
      "description": null,
      "model": "gpt-4o",
      "instructions": "You are a helpful assistant.",
      "tools": [],
      "metadata": {}
    }
  ],
  "first_id": "asst_abc123",
  "last_id": "asst_abc456",
  "has_more": false
}