### Setup for Structured Outputs Examples Source: https://developers.openai.com/cookbook/examples/structured_outputs_intro Installs the OpenAI Python client and imports necessary libraries. Initializes the OpenAI client and sets the model to be used for the examples. ```python import json from textwrap import dedent from openai import OpenAI client = OpenAI() MODEL = "gpt-4o-2024-08-06" ``` -------------------------------- ### Manual Setup Script for Dependencies Source: https://developers.openai.com/llms-full.txt Use a custom setup script for complex project dependencies. This example shows installing a type checker and project dependencies using pip and poetry, and pnpm. ```bash # Install type checker pip install pyright # Install dependencies poetry install --with test pnpm install ``` -------------------------------- ### Start Windows sandbox setup with windowsSandbox/setupStart Source: https://developers.openai.com/llms-full.txt Trigger sandbox setup asynchronously for custom Windows clients using `windowsSandbox/setupStart`. The `mode` parameter can be `elevated` or `unelevated`. ```json { "method": "windowsSandbox/setupStart", "id": 53, "params": { "mode": "elevated" } } ``` ```json { "id": 53, "result": { "started": true } } ``` -------------------------------- ### Python: Basic Chat Completion Request Source: https://developers.openai.com/docs/api-reference/responses A simple example demonstrating how to make a chat completion request using the OpenAI Python client. Ensure you have the 'openai' library installed and your API key configured. ```python from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."} ] ) print(response.choices[0].message.content) ``` -------------------------------- ### Initialization and Event Setup (JavaScript) Source: https://developers.openai.com/docs/api-reference/responses Sets up the sidebar functionality, including scroll event listeners and initial scroll position restoration. It also calls functions to set up overview section highlighting and sync sidebar states. ```javascript const initialize = () => { setupSidebar(); setupOverviewSectionHighlight(); syncModelAnchorSidebarActiveState(); // Wait a frame so sidebar DOM/layout settles after client navigation. requestAnimationFrame(restoreAndMaybeCenter); }; ``` -------------------------------- ### Node.js: Image Generation Request Source: https://developers.openai.com/docs/api-reference/responses Example for generating an image using DALL·E with the OpenAI Node.js library. Ensure the 'openai' package is installed and the API key is configured. ```javascript import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const image = await openai.images.generate({ model: "dall-e-3", prompt: "a cute baby sea otter", size: "1024x1024", quality: "standard", n: 1, }); const imageUrl = image.data[0].url; console.log(imageUrl); } main(); ``` -------------------------------- ### Python: Audio Translation Request Source: https://developers.openai.com/docs/api-reference/responses This example demonstrates translating an audio file from a foreign language into English text using the Whisper model via the OpenAI Python client. ```python from openai import OpenAI client = OpenAI() with open("/path/to/your/audio.mp3", "rb") as audio_file: translation = client.audio.translations.create( model="whisper-1", file=audio_file ) print(translation.text) ``` -------------------------------- ### Node.js: Embeddings Request Source: https://developers.openai.com/docs/api-reference/responses Example for generating text embeddings using the OpenAI Node.js library. This is useful for tasks like semantic search, clustering, and recommendations. Ensure the 'openai' package is installed. ```javascript import OpenAI from "openai"; const openai = new OpenAI(); async function main() { const embedding = await openai.embeddings.create({ model: "text-embedding-ada-002", input: ["The food was delicious!", "I"], }); console.log(embedding.data[0].embedding); } main(); ``` -------------------------------- ### windowsSandbox/setupStart Source: https://developers.openai.com/llms-full.txt Starts Windows sandbox setup for `elevated` or `unelevated` mode. Returns quickly and later emits `windowsSandbox/setupCompleted`. ```APIDOC ## windowsSandbox/setupStart ### Description Starts Windows sandbox setup for `elevated` or `unelevated` mode. ### Method Not specified (likely POST) ### Endpoint `/windowsSandbox/setupStart` ### Parameters #### Request Body - **mode** (string) - Required - The mode for setup: `"elevated"` or `"unelevated"`. ``` -------------------------------- ### Set up Python Virtual Environment and Install Dependencies Source: https://developers.openai.com/llms-full.txt Create a virtual environment and install required packages from requirements.txt. This is a prerequisite for running the tutorial's code. ```bash python -m venv env source env/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Complete Tool Calling Example in Python Source: https://developers.openai.com/docs/guides/function-calling This Python script demonstrates the full workflow of function calling. It defines a tool, calls the model to get a function call, executes the function, and then provides the result back to the model to get a final answer. Ensure you have the OpenAI Python library installed (`pip install openai`). ```python from openai import OpenAI import json client = OpenAI() # 1. Define a list of callable tools for the model tools = [ { "type": "function", "name": "get_horoscope", "description": "Get today's horoscope for an astrological sign.", "parameters": { "type": "object", "properties": { "sign": { "type": "string", "description": "An astrological sign like Taurus or Aquarius", }, }, "required": ["sign"], }, }, ] def get_horoscope(sign): return f"{sign}: Next Tuesday you will befriend a baby otter." # Create a running input list we will add to over time input_list = [ {"role": "user", "content": "What is my horoscope? I am an Aquarius."} ] # 2. Prompt the model with tools defined response = client.responses.create( model="gpt-5.5", tools=tools, input=input_list, ) # Save function call outputs for subsequent requests input_list += response.output for item in response.output: if item.type == "function_call": if item.name == "get_horoscope": # 3. Execute the function logic for get_horoscope sign = json.loads(item.arguments)("sign") horoscope = get_horoscope(sign) # 4. Provide function call results to the model input_list.append({ "type": "function_call_output", "call_id": item.call_id, "output": horoscope, }) print("Final input:") print(input_list) response = client.responses.create( model="gpt-5.5", instructions="Respond only with a horoscope generated by a tool.", tools=tools, input=input_list, ) # 5. The model should be able to give a response! print("Final output:") print(response.model_dump_json(indent=2)) print("\n" + response.output_text) ``` -------------------------------- ### windowsSandbox/setupStart Source: https://developers.openai.com/llms-full.txt Triggers the Windows sandbox setup asynchronously, allowing clients to avoid blocking on startup checks. ```APIDOC ## windowsSandbox/setupStart ### Description Triggers the Windows sandbox setup asynchronously, allowing clients to avoid blocking on startup checks. ### Method POST ### Endpoint /windowsSandbox/setupStart ### Parameters #### Request Body - **mode** (string) - Required - The setup mode. Can be `elevated` or `unelevated`. ### Request Example { "method": "windowsSandbox/setupStart", "id": 53, "params": {"mode": "elevated"} } ### Response #### Success Response (200) - **started** (boolean) - True if the setup process was started successfully. #### Response Example { "id": 53, "result": {"started": true} } ``` -------------------------------- ### Basic Function Calling Example Source: https://developers.openai.com/docs/guides/function-calling This example demonstrates a basic function call to get the current weather. ```python from openai import OpenAI client = OpenAI() # Example function calling the 'get_current_weather' function. response = client.chat.completions.create( model="gpt-4", messages=[ {"role": "user", "content": "What's the weather like in Boston?" }], functions=[ { "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"], "description": "The temperature unit to use. Infer this from the user's request.", }, }, "required": ["location"], }, } ], function_call="auto", ) print(response.choices[0].message.function_call) ``` -------------------------------- ### Basic Function Call Example Source: https://developers.openai.com/api/docs/guides/function-calling This example demonstrates a simple function call to get the current weather. ```python from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="gpt-4", messages=[ {"role": "user", "content": "What's the weather like in Boston?"} ], functions=[ { "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"], }, } ], function_call="auto", ) print(response.choices[0].message.function_call.arguments) ``` -------------------------------- ### Initialize Application Source: https://developers.openai.com/api/docs/api-reference/realtime-server-events/response/output_item/done Calls the main initialization function to set up the application. ```javascript initialize(); ``` -------------------------------- ### Get Ad Group - Request Example Source: https://developers.openai.com/ads/api-reference/ad-groups Example of a request to retrieve a specific ad group by its ID. ```json { "ad_group_id": "0987654321" } ``` -------------------------------- ### Few-Shot Prompting Example Source: https://developers.openai.com/codex/prompting Demonstrates few-shot prompting by providing examples within the prompt to guide Codex. ```javascript const prompt = "// write a javascript function to add two numbers\nfunction add(a, b) { return a + b }\n // write a javascript function to subtract two numbers\nfunction subtract(a, b) { return a - b }\n // write a javascript function to multiply two numbers\n"; const completion = await openai.completions.create({ model: "code-davinci-002", prompt: prompt, temperature: 0, max_tokens: 64, top_p: 1.0, frequency_penalty: 0.0, presence_penalty: 0.0, stop: ["\n"] }); console.log(completion.choices[0].text); ``` -------------------------------- ### Client Initialization and Response Creation Source: https://developers.openai.com/cookbook/examples/gpt4-1_prompting_guide Demonstrates how to initialize a client and create a response using a specified model and tools. It includes setting system prompts and providing user input for the model. ```python # Additional harness setup: # - Add your repo to /testbed # - Add your issue to the first user message # - Note: Even though we used a single tool for python, bash, and apply_patch, we generally recommend defining more granular tools that are focused on a single function response = client.responses.create( instructions=SYS_PROMPT_SWEBENCH, model="gpt-4.1-2025-04-14", tools=[python_bash_patch_tool], input=f"Please answer the following question:\nBug: Typerror..." ) response.to_dict()["output"] ``` -------------------------------- ### Customize Composer Placeholder and Start Screen Greeting Source: https://developers.openai.com/llms-full.txt Change the composer's placeholder text to guide user input and customize the start screen greeting. This helps users know what to ask or guides their first input. ```jsx const options: Partial = { composer: { placeholder: "Ask anything about your data…", }, startScreen: { greeting: "Welcome to FeedbackBot!", }, }; ``` -------------------------------- ### Configure AWS SDK with Environment Variables Source: https://developers.openai.com/codex/amazon-bedrock This example demonstrates initializing the AWS SDK using credentials provided through environment variables. This is a common and recommended practice for security. ```javascript const AWS = require("aws-sdk"); const bedrockruntime = new AWS.BedrockRuntime({ region: "us-east-1", // e.g., us-east-1 }); // Credentials will be loaded from environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, etc.) ``` -------------------------------- ### One-Shot Prompting Example Source: https://developers.openai.com/api/docs/guides/prompting This shows one-shot prompting, providing a single example to guide the model's response. ```python response = client.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Translate the following English text to French: 'sea otter'"}, {"role": "assistant", "content": "loutre de mer"} ] ) print(response.choices[0].message.content) ``` -------------------------------- ### Python Example: Authenticating with OpenAI Source: https://developers.openai.com/codex/auth Demonstrates how to initialize the OpenAI client in Python using an API key. Ensure you have the 'openai' library installed. ```python import openai openai.api_key = os.getenv("OPENAI_API_KEY") ``` -------------------------------- ### One-Shot Prompting Example Source: https://developers.openai.com/api/docs/guides/prompting This example shows one-shot prompting, providing a single example to guide the model's response. It's effective when the task requires a specific format or style. ```python import openai openai.api_key = "YOUR_API_KEY" response = openai.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Summarize the following article in one sentence. Article: [Article text here]"}, {"role": "assistant", "content": "[One-sentence summary here]"}, {"role": "user", "content": "Summarize the following article in one sentence. Article: [Another article text here]"} ] ) print(response.choices[0].message.content) ``` -------------------------------- ### Example Function Implementation Source: https://developers.openai.com/docs/guides/function-calling Implement the function that the model can call. This example shows a simple Python function to get weather information. ```python import json def get_current_weather(location: str, unit: str = "fahrenheit") -> str: """Get the current weather in a given location""" weather_info = { "location": location, "temperature": "72", "unit": unit, } return json.dumps(weather_info) ``` -------------------------------- ### Example Instructions for Weather GPT Source: https://developers.openai.com/llms-full.txt This example demonstrates how to structure instructions for a Custom GPT, including context, step-by-step actions referencing API calls and parameters, and additional notes for handling user preferences and initial interactions. ```text **Context**: A user needs information related to a weather forecast of a specific location. **Instructions**: 1. The user will provide a lat-long point or a general location or landmark (e.g. New York City, the White House). If the user does not provide one, ask for the relevant location 2. If the user provides a general location or landmark, convert that into a lat-long coordinate. If required, browse the web to look up the lat-long point. 3. Run the "getPointData" API action and retrieve back the gridId, gridX, and gridY parameters. 4. Apply those variables as the office, gridX, and gridY variables in the "getGridpointForecast" API action to retrieve back a forecast 5. Use that forecast to answer the user's question **Additional Notes**: - Assume the user uses US weather units (e.g. Fahrenheit) unless otherwise specified - If the user says "Let's get started" or "What do I do?", explain the purpose of this Custom GPT ``` -------------------------------- ### Get Start Prompt Analytics for Route Source: https://developers.openai.com/ads/api-reference/authentication Generates analytics data for start prompts associated with a given route, filtering out invalid prompts. ```javascript const startPromptAnalyticsForRoute = (pathname) => startPromptsForRoute(pathname) .map((prompt, index) => { const promptText = normalizeAnalyticsText(prompt?.prompt); if (!promptText) return null; return { id: analyticsSlug(prompt?.label, `prompt_${index + 1}`), label: normalizeAnalyticsText(prompt?.label) || `Prompt ${index + 1}`, position: index + 1, text: promptText, }; }) .filter(Boolean); ``` -------------------------------- ### Python Setup for Structured Outputs Source: https://developers.openai.com/cookbook/examples/structured_outputs_intro Imports necessary libraries and defines the product search prompt and Pydantic models for structured output. ```python from enum import Enum from typing import Union import openai product_search_prompt = ''' You are a clothes recommendation agent, specialized in finding the perfect match for a user. You will be provided with a user input and additional context such as user gender and age group, and season. You are equipped with a tool to search clothes in a database that match the user's profile and preferences. Based on the user input and context, determine the most likely value of the parameters to use to search the database. Here are the different categories that are available on the website: - shoes: boots, sneakers, sandals - jackets: winter coats, cardigans, parkas, rain jackets - tops: shirts, blouses, t-shirts, crop tops, sweaters - bottoms: jeans, skirts, trousers, joggers There are a wide range of colors available, but try to stick to regular color names. ''' class Category(str, Enum): shoes = "shoes" jackets = "jackets" tops = "tops" bottoms = "bottoms" class ProductSearchParameters(BaseModel): category: Category subcategory: str color: str ``` -------------------------------- ### XML Delimiter Example for Examples Section Source: https://developers.openai.com/api/docs/guides/prompt-guidance Shows how to use XML tags to structure examples within a prompt, including input and output pairs. ```xml San Francisco - SF ``` -------------------------------- ### Shell script for pnpm installation Source: https://developers.openai.com/codex/cloud/environments This shell script shows how to install project dependencies using pnpm as part of a manual setup process. ```shell pnpm install ``` -------------------------------- ### Set up Working Directory and API Key Source: https://developers.openai.com/llms-full.txt Create a new directory for your project and add your OpenAI API key to a .env file. This sets up the environment for the workflow. ```bash mkdir codex-workflows cd codex-workflows printf "OPENAI_API_KEY=sk-..." > .env ``` -------------------------------- ### Few-Shot Prompting Example Source: https://developers.openai.com/api/docs/guides/prompt-engineering Illustrates few-shot prompting by providing examples within the prompt to guide the model's response format and style. ```python import openai openai.api_key = "YOUR_API_KEY" response = openai.Completion.create( engine="davinci", prompt="" "Summarize the following movie reviews:\n\nReview: This movie was absolutely fantastic! The acting was superb and the plot was gripping. I highly recommend it.\nSummary: A highly recommended movie with superb acting and a gripping plot.\n\nReview: I was really disappointed with this film. The characters were flat and the story made no sense.\nSummary: A disappointing film with flat characters and a nonsensical story.\n\nReview: The movie was okay, but not great. The visuals were stunning, but the pacing was a bit slow.\nSummary: "", temperature=0.7, max_tokens=60, top_p=1.0, frequency_penalty=0.0, presence_penalty=0.0 ) print(response.choices[0].text.strip()) ``` -------------------------------- ### windowsSandbox/setupCompleted Source: https://developers.openai.com/llms-full.txt Emitted after a `windowsSandbox/setupStart` request finishes, indicating the status of the sandbox setup. ```APIDOC ## POST windowsSandbox/setupCompleted ### Description Notification emitted after a `windowsSandbox/setupStart` request completes, reporting the outcome. ### Method POST ### Endpoint /windowsSandbox/setupCompleted ### Parameters #### Request Body - **mode** (string) - Required - The mode in which the sandbox was set up. - **success** (boolean) - Required - Indicates whether the setup was successful. - **error** (object) - Optional - Contains error details if the setup failed. ``` -------------------------------- ### Start Dev Container from CLI Source: https://developers.openai.com/llms-full.txt Use this command to start the dev container from the command line. Ensure you have the Dev Containers CLI installed and configured. ```bash devcontainer up --workspace-folder . --config .devcontainer/devcontainer.secure.json ``` -------------------------------- ### Install and Run Codex in WSL Source: https://developers.openai.com/codex/windows These commands install the default Linux distribution (like Ubuntu) and then start a shell inside Windows Subsystem for Linux. After that, it downloads and executes the Codex installation script and launches Codex. ```bash # Install default Linux distribution (like Ubuntu) wsl --install # Start a shell inside Windows Subsystem for Linux wsl # Install and run Codex in WSL curl -fsSL https://chatgpt.com/codex/install.sh | sh codex ``` -------------------------------- ### Example Project Layout Source: https://developers.openai.com/llms-full.txt Illustrates a typical project structure for a ChatGPT App, showing the organization of the MCP server and the web UI bundle. ```text your-chatgpt-app/ ├─ server/ │ └─ src/index.ts # MCP server + tool handlers ├─ web/ │ ├─ src/component.tsx # React widget │ └─ dist/app.{js,css} # Bundled assets referenced by the server └─ package.json ``` -------------------------------- ### Audio Example with Old Model Source: https://developers.openai.com/cookbook/examples/realtime_prompting_guide Demonstrates playing an audio file using the old gpt-4o-realtime-preview-2025-06-03 model with speed instructions. ```python Audio("./data/audio/pace_06.mp3") ```