### Pagination Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Example of how to use cursor-based pagination with list endpoints. Parameters like 'limit' and 'after' control the number of items returned and the starting point. ```bash GET /v1/files?limit=100&after=file_abc123 ``` -------------------------------- ### List Endpoint Pagination Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/configuration.md Demonstrates how to use query parameters for pagination on list endpoints. You can control the number of items and specify a starting point. ```bash GET /v1/models?limit=100&after=model-id-123 ``` -------------------------------- ### Chat Completion Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md A 'Hello World' example demonstrating a basic chat completion request and its expected response. ```APIDOC ## Hello World: Chat Completion ```bash curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "messages": [{"role": "user", "content": "Hello, how are you?"}] }' ``` Response: ```json { "id": "chatcmpl-123", "object": "chat.completion", "created": 1234567890, "model": "gpt-4o", "choices": [{ "index": 0, "message": { "role": "assistant", "content": "Hello! I'm doing well, thank you for asking..." }, "finish_reason": "stop" }], "usage": { "prompt_tokens": 10, "completion_tokens": 25, "total_tokens": 35 } } ``` ``` -------------------------------- ### Complete Python Example with Tool Integration Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md A full Python example demonstrating how to use the OpenAI client library to interact with chat completions that utilize tools. It includes defining tools, a helper function for tool execution, and a conversation loop. ```python import json import openai client = openai.OpenAI() # Define tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get weather for a location", "parameters": { "type": "object", "properties": { "location": {"type": "string"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["location"] } } } ] # Helper function def get_weather(location, unit="celsius"): """Simulate weather lookup""" weather_data = { "San Francisco": {"celsius": 22, "fahrenheit": 72}, "New York": {"celsius": 18, "fahrenheit": 65} } return f"{location}: {weather_data[location][unit]}°{unit[0].upper()}" # Conversation loop messages = [{"role": "user", "content": "What's the weather in SF and NYC?"}] while True: response = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools, tool_choice="auto" ) assistant_message = response.choices[0].message messages.append(assistant_message) # Check if tool was called if response.choices[0].finish_reason == "tool_calls": tool_results = [] for tool_call in assistant_message.tool_calls: args = json.loads(tool_call.function.arguments) result = get_weather(**args) tool_results.append({ "role": "tool", "tool_call_id": tool_call.id, "content": result }) messages.extend(tool_results) else: # Model finished without tool calls print(assistant_message.content) break ``` -------------------------------- ### API Key Authentication Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Example of how to use an API key for authentication. The key should be included in the Authorization header as a Bearer token. ```text Authorization: Bearer sk-... ``` -------------------------------- ### Create Embedding Request Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md This example demonstrates how to create embeddings for text input using the OpenAI API. Ensure you have set the OPENAI_API_KEY environment variable. ```bash curl https://api.openai.com/v1/embeddings \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "input": "The quick brown fox jumps over the lazy dog", "model": "text-embedding-3-small" }' ``` -------------------------------- ### Authentication Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Demonstrates how to authenticate requests to the OpenAI API using an API key. ```APIDOC ## Authentication All requests require an `Authorization` header. ```bash curl https://api.openai.com/v1/models \ -H "Authorization: Bearer $OPENAI_API_KEY" ``` Get your API key from [platform.openai.com](https://platform.openai.com/account/api-keys). ``` -------------------------------- ### HTTP Response Header Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/configuration.md Example of a standard HTTP header for a successful JSON response. ```http HTTP/1.1 200 OK Content-Type: application/json Date: Mon, 11 Jun 2026 12:00:00 GMT Transfer-Encoding: chunked ``` -------------------------------- ### Configure OpenAI Client with API Key and Project Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/configuration.md This JavaScript example shows how to initialize the OpenAI client with an API key, organization ID, project ID, and other configuration options like max retries and timeout. ```javascript const OpenAI = require('openai'); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, organization: 'org-xxxxx', defaultHeaders: { 'OpenAI-Project': 'proj-xxxxx' }, maxRetries: 3, timeout: 30000 // 30 seconds }); const response = await openai.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello' }], temperature: 0.7, top_p: 0.9, max_tokens: 500, seed: 12345 }); ``` -------------------------------- ### Python Client Implementation Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Example of how to implement streaming using the OpenAI Python client library. It iterates over the stream to process each chunk as it arrives. ```APIDOC ### Python ```python from openai import OpenAI client = OpenAI(api_key="sk-...") stream = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Hello"}], stream=True, stream_options={"include_usage": True} ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="") ``` ``` -------------------------------- ### Making Function Calls - Step 1: Define Tools Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md This example demonstrates how to make a function call by defining tools in the API request to the chat completions endpoint. ```APIDOC ## Making Function Calls - Step 1: Define Tools ### Description This example shows how to initiate a function call by including the `tools` parameter in your request to the chat completions API. The model will then decide whether to use one of the provided tools. ### Method `POST` ### Endpoint `/v1/chat/completions` ### Request Body ```json { "model": "gpt-4o", "messages": [ { "role": "user", "content": "What is the weather in San Francisco?" } ], "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Get current weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City name" } }, "required": ["location"] } } } ] } ``` ### Request Example ```bash curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ ... }' # Request body as shown above ``` ``` -------------------------------- ### List Files with Pagination Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Example of how to list files using the API, demonstrating pagination parameters like limit and after. Ensure your OpenAI API key is set as an environment variable or passed directly. ```bash curl "https://api.openai.com/v1/files?limit=100&after=file_abc123" \ -H "Authorization: Bearer $OPENAI_API_KEY" ``` -------------------------------- ### Permission Error Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/errors.md This `permission_error` example indicates that the request failed due to insufficient permissions or exceeding a quota, such as hitting a rate limit or plan limit. ```json { "error": { "message": "You exceeded your current quota, please check your plan and billing settings.", "type": "permission_error", "param": null, "code": "exceeds_maximum_allowed_size" } } ``` -------------------------------- ### Making Function Calls - Step 2: Handle Tool Calls Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md This example shows the model's response when it decides to call a tool, including the structure of the `tool_calls` object. ```APIDOC ## Making Function Calls - Step 2: Handle Tool Calls ### Description This is an example of the model's response when it invokes a tool. The response includes a `finish_reason` of `tool_calls` and a `tool_calls` array containing the function name and arguments to be executed by the client. ### Response Example (Success) ```json { "id": "chatcmpl-123", "object": "chat.completion", "created": 1234567890, "model": "gpt-4o", "choices": [ { "index": 0, "message": { "role": "assistant", "content": null, "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "get_weather", "arguments": "{\"location\": \"San Francisco\"}" } } ] }, "finish_reason": "tool_calls" } ] } ``` ### Key Points - `finish_reason: "tool_calls"` indicates the model called a tool. - `tool_calls` array contains one or more function invocations. - `arguments` is a JSON string that must be parsed. - The model does not execute the function; the client must do so. ``` -------------------------------- ### JavaScript Client Implementation Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Example of how to implement streaming using the OpenAI JavaScript client library. It uses an async iterator to handle incoming chunks. ```APIDOC ### JavaScript ```javascript const OpenAI = require('openai'); const openai = new OpenAI({ apiKey: 'sk-...' }); const stream = await openai.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello' }], stream: true, stream_options: { include_usage: true } }); for await (const chunk of stream) { if (chunk.choices[0]?.delta?.content) { process.stdout.write(chunk.choices[0].delta.content); } } ``` ``` -------------------------------- ### Browser Fetch API Streaming Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Demonstrates how to fetch streaming chat completions using the browser's Fetch API and process the response chunk by chunk. ```javascript const response = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello' }], stream: true }) }); const reader = response.body.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; const text = new TextDecoder().decode(value); const lines = text.split('\n'); for (const line of lines) { if (line.startsWith('data: ')) { const data = JSON.parse(line.slice(6)); console.log(data.choices[0].delta.content); } } } ``` -------------------------------- ### Getting Help Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Resources for obtaining help and support, including documentation, status pages, and community forums. ```APIDOC ## Getting Help - **Documentation:** [platform.openai.com/docs](https://platform.openai.com/docs) - **API Status:** [status.openai.com](https://status.openai.com) - **Support:** [help.openai.com](https://help.openai.com) - **Community:** [community.openai.com](https://community.openai.com) ``` -------------------------------- ### Buffering and Rendering Stream Content in Python Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Batch stream content chunks before rendering to the UI. This example accumulates content until a buffer size is reached, then renders the buffered text and flushes any remaining content. ```python buffer = "" buffer_size = 50 for chunk in stream: if chunk.choices[0].delta.content: buffer += chunk.choices[0].delta.content if len(buffer) >= buffer_size: render_text(buffer) buffer = "" if buffer: render_text(buffer) # Flush remaining ``` -------------------------------- ### Hello World Chat Completion Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md A basic example of how to perform a chat completion using the OpenAI API. It sends a simple message and expects a text response. ```bash curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "messages": [ {"role": "user", "content": "Hello, how are you?"} ] }' ``` -------------------------------- ### Get File Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Retrieves detailed information about a specific file. ```APIDOC ## GET /files/{file_id} ### Description Retrieve information about a file. ### Method GET ### Endpoint /files/{file_id} ### Parameters #### Path Parameters - **file_id** (string) - Required - The ID of the file to retrieve. ### Response #### Success Response (200) - **OpenAIFile** (object) - Information about the file, including: - **id** (string) - File ID. - **object** (string) - "file". - **bytes** (integer) - File size in bytes. - **created_at** (integer) - Unix timestamp of creation. - **filename** (string) - Original filename. - **purpose** (string) - The file purpose. ``` -------------------------------- ### Parallel Function Calls Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md Demonstrates how the model can call multiple functions simultaneously within a single response. This is useful for gathering multiple pieces of information at once. ```json { "tool_calls": [ { "id": "call_1", "type": "function", "function": { "name": "get_weather", "arguments": "{\"location\": \"San Francisco\"}" } }, { "id": "call_2", "type": "function", "function": { "name": "get_weather", "arguments": "{\"location\": \"New York\"}" } } ] } ``` -------------------------------- ### Rate Limit Headers Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Response headers indicating current rate limits for requests and tokens. These headers provide real-time information on usage and reset times. ```text x-ratelimit-limit-requests: 3500 x-ratelimit-limit-tokens: 200000 x-ratelimit-remaining-requests: 3499 x-ratelimit-remaining-tokens: 199950 x-ratelimit-reset-requests: 30s ``` -------------------------------- ### Python Client for Streaming Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Example of using the OpenAI Python client to create a chat completion with streaming enabled and `include_usage` set to true. It iterates through chunks and prints content. ```python from openai import OpenAI client = OpenAI(api_key="sk-...") stream = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Hello"}], stream=True, stream_options={"include_usage": True} ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="") ``` -------------------------------- ### JavaScript Client for Streaming Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Example of using the OpenAI JavaScript client to create a chat completion with streaming and `include_usage` enabled. It processes chunks asynchronously and writes content to standard output. ```javascript const OpenAI = require('openai'); const openai = new OpenAI({ apiKey: 'sk-...' }); const stream = await openai.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello' }], stream: true, stream_options: { include_usage: true } }); for await (const chunk of stream) { if (chunk.choices[0]?.delta?.content) { process.stdout.write(chunk.choices[0].delta.content); } } ``` -------------------------------- ### Chat Completion Response Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Illustrates the structure of a successful response from the chat completions endpoint, including message content, model used, and token usage. ```json { "id": "chatcmpl-123", "object": "chat.completion", "created": 1234567890, "model": "gpt-4o", "choices": [{ "index": 0, "message": { "role": "assistant", "content": "Hello! I'm doing well, thank you for asking..." }, "finish_reason": "stop" }], "usage": { "prompt_tokens": 10, "completion_tokens": 25, "total_tokens": 35 } } ``` -------------------------------- ### Generate Image with DALL-E 3 Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/models.md Generate an image based on a text prompt using the dall-e-3 model. This example specifies a high-quality output and vivid style. Ensure your API key is set. ```bash curl https://api.openai.com/v1/images/generations \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "dall-e-3", "prompt": "A serene landscape with mountains and lake", "n": 1, "size": "1024x1024", "quality": "hd", "style": "vivid" }' ``` -------------------------------- ### Get Assistant Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Use this endpoint to retrieve a specific assistant by its ID. Note: This endpoint is deprecated. ```bash curl "https://api.openai.com/v1/assistants/asst_abc123" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" ``` -------------------------------- ### Example cURL Request with Rate Limiting Headers Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/configuration.md This cURL command shows a typical request to the chat completions endpoint, including authentication and content type headers. The response headers indicate rate limit status. ```bash curl -i https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{...}' ``` -------------------------------- ### Tool Calling Function Definition Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Example of defining a function for the model to invoke, including its type, name, and parameters. This is part of the tool calling feature. ```json { "tools": [{ "type": "function", "function": { "name": "get_weather", "parameters": {"type": "object", "properties": {...}} } }] } ``` -------------------------------- ### Define Tools for Chat Completion API Call Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md Example of making a `curl` request to the Chat Completions API, including a tool definition for fetching weather information. The model will use this definition to decide if and how to call the tool. ```bash curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "messages": [ { "role": "user", "content": "What is the weather in San Francisco?" } ], "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Get current weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City name" } }, "required": ["location"] } } } ] }' ``` -------------------------------- ### Generate Embeddings with Text Embedding 3 Large Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/models.md This example demonstrates how to generate embeddings for a given text input using the 'text-embedding-3-large' model. You can configure the output dimensions for flexibility. Ensure your API key is set. ```bash curl https://api.openai.com/v1/embeddings \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "text-embedding-3-large", "input": "The quick brown fox", "dimensions": 256 }' ``` -------------------------------- ### Model Response Indicating Tool Call Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md Example JSON response from the Chat Completions API when the model decides to call a tool. The `finish_reason` will be 'tool_calls', and `tool_calls` will contain the function name and arguments. ```json { "id": "chatcmpl-123", "object": "chat.completion", "created": 1234567890, "model": "gpt-4o", "choices": [ { "index": 0, "message": { "role": "assistant", "content": null, "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "get_weather", "arguments": "{\"location\": \"San Francisco\"}" } } ] }, "finish_reason": "tool_calls" } ] } ``` -------------------------------- ### SSE Stream Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Streamed responses from the OpenAI API follow the Server-Sent Events (SSE) format. Each event is prefixed with `data: ` and the stream concludes with `data: [DONE]`. ```text data: {"object":"chat.completion.chunk","choices":[{"delta":{"content":"Hello"}}]} data: {"object":"chat.completion.chunk","choices":[{"delta":{"content":" world"}}]} data: {"object":"chat.completion.chunk","choices":[{"delta":{"finish_reason":"stop"}}]} data: [DONE] ``` -------------------------------- ### Example of an Invalid API Key Request Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/configuration.md This cURL command shows an API request using an old or invalid API key. Such requests will result in a 401 Unauthorized error, indicating the need for API key rotation. ```bash # Invalid after rotation curl https://api.openai.com/v1/models \ -H "Authorization: Bearer sk-old-key-xxxxx" # Returns 401 Unauthorized ``` -------------------------------- ### Invalid Request Error Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/errors.md This example shows an `invalid_request_error` typically returned when a request parameter is malformed or invalid, such as an incorrect model name. ```json { "error": { "message": "Invalid model: gpt-99", "type": "invalid_request_error", "param": "model", "code": "invalid_value" } } ``` -------------------------------- ### List Available Models Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Demonstrates how to list available models using the OpenAI API. Requires an API key for authentication. ```bash curl https://api.openai.com/v1/models \ -H "Authorization: Bearer $OPENAI_API_KEY" ``` -------------------------------- ### Get Assistant Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Retrieve a specific assistant. (Deprecated) ```APIDOC ## GET /assistants/{assistant_id} ### Description Retrieve a specific assistant. (Deprecated) ### Method GET ### Endpoint /assistants/{assistant_id} ### Parameters #### Path Parameters - **assistant_id** (string) - Yes - The ID of the assistant to retrieve ### Request Example ```bash curl "https://api.openai.com/v1/assistants/asst_abc123" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" ``` ### Response #### Success Response (200) - **Response:** `AssistantObject` ``` -------------------------------- ### Get Model Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Retrieve detailed information about a specific model. ```APIDOC ## GET /models/{model} ### Description Retrieve detailed information about a specific model. ### Method GET ### Endpoint /models/{model} ### Parameters #### Path Parameters - **model** (string) - Yes - Model identifier ### Response #### Success Response - **Model object** with detailed properties ``` -------------------------------- ### Get Chat Completion Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Retrieve a specific chat completion by its ID. ```APIDOC ## GET /chat/completions/{completion_id} ### Description Retrieve a specific chat completion by ID. ### Method GET ### Endpoint /chat/completions/{completion_id} ### Parameters #### Path Parameters - **completion_id** (string) - Yes - The completion ID ### Response #### Success Response - **ChatCompletionDeleted** ``` -------------------------------- ### Get Fine-tuning Job Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Retrieves the status and details of a specific fine-tuning job. ```APIDOC ## GET /fine_tuning/jobs/{fine_tuning_job_id} ### Description Retrieve a specific fine-tuning job. ### Method GET ### Endpoint /fine_tuning/jobs/{fine_tuning_job_id} ### Parameters #### Path Parameters - **fine_tuning_job_id** (string) - Required - The ID of the fine-tuning job to retrieve. ### Response #### Success Response (200) - **FineTuningJob** (object) - Details of the specified fine-tuning job. ``` -------------------------------- ### Get Voice Consent Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Retrieve a specific voice consent record by its ID. ```APIDOC ## GET /audio/voice_consents/{consent_id} ### Description Retrieve a specific voice consent record. ### Method GET ### Endpoint /audio/voice_consents/{consent_id} ### Parameters #### Path Parameters - **consent_id** (string) - Yes - The voice consent ID ### Response #### Success Response - **Voice consent object** ``` -------------------------------- ### CreateFineTuningJobRequest Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/types.md Defines the structure for creating a fine-tuning job, specifying the model, training data, and optional hyperparameters. ```APIDOC ## CreateFineTuningJobRequest ### Description Request to create a fine-tuning job. ### Parameters #### Request Body - **model** (string) - Required - ("gpt-3.5-turbo", "gpt-4", etc.) - **training_file** (string) - Required - Training data file ID - **validation_file** (string) - Optional - Validation data file ID - **hyperparameters** (object) - Optional - Hyperparameters - **batch_size** (integer | "auto") - Optional - **learning_rate_multiplier** (number | "auto") - Optional - **n_epochs** (integer | "auto") - Optional - **suffix** (string) - Optional - Model name suffix (max 18 chars) - **seed** (integer) - Optional - Reproducibility seed ``` -------------------------------- ### Create Assistant Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Use this endpoint to create a new assistant. You must specify the model, and can optionally provide a name, instructions, and tools. Note: This endpoint is deprecated. ```bash curl "https://api.openai.com/v1/assistants" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "model": "gpt-4o", "name": "Math Tutor", "instructions": "You are a personal math tutor.", "tools": [{"type": "code_interpreter"}] }' ``` -------------------------------- ### Authentication Error Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/errors.md An `authentication_error` is returned when there is a problem with the API key, such as it being missing, invalid, or expired. ```json { "error": { "message": "Incorrect API key provided. You can find your API key at https://platform.openai.com/account/api-keys.", "type": "authentication_error", "param": null, "code": "invalid_api_key" } } ``` -------------------------------- ### Enable Beta Features with OpenAI-Beta Header Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/configuration.md Use the OpenAI-Beta header to enable specific beta features. The value depends on the beta program you wish to use. ```bash OpenAI-Beta: assistants=v2 ``` -------------------------------- ### Get Batch Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Fetches the details of a specific batch job using its ID. Provides information about the status and results of a batch operation. ```APIDOC ## GET /batches/{batch_id} ### Description Retrieve a specific batch job. ### Method GET ### Endpoint /batches/{batch_id} ### Parameters #### Path Parameters - **batch_id** (string) - Yes - The batch ID ### Response #### Success Response (200) - **Batch** ``` -------------------------------- ### Create Assistant Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Create a new assistant with a model and instructions. (Deprecated) ```APIDOC ## POST /assistants ### Description Create a new assistant with a model and instructions. (Deprecated) ### Method POST ### Endpoint /assistants ### Request Body - **Request Body:** `CreateAssistantRequest` ### Request Example ```bash curl "https://api.openai.com/v1/assistants" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Beta: assistants=v2" \ -d '{ "model": "gpt-4o", "name": "Math Tutor", "instructions": "You are a personal math tutor.", "tools": [{"type": "code_interpreter"}] }' ``` ### Response #### Success Response (200) - **Response:** `AssistantObject` ``` -------------------------------- ### Get Admin API Key Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Retrieves details of a specific admin API key by its ID. This allows for inspection of existing administrative keys. ```APIDOC ## GET /organization/admin_api_keys/{admin_api_key_id} ### Description Retrieve a specific admin API key. ### Method GET ### Endpoint /organization/admin_api_keys/{admin_api_key_id} ### Parameters #### Path Parameters - **admin_api_key_id** (string) - Yes - The admin API key ID ### Response #### Success Response (200) - **AdminApiKey** ``` -------------------------------- ### Raw HTTP (curl) Implementation Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Demonstrates how to make a streaming request using `curl`. The `--no-buffer` flag is crucial for receiving chunks immediately. ```APIDOC ### Raw HTTP (curl) ```bash curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}], "stream": true }' \ --no-buffer ``` The `--no-buffer` flag ensures each chunk is printed immediately. ``` -------------------------------- ### Function Description for Get Weather Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md Defines a function to retrieve current weather conditions, specifying parameters like location and expected output. ```json { "name": "get_weather", "description": "Get current weather conditions for a specific city. Returns temperature, precipitation, and wind conditions.", "parameters": { "properties": { "location": { "type": "string", "description": "The city name (e.g., 'San Francisco', 'London'). Use ISO-3166 country codes if ambiguous." } } } } ``` -------------------------------- ### File Search Configuration with Vector Stores Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md Configures the file search tool by associating it with specific vector store IDs. ```json { "tool_resources": { "file_search": { "vector_store_ids": ["vs_abc123"] } } } ``` -------------------------------- ### List Models Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md List all available models supported by the API. ```APIDOC ## GET /models ### Description List all available models. ### Method GET ### Endpoint /models ### Response #### Success Response - **ModelListResponse** - **data** (array) - Array of model objects with `id`, `object`, `created`, and `owned_by` properties. ``` -------------------------------- ### Making Function Calls - Step 3: Execute the Function Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md This Python snippet demonstrates how to parse the tool call arguments from the model's response and execute the corresponding function. ```APIDOC ## Making Function Calls - Step 3: Execute the Function ### Description This Python code illustrates how to process the tool call information received from the model. It involves parsing the JSON arguments and then calling the appropriate function based on the `function_name`. ### Code Example (Python) ```python import json # Assuming 'response' is the JSON object received from the API tool_call = response.choices[0].message.tool_calls[0] function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) # Execute your function based on the name and arguments if function_name == "get_weather": # Example of calling a hypothetical get_weather function # You would need to define this function in your application result = get_weather( location=function_args["location"], unit=function_args.get("unit", "celsius") # Using .get for optional parameters ) else: result = "Unknown function" # The 'result' would then be sent back to the model in a subsequent API call. ``` ``` -------------------------------- ### OpenAI API Documentation Overview Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/MANIFEST.txt This section provides a high-level overview of the OpenAI API documentation, including its structure, content, and key features. ```APIDOC ## OpenAI API Technical Reference This documentation provides a comprehensive guide to the OpenAI API. ### Key Documentation Files: * **README.md**: Overview, quick start, feature summary, index, and help resources. * **endpoints.md**: Detailed information on 162 unique endpoint paths and 242 HTTP operations, organized by category (Assistants, Audio, Chat Completions, etc.). Includes request/response formats, parameter tables, examples, status codes, rate limits, and pagination. * **types.md**: Definitions for over 500 schema types, including core request/response types for Chat Completions, Audio, Embeddings, Images, Files, fine-tuning, batch, and moderation. * **models.md**: Information on all available models (Chat, Embedding, Audio, Image, Moderation), their capabilities, context windows, pricing, and use cases. * **configuration.md**: Details on authentication methods, API key types, request headers, query parameters, rate limiting, timeouts, request body parameters, response formats, streaming options, and security settings. * **errors.md**: Documentation on HTTP status codes, error response formats, error types (invalid_request_error, authentication_error, etc.), specific error codes, and handling patterns. * **streaming.md**: Information on Server-Sent Events (SSE), enabling streaming, response formats, chunk structure, client implementations, and best practices for streaming. * **tools.md**: Overview of function calling, tool types (functions, code_interpreter, file_search), the function calling flow, `tool_choice` parameter, parallel calls, and error handling. ### Key Features Documented: * Chat Completions API (streaming, tools, vision, JSON mode) * Audio API (transcription, text-to-speech, voice consent) * Image Generation API * Embeddings API * Fine-tuning and Batch Processing * Organization and Administration * Audit Logs * Function Calling and Tool Usage ``` -------------------------------- ### Resource Retrieval with Path Parameters Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/configuration.md Illustrates the use of path parameters to identify specific resources in API requests. Ensure path parameters containing special characters are URL-encoded. ```bash GET /v1/assistants/{assistant_id} GET /v1/files/{file_id} GET /v1/models/{model} ``` -------------------------------- ### Tool Calling Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Guidance on defining functions that the model can invoke. ```APIDOC ## Tool Calling Define functions the model can invoke: ```json { "tools": [{ "type": "function", "function": { "name": "get_weather", "parameters": {"type": "object", "properties": {...}} } }] } ``` See [tools.md](tools.md) for complete guide. ``` -------------------------------- ### Rate Limited Response Example Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/configuration.md When a rate limit is exceeded, the API returns a 429 status code. The response includes headers like 'Retry-After' to indicate when to resend the request. ```http HTTP/1.1 429 Too Many Requests Retry-After: 0.5 x-ratelimit-limit-requests: 3500 x-ratelimit-remaining-requests: 0 x-ratelimit-reset-requests: 30s ``` -------------------------------- ### Raw HTTP Request for Streaming (curl) Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Demonstrates how to make a raw HTTP request to the OpenAI API for chat completions with streaming enabled using curl. The `--no-buffer` flag is used to ensure immediate output of chunks. ```bash curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}], "stream": true }' \ --no-buffer ``` -------------------------------- ### Pagination Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Details on how to implement cursor-based pagination for list endpoints. ```APIDOC ## Pagination List endpoints support cursor-based pagination: ```bash GET /v1/files?limit=100&after=file_abc123 ``` Parameters: `limit`, `order`, `after`, `before` ``` -------------------------------- ### Enable Code Interpreter via API Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md Demonstrates how to enable the code interpreter tool for a chat completion request using cURL. ```bash curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "messages": [ {"role": "user", "content": "Calculate the sum of 1 to 100"} ], "tools": [ {"type": "code_interpreter"} ] }' ``` -------------------------------- ### CreateSpeechRequest Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/types.md Defines the parameters for generating audio from text. ```APIDOC ## CreateSpeechRequest ### Description Request for text-to-speech generation. ### Parameters #### Request Body - **model** (string) - Required ("tts-1" or "tts-1-hd") - **input** (string) - Required (up to 4096 chars) - **voice** (string) - Required ("alloy", "echo", "fable", "onyx", "nova", "shimmer") - **response_format** (string) - Optional ("mp3", "opus", "aac", "flac", default "mp3") - **speed** (number) - Optional (0.25-4.0, default 1.0) ### Returns Binary audio data ``` -------------------------------- ### SDK Availability Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md List of official and community SDKs for interacting with the OpenAI API. ```APIDOC ## SDK Availability Official SDKs: - **Python:** `openai` package - **Node.js/JavaScript:** `openai` package - **Java:** `openai-java` - **Go:** `openai-go` - **Ruby:** `ruby-openai` Community SDKs available for other languages. ``` -------------------------------- ### Example of HTTP Error Response for Invalid Model Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Demonstrates the structure of an HTTP error response when a streaming request is made with an invalid model name. Errors before streaming begins are returned as standard HTTP error responses. ```bash curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "invalid-model", "messages": [...], "stream": true }' ``` ```json HTTP/1.1 400 Bad Request { "error": { "message": "The model `invalid-model` does not exist", "type": "invalid_request_error" } } ``` -------------------------------- ### Authentication Methods Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Overview of available authentication methods, including API keys and service accounts. ```APIDOC ## Authentication Methods | Method | Use Case | Example | |---|---|---| | API Key | Default, for users | `Authorization: Bearer sk-...` | | Service Account | Non-interactive | Organization-scoped | | Admin Key | Organization admin | Full admin access | | Project Key | Project-scoped | Limit to specific project | Manage API keys at [platform.openai.com](https://platform.openai.com/account/api-keys). ``` -------------------------------- ### Call GPT-4o with Multimodal Input Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/models.md Use this snippet to interact with the GPT-4o model, providing both text and image input for analysis. Ensure your OPENAI_API_KEY is set as an environment variable. ```bash curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, { "type": "image_url", "image_url": {"url": "https://example.com/image.jpg"} } ] } ] }' ``` -------------------------------- ### Pricing Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md General pricing guidelines for various OpenAI API services. ```APIDOC ## Pricing Pricing varies by model. Check [openai.com/pricing](https://openai.com/pricing) for current rates. Generally: - **Chat:** Pay per input/output token (output ~2-3x input) - **Embeddings:** Pay per 1M input tokens - **Images:** Fixed per image - **Audio:** Per minute (speech-to-text) or per character (text-to-speech) ``` -------------------------------- ### Configure Tool Choice: Auto Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md Set the 'tool_choice' parameter to 'auto' to allow the model to decide whether to use tools or respond directly. This is the default behavior. ```json { "model": "gpt-4o", "messages": [...], "tools": [...], "tool_choice": "auto" // See options below } ``` -------------------------------- ### Capture Raw Stream Data with Python Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/streaming.md Shows how to iterate over a streaming response from the OpenAI API and print the raw chunk objects for inspection. ```python stream = client.chat.completions.create( model="gpt-4o", messages=[...], stream=True ) for chunk in stream: print(repr(chunk)) # Raw chunk object ``` -------------------------------- ### List Files Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Lists all files associated with the organization. ```APIDOC ## GET /files ### Description List all files in the organization. ### Method GET ### Endpoint /files ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum items to return (1-10000). Default: 20. - **order** (string) - Optional - Sort order: `asc` or `desc`. Default: `desc`. - **after** (string) - Optional - Pagination cursor. ### Response #### Success Response (200) - **FileListResponse** (object) - Response containing a list of files. ``` -------------------------------- ### Streaming Response Options Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/README.md Configuration for enabling real-time response generation using Server-Sent Events (SSE). The 'include_usage' option can be set to true to include usage information in the stream. ```json { "stream": true, "stream_options": {"include_usage": true} } ``` -------------------------------- ### Create Audio Transcription Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/endpoints.md Use this endpoint to transcribe audio files into text. Ensure the audio file is in a supported format and specify the model. ```bash curl https://api.openai.com/v1/audio/transcriptions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -F "file=@audio.mp3" \ -F "model=whisper-1" ``` -------------------------------- ### Specify Project Header Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/configuration.md For organization-level APIs, specify a project using the `OpenAI-Project` header. This is used in conjunction with the organization header. ```bash curl https://api.openai.com/v1/organization/admin_api_keys \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "OpenAI-Organization: org-abcdef1234567890" \ -H "OpenAI-Project: proj-1234567890" ``` -------------------------------- ### Default Output Format Source: https://github.com/openai/openai-openapi/blob/master/_autodocs/tools.md Sets a default value for the output format, allowing 'json' or 'text'. ```json { "format": { "type": "string", "description": "Output format", "enum": ["json", "text"], "default": "json" } } ```