# k-openai-openapi-20250315 ``` openapi: 3.0.0 info: title: OpenAI API description: The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details. version: 2.3.0 termsOfService: https://openai.com/policies/terms-of-use contact: name: OpenAI Support url: https://help.openai.com/ license: name: MIT url: https://github.com/openai/openai-openapi/blob/master/LICENSE servers: - url: https://api.openai.com/v1 tags: - name: Assistants description: Build Assistants that can call models and use tools. - name: Audio description: Turn audio into text or text into audio. - name: Chat description: Given a list of messages comprising a conversation, the model will return a response. - name: Completions description: Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position. - name: Embeddings description: Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. - name: Fine-tuning description: Manage fine-tuning jobs to tailor a model to your specific training data. - name: Batch description: Create large batches of API requests to run asynchronously. - name: Files description: Files are used to upload documents that can be used with features like Assistants and Fine-tuning. - name: Uploads description: Use Uploads to upload large files in multiple parts. - name: Images description: Given a prompt and/or an input image, the model will generate a new image. - name: Models description: List and describe the various models available in the API. - name: Moderations description: Given text and/or image inputs, classifies if those inputs are potentially harmful. - name: Audit Logs description: List user actions and configuration changes within this organization. paths: /assistants: get: operationId: listAssistants tags: - Assistants summary: Returns a list of assistants. parameters: - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 - name: order in: query description: > Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. schema: type: string default: desc enum: - asc - desc - name: after in: query description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. schema: type: string - name: before in: query description: > A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. schema: type: string responses: "200": description: OK content: application/json: schema: $ref: "#/components/schemas/ListAssistantsResponse" x-oaiMeta: name: List assistants group: assistants beta: true returns: A list of [assistant](/docs/api-reference/assistants/object) objects. examples: request: curl: | 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" python: | from openai import OpenAI client = OpenAI() my_assistants = client.beta.assistants.list( order="desc", limit="20", ) print(my_assistants.data) node.js: |- import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const myAssistants = await openai.beta.assistants.list({ order: "desc", limit: "20", }); console.log(myAssistants.data); } main(); response: > { "object": "list", "data": [ { "id": "asst_abc123", "object": "assistant", "created_at": 1698982736, "name": "Coding Tutor", "description": null, "model": "gpt-4o", "instructions": "You are a helpful assistant designed to make me better at coding!", "tools": [], "tool_resources": {}, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" }, { "id": "asst_abc456", "object": "assistant", "created_at": 1698982718, "name": "My Assistant", "description": null, "model": "gpt-4o", "instructions": "You are a helpful assistant designed to make me better at coding!", "tools": [], "tool_resources": {}, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" }, { "id": "asst_abc789", "object": "assistant", "created_at": 1698982643, "name": null, "description": null, "model": "gpt-4o", "instructions": null, "tools": [], "tool_resources": {}, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } ], "first_id": "asst_abc123", "last_id": "asst_abc789", "has_more": false } post: operationId: createAssistant tags: - Assistants summary: Create an assistant with a model and instructions. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateAssistantRequest" responses: "200": description: OK content: application/json: schema: $ref: "#/components/schemas/AssistantObject" x-oaiMeta: name: Create assistant group: assistants beta: true returns: An [assistant](/docs/api-reference/assistants/object) object. examples: - title: Code Interpreter request: curl: > 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. When asked a question, write and run Python code to answer the question.", "name": "Math Tutor", "tools": [{"type": "code_interpreter"}], "model": "gpt-4o" }' python: > from openai import OpenAI client = OpenAI() my_assistant = client.beta.assistants.create( instructions="You are a personal math tutor. When asked a question, write and run Python code to answer the question.", name="Math Tutor", tools=[{"type": "code_interpreter"}], model="gpt-4o", ) print(my_assistant) node.js: >- import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const myAssistant = await openai.beta.assistants.create({ instructions: "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", name: "Math Tutor", tools: [{ type: "code_interpreter" }], model: "gpt-4o", }); console.log(myAssistant); } main(); response: > { "id": "asst_abc123", "object": "assistant", "created_at": 1698984975, "name": "Math Tutor", "description": null, "model": "gpt-4o", "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", "tools": [ { "type": "code_interpreter" } ], "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } - title: Files request: curl: > 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 an HR bot, and you have access to files to answer employee questions about company policies.", "tools": [{"type": "file_search"}], "tool_resources": {"file_search": {"vector_store_ids": ["vs_123"]}}, "model": "gpt-4o" }' python: > from openai import OpenAI client = OpenAI() my_assistant = client.beta.assistants.create( instructions="You are an HR bot, and you have access to files to answer employee questions about company policies.", name="HR Helper", tools=[{"type": "file_search"}], tool_resources={"file_search": {"vector_store_ids": ["vs_123"]}}, model="gpt-4o" ) print(my_assistant) node.js: >- import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const myAssistant = await openai.beta.assistants.create({ instructions: "You are an HR bot, and you have access to files to answer employee questions about company policies.", name: "HR Helper", tools: [{ type: "file_search" }], tool_resources: { file_search: { vector_store_ids: ["vs_123"] } }, model: "gpt-4o" }); console.log(myAssistant); } main(); response: > { "id": "asst_abc123", "object": "assistant", "created_at": 1699009403, "name": "HR Helper", "description": null, "model": "gpt-4o", "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", "tools": [ { "type": "file_search" } ], "tool_resources": { "file_search": { "vector_store_ids": ["vs_123"] } }, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } /assistants/{assistant_id}: get: operationId: getAssistant tags: - Assistants summary: Retrieves an assistant. parameters: - in: path name: assistant_id required: true schema: type: string description: The ID of the assistant to retrieve. responses: "200": description: OK content: application/json: schema: $ref: "#/components/schemas/AssistantObject" x-oaiMeta: name: Retrieve assistant group: assistants beta: true returns: The [assistant](/docs/api-reference/assistants/object) object matching the specified ID. examples: request: curl: | curl https://api.openai.com/v1/assistants/asst_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" python: | from openai import OpenAI client = OpenAI() my_assistant = client.beta.assistants.retrieve("asst_abc123") print(my_assistant) node.js: |- import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const myAssistant = await openai.beta.assistants.retrieve( "asst_abc123" ); console.log(myAssistant); } main(); response: > { "id": "asst_abc123", "object": "assistant", "created_at": 1699009709, "name": "HR Helper", "description": null, "model": "gpt-4o", "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", "tools": [ { "type": "file_search" } ], "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } post: operationId: modifyAssistant tags: - Assistants summary: Modifies an assistant. parameters: - in: path name: assistant_id required: true schema: type: string description: The ID of the assistant to modify. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ModifyAssistantRequest" responses: "200": description: OK content: application/json: schema: $ref: "#/components/schemas/AssistantObject" x-oaiMeta: name: Modify assistant group: assistants beta: true returns: The modified [assistant](/docs/api-reference/assistants/object) object. examples: request: curl: > curl https://api.openai.com/v1/assistants/asst_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", "tools": [{"type": "file_search"}], "model": "gpt-4o" }' python: > from openai import OpenAI client = OpenAI() my_updated_assistant = client.beta.assistants.update( "asst_abc123", instructions="You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", name="HR Helper", tools=[{"type": "file_search"}], model="gpt-4o" ) print(my_updated_assistant) node.js: >- import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const myUpdatedAssistant = await openai.beta.assistants.update( "asst_abc123", { instructions: "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", name: "HR Helper", tools: [{ type: "file_search" }], model: "gpt-4o" } ); console.log(myUpdatedAssistant); } main(); response: > { "id": "asst_123", "object": "assistant", "created_at": 1699009709, "name": "HR Helper", "description": null, "model": "gpt-4o", "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", "tools": [ { "type": "file_search" } ], "tool_resources": { "file_search": { "vector_store_ids": [] } }, "metadata": {}, "top_p": 1.0, "temperature": 1.0, "response_format": "auto" } delete: operationId: deleteAssistant tags: - Assistants summary: Delete an assistant. parameters: - in: path name: assistant_id required: true schema: type: string description: The ID of the assistant to delete. responses: "200": description: OK content: application/json: schema: $ref: "#/components/schemas/DeleteAssistantResponse" x-oaiMeta: name: Delete assistant group: assistants beta: true returns: Deletion status examples: request: curl: | curl https://api.openai.com/v1/assistants/asst_abc123 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -X DELETE python: | from openai import OpenAI client = OpenAI() response = client.beta.assistants.delete("asst_abc123") print(response) node.js: >- import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const response = await openai.beta.assistants.del("asst_abc123"); console.log(response); } main(); response: | { "id": "asst_abc123", "object": "assistant.deleted", "deleted": true } /audio/speech: post: operationId: createSpeech tags: - Audio summary: Generates audio from the input text. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateSpeechRequest" responses: "200": description: OK headers: Transfer-Encoding: schema: type: string description: chunked content: application/octet-stream: schema: type: string format: binary x-oaiMeta: name: Create speech group: audio returns: The audio file content. examples: request: curl: | 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 python: | from pathlib import Path import openai speech_file_path = Path(__file__).parent / "speech.mp3" response = openai.audio.speech.create( model="tts-1", voice="alloy", input="The quick brown fox jumped over the lazy dog." ) response.stream_to_file(speech_file_path) node: > import fs from "fs"; import path from "path"; import OpenAI from "openai"; const openai = new OpenAI(); const speechFile = path.resolve("./speech.mp3"); async function main() { const mp3 = await openai.audio.speech.create({ model: "tts-1", voice: "alloy", input: "Today is a wonderful day to build something people love!", }); console.log(speechFile); const buffer = Buffer.from(await mp3.arrayBuffer()); await fs.promises.writeFile(speechFile, buffer); } main(); csharp: | using System; using System.IO; using OpenAI.Audio; AudioClient client = new( model: "tts-1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); BinaryData speech = client.GenerateSpeech( text: "The quick brown fox jumped over the lazy dog.", voice: GeneratedSpeechVoice.Alloy ); using FileStream stream = File.OpenWrite("speech.mp3"); speech.ToStream().CopyTo(stream); /audio/transcriptions: post: operationId: createTranscription tags: - Audio summary: Transcribes audio into the input language. requestBody: required: true content: multipart/form-data: schema: $ref: "#/components/schemas/CreateTranscriptionRequest" responses: "200": description: OK content: application/json: schema: oneOf: - $ref: "#/components/schemas/CreateTranscriptionResponseJson" - $ref: "#/components/schemas/CreateTranscriptionResponseVerboseJson" x-oaiMeta: name: Create transcription group: audio returns: The [transcription object](/docs/api-reference/audio/json-object) or a [verbose transcription object](/docs/api-reference/audio/verbose-json-object). examples: - title: Default request: curl: | 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" python: | from openai import OpenAI client = OpenAI() audio_file = open("speech.mp3", "rb") transcript = client.audio.transcriptions.create( model="whisper-1", file=audio_file ) node: > import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const transcription = await openai.audio.transcriptions.create({ file: fs.createReadStream("audio.mp3"), model: "whisper-1", }); console.log(transcription.text); } main(); csharp: > using System; using OpenAI.Audio; string audioFilePath = "audio.mp3"; AudioClient client = new( model: "whisper-1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); AudioTranscription transcription = client.TranscribeAudio(audioFilePath); Console.WriteLine($"{transcription.Text}"); 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. This is a place where you can get to do that." } - title: Word timestamps request: curl: | 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 "timestamp_granularities[]=word" \ -F model="whisper-1" \ -F response_format="verbose_json" python: | from openai import OpenAI client = OpenAI() audio_file = open("speech.mp3", "rb") transcript = client.audio.transcriptions.create( file=audio_file, model="whisper-1", response_format="verbose_json", timestamp_granularities=["word"] ) print(transcript.words) node: > import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const transcription = await openai.audio.transcriptions.create({ file: fs.createReadStream("audio.mp3"), model: "whisper-1", response_format: "verbose_json", timestamp_granularities: ["word"] }); console.log(transcription.text); } main(); csharp: > using System; using OpenAI.Audio; string audioFilePath = "audio.mp3"; AudioClient client = new( model: "whisper-1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); AudioTranscriptionOptions options = new() { ResponseFormat = AudioTranscriptionFormat.Verbose, TimestampGranularities = AudioTimestampGranularities.Word, }; AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options); Console.WriteLine($"{transcription.Text}"); response: > { "task": "transcribe", "language": "english", "duration": 8.470000267028809, "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.", "words": [ { "word": "The", "start": 0.0, "end": 0.23999999463558197 }, ... { "word": "volleyball", "start": 7.400000095367432, "end": 7.900000095367432 } ] } - title: Segment timestamps request: curl: | 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 "timestamp_granularities[]=segment" \ -F model="whisper-1" \ -F response_format="verbose_json" python: | from openai import OpenAI client = OpenAI() audio_file = open("speech.mp3", "rb") transcript = client.audio.transcriptions.create( file=audio_file, model="whisper-1", response_format="verbose_json", timestamp_granularities=["segment"] ) print(transcript.words) node: > import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const transcription = await openai.audio.transcriptions.create({ file: fs.createReadStream("audio.mp3"), model: "whisper-1", response_format: "verbose_json", timestamp_granularities: ["segment"] }); console.log(transcription.text); } main(); csharp: > using System; using OpenAI.Audio; string audioFilePath = "audio.mp3"; AudioClient client = new( model: "whisper-1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); AudioTranscriptionOptions options = new() { ResponseFormat = AudioTranscriptionFormat.Verbose, TimestampGranularities = AudioTimestampGranularities.Segment, }; AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options); Console.WriteLine($"{transcription.Text}"); response: > { "task": "transcribe", "language": "english", "duration": 8.470000267028809, "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.", "segments": [ { "id": 0, "seek": 0, "start": 0.0, "end": 3.319999933242798, "text": " The beach was a popular spot on a hot summer day.", "tokens": [ 50364, 440, 7534, 390, 257, 3743, 4008, 322, 257, 2368, 4266, 786, 13, 50530 ], "temperature": 0.0, "avg_logprob": -0.2860786020755768, "compression_ratio": 1.2363636493682861, "no_speech_prob": 0.00985979475080967 }, ... ] } /audio/translations: post: operationId: createTranslation tags: - Audio summary: Translates audio into English. requestBody: required: true content: multipart/form-data: schema: $ref: "#/components/schemas/CreateTranslationRequest" responses: "200": description: OK content: application/json: schema: oneOf: - $ref: "#/components/schemas/CreateTranslationResponseJson" - $ref: "#/components/schemas/CreateTranslationResponseVerboseJson" x-oaiMeta: name: Create translation group: audio returns: The translated text. examples: request: curl: | curl https://api.openai.com/v1/audio/translations \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: multipart/form-data" \ -F file="@/path/to/file/german.m4a" \ -F model="whisper-1" python: | from openai import OpenAI client = OpenAI() audio_file = open("speech.mp3", "rb") transcript = client.audio.translations.create( model="whisper-1", file=audio_file ) node: | import fs from "fs"; import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const translation = await openai.audio.translations.create({ file: fs.createReadStream("speech.mp3"), model: "whisper-1", }); console.log(translation.text); } main(); csharp: > using System; using OpenAI.Audio; string audioFilePath = "audio.mp3"; AudioClient client = new( model: "whisper-1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); AudioTranscription transcription = client.TranscribeAudio(audioFilePath); Console.WriteLine($"{transcription.Text}"); response: > { "text": "Hello, my name is Wolfgang and I come from Germany. Where are you heading today?" } /batches: post: summary: Creates and executes a batch from an uploaded file of requests operationId: createBatch tags: - Batch requestBody: required: true content: application/json: schema: type: object required: - input_file_id - endpoint - completion_window properties: input_file_id: type: string description: > The ID of an uploaded file that contains requests for the new batch. See [upload file](/docs/api-reference/files/create) for how to upload a file. Your input file must be formatted as a [JSONL file](/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 200 MB in size. endpoint: type: string enum: - /v1/chat/completions - /v1/embeddings - /v1/completions description: The endpoint to be used for all requests in the batch. Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch. completion_window: type: string enum: - 24h description: The time frame within which the batch should be processed. Currently only `24h` is supported. metadata: $ref: "#/components/schemas/Metadata" responses: "200": description: Batch created successfully. content: application/json: schema: $ref: "#/components/schemas/Batch" x-oaiMeta: name: Create batch group: batch returns: The created [Batch](/docs/api-reference/batch/object) object. examples: request: curl: | curl https://api.openai.com/v1/batches \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "input_file_id": "file-abc123", "endpoint": "/v1/chat/completions", "completion_window": "24h" }' python: | from openai import OpenAI client = OpenAI() client.batches.create( input_file_id="file-abc123", endpoint="/v1/chat/completions", completion_window="24h" ) node: | import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const batch = await openai.batches.create({ input_file_id: "file-abc123", endpoint: "/v1/chat/completions", completion_window: "24h" }); console.log(batch); } main(); response: | { "id": "batch_abc123", "object": "batch", "endpoint": "/v1/chat/completions", "errors": null, "input_file_id": "file-abc123", "completion_window": "24h", "status": "validating", "output_file_id": null, "error_file_id": null, "created_at": 1711471533, "in_progress_at": null, "expires_at": null, "finalizing_at": null, "completed_at": null, "failed_at": null, "expired_at": null, "cancelling_at": null, "cancelled_at": null, "request_counts": { "total": 0, "completed": 0, "failed": 0 }, "metadata": { "customer_id": "user_123456789", "batch_description": "Nightly eval job", } } get: operationId: listBatches tags: - Batch summary: List your organization's batches. parameters: - in: query name: after required: false schema: type: string description: > A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - name: limit in: query description: > A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. required: false schema: type: integer default: 20 responses: "200": description: Batch listed successfully. content: application/json: schema: $ref: "#/components/schemas/ListBatchesResponse" x-oaiMeta: name: List batch group: batch returns: A list of paginated [Batch](/docs/api-reference/batch/object) objects. examples: request: curl: | curl https://api.openai.com/v1/batches?limit=2 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: | from openai import OpenAI client = OpenAI() client.batches.list() node: | import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const list = await openai.batches.list(); for await (const batch of list) { console.log(batch); } } main(); response: | { "object": "list", "data": [ { "id": "batch_abc123", "object": "batch", "endpoint": "/v1/chat/completions", "errors": null, "input_file_id": "file-abc123", "completion_window": "24h", "status": "completed", "output_file_id": "file-cvaTdG", "error_file_id": "file-HOWS94", "created_at": 1711471533, "in_progress_at": 1711471538, "expires_at": 1711557933, "finalizing_at": 1711493133, "completed_at": 1711493163, "failed_at": null, "expired_at": null, "cancelling_at": null, "cancelled_at": null, "request_counts": { "total": 100, "completed": 95, "failed": 5 }, "metadata": { "customer_id": "user_123456789", "batch_description": "Nightly job", } }, { ... }, ], "first_id": "batch_abc123", "last_id": "batch_abc456", "has_more": true } /batches/{batch_id}: get: operationId: retrieveBatch tags: - Batch summary: Retrieves a batch. parameters: - in: path name: batch_id required: true schema: type: string description: The ID of the batch to retrieve. responses: "200": description: Batch retrieved successfully. content: application/json: schema: $ref: "#/components/schemas/Batch" x-oaiMeta: name: Retrieve batch group: batch returns: The [Batch](/docs/api-reference/batch/object) object matching the specified ID. examples: request: curl: | curl https://api.openai.com/v1/batches/batch_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ python: | from openai import OpenAI client = OpenAI() client.batches.retrieve("batch_abc123") node: | import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const batch = await openai.batches.retrieve("batch_abc123"); console.log(batch); } main(); response: | { "id": "batch_abc123", "object": "batch", "endpoint": "/v1/completions", "errors": null, "input_file_id": "file-abc123", "completion_window": "24h", "status": "completed", "output_file_id": "file-cvaTdG", "error_file_id": "file-HOWS94", "created_at": 1711471533, "in_progress_at": 1711471538, "expires_at": 1711557933, "finalizing_at": 1711493133, "completed_at": 1711493163, "failed_at": null, "expired_at": null, "cancelling_at": null, "cancelled_at": null, "request_counts": { "total": 100, "completed": 95, "failed": 5 }, "metadata": { "customer_id": "user_123456789", "batch_description": "Nightly eval job", } } /batches/{batch_id}/cancel: post: operationId: cancelBatch tags: - Batch summary: Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, before changing to `cancelled`, where it will have partial results (if any) available in the output file. parameters: - in: path name: batch_id required: true schema: type: string description: The ID of the batch to cancel. responses: "200": description: Batch is cancelling. Returns the cancelling batch's details. content: application/json: schema: $ref: "#/components/schemas/Batch" x-oaiMeta: name: Cancel batch group: batch returns: The [Batch](/docs/api-reference/batch/object) object matching the specified ID. examples: request: curl: | curl https://api.openai.com/v1/batches/batch_abc123/cancel \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -X POST python: | from openai import OpenAI client = OpenAI() client.batches.cancel("batch_abc123") node: | import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const batch = await openai.batches.cancel("batch_abc123"); console.log(batch); } main(); response: | { "id": "batch_abc123", "object": "batch", "endpoint": "/v1/chat/completions", "errors": null, "input_file_id": "file-abc123", "completion_window": "24h", "status": "cancelling", "output_file_id": null, "error_file_id": null, "created_at": 1711471533, "in_progress_at": 1711471538, "expires_at": 1711557933, "finalizing_at": null, "completed_at": null, "failed_at": null, "expired_at": null, "cancelling_at": 1711475133, "cancelled_at": null, "request_counts": { "total": 100, "completed": 23, "failed": 1 }, "metadata": { "customer_id": "user_123456789", "batch_description": "Nightly eval job", } } /chat/completions: get: operationId: listChatCompletions tags: - Chat summary: > List stored Chat Completions. Only Chat Completions that have been stored with the `store` parameter set to `true` will be returned. parameters: - name: model in: query description: The model used to generate the Chat Completions. required: false schema: type: string - name: metadata in: query description: | A list of metadata keys to filter the Chat Completions by. Example: `metadata[key1]=value1&metadata[key2]=value2` required: false schema: $ref: "#/components/schemas/Metadata" - name: after in: query description: Identifier for the last chat completion from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of Chat Completions to retrieve. required: false schema: type: integer default: 20 - name: order in: query description: Sort order for Chat Completions by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. required: false schema: type: string enum: - asc - desc default: asc responses: "200": description: A list of Chat Completions content: application/json: schema: $ref: "#/components/schemas/ChatCompletionList" x-oaiMeta: name: List Chat Completions group: chat returns: A list of [Chat Completions](/docs/api-reference/chat/list-object) matching the specified filters. path: list examples: request: curl: | curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: | from openai import OpenAI client = OpenAI() completions = client.chat.completions.list() print(completions) response: > { "object": "list", "data": [ { "object": "chat.completion", "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "model": "gpt-4o-2024-08-06", "created": 1738960610, "request_id": "req_ded8ab984ec4bf840f37566c1011c417", "tool_choice": null, "usage": { "total_tokens": 31, "completion_tokens": 18, "prompt_tokens": 13 }, "seed": 4944116822809979520, "top_p": 1.0, "temperature": 1.0, "presence_penalty": 0.0, "frequency_penalty": 0.0, "system_fingerprint": "fp_50cad350e4", "input_user": null, "service_tier": "default", "tools": null, "metadata": {}, "choices": [ { "index": 0, "message": { "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", "role": "assistant", "tool_calls": null, "function_call": null }, "finish_reason": "stop", "logprobs": null } ], "response_format": null } ], "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "has_more": false } post: operationId: createChatCompletion tags: - Chat summary: > **Starting a new project?** We recommend trying [Responses](/docs/api-reference/responses) to take advantage of the latest OpenAI platform features. Compare [Chat Completions with Responses](/docs/guides/responses-vs-chat-completions?api-mode=responses). --- Creates a model response for the given chat conversation. Learn more in the [text generation](/docs/guides/text-generation), [vision](/docs/guides/vision), and [audio](/docs/guides/audio) guides. Parameter support can differ depending on the model used to generate the response, particularly for newer reasoning models. Parameters that are only supported for reasoning models are noted below. For the current state of unsupported parameters in reasoning models, [refer to the reasoning guide](/docs/guides/reasoning). requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateChatCompletionRequest" responses: "200": description: OK content: application/json: schema: $ref: "#/components/schemas/CreateChatCompletionResponse" text/event-stream: schema: $ref: "#/components/schemas/CreateChatCompletionStreamResponse" x-oaiMeta: name: Create chat completion group: chat returns: > Returns a [chat completion](/docs/api-reference/chat/object) object, or a streamed sequence of [chat completion chunk](/docs/api-reference/chat/streaming) objects if the request is streamed. path: create examples: - title: Default request: curl: | curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "VAR_chat_model_id", "messages": [ { "role": "developer", "content": "You are a helpful assistant." }, { "role": "user", "content": "Hello!" } ] }' python: > from openai import OpenAI client = OpenAI() completion = client.chat.completions.create( model="VAR_chat_model_id", messages=[ {"role": "developer", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"} ] ) print(completion.choices[0].message) node.js: > import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const completion = await openai.chat.completions.create({ messages: [{ role: "developer", content: "You are a helpful assistant." }], model: "VAR_chat_model_id", store: true, }); console.log(completion.choices[0]); } main(); csharp: | using System; using System.Collections.Generic; using OpenAI.Chat; ChatClient client = new( model: "gpt-4o", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); List<ChatMessage> messages = [ new SystemChatMessage("You are a helpful assistant."), new UserChatMessage("Hello!") ]; ChatCompletion completion = client.CompleteChat(messages); Console.WriteLine(completion.Content[0].Text); response: | { "id": "chatcmpl-B9MBs8CjcvOU2jLn4n570S5qMJKcT", "object": "chat.completion", "created": 1741569952, "model": "gpt-4o-2024-08-06", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! How can I assist you today?", "refusal": null, "annotations": [] }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 19, "completion_tokens": 10, "total_tokens": 29, "prompt_tokens_details": { "cached_tokens": 0, "audio_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 0, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } }, "service_tier": "default" } - title: Image input request: curl: > 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": [ { "type": "text", "text": "What is in this image?" }, { "type": "image_url", "image_url": { "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" } } ] } ], "max_tokens": 300 }' python: > from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="gpt-4o", messages=[ { "role": "user", "content": [ {"type": "text", "text": "What's in this image?"}, { "type": "image_url", "image_url": { "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", } }, ], } ], max_tokens=300, ) print(response.choices[0]) node.js: > import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const response = await openai.chat.completions.create({ model: "gpt-4o", messages: [ { role: "user", content: [ { type: "text", text: "What's in this image?" }, { type: "image_url", image_url: { "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", }, } ], }, ], }); console.log(response.choices[0]); } main(); csharp: > using System; using System.Collections.Generic; using OpenAI.Chat; ChatClient client = new( model: "gpt-4o", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); List<ChatMessage> messages = [ new UserChatMessage( [ ChatMessageContentPart.CreateTextPart("What's in this image?"), ChatMessageContentPart.CreateImagePart(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg")) ]) ]; ChatCompletion completion = client.CompleteChat(messages); Console.WriteLine(completion.Content[0].Text); response: > { "id": "chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG", "object": "chat.completion", "created": 1741570283, "model": "gpt-4o-2024-08-06", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The image shows a wooden boardwalk path running through a lush green field or meadow. The sky is bright blue with some scattered clouds, giving the scene a serene and peaceful atmosphere. Trees and shrubs are visible in the background.", "refusal": null, "annotations": [] }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 1117, "completion_tokens": 46, "total_tokens": 1163, "prompt_tokens_details": { "cached_tokens": 0, "audio_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 0, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } }, "service_tier": "default" } - title: Streaming request: curl: | curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "VAR_chat_model_id", "messages": [ { "role": "developer", "content": "You are a helpful assistant." }, { "role": "user", "content": "Hello!" } ], "stream": true }' python: > from openai import OpenAI client = OpenAI() completion = client.chat.completions.create( model="VAR_chat_model_id", messages=[ {"role": "developer", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"} ], stream=True ) for chunk in completion: print(chunk.choices[0].delta) node.js: > import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const completion = await openai.chat.completions.create({ model: "VAR_chat_model_id", messages: [ {"role": "developer", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"} ], stream: true, }); for await (const chunk of completion) { console.log(chunk.choices[0].delta.content); } } main(); csharp: > using System; using System.ClientModel; using System.Collections.Generic; using System.Threading.Tasks; using OpenAI.Chat; ChatClient client = new( model: "gpt-4o", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); List<ChatMessage> messages = [ new SystemChatMessage("You are a helpful assistant."), new UserChatMessage("Hello!") ]; AsyncCollectionResult<StreamingChatCompletionUpdate> completionUpdates = client.CompleteChatStreamingAsync(messages); await foreach (StreamingChatCompletionUpdate completionUpdate in completionUpdates) { if (completionUpdate.ContentUpdate.Count > 0) { Console.Write(completionUpdate.ContentUpdate[0].Text); } } response: > {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]} {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]} .... {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - title: Functions request: curl: > 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": "What is the weather like in Boston today?" } ], "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } } ], "tool_choice": "auto" }' python: > from openai import OpenAI client = OpenAI() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location"], }, } } ] messages = [{"role": "user", "content": "What's the weather like in Boston today?"}] completion = client.chat.completions.create( model="VAR_chat_model_id", messages=messages, tools=tools, tool_choice="auto" ) print(completion) node.js: > import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const messages = [{"role": "user", "content": "What's the weather like in Boston today?"}]; const tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location"], }, } } ]; const response = await openai.chat.completions.create({ model: "gpt-4o", messages: messages, tools: tools, tool_choice: "auto", }); console.log(response); } main(); csharp: > using System; using System.Collections.Generic; using OpenAI.Chat; ChatClient client = new( model: "gpt-4o", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool( functionName: "get_current_weather", functionDescription: "Get the current weather in a given location", functionParameters: BinaryData.FromString(""" { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": [ "celsius", "fahrenheit" ] } }, "required": [ "location" ] } """) ); List<ChatMessage> messages = [ new UserChatMessage("What's the weather like in Boston today?"), ]; ChatCompletionOptions options = new() { Tools = { getCurrentWeatherTool }, ToolChoice = ChatToolChoice.CreateAutoChoice(), }; ChatCompletion completion = client.CompleteChat(messages, options); response: | { "id": "chatcmpl-abc123", "object": "chat.completion", "created": 1699896916, "model": "gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": null, "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "get_current_weather", "arguments": "{\n\"location\": \"Boston, MA\"\n}" } } ] }, "logprobs": null, "finish_reason": "tool_calls" } ], "usage": { "prompt_tokens": 82, "completion_tokens": 17, "total_tokens": 99, "completion_tokens_details": { "reasoning_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } } } - title: Logprobs request: curl: | curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "VAR_chat_model_id", "messages": [ { "role": "user", "content": "Hello!" } ], "logprobs": true, "top_logprobs": 2 }' python: | from openai import OpenAI client = OpenAI() completion = client.chat.completions.create( model="VAR_chat_model_id", messages=[ {"role": "user", "content": "Hello!"} ], logprobs=True, top_logprobs=2 ) print(completion.choices[0].message) print(completion.choices[0].logprobs) node.js: | import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const completion = await openai.chat.completions.create({ messages: [{ role: "user", content: "Hello!" }], model: "VAR_chat_model_id", logprobs: true, top_logprobs: 2, }); console.log(completion.choices[0]); } main(); csharp: > using System; using System.Collections.Generic; using OpenAI.Chat; ChatClient client = new( model: "gpt-4o", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") ); List<ChatMessage> messages = [ new UserChatMessage("Hello!") ]; ChatCompletionOptions options = new() { IncludeLogProbabilities = true, TopLogProbabilityCount = 2 }; ChatCompletion completion = client.CompleteChat(messages, options); Console.WriteLine(completion.Content[0].Text); response: | { "id": "chatcmpl-123", "object": "chat.completion", "created": 1702685778, "model": "gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! How can I assist you today?" }, "logprobs": { "content": [ { "token": "Hello", "logprob": -0.31725305, "bytes": [72, 101, 108, 108, 111], "top_logprobs": [ { "token": "Hello", "logprob": -0.31725305, "bytes": [72, 101, 108, 108, 111] }, { "token": "Hi", "logprob": -1.3190403, "bytes": [72, 105] } ] }, { "token": "!", "logprob": -0.02380986, "bytes": [ 33 ], "top_logprobs": [ { "token": "!", "logprob": -0.02380986, "bytes": [33] }, { "token": " there", "logprob": -3.787621, "bytes": [32, 116, 104, 101, 114, 101] } ] }, { "token": " How", "logprob": -0.000054669687, "bytes": [32, 72, 111, 119], "top_logprobs": [ { "token": " How", "logprob": -0.000054669687, "bytes": [32, 72, 111, 119] }, { "token": "<|end|>", "logprob": -10.953937, "bytes": null } ] }, { "token": " can", "logprob": -0.015801601, "bytes": [32, 99, 97, 110], "top_logprobs": [ { "token": " can", "logprob": -0.015801601, "bytes": [32, 99, 97, 110] }, { "token": " may", "logprob": -4.161023, "bytes": [32, 109, 97, 121] } ] }, { "token": " I", "logprob": -3.7697225e-6, "bytes": [ 32, 73 ], "top_logprobs": [ { "token": " I", "logprob": -3.7697225e-6, "bytes": [32, 73] }, { "token": " assist", "logprob": -13.596657, "bytes": [32, 97, 115, 115, 105, 115, 116] } ] }, { "token": " assist", "logprob": -0.04571125, "bytes": [32, 97, 115, 115, 105, 115, 116], "top_logprobs": [ { "token": " assist", "logprob": -0.04571125, "bytes": [32, 97, 115, 115, 105, 115, 116] }, { "token": " help", "logprob": -3.1089056, "bytes": [32, 104, 101, 108, 112] } ] }, { "token": " you", "logprob": -5.4385737e-6, "bytes": [32, 121, 111, 117], "top_logprobs": [ { "token": " you", "logprob": -5.4385737e-6, "bytes": [32, 121, 111, 117] }, { "token": " today", "logprob": -12.807695, "bytes": [32, 116, 111, 100, 97, 121] } ] }, { "token": " today", "logprob": -0.0040071653, "bytes": [32, 116, 111, 100, 97, 121], "top_logprobs": [ { "token": " today", "logprob": -0.0040071653, "bytes": [32, 116, 111, 100, 97, 121] }, { "token": "?", "logprob": -5.5247097, "bytes": [63] } ] }, { "token": "?", "logprob": -0.0008108172, "bytes": [63], "top_logprobs": [ { "token": "?", "logprob": -0.0008108172, "bytes": [63] }, { "token": "?\n", "logprob": -7.184561, "bytes": [63, 10] } ] } ] }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 9, "completion_tokens": 9, "total_tokens": 18, "completion_tokens_details": { "reasoning_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } }, "system_fingerprint": null } /chat/completions/{completion_id}: get: operationId: getChatCompletion tags: - Chat summary: > Get a stored chat completion. Only Chat Completions that have been created with the `store` parameter set to `true` will be returned. parameters: - in: path name: completion_id required: true schema: type: string description: The ID of the chat completion to retrieve. responses: "200": description: A chat completion content: application/json: schema: $ref: "#/components/schemas/CreateChatCompletionResponse" x-oaiMeta: name: Get chat completion group: chat returns: The [ChatCompletion](/docs/api-reference/chat/object) object matching the specified ID. examples: request: curl: | curl https://api.openai.com/v1/chat/completions/chatcmpl-abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: > from openai import OpenAI client = OpenAI() completions = client.chat.completions.list() first_id = completions[0].id first_completion = client.chat.completions.retrieve(completion_id=first_id) print(first_completion) response: > { "object": "chat.completion", "id": "chatcmpl-abc123", "model": "gpt-4o-2024-08-06", "created": 1738960610, "request_id": "req_ded8ab984ec4bf840f37566c1011c417", "tool_choice": null, "usage": { "total_tokens": 31, "completion_tokens": 18, "prompt_tokens": 13 }, "seed": 4944116822809979520, "top_p": 1.0, "temperature": 1.0, "presence_penalty": 0.0, "frequency_penalty": 0.0, "system_fingerprint": "fp_50cad350e4", "input_user": null, "service_tier": "default", "tools": null, "metadata": {}, "choices": [ { "index": 0, "message": { "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", "role": "assistant", "tool_calls": null, "function_call": null }, "finish_reason": "stop", "logprobs": null } ], "response_format": null } post: operationId: updateChatCompletion tags: - Chat summary: > Modify a stored chat completion. Only Chat Completions that have been created with the `store` parameter set to `true` can be modified. Currently, the only supported modification is to update the `metadata` field. parameters: - in: path name: completion_id required: true schema: type: string description: The ID of the chat completion to update. requestBody: required: true content: application/json: schema: type: object required: - metadata properties: metadata: $ref: "#/components/schemas/Metadata" responses: "200": description: A chat completion content: application/json: schema: $ref: "#/components/schemas/CreateChatCompletionResponse" x-oaiMeta: name: Update chat completion group: chat returns: The [ChatCompletion](/docs/api-reference/chat/object) object matching the specified ID. examples: request: curl: > curl -X POST https://api.openai.com/v1/chat/completions/chat_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{"metadata": {"foo": "bar"}}' python: > from openai import OpenAI client = OpenAI() completions = client.chat.completions.list() first_id = completions[0].id updated_completion = client.chat.completions.update(completion_id=first_id, request_body={"metadata": {"foo": "bar"}}) print(updated_completion) response: > { "object": "chat.completion", "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "model": "gpt-4o-2024-08-06", "created": 1738960610, "request_id": "req_ded8ab984ec4bf840f37566c1011c417", "tool_choice": null, "usage": { "total_tokens": 31, "completion_tokens": 18, "prompt_tokens": 13 }, "seed": 4944116822809979520, "top_p": 1.0, "temperature": 1.0, "presence_penalty": 0.0, "frequency_penalty": 0.0, "system_fingerprint": "fp_50cad350e4", "input_user": null, "service_tier": "default", "tools": null, "metadata": { "foo": "bar" }, "choices": [ { "index": 0, "message": { "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", "role": "assistant", "tool_calls": null, "function_call": null }, "finish_reason": "stop", "logprobs": null } ], "response_format": null } delete: operationId: deleteChatCompletion tags: - Chat summary: | Delete a stored chat completion. Only Chat Completions that have been created with the `store` parameter set to `true` can be deleted. parameters: - in: path name: completion_id required: true schema: type: string description: The ID of the chat completion to delete. responses: "200": description: The chat completion was deleted successfully. content: application/json: schema: $ref: "#/components/schemas/ChatCompletionDeleted" x-oaiMeta: name: Delete chat completion group: chat returns: A deletion confirmation object. examples: request: curl: > curl -X DELETE https://api.openai.com/v1/chat/completions/chat_abc123 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: > from openai import OpenAI client = OpenAI() completions = client.chat.completions.list() first_id = completions[0].id delete_response = client.chat.completions.delete(completion_id=first_id) print(delete_response) response: | { "object": "chat.completion.deleted", "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", "deleted": true } /chat/completions/{completion_id}/messages: get: operationId: getChatCompletionMessages tags: - Chat summary: | Get the messages in a stored chat completion. Only Chat Completions that have been created with the `store` parameter set to `true` will be returned. parameters: - in: path name: completion_id required: true schema: type: string description: The ID of the chat completion to retrieve messages from. - name: after in: query description: Identifier for the last message from the previous pagination request. required: false schema: type: string - name: limit in: query description: Number of messages to retrieve. required: false schema: type: integer default: 20 - name: order in: query description: Sort order for messages by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. required: false schema: type: string enum: - asc - desc default: asc responses: "200": description: A list of messages content: application/json: schema: $ref: "#/components/schemas/ChatCompletionMessageList" x-oaiMeta: name: Get chat messages group: chat returns: A list of [messages](/docs/api-reference/chat/message-list) for the specified chat completion. examples: request: curl: > curl https://api.openai.com/v1/chat/completions/chat_abc123/messages \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" python: > from openai import OpenAI client = OpenAI() completions = client.chat.completions.list() first_id = completions[0].id first_completion = client.chat.completions.retrieve(completion_id=first_id) messages = client.chat.completions.messages.list(completion_id=first_id) print(messages) response: | { "object": "list", "data": [ { "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", "role": "user", "content": "write a haiku about ai", "name": null, "content_parts": null } ], "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", "has_more": false } /completions: post: operationId: createCompletion tags: - Completions summary: Creates a completion for the provided prompt and parameters. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateCompletionRequest" responses: "200": description: OK content: application/json: schema: $ref: "#/components/schemas/CreateCompletionResponse" x-oaiMeta: name: Create completion group: completions returns: > Returns a [completion](/docs/api-reference/completions/object) object, or a sequence of completion objects if the request is streamed. legacy: true examples: - title: No streaming request: curl: | curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "VAR_completion_model_id", "prompt": "Say this is a test", "max_tokens": 7, "temperature": 0 }' python: | from openai import OpenAI client = OpenAI() client.completions.create( model="VAR_completion_model_id", prompt="Say this is a test", max_tokens=7, temperature=0 ) node.js: |- import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const completion = await openai.completions.create({ model: "VAR_completion_model_id", prompt: "Say this is a test.", max_tokens: 7, temperature: 0, }); console.log(completion); } main(); response: | { "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", "object": "text_completion", "created": 1589478378, "model": "VAR_completion_model_id", "system_fingerprint": "fp_44709d6fcb", "choices": [ { "text": "\n\nThis is indeed a test", "index": 0, "logprobs": null, "finish_reason": "length" } ], "usage": { "prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12 } } - title: Streaming request: curl: | curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "VAR_completion_model_id", "prompt": "Say this is a test", "max_tokens": 7, "temperature": 0, "stream": true }' python: | from openai import OpenAI client = OpenAI() for chunk in client.completions.create( model="VAR_completion_model_id", prompt="Say this is a test", max_tokens=7, temperature=0, stream=True ): print(chunk.choices[0].text) node.js: |-