### Add Starter Prompts to ChatKit Start Screen with JavaScript Source: https://developers.openai.com/api/docs/guides/chatkit-themes Provide a list of predefined prompts on the start screen to suggest conversation starters and guide users on potential actions. ```js const options: Partial = { startScreen: { greeting: "What can I help you build today?", prompts: [ { name: "Check on the status of a ticket", prompt: "Can you help me check on the status of a ticket?", icon: "search" }, { name: "Create Ticket", prompt: "Can you help me create a new support ticket?", icon: "write" } ] } }; ``` -------------------------------- ### Speed Instructions Example Source: https://developers.openai.com/api/docs/guides/realtime-models-prompting Guide the model's speaking style for faster delivery without sounding rushed. This example specifies a fast pace while maintaining content integrity. ```markdown # Personality & Tone ## Personality - Friendly, calm and approachable expert customer service assistant. ## Tone - Warm, concise, confident, never fawning. ## Length - 2–3 sentences per turn. ## Pacing - Deliver your audio response fast, but do not sound rushed. - Do not modify the content of your response, only increase speaking speed for the same response. ``` -------------------------------- ### Example: Patch Count for 1024x1024 Image (1536-patch budget) Source: https://developers.openai.com/api/docs/guides/images-vision This example demonstrates the patch-based tokenization calculation for a 1024x1024 image, showing that no resizing is needed as it fits within a 1,536-patch budget. ```calculation example A. `original_patch_count = ceil(1024 / 32) * ceil(1024 / 32) = 32 * 32 = 1024` B. `1024` is below the `1,536` patch budget, so no resize is needed. C. `resized_patch_count = 1024` Resized patch count before the model multiplier: `1024` Multiply by the model's token multiplier to get the billed token units. ``` -------------------------------- ### Example: Patch Count for 1800x2400 Image (1536-patch budget) Source: https://developers.openai.com/api/docs/guides/images-vision This example illustrates the patch-based tokenization calculation for an 1800x2400 image, demonstrating how it is scaled down to fit within a 1,536-patch budget. ```calculation example A. `original_patch_count = ceil(1800 / 32) * ceil(2400 / 32) = 57 * 75 = 4275` B. `4275` exceeds the `1,536` patch budget, so we first compute `shrink_factor = sqrt((32^2 * 1536) / (1800 * 2400)) = 0.603`. We then adjust that scale so the final integer pixel dimensions stay within budget after patch counting: `adjusted_shrink_factor = 0.603 * min(floor(1800 * 0.603 / 32) / (1800 * 0.603 / 32), floor(2400 * 0.603 / 32) / (2400 * 0.603 / 32)) = 0.586`. Resized image in integer pixels: `1056 x 1408` C. `resized_patch_count = ceil(1056 / 32) * ceil(1408 / 32) = 33 * 44 = 1452` Resized patch count before the model multiplier: `1452` Multiply by the model's token multiplier to get the billed token units. ``` -------------------------------- ### Install OpenAI CLI with Go Source: https://developers.openai.com/api/docs/libraries/openai-cli Install the OpenAI CLI using Go 1.25 or later, fetching the latest version from GitHub. ```bash go install 'github.com/openai/openai-cli/cmd/openai@latest' ``` -------------------------------- ### Install the ChatKit server package Source: https://developers.openai.com/api/docs/guides/custom-chatkit Installs the `openai-chatkit` Python package, which provides the necessary components for building a ChatKit server. ```bash pip install openai-chatkit ``` -------------------------------- ### Example Input Question for Security Review Source: https://developers.openai.com/api/docs/guides/reinforcement-fine-tuning This is an example of a user query provided to the model for a security posture review task. ```text Do you have a dedicated security team? ``` -------------------------------- ### Install ChatKit React Bindings Source: https://developers.openai.com/api/docs/guides/chatkit Install the ChatKit React bindings using npm to integrate ChatKit into a React project. ```bash npm install @openai/chatkit-react ``` -------------------------------- ### Install SDK and Set API Key Source: https://developers.openai.com/api/docs/guides/agents/quickstart Install the OpenAI Agents SDK for TypeScript and Python, and set your OpenAI API key as an environment variable for authentication. ```bash # TypeScript npm install @openai/agents zod # Python pip install openai-agents export OPENAI_API_KEY=sk-... ``` -------------------------------- ### Personality and Tone: Multi-Emotion Example Source: https://developers.openai.com/api/docs/guides/realtime-models-prompting Instruct the model to switch emotions throughout its response. This example requires the model to start happy, become sad midway, and end angry. ```markdown # Personality & Tone - Start your response very happy - Midway, change to sad - At the end change your mood to very angry ``` -------------------------------- ### Realtime 2.0 Prompt Structure Example Source: https://developers.openai.com/api/docs/guides/realtime-models-prompting Use short, labeled sections for clarity. Add sections relevant to your product's needs. ```text # Role and Objective # Personality and Tone # Language # Reasoning # Message Channels # Preambles # Verbosity # Tools # Unclear Audio # Entity Capture # Long Context Behavior # Escalation ``` -------------------------------- ### Create Container with Inline Skill and Process File Source: https://developers.openai.com/api/docs/guides/tools-shell This example demonstrates how to create a container with an inline skill and an inline file, then use a shell tool to process the file with the skill. This approach ensures that content and files are ephemeral within the hosted lifecycle. ```bash INLINE_ZIP=$(base64 -i ./csv_insights.zip) REPORT_CSV=$(base64 -i ./report.csv) CONTAINER_ID=( curl -sL 'https://api.openai.com/v1/containers' \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "name": "inline-skill-container", "skills": [ { "type": "inline", "name": "csv-insights", "description": "Summarize CSV files and produce a markdown report.", "source": { "type": "base64", "media_type": "application/zip", "data": "'"$INLINE_ZIP"'" } } ] }' | jq -r '.id' ) curl -L 'https://api.openai.com/v1/responses' \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-5.5", "tools": [ { "type": "shell", "environment": { "type": "container_reference", "container_id": "'"$CONTAINER_ID"'" } } ], "input": [ { "role": "user", "content": [ { "type": "input_file", "filename": "report.csv", "file_data": "data:text/csv;base64,'"${REPORT_CSV}"'" }, { "type": "input_text", "text": "Use the csv-insights skill to summarize report.csv." } ] } ] }' ``` ```javascript import fs from "fs"; import OpenAI from "openai"; const client = new OpenAI(); const inlineZip = fs.readFileSync("csv_insights.zip").toString("base64"); const reportCsv = fs.readFileSync("report.csv").toString("base64"); const container = await client.containers.create({ name: "inline-skill-container", skills: [ { type: "inline", name: "csv-insights", description: "Summarize CSV files and produce a markdown report.", source: { type: "base64", media_type: "application/zip", data: inlineZip, }, }, ], }); const response = await client.responses.create({ model: "gpt-5.5", tools: [ { type: "shell", environment: { type: "container_reference", container_id: container.id, }, }, ], input: [ { role: "user", content: [ { type: "input_file", filename: "report.csv", file_data: `data:text/csv;base64,${reportCsv}`, }, { type: "input_text", text: "Use the csv-insights skill to summarize report.csv.", }, ], }, ], }); console.log(response.output_text); ``` ```python import base64 from openai import OpenAI client = OpenAI() with open("csv_insights.zip", "rb") as f: inline_zip = base64.b64encode(f.read()).decode("utf-8") with open("report.csv", "rb") as f: base64_string = base64.b64encode(f.read()).decode("utf-8") container = client.containers.create( name="inline-skill-container", skills=[ { "type": "inline", "name": "csv-insights", "description": "Summarize CSV files and produce a markdown report.", "source": { "type": "base64", "media_type": "application/zip", "data": inline_zip, }, } ], ) response = client.responses.create( model="gpt-5.5", tools=[ { "type": "shell", "environment": { "type": "container_reference", "container_id": container.id, }, } ], input=[ { "role": "user", "content": [ { "type": "input_file", "filename": "report.csv", "file_data": f"data:text/csv;base64,{base64_string}", }, { "type": "input_text", "text": "Use the csv-insights skill to summarize report.csv.", }, ], } ], ) print(response.output_text) ``` -------------------------------- ### Create Project, Service Account, and API Key with OpenAI CLI Source: https://developers.openai.com/api/docs/libraries/openai-cli This bash script demonstrates how to provision a new machine credential by creating a project, a service account within that project, and extracting the generated API key into an environment file. Ensure `OPENAI_ADMIN_KEY` is set before execution. ```bash # Create the project that will own this app or agent and save the response. openai admin:organization:projects create \ --name "automation project" \ --format json > project.json PROJECT_ID="$(jq -r '.id' project.json)" # Create a service account inside the project and save the full response. openai admin:organization:projects:service-accounts create \ --project-id "$PROJECT_ID" \ --name "automation bot" \ --format json > service-account.json # Extract the returned API key into an env file for the workload to use. jq -r '.api_key.value | "OPENAI_API_KEY=\(.)"' \ service-account.json > .env ``` -------------------------------- ### Python Example: Local Shell Tool Workflow Source: https://developers.openai.com/api/docs/guides/tools-local-shell This example demonstrates a full request/response loop for using the local shell tool. It shows how to initiate a request, identify and execute `local_shell_call` commands, and feed the command output back to the model. Note that error handling and security checks are omitted for brevity. ```python import os import shlex import subprocess from openai import OpenAI client = OpenAI() # 1) Create the initial response request with the tool enabled response = client.responses.create( model="codex-mini-latest", tools=[{"type": "local_shell"}], input=[ { "role": "user", "content": [ {"type": "input_text", "text": "List files in the current directory"}, ], } ], ) while True: # 2) Look for a local_shell_call in the model's output items shell_calls = [] for item in response.output: item_type = getattr(item, "type", None) if item_type == "local_shell_call": shell_calls.append(item) elif item_type == "tool_call" and getattr(item, "tool_name", None) == "local_shell": shell_calls.append(item) if not shell_calls: # No more commands break call = shell_calls[0] args = getattr(call, "action", None) or getattr(call, "arguments", None) # 3) Execute the command locally (here we just trust the command!) # The command is already split into argv tokens. def _get(obj, key, default=None): if isinstance(obj, dict): return obj.get(key, default) return getattr(obj, key, default) timeout_ms = _get(args, "timeout_ms") command = _get(args, "command") if not command: break if isinstance(command, str): command = shlex.split(command) completed = subprocess.run( command, cwd=_get(args, "working_directory") or os.getcwd(), env={**os.environ, **(_get(args, "env") or {})}, capture_output=True, text=True, timeout=(timeout_ms / 1000) if timeout_ms else None, ) output_item = { "type": "local_shell_call_output", "call_id": getattr(call, "call_id", None), "output": completed.stdout + completed.stderr, } # 4) Send the output back to the model to continue the conversation response = client.responses.create( model="codex-mini-latest", tools=[{"type": "local_shell"}], previous_response_id=response.id, input=[output_item], ) # Print the assistant's final answer print(response.output_text) ``` -------------------------------- ### Customize ChatKit Composer Placeholder and Start Screen Greeting with JSX Source: https://developers.openai.com/api/docs/guides/chatkit-themes Set a custom placeholder text for the composer input and define a greeting message for the start screen to guide user input. ```jsx const options: Partial = { composer: { placeholder: "Ask anything about your data…", }, startScreen: { greeting: "Welcome to FeedbackBot!", }, }; ``` -------------------------------- ### Example Response for Video Generation Job Source: https://developers.openai.com/api/docs/guides/video-generation Shows the JSON object returned by the API after a video generation job has been successfully started, including its unique ID, status, and specified parameters. ```json { "id": "video_68d7512d07848190b3e45da0ecbebcde004da08e1e0678d5", "object": "video", "created_at": 1758941485, "status": "queued", "model": "sora-2-pro", "progress": 0, "seconds": "8", "size": "1280x720" } ``` -------------------------------- ### Example Video Status Response Source: https://developers.openai.com/api/docs/guides/video-generation This JSON object illustrates a typical response from the `GET /videos/{video_id}` endpoint, showing the video's ID, status, progress, and other details while it is in progress. ```json { "id": "video_68d7512d07848190b3e45da0ecbebcde004da08e1e0678d5", "object": "video", "created_at": 1758941485, "status": "in_progress", "model": "sora-2-pro", "progress": 33, "seconds": "8", "size": "1280x720" } ``` -------------------------------- ### Initial Hono server application setup Source: https://developers.openai.com/api/docs/guides/predicted-outputs Defines a basic Hono server with a GET route for "/api" and static file serving, used as a base for model regeneration. ```typescript const app = new Hono(); app.get("/api", (c) => { return c.text("Hello Hono!"); }); // You will need to build the client code first `pnpm run ui:build` app.use( "/*", serveStatic({ rewriteRequestPath: (path) => `./dist${path}`, }) ); const port = 3000; console.log(`Server is running on port ${port}`); serve({ fetch: app.fetch, port, }); ``` -------------------------------- ### Rephrase Supervisor Tool Usage Source: https://developers.openai.com/api/docs/guides/realtime-models-prompting This example illustrates the use of the Rephrase Supervisor tool, which guides a responder model to rephrase a thinker's text into a short, natural, speech-first reply. It's useful when spoken output sounds robotic, too long, or awkward. ```text # Tools ``` -------------------------------- ### Perform Web Search with Domain Filtering and List Sources Source: https://developers.openai.com/api/docs/guides/tools-web-search Use these examples to perform a web search with specified allowed and blocked domains, and include the full list of sources in the response. Domain filtering is only available with the `web_search` tool, and sources can be retrieved with both `web_search` and `web_search_preview` tools by including `web_search_call.action.sources`. ```bash curl "https://api.openai.com/v1/responses" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-5.5", "reasoning": { "effort": "low" }, "tools": [ { "type": "web_search", "filters": { "allowed_domains": [ "pubmed.ncbi.nlm.nih.gov", "clinicaltrials.gov", "www.who.int", "www.cdc.gov", "www.fda.gov" ], "blocked_domains": [ "reddit.com", "quora.com", "wikipedia.org" ] } } ], "tool_choice": "auto", "include": ["web_search_call.action.sources"], "input": "Please perform a web search on how semaglutide is used in the treatment of diabetes." }' ``` ```javascript import OpenAI from "openai"; const client = new OpenAI(); const response = await client.responses.create({ model: "gpt-5.5", reasoning: { effort: "low" }, tools: [ { type: "web_search", filters: { allowed_domains: [ "pubmed.ncbi.nlm.nih.gov", "clinicaltrials.gov", "www.who.int", "www.cdc.gov", "www.fda.gov", ], blocked_domains: [ "reddit.com", "quora.com", "wikipedia.org", ], }, }, ], tool_choice: "auto", include: ["web_search_call.action.sources"], input: "Please perform a web search on how semaglutide is used in the treatment of diabetes.", }); console.log(response.output_text); ``` ```python from openai import OpenAI client = OpenAI() response = client.responses.create( model="gpt-5.5", reasoning={"effort": "low"}, tools=[ { "type": "web_search", "filters": { "allowed_domains": [ "pubmed.ncbi.nlm.nih.gov", "clinicaltrials.gov", "www.who.int", "www.cdc.gov", "www.fda.gov", ], "blocked_domains": [ "reddit.com", "quora.com", "wikipedia.org", ], }, } ], tool_choice="auto", include=["web_search_call.action.sources"], input="Please perform a web search on how semaglutide is used in the treatment of diabetes.", ) print(response.output_text) ``` -------------------------------- ### Set up OpenAI SDK with an Admin API key Source: https://developers.openai.com/api/docs/guides/admin-apis Initialize the OpenAI client across various languages using an Admin API key. Ensure the OPENAI_ADMIN_KEY environment variable is set before running. ```javascript import OpenAI from "openai"; const client = new OpenAI({ adminAPIKey: process.env.OPENAI_ADMIN_KEY, }); ``` ```python import os from openai import OpenAI client = OpenAI( admin_api_key=os.environ["OPENAI_ADMIN_KEY"], ) ``` ```go package main import ( "os" "github.com/openai/openai-go/v3" "github.com/openai/openai-go/v3/option" ) func main() { client := openai.NewClient( option.WithAdminAPIKey(os.Getenv("OPENAI_ADMIN_KEY")), ) _ = client } ``` ```ruby require "openai" openai = OpenAI::Client.new( admin_api_key: ENV.fetch("OPENAI_ADMIN_KEY") ) ``` ```java import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; OpenAIClient client = OpenAIOkHttpClient.builder() .adminApiKey(System.getenv("OPENAI_ADMIN_KEY")) .build(); ``` -------------------------------- ### Build Prompt with Helper Function Source: https://developers.openai.com/api/docs/guides/prompting/migrate-from-prompt-object Demonstrates how to construct a prompt using a helper function that accepts dynamic arguments and passes the resulting messages directly to the `input` parameter of the `client.responses.create` call. ```javascript import OpenAI from "openai"; const client = new OpenAI(); function buildSupportPrompt({ customerName, issue }) { return [ { role: "system", content: "You are a helpful support assistant. Be concise, accurate, and friendly. Do not invent policy details.", }, { role: "user", content: `Customer name: ${customerName}. Issue: ${issue}. Write a response to the customer.`, }, ]; } const response = await client.responses.create({ model: "gpt-5.5", input: buildSupportPrompt({ customerName: "Acme", issue: "billing question", }), }); ``` ```python from openai import OpenAI client = OpenAI() def build_support_prompt(customer_name, issue): return [ { "role": "system",", "content": "You are a helpful support assistant. Be concise, accurate, and friendly. Do not invent policy details.", }, { "role": "user", "content": f"Customer name: {customer_name}. Issue: {issue}. Write a response to the customer.", }, ] response = client.responses.create( model="gpt-5.5", input=build_support_prompt( customer_name="Acme", issue="billing question", ), ) ``` -------------------------------- ### Install OpenAI CLI with Homebrew Source: https://developers.openai.com/api/docs/libraries/openai-cli Use Homebrew to install the OpenAI command-line interface on macOS or Linux systems. ```bash brew install openai/tools/openai ``` -------------------------------- ### JSONL Training Data Example with Tool Calls Source: https://developers.openai.com/api/docs/guides/distillation This example demonstrates the JSONL format for training data, where the model is expected to call a 'get_current_weather' function based on user queries. Each line represents a complete JSON structure for a single training example. ```jsonl {"messages":[{"role":"user","content":"What is the weather in San Francisco?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"San Francisco, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. San Francisco, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]} {"messages":[{"role":"user","content":"What is the weather in Minneapolis?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Minneapolis, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. Minneapolis, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]} {"messages":[{"role":"user","content":"What is the weather in San Diego?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"San Diego, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. San Diego, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]} {"messages":[{"role":"user","content":"What is the weather in Memphis?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Memphis, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. Memphis, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]} {"messages":[{"role":"user","content":"What is the weather in Atlanta?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"Atlanta, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. Atlanta, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]} ``` -------------------------------- ### Make an API Request with MCP Tool (Python) Source: https://developers.openai.com/api/docs/guides/tools-connectors-mcp Demonstrates how to use the OpenAI Python client to create a response with an MCP tool. Initialize the client and provide the tool configuration within the `tools` array. ```python from openai import OpenAI client = OpenAI() resp = client.responses.create( model="gpt-5.5", tools=[ { "type": "mcp", "server_label": "Dropbox", "connector_id": "connector_dropbox", "authorization": "", "require_approval": "never", }, ], input="Summarize the Q2 earnings report.", ) print(resp.output_text) ``` -------------------------------- ### Example Decoded JWT-SVID Header Source: https://developers.openai.com/api/docs/guides/workload-identity-federation/spiffe An example of the header section of a decoded SPIFFE JWT-SVID, showing the algorithm and key ID. ```json { "alg": "ES256", "kid": "jwt-svid-key-1" } ```