Repository Public
1# Prompt generation23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45The **Generate** button in the [Playground](https://platform.openai.com/chat/edit) lets you generate prompts, [functions](https://developers.openai.com/api/docs/guides/function-calling), and [schemas](https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas) from just a description of your task. This guide will walk through exactly how it works.67## Overview89Creating prompts and schemas from scratch can be time-consuming, so generating them can help you get started quickly. The Generate button uses two main approaches:10111. **Prompts:** We use **meta-prompts** that incorporate best practices to generate or improve prompts.121. **Schemas:** We use **meta-schemas** that produce valid JSON and function syntax.1314While we currently use meta prompts and schemas, we may integrate more advanced techniques in the future like [DSPy](https://arxiv.org/abs/2310.03714) and ["Gradient Descent"](https://arxiv.org/abs/2305.03495).1516## Prompts1718A **meta-prompt** instructs the model to create a good prompt based on your task description or improve an existing one. The meta-prompts in the Playground draw from our [prompt engineering](https://developers.openai.com/api/docs/guides/prompt-engineering) best practices and real-world experience with users.1920We use specific meta-prompts for different output types, like audio, to ensure the generated prompts meet the expected format.2122### Meta-prompts23242526Text-out2728 Text meta-prompt2930```javascript31import OpenAI from "openai";3233const client = new OpenAI();3435const metaPrompt = `Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.3637# Guidelines3839- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.40- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.41- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!42 - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.43 - Conclusion, classifications, or results should ALWAYS appear last.44- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.45 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.46- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.47- Formatting: Use markdown features for readability. DO NOT USE \`\`\` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.48- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.49- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.50- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)51 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.52 - JSON should never be wrapped in code blocks (\`\`\`) unless explicitly requested.5354The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")5556[Concise instruction describing the task - this should be the first line in the prompt, no section header]5758[Additional details as needed.]5960[Optional sections with headings or bullet points for detailed steps.]6162# Steps [optional]6364[optional: a detailed breakdown of the steps necessary to accomplish the task]6566# Output Format6768[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]6970# Examples [optional]7172[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]73[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]7475# Notes [optional]7677[optional: edge cases, details, and an area to call or repeat out specific important considerations]`;7879async function generatePrompt(taskOrPrompt) {80 const completion = await client.chat.completions.create({81 model: "gpt-6-astra",82 messages: [83 { role: "system", content: metaPrompt },84 {85 role: "user",86 content: "Task, Goal, or Current Prompt:\n" + taskOrPrompt,87 },88 ],89 });9091 return completion.choices[0].message.content;92}9394console.log(95 await generatePrompt("Write a concise product launch announcement.")96);97```9899````python100from openai import OpenAI101102client = OpenAI()103104META_PROMPT = """105Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.106107# Guidelines108109- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.110- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.111- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!112 - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.113 - Conclusion, classifications, or results should ALWAYS appear last.114- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.115 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.116- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.117- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.118- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.119- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.120- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)121 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.122 - JSON should never be wrapped in code blocks (```) unless explicitly requested.123124The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")125126[Concise instruction describing the task - this should be the first line in the prompt, no section header]127128[Additional details as needed.]129130[Optional sections with headings or bullet points for detailed steps.]131132# Steps [optional]133134[optional: a detailed breakdown of the steps necessary to accomplish the task]135136# Output Format137138[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]139140# Examples [optional]141142[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]143[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]144145# Notes [optional]146147[optional: edge cases, details, and an area to call or repeat out specific important considerations]148""".strip()149150151def generate_prompt(task_or_prompt: str):152 completion = client.chat.completions.create(153 model="gpt-6-astra",154 messages=[155 {156 "role": "system",157 "content": META_PROMPT,158 },159 {160 "role": "user",161 "content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,162 },163 ],164 )165166 return completion.choices[0].message.content167````168169````java170import com.openai.client.OpenAIClient;171import com.openai.client.okhttp.OpenAIOkHttpClient;172import com.openai.models.chat.completions.ChatCompletionCreateParams;173174String metaPrompt =175 """176 Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.177178 # Guidelines179180 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.181 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.182 - Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!183 - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.184 - Conclusion, classifications, or results should ALWAYS appear last.185 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.186 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.187 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.188 - Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.189 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.190 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.191 - Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)192 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.193 - JSON should never be wrapped in code blocks (```) unless explicitly requested.194195 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")196197 [Concise instruction describing the task - this should be the first line in the prompt, no section header]198199 [Additional details as needed.]200201 [Optional sections with headings or bullet points for detailed steps.]202203 # Steps [optional]204205 [optional: a detailed breakdown of the steps necessary to accomplish the task]206207 # Output Format208209 [Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]210211 # Examples [optional]212213 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]214 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]215216 # Notes [optional]217218 [optional: edge cases, details, and an area to call or repeat out specific important considerations]219 """220 .strip();221222ChatCompletionCreateParams params =223 ChatCompletionCreateParams.builder()224 .model("gpt-6-astra")225 .addSystemMessage(metaPrompt)226 .addUserMessage(227 "Task, Goal, or Current Prompt:\nWrite a concise product launch announcement.")228 .build();229230client.chat().completions().create(params).choices().stream()231 .flatMap(choice -> choice.message().content().stream())232 .forEach(System.out::println);233````234235````ruby236require "openai"237238client = OpenAI::Client.new239meta_prompt = <<~PROMPT240 Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.241242 # Guidelines243244 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.245 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.246 - Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!247 - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.248 - Conclusion, classifications, or results should ALWAYS appear last.249 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.250 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.251 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.252 - Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.253 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.254 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.255 - Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)256 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.257 - JSON should never be wrapped in code blocks (```) unless explicitly requested.258259 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")260261 [Concise instruction describing the task - this should be the first line in the prompt, no section header]262263 [Additional details as needed.]264265 [Optional sections with headings or bullet points for detailed steps.]266267 # Steps [optional]268269 [optional: a detailed breakdown of the steps necessary to accomplish the task]270271 # Output Format272273 [Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]274275 # Examples [optional]276277 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]278 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]279280 # Notes [optional]281282 [optional: edge cases, details, and an area to call or repeat out specific important considerations]283PROMPT284285def generate_prompt(client, meta_prompt, task_or_prompt)286 completion = client.chat.completions.create(287 model: "gpt-6-astra",288 messages: [289 {290 role: :system,291 content: meta_prompt292 },293 {294 role: :user,295 content: "Task, Goal, or Current Prompt:\n#{task_or_prompt}"296 }297 ]298 )299300 completion.choices.fetch(0).message.content301end302303puts(generate_prompt(client, meta_prompt, "Write a concise product launch announcement."))304````305306 307308 309310 311Audio-out312313 Audio meta-prompt314315```javascript316import OpenAI from "openai";317318const client = new OpenAI();319320const metaPrompt = `Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.321322# Guidelines323324- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.325- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.326- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.327- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.328- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.329 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.330 - It is very important that any examples included reflect the short, conversational output responses of the model.331Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.332 - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.333 - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.334- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.335- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.336- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.337338The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")339340[Concise instruction describing the task - this should be the first line in the prompt, no section header]341342[Additional details as needed.]343344[Optional sections with headings or bullet points for detailed steps.]345346# Examples [optional]347348[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]349[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]350351# Notes [optional]352353[optional: edge cases, details, and an area to call or repeat out specific important considerations]`;354355async function generatePrompt(taskOrPrompt) {356 const completion = await client.chat.completions.create({357 model: "gpt-6-astra",358 messages: [359 { role: "system", content: metaPrompt },360 {361 role: "user",362 content: "Task, Goal, or Current Prompt:\n" + taskOrPrompt,363 },364 ],365 });366367 return completion.choices[0].message.content;368}369370console.log(371 await generatePrompt("Create a friendly voice assistant for a bike shop.")372);373```374375```python376from openai import OpenAI377378client = OpenAI()379380META_PROMPT = """381Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.382383# Guidelines384385- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.386- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.387- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.388- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.389- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.390 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.391 - It is very important that any examples included reflect the short, conversational output responses of the model.392Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.393 - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.394 - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.395- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.396- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.397- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.398399The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")400401[Concise instruction describing the task - this should be the first line in the prompt, no section header]402403[Additional details as needed.]404405[Optional sections with headings or bullet points for detailed steps.]406407# Examples [optional]408409[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]410[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]411412# Notes [optional]413414[optional: edge cases, details, and an area to call or repeat out specific important considerations]415""".strip()416417418def generate_prompt(task_or_prompt: str):419 completion = client.chat.completions.create(420 model="gpt-6-astra",421 messages=[422 {423 "role": "system",424 "content": META_PROMPT,425 },426 {427 "role": "user",428 "content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,429 },430 ],431 )432433 return completion.choices[0].message.content434```435436```java437import com.openai.client.OpenAIClient;438import com.openai.client.okhttp.OpenAIOkHttpClient;439import com.openai.models.chat.completions.ChatCompletionCreateParams;440441String metaPrompt =442 """443 Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.444445 # Guidelines446447 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.448 - Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.449 - Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.450 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.451 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.452 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.453 - It is very important that any examples included reflect the short, conversational output responses of the model.454 Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.455 - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.456 - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.457 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.458 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.459 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.460461 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")462463 [Concise instruction describing the task - this should be the first line in the prompt, no section header]464465 [Additional details as needed.]466467 [Optional sections with headings or bullet points for detailed steps.]468469 # Examples [optional]470471 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]472 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]473474 # Notes [optional]475476 [optional: edge cases, details, and an area to call or repeat out specific important considerations]477 """478 .strip();479480ChatCompletionCreateParams params =481 ChatCompletionCreateParams.builder()482 .model("gpt-6-astra")483 .addSystemMessage(metaPrompt)484 .addUserMessage(485 "Task, Goal, or Current Prompt:\n"486 + "Create a friendly voice assistant for a bike shop.")487 .build();488489client.chat().completions().create(params).choices().stream()490 .flatMap(choice -> choice.message().content().stream())491 .forEach(System.out::println);492```493494```ruby495require "openai"496497client = OpenAI::Client.new498meta_prompt = <<~PROMPT499 Given a task description or existing prompt, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.500501 # Guidelines502503 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.504 - Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.505 - Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.506 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.507 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.508 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.509 - It is very important that any examples included reflect the short, conversational output responses of the model.510 Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.511 - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.512 - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.513 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.514 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.515 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.516517 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")518519 [Concise instruction describing the task - this should be the first line in the prompt, no section header]520521 [Additional details as needed.]522523 [Optional sections with headings or bullet points for detailed steps.]524525 # Examples [optional]526527 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]528 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]529530 # Notes [optional]531532 [optional: edge cases, details, and an area to call or repeat out specific important considerations]533PROMPT534535def generate_prompt(client, meta_prompt, task_or_prompt)536 completion = client.chat.completions.create(537 model: "gpt-6-astra",538 messages: [539 {540 role: :system,541 content: meta_prompt542 },543 {544 role: :user,545 content: "Task, Goal, or Current Prompt:\n#{task_or_prompt}"546 }547 ]548 )549550 completion.choices.fetch(0).message.content551end552553puts(generate_prompt(client, meta_prompt, "Create a friendly voice assistant for a bike shop."))554```555556557558### Prompt edits559560To edit prompts, we use a slightly modified meta-prompt. While direct edits are straightforward to apply, identifying necessary changes for more open-ended revisions can be challenging. To address this, we include a **reasoning section** at the beginning of the response. This section helps guide the model in determining what changes are needed by evaluating the existing prompt's clarity, chain-of-thought ordering, overall structure, and specificity, among other factors. The reasoning section makes suggestions for improvements and is then parsed out from the final response.561562563564Text-out565566 Text meta-prompt for edits567568```javascript569import OpenAI from "openai";570571const client = new OpenAI();572573const metaPrompt = `Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.574575Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:576<reasoning>577- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)578- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?579 - Identify: (max 10 words) if so, which section(s) utilize reasoning?580 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?581 - Ordering: (before/after) is the chain of though located before or after582- Structure: (yes/no) does the input prompt have a well defined structure583- Examples: (yes/no) does the input prompt have few-shot examples584 - Representative: (1-5) if present, how representative are the examples?585- Complexity: (1-5) how complex is the input prompt?586 - Task: (1-5) how complex is the implied task?587 - Necessity: ()588- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)589- Prioritization: (list) what 1-3 categories are the MOST important to address.590- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed591</reasoning>592593# Guidelines594595- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.596- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.597- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!598 - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.599 - Conclusion, classifications, or results should ALWAYS appear last.600- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.601 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.602- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.603- Formatting: Use markdown features for readability. DO NOT USE \`\`\` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.604- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.605- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.606- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)607 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.608 - JSON should never be wrapped in code blocks (\`\`\`) unless explicitly requested.609610The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")611612[Concise instruction describing the task - this should be the first line in the prompt, no section header]613614[Additional details as needed.]615616[Optional sections with headings or bullet points for detailed steps.]617618# Steps [optional]619620[optional: a detailed breakdown of the steps necessary to accomplish the task]621622# Output Format623624[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]625626# Examples [optional]627628[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]629[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]630631# Notes [optional]632633[optional: edge cases, details, and an area to call or repeat out specific important considerations]634[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]`;635636async function generatePrompt(taskOrPrompt) {637 const completion = await client.chat.completions.create({638 model: "gpt-6-astra",639 messages: [640 { role: "system", content: metaPrompt },641 {642 role: "user",643 content: "Task, Goal, or Current Prompt:\n" + taskOrPrompt,644 },645 ],646 });647648 return completion.choices[0].message.content;649}650651console.log(652 await generatePrompt("Make this support prompt more concise and empathetic.")653);654```655656````python657from openai import OpenAI658659client = OpenAI()660661META_PROMPT = """662Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.663664Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:665<reasoning>666- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)667- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?668 - Identify: (max 10 words) if so, which section(s) utilize reasoning?669 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?670 - Ordering: (before/after) is the chain of though located before or after671- Structure: (yes/no) does the input prompt have a well defined structure672- Examples: (yes/no) does the input prompt have few-shot examples673 - Representative: (1-5) if present, how representative are the examples?674- Complexity: (1-5) how complex is the input prompt?675 - Task: (1-5) how complex is the implied task?676 - Necessity: ()677- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)678- Prioritization: (list) what 1-3 categories are the MOST important to address.679- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed680</reasoning>681682# Guidelines683684- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.685- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.686- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!687 - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.688 - Conclusion, classifications, or results should ALWAYS appear last.689- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.690 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.691- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.692- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.693- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.694- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.695- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)696 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.697 - JSON should never be wrapped in code blocks (```) unless explicitly requested.698699The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")700701[Concise instruction describing the task - this should be the first line in the prompt, no section header]702703[Additional details as needed.]704705[Optional sections with headings or bullet points for detailed steps.]706707# Steps [optional]708709[optional: a detailed breakdown of the steps necessary to accomplish the task]710711# Output Format712713[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]714715# Examples [optional]716717[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]718[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]719720# Notes [optional]721722[optional: edge cases, details, and an area to call or repeat out specific important considerations]723[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]724""".strip()725726727def generate_prompt(task_or_prompt: str):728 completion = client.chat.completions.create(729 model="gpt-6-astra",730 messages=[731 {732 "role": "system",733 "content": META_PROMPT,734 },735 {736 "role": "user",737 "content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,738 },739 ],740 )741742 return completion.choices[0].message.content743````744745````java746import com.openai.client.OpenAIClient;747import com.openai.client.okhttp.OpenAIOkHttpClient;748import com.openai.models.chat.completions.ChatCompletionCreateParams;749750String metaPrompt =751 """752 Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.753754 Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:755 <reasoning>756 - Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)757 - Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?758 - Identify: (max 10 words) if so, which section(s) utilize reasoning?759 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?760 - Ordering: (before/after) is the chain of though located before or after761 - Structure: (yes/no) does the input prompt have a well defined structure762 - Examples: (yes/no) does the input prompt have few-shot examples763 - Representative: (1-5) if present, how representative are the examples?764 - Complexity: (1-5) how complex is the input prompt?765 - Task: (1-5) how complex is the implied task?766 - Necessity: ()767 - Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)768 - Prioritization: (list) what 1-3 categories are the MOST important to address.769 - Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed770 </reasoning>771772 # Guidelines773774 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.775 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.776 - Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!777 - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.778 - Conclusion, classifications, or results should ALWAYS appear last.779 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.780 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.781 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.782 - Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.783 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.784 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.785 - Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)786 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.787 - JSON should never be wrapped in code blocks (```) unless explicitly requested.788789 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")790791 [Concise instruction describing the task - this should be the first line in the prompt, no section header]792793 [Additional details as needed.]794795 [Optional sections with headings or bullet points for detailed steps.]796797 # Steps [optional]798799 [optional: a detailed breakdown of the steps necessary to accomplish the task]800801 # Output Format802803 [Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]804805 # Examples [optional]806807 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]808 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]809810 # Notes [optional]811812 [optional: edge cases, details, and an area to call or repeat out specific important considerations]813 [NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]814 """815 .strip();816817ChatCompletionCreateParams params =818 ChatCompletionCreateParams.builder()819 .model("gpt-6-astra")820 .addSystemMessage(metaPrompt)821 .addUserMessage(822 "Task, Goal, or Current Prompt:\nMake this product launch announcement clearer and more concise.")823 .build();824825client.chat().completions().create(params).choices().stream()826 .flatMap(choice -> choice.message().content().stream())827 .forEach(System.out::println);828````829830````ruby831require "openai"832833client = OpenAI::Client.new834meta_prompt = <<~PROMPT835 Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.836837 Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:838 <reasoning>839 - Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)840 - Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?841 - Identify: (max 10 words) if so, which section(s) utilize reasoning?842 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?843 - Ordering: (before/after) is the chain of though located before or after844 - Structure: (yes/no) does the input prompt have a well defined structure845 - Examples: (yes/no) does the input prompt have few-shot examples846 - Representative: (1-5) if present, how representative are the examples?847 - Complexity: (1-5) how complex is the input prompt?848 - Task: (1-5) how complex is the implied task?849 - Necessity: ()850 - Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)851 - Prioritization: (list) what 1-3 categories are the MOST important to address.852 - Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed853 </reasoning>854855 # Guidelines856857 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.858 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.859 - Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!860 - Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.861 - Conclusion, classifications, or results should ALWAYS appear last.862 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.863 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.864 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.865 - Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.866 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.867 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.868 - Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)869 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.870 - JSON should never be wrapped in code blocks (```) unless explicitly requested.871872 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")873874 [Concise instruction describing the task - this should be the first line in the prompt, no section header]875876 [Additional details as needed.]877878 [Optional sections with headings or bullet points for detailed steps.]879880 # Steps [optional]881882 [optional: a detailed breakdown of the steps necessary to accomplish the task]883884 # Output Format885886 [Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]887888 # Examples [optional]889890 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]891 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]892893 # Notes [optional]894895 [optional: edge cases, details, and an area to call or repeat out specific important considerations]896 [NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]897PROMPT898899def generate_prompt(client, meta_prompt, task_or_prompt)900 completion = client.chat.completions.create(901 model: "gpt-6-astra",902 messages: [903 {904 role: :system,905 content: meta_prompt906 },907 {908 role: :user,909 content: "Task, Goal, or Current Prompt:\n#{task_or_prompt}"910 }911 ]912 )913914 completion.choices.fetch(0).message.content915end916917puts(generate_prompt(client, meta_prompt, "Make this support prompt more concise and empathetic."))918````919920 921922 923924 925Audio-out926927 Audio meta-prompt for edits928929```javascript930import OpenAI from "openai";931932const client = new OpenAI();933934const metaPrompt = `Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.935936Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:937<reasoning>938- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)939- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?940 - Identify: (max 10 words) if so, which section(s) utilize reasoning?941 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?942 - Ordering: (before/after) is the chain of though located before or after943- Structure: (yes/no) does the input prompt have a well defined structure944- Examples: (yes/no) does the input prompt have few-shot examples945 - Representative: (1-5) if present, how representative are the examples?946- Complexity: (1-5) how complex is the input prompt?947 - Task: (1-5) how complex is the implied task?948 - Necessity: ()949- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)950- Prioritization: (list) what 1-3 categories are the MOST important to address.951- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed952</reasoning>953954# Guidelines955956- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.957- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.958- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.959- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.960- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.961 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.962 - It is very important that any examples included reflect the short, conversational output responses of the model.963Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.964 - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.965 - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.966- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.967- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.968- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.969970The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")971972[Concise instruction describing the task - this should be the first line in the prompt, no section header]973974[Additional details as needed.]975976[Optional sections with headings or bullet points for detailed steps.]977978# Examples [optional]979980[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]981[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]982983# Notes [optional]984985[optional: edge cases, details, and an area to call or repeat out specific important considerations]986[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]`;987988async function generatePrompt(taskOrPrompt) {989 const completion = await client.chat.completions.create({990 model: "gpt-6-astra",991 messages: [992 { role: "system", content: metaPrompt },993 {994 role: "user",995 content: "Task, Goal, or Current Prompt:\n" + taskOrPrompt,996 },997 ],998 });9991000 return completion.choices[0].message.content;1001}10021003console.log(1004 await generatePrompt(1005 "Make this voice assistant prompt warmer and more direct."1006 )1007);1008```10091010```python1011from openai import OpenAI10121013client = OpenAI()10141015META_PROMPT = """1016Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.10171018Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:1019<reasoning>1020- Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)1021- Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?1022 - Identify: (max 10 words) if so, which section(s) utilize reasoning?1023 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?1024 - Ordering: (before/after) is the chain of though located before or after1025- Structure: (yes/no) does the input prompt have a well defined structure1026- Examples: (yes/no) does the input prompt have few-shot examples1027 - Representative: (1-5) if present, how representative are the examples?1028- Complexity: (1-5) how complex is the input prompt?1029 - Task: (1-5) how complex is the implied task?1030 - Necessity: ()1031- Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)1032- Prioritization: (list) what 1-3 categories are the MOST important to address.1033- Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed1034</reasoning>10351036# Guidelines10371038- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.1039- Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.1040- Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.1041- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.1042- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.1043 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.1044 - It is very important that any examples included reflect the short, conversational output responses of the model.1045Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.1046 - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.1047 - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.1048- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.1049- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.1050- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.10511052The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")10531054[Concise instruction describing the task - this should be the first line in the prompt, no section header]10551056[Additional details as needed.]10571058[Optional sections with headings or bullet points for detailed steps.]10591060# Examples [optional]10611062[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]1063[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]10641065# Notes [optional]10661067[optional: edge cases, details, and an area to call or repeat out specific important considerations]1068[NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]1069""".strip()107010711072def generate_prompt(task_or_prompt: str):1073 completion = client.chat.completions.create(1074 model="gpt-6-astra",1075 messages=[1076 {1077 "role": "system",1078 "content": META_PROMPT,1079 },1080 {1081 "role": "user",1082 "content": "Task, Goal, or Current Prompt:\n" + task_or_prompt,1083 },1084 ],1085 )10861087 return completion.choices[0].message.content1088```10891090```java1091import com.openai.client.OpenAIClient;1092import com.openai.client.okhttp.OpenAIOkHttpClient;1093import com.openai.models.chat.completions.ChatCompletionCreateParams;10941095String metaPrompt =1096 """1097 Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.10981099 Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:1100 <reasoning>1101 - Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)1102 - Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?1103 - Identify: (max 10 words) if so, which section(s) utilize reasoning?1104 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?1105 - Ordering: (before/after) is the chain of though located before or after1106 - Structure: (yes/no) does the input prompt have a well defined structure1107 - Examples: (yes/no) does the input prompt have few-shot examples1108 - Representative: (1-5) if present, how representative are the examples?1109 - Complexity: (1-5) how complex is the input prompt?1110 - Task: (1-5) how complex is the implied task?1111 - Necessity: ()1112 - Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)1113 - Prioritization: (list) what 1-3 categories are the MOST important to address.1114 - Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed1115 </reasoning>11161117 # Guidelines11181119 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.1120 - Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.1121 - Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.1122 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.1123 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.1124 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.1125 - It is very important that any examples included reflect the short, conversational output responses of the model.1126 Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.1127 - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.1128 - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.1129 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.1130 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.1131 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.11321133 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")11341135 [Concise instruction describing the task - this should be the first line in the prompt, no section header]11361137 [Additional details as needed.]11381139 [Optional sections with headings or bullet points for detailed steps.]11401141 # Examples [optional]11421143 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]1144 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]11451146 # Notes [optional]11471148 [optional: edge cases, details, and an area to call or repeat out specific important considerations]1149 [NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]1150 """1151 .strip();11521153ChatCompletionCreateParams params =1154 ChatCompletionCreateParams.builder()1155 .model("gpt-6-astra")1156 .addSystemMessage(metaPrompt)1157 .addUserMessage(1158 "Task, Goal, or Current Prompt:\nMake this voice assistant prompt warmer and more direct.")1159 .build();11601161client.chat().completions().create(params).choices().stream()1162 .flatMap(choice -> choice.message().content().stream())1163 .forEach(System.out::println);1164```11651166```ruby1167require "openai"11681169client = OpenAI::Client.new1170meta_prompt = <<~PROMPT1171 Given a current prompt and a change description, produce a detailed system prompt to guide a realtime audio output language model in completing the task effectively.11721173 Your final output will be the full corrected prompt verbatim. However, before that, at the very beginning of your response, use <reasoning> tags to analyze the prompt and determine the following, explicitly:1174 <reasoning>1175 - Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)1176 - Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?1177 - Identify: (max 10 words) if so, which section(s) utilize reasoning?1178 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?1179 - Ordering: (before/after) is the chain of though located before or after1180 - Structure: (yes/no) does the input prompt have a well defined structure1181 - Examples: (yes/no) does the input prompt have few-shot examples1182 - Representative: (1-5) if present, how representative are the examples?1183 - Complexity: (1-5) how complex is the input prompt?1184 - Task: (1-5) how complex is the implied task?1185 - Necessity: ()1186 - Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)1187 - Prioritization: (list) what 1-3 categories are the MOST important to address.1188 - Conclusion: (max 30 words) given the previous assessment, give a very concise, imperative description of what should be changed and how. this does not have to adhere strictly to only the categories listed1189 </reasoning>11901191 # Guidelines11921193 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.1194 - Tone: Make sure to specifically call out the tone. By default it should be emotive and friendly, and speak quickly to avoid keeping the user just waiting.1195 - Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.1196 - Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.1197 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.1198 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.1199 - It is very important that any examples included reflect the short, conversational output responses of the model.1200 Keep the sentences very short by default. Instead of 3 sentences in a row by the assistant, it should be split up with a back and forth with the user instead.1201 - By default each sentence should be a few words only (5-20ish words). However, if the user specifically asks for "short" responses, then the examples should truly have 1-10 word responses max.1202 - Make sure the examples are multi-turn (at least 4 back-forth-back-forth per example), not just one questions an response. They should reflect an organic conversation.1203 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.1204 - Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.1205 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.12061207 The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")12081209 [Concise instruction describing the task - this should be the first line in the prompt, no section header]12101211 [Additional details as needed.]12121213 [Optional sections with headings or bullet points for detailed steps.]12141215 # Examples [optional]12161217 [Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]1218 [If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]12191220 # Notes [optional]12211222 [optional: edge cases, details, and an area to call or repeat out specific important considerations]1223 [NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]1224PROMPT12251226def generate_prompt(client, meta_prompt, task_or_prompt)1227 completion = client.chat.completions.create(1228 model: "gpt-6-astra",1229 messages: [1230 {1231 role: :system,1232 content: meta_prompt1233 },1234 {1235 role: :user,1236 content: "Task, Goal, or Current Prompt:\n#{task_or_prompt}"1237 }1238 ]1239 )12401241 completion.choices.fetch(0).message.content1242end12431244puts(generate_prompt(client, meta_prompt, "Make this voice assistant prompt warmer and more direct."))1245```1246124712481249## Schemas12501251[Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs) schemas and function schemas are themselves JSON objects, so we leverage Structured Outputs to generate them.1252This requires defining a schema for the desired output, which in this case is itself a schema. To do this, we use a self-describing schema – a **meta-schema**.12531254Because the `parameters` field in a function schema is itself a schema, we use the same meta-schema to generate functions.12551256### Defining a constrained meta-schema12571258[Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs) supports two modes: `strict=true` and `strict=false`. Both modes use the same model trained to follow the provided schema, but only "strict mode" guarantees perfect adherence through constrained sampling.12591260Our goal is to generate schemas for strict mode using strict mode itself. However, the official meta-schemas provided by the [JSON Schema Specification](https://json-schema.org/specification#meta-schemas) rely on features [not currently supported](https://developers.openai.com/api/docs/guides/structured-outputs#some-type-specific-keywords-are-not-yet-supported) in strict mode. This poses challenges that affect both input and output schemas.126112621. **Input schema:** We can't use [unsupported features](https://developers.openai.com/api/docs/guides/structured-outputs#some-type-specific-keywords-are-not-yet-supported) in the input schema to describe the output schema.12632. **Output schema:** The generated schema must not include [unsupported features](https://developers.openai.com/api/docs/guides/structured-outputs#some-type-specific-keywords-are-not-yet-supported).12641265Because we need to generate new keys in the output schema, the input meta-schema must use `additionalProperties`. This means we can't currently use strict mode to generate schemas. However, we still want the generated schema to conform to strict mode constraints.12661267To overcome this limitation, we define a **pseudo-meta-schema** — a meta-schema that uses features not supported in strict mode to describe only the features that are supported in strict mode. Essentially, this approach steps outside strict mode for the meta-schema definition while still ensuring that the generated schemas adhere to strict mode constraints.1268126912701271Constructing a constrained meta-schema is a challenging task, so we leveraged our models to help.12721273We began by giving `o1-preview` and `gpt-4o` in JSON mode a description of our goal using the Structured Outputs documentation.1274After a few iterations, we developed our first functional meta-schema.12751276We then used `gpt-4o` with Structured Outputs and provided _that initial schema_ along with our task description and documentation, to generate better candidates. With each iteration we used a better schema to generate the next, until we finally reviewed it carefully by hand.12771278Finally, after cleaning the output, we validated the schemas against a set of evals for schemas and functions.1279128012811282### Output cleaning12831284Strict mode guarantees perfect schema adherence. Because we can't use it during generation, however, we need to validate and transform the output after generating it.12851286After generating a schema, we perform the following steps:128712881. **Set `additionalProperties` to `false`** for all objects.12891. **Mark all properties as required**.12901. **For structured output schemas**, wrap them in [`json_schema`](https://developers.openai.com/api/docs/guides/structured-outputs?context=without_parse#how-to-use) object.12911. **For functions**, wrap them in a [`function`](https://developers.openai.com/api/docs/guides/function-calling#defining-functions) object.12921293The Realtime API1294 [function](https://developers.openai.com/api/docs/guides/realtime-conversations#function-calling) object1295 differs slightly from the Chat Completions API, but uses the same schema.12961297### Meta-schemas12981299Each meta-schema has a corresponding prompt which includes few-shot examples. When combined with the reliability of Structured Outputs — even without strict mode — we were able to generate schemas.1300130113021303Structured output schema13041305 Structured output meta-schema13061307```javascript1308import OpenAI from "openai";13091310const client = new OpenAI();13111312const metaSchema = {1313 name: "metaschema",1314 schema: {1315 type: "object",1316 properties: {1317 name: {1318 type: "string",1319 description: "The name of the schema",1320 },1321 type: {1322 type: "string",1323 enum: ["object", "array", "string", "number", "boolean", "null"],1324 },1325 properties: {1326 type: "object",1327 additionalProperties: {1328 $ref: "#/$defs/schema_definition",1329 },1330 },1331 items: {1332 anyOf: [1333 {1334 $ref: "#/$defs/schema_definition",1335 },1336 {1337 type: "array",1338 items: {1339 $ref: "#/$defs/schema_definition",1340 },1341 },1342 ],1343 },1344 required: {1345 type: "array",1346 items: {1347 type: "string",1348 },1349 },1350 additionalProperties: {1351 type: "boolean",1352 },1353 },1354 required: ["type"],1355 additionalProperties: false,1356 if: {1357 properties: {1358 type: {1359 const: "object",1360 },1361 },1362 },1363 then: {1364 required: ["properties"],1365 },1366 $defs: {1367 schema_definition: {1368 type: "object",1369 properties: {1370 type: {1371 type: "string",1372 enum: ["object", "array", "string", "number", "boolean", "null"],1373 },1374 properties: {1375 type: "object",1376 additionalProperties: {1377 $ref: "#/$defs/schema_definition",1378 },1379 },1380 items: {1381 anyOf: [1382 {1383 $ref: "#/$defs/schema_definition",1384 },1385 {1386 type: "array",1387 items: {1388 $ref: "#/$defs/schema_definition",1389 },1390 },1391 ],1392 },1393 required: {1394 type: "array",1395 items: {1396 type: "string",1397 },1398 },1399 additionalProperties: {1400 type: "boolean",1401 },1402 },1403 required: ["type"],1404 additionalProperties: false,1405 if: {1406 properties: {1407 type: {1408 const: "object",1409 },1410 },1411 },1412 then: {1413 required: ["properties"],1414 },1415 },1416 },1417 },1418};14191420const metaPrompt = `# Instructions1421Return a valid schema for the described JSON.14221423You must also make sure:1424- all fields in an object are set as required1425- I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED1426- all objects must have additionalProperties set to false1427 - because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties1428- all objects must have properties defined1429- field order matters. any form of "thinking" or "explanation" should come before the conclusion1430- $defs must be defined under the schema param14311432Notable keywords NOT supported include:1433- For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties1434- For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems14351436Other notes:1437- definitions and recursion are supported1438- only if necessary to include references e.g. "$defs", it must be inside the "schema" object14391440# Examples1441Input: Generate a math reasoning schema with steps and a final answer.1442Output: {1443 "name": "math_reasoning",1444 "type": "object",1445 "properties": {1446 "steps": {1447 "type": "array",1448 "description": "A sequence of steps involved in solving the math problem.",1449 "items": {1450 "type": "object",1451 "properties": {1452 "explanation": {1453 "type": "string",1454 "description": "Description of the reasoning or method used in this step."1455 },1456 "output": {1457 "type": "string",1458 "description": "Result or outcome of this specific step."1459 }1460 },1461 "required": [1462 "explanation",1463 "output"1464 ],1465 "additionalProperties": false1466 }1467 },1468 "final_answer": {1469 "type": "string",1470 "description": "The final solution or answer to the math problem."1471 }1472 },1473 "required": [1474 "steps",1475 "final_answer"1476 ],1477 "additionalProperties": false1478}14791480Input: Give me a linked list1481Output: {1482 "name": "linked_list",1483 "type": "object",1484 "properties": {1485 "linked_list": {1486 "$ref": "#/$defs/linked_list_node",1487 "description": "The head node of the linked list."1488 }1489 },1490 "$defs": {1491 "linked_list_node": {1492 "type": "object",1493 "description": "Defines a node in a singly linked list.",1494 "properties": {1495 "value": {1496 "type": "number",1497 "description": "The value stored in this node."1498 },1499 "next": {1500 "anyOf": [1501 {1502 "$ref": "#/$defs/linked_list_node"1503 },1504 {1505 "type": "null"1506 }1507 ],1508 "description": "Reference to the next node; null if it is the last node."1509 }1510 },1511 "required": [1512 "value",1513 "next"1514 ],1515 "additionalProperties": false1516 }1517 },1518 "required": [1519 "linked_list"1520 ],1521 "additionalProperties": false1522}15231524Input: Dynamically generated UI1525Output: {1526 "name": "ui",1527 "type": "object",1528 "properties": {1529 "type": {1530 "type": "string",1531 "description": "The type of the UI component",1532 "enum": [1533 "div",1534 "button",1535 "header",1536 "section",1537 "field",1538 "form"1539 ]1540 },1541 "label": {1542 "type": "string",1543 "description": "The label of the UI component, used for buttons or form fields"1544 },1545 "children": {1546 "type": "array",1547 "description": "Nested UI components",1548 "items": {1549 "$ref": "#"1550 }1551 },1552 "attributes": {1553 "type": "array",1554 "description": "Arbitrary attributes for the UI component, suitable for any element",1555 "items": {1556 "type": "object",1557 "properties": {1558 "name": {1559 "type": "string",1560 "description": "The name of the attribute, for example onClick or className"1561 },1562 "value": {1563 "type": "string",1564 "description": "The value of the attribute"1565 }1566 },1567 "required": [1568 "name",1569 "value"1570 ],1571 "additionalProperties": false1572 }1573 }1574 },1575 "required": [1576 "type",1577 "label",1578 "children",1579 "attributes"1580 ],1581 "additionalProperties": false1582}`;15831584async function generateSchema(description) {1585 const completion = await client.chat.completions.create({1586 model: "gpt-5.6-terra",1587 response_format: { type: "json_schema", json_schema: metaSchema },1588 messages: [1589 { role: "system", content: metaPrompt },1590 { role: "user", content: "Description:\n" + description },1591 ],1592 });15931594 const content = completion.choices[0].message.content;1595 if (!content) throw new Error("The model did not return a schema.");1596 return JSON.parse(content);1597}15981599console.log(1600 JSON.stringify(await generateSchema("Describe a calendar event."), null, 2)1601);1602```16031604```python1605from openai import OpenAI1606import json16071608client = OpenAI()16091610META_SCHEMA = {1611 "name": "metaschema",1612 "schema": {1613 "type": "object",1614 "properties": {1615 "name": {"type": "string", "description": "The name of the schema"},1616 "type": {1617 "type": "string",1618 "enum": ["object", "array", "string", "number", "boolean", "null"],1619 },1620 "properties": {1621 "type": "object",1622 "additionalProperties": {"$ref": "#/$defs/schema_definition"},1623 },1624 "items": {1625 "anyOf": [1626 {"$ref": "#/$defs/schema_definition"},1627 {"type": "array", "items": {"$ref": "#/$defs/schema_definition"}},1628 ]1629 },1630 "required": {"type": "array", "items": {"type": "string"}},1631 "additionalProperties": {"type": "boolean"},1632 },1633 "required": ["type"],1634 "additionalProperties": False,1635 "if": {"properties": {"type": {"const": "object"}}},1636 "then": {"required": ["properties"]},1637 "$defs": {1638 "schema_definition": {1639 "type": "object",1640 "properties": {1641 "type": {1642 "type": "string",1643 "enum": [1644 "object",1645 "array",1646 "string",1647 "number",1648 "boolean",1649 "null",1650 ],1651 },1652 "properties": {1653 "type": "object",1654 "additionalProperties": {"$ref": "#/$defs/schema_definition"},1655 },1656 "items": {1657 "anyOf": [1658 {"$ref": "#/$defs/schema_definition"},1659 {1660 "type": "array",1661 "items": {"$ref": "#/$defs/schema_definition"},1662 },1663 ]1664 },1665 "required": {"type": "array", "items": {"type": "string"}},1666 "additionalProperties": {"type": "boolean"},1667 },1668 "required": ["type"],1669 "additionalProperties": False,1670 "if": {"properties": {"type": {"const": "object"}}},1671 "then": {"required": ["properties"]},1672 }1673 },1674 },1675}16761677META_PROMPT = """1678# Instructions1679Return a valid schema for the described JSON.16801681You must also make sure:1682- all fields in an object are set as required1683- I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED1684- all objects must have additionalProperties set to false1685 - because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties1686- all objects must have properties defined1687- field order matters. any form of "thinking" or "explanation" should come before the conclusion1688- $defs must be defined under the schema param16891690Notable keywords NOT supported include:1691- For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties1692- For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems16931694Other notes:1695- definitions and recursion are supported1696- only if necessary to include references e.g. "$defs", it must be inside the "schema" object16971698# Examples1699Input: Generate a math reasoning schema with steps and a final answer.1700Output: {1701 "name": "math_reasoning",1702 "type": "object",1703 "properties": {1704 "steps": {1705 "type": "array",1706 "description": "A sequence of steps involved in solving the math problem.",1707 "items": {1708 "type": "object",1709 "properties": {1710 "explanation": {1711 "type": "string",1712 "description": "Description of the reasoning or method used in this step."1713 },1714 "output": {1715 "type": "string",1716 "description": "Result or outcome of this specific step."1717 }1718 },1719 "required": [1720 "explanation",1721 "output"1722 ],1723 "additionalProperties": false1724 }1725 },1726 "final_answer": {1727 "type": "string",1728 "description": "The final solution or answer to the math problem."1729 }1730 },1731 "required": [1732 "steps",1733 "final_answer"1734 ],1735 "additionalProperties": false1736}17371738Input: Give me a linked list1739Output: {1740 "name": "linked_list",1741 "type": "object",1742 "properties": {1743 "linked_list": {1744 "$ref": "#/$defs/linked_list_node",1745 "description": "The head node of the linked list."1746 }1747 },1748 "$defs": {1749 "linked_list_node": {1750 "type": "object",1751 "description": "Defines a node in a singly linked list.",1752 "properties": {1753 "value": {1754 "type": "number",1755 "description": "The value stored in this node."1756 },1757 "next": {1758 "anyOf": [1759 {1760 "$ref": "#/$defs/linked_list_node"1761 },1762 {1763 "type": "null"1764 }1765 ],1766 "description": "Reference to the next node; null if it is the last node."1767 }1768 },1769 "required": [1770 "value",1771 "next"1772 ],1773 "additionalProperties": false1774 }1775 },1776 "required": [1777 "linked_list"1778 ],1779 "additionalProperties": false1780}17811782Input: Dynamically generated UI1783Output: {1784 "name": "ui",1785 "type": "object",1786 "properties": {1787 "type": {1788 "type": "string",1789 "description": "The type of the UI component",1790 "enum": [1791 "div",1792 "button",1793 "header",1794 "section",1795 "field",1796 "form"1797 ]1798 },1799 "label": {1800 "type": "string",1801 "description": "The label of the UI component, used for buttons or form fields"1802 },1803 "children": {1804 "type": "array",1805 "description": "Nested UI components",1806 "items": {1807 "$ref": "#"1808 }1809 },1810 "attributes": {1811 "type": "array",1812 "description": "Arbitrary attributes for the UI component, suitable for any element",1813 "items": {1814 "type": "object",1815 "properties": {1816 "name": {1817 "type": "string",1818 "description": "The name of the attribute, for example onClick or className"1819 },1820 "value": {1821 "type": "string",1822 "description": "The value of the attribute"1823 }1824 },1825 "required": [1826 "name",1827 "value"1828 ],1829 "additionalProperties": false1830 }1831 }1832 },1833 "required": [1834 "type",1835 "label",1836 "children",1837 "attributes"1838 ],1839 "additionalProperties": false1840}1841""".strip()184218431844def generate_schema(description: str):1845 completion = client.chat.completions.create(1846 model="gpt-5.6-terra",1847 response_format={"type": "json_schema", "json_schema": META_SCHEMA},1848 messages=[1849 {1850 "role": "system",1851 "content": META_PROMPT,1852 },1853 {1854 "role": "user",1855 "content": "Description:\n" + description,1856 },1857 ],1858 )18591860 return json.loads(completion.choices[0].message.content)1861```18621863```java1864import com.openai.client.OpenAIClient;1865import com.openai.client.okhttp.OpenAIOkHttpClient;1866import com.openai.core.JsonValue;1867import com.openai.models.chat.completions.ChatCompletionCreateParams;1868import java.util.List;1869import java.util.Map;18701871String metaPrompt =1872 """1873 # Instructions1874 Return a valid schema for the described JSON.18751876 You must also make sure:1877 - all fields in an object are set as required1878 - I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED1879 - all objects must have additionalProperties set to false1880 - because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties1881 - all objects must have properties defined1882 - field order matters. any form of "thinking" or "explanation" should come before the conclusion1883 - $defs must be defined under the schema param18841885 Notable keywords NOT supported include:1886 - For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties1887 - For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems18881889 Other notes:1890 - definitions and recursion are supported1891 - only if necessary to include references e.g. "$defs", it must be inside the "schema" object18921893 # Examples1894 Input: Generate a math reasoning schema with steps and a final answer.1895 Output: {1896 "name": "math_reasoning",1897 "type": "object",1898 "properties": {1899 "steps": {1900 "type": "array",1901 "description": "A sequence of steps involved in solving the math problem.",1902 "items": {1903 "type": "object",1904 "properties": {1905 "explanation": {1906 "type": "string",1907 "description": "Description of the reasoning or method used in this step."1908 },1909 "output": {1910 "type": "string",1911 "description": "Result or outcome of this specific step."1912 }1913 },1914 "required": [1915 "explanation",1916 "output"1917 ],1918 "additionalProperties": false1919 }1920 },1921 "final_answer": {1922 "type": "string",1923 "description": "The final solution or answer to the math problem."1924 }1925 },1926 "required": [1927 "steps",1928 "final_answer"1929 ],1930 "additionalProperties": false1931 }19321933 Input: Give me a linked list1934 Output: {1935 "name": "linked_list",1936 "type": "object",1937 "properties": {1938 "linked_list": {1939 "$ref": "#/$defs/linked_list_node",1940 "description": "The head node of the linked list."1941 }1942 },1943 "$defs": {1944 "linked_list_node": {1945 "type": "object",1946 "description": "Defines a node in a singly linked list.",1947 "properties": {1948 "value": {1949 "type": "number",1950 "description": "The value stored in this node."1951 },1952 "next": {1953 "anyOf": [1954 {1955 "$ref": "#/$defs/linked_list_node"1956 },1957 {1958 "type": "null"1959 }1960 ],1961 "description": "Reference to the next node; null if it is the last node."1962 }1963 },1964 "required": [1965 "value",1966 "next"1967 ],1968 "additionalProperties": false1969 }1970 },1971 "required": [1972 "linked_list"1973 ],1974 "additionalProperties": false1975 }19761977 Input: Dynamically generated UI1978 Output: {1979 "name": "ui",1980 "type": "object",1981 "properties": {1982 "type": {1983 "type": "string",1984 "description": "The type of the UI component",1985 "enum": [1986 "div",1987 "button",1988 "header",1989 "section",1990 "field",1991 "form"1992 ]1993 },1994 "label": {1995 "type": "string",1996 "description": "The label of the UI component, used for buttons or form fields"1997 },1998 "children": {1999 "type": "array",2000 "description": "Nested UI components",2001 "items": {2002 "$ref": "#"2003 }2004 },2005 "attributes": {2006 "type": "array",2007 "description": "Arbitrary attributes for the UI component, suitable for any element",2008 "items": {2009 "type": "object",2010 "properties": {2011 "name": {2012 "type": "string",2013 "description": "The name of the attribute, for example onClick or className"2014 },2015 "value": {2016 "type": "string",2017 "description": "The value of the attribute"2018 }2019 },2020 "required": [2021 "name",2022 "value"2023 ],2024 "additionalProperties": false2025 }2026 }2027 },2028 "required": [2029 "type",2030 "label",2031 "children",2032 "attributes"2033 ],2034 "additionalProperties": false2035 }2036 """2037 .strip();2038Map<String, Object> metaSchema =2039 Map.ofEntries(2040 Map.entry("name", "metaschema"),2041 Map.entry(2042 "schema",2043 Map.ofEntries(2044 Map.entry("type", "object"),2045 Map.entry(2046 "properties",2047 Map.ofEntries(2048 Map.entry(2049 "name",2050 Map.ofEntries(2051 Map.entry("type", "string"),2052 Map.entry("description", "The name of the schema"))),2053 Map.entry(2054 "type",2055 Map.ofEntries(2056 Map.entry("type", "string"),2057 Map.entry(2058 "enum",2059 List.of(2060 "object", "array", "string", "number", "boolean",2061 "null")))),2062 Map.entry(2063 "properties",2064 Map.ofEntries(2065 Map.entry("type", "object"),2066 Map.entry(2067 "additionalProperties",2068 Map.ofEntries(2069 Map.entry("$ref", "#/$defs/schema_definition"))))),2070 Map.entry(2071 "items",2072 Map.ofEntries(2073 Map.entry(2074 "anyOf",2075 List.of(2076 Map.ofEntries(2077 Map.entry("$ref", "#/$defs/schema_definition")),2078 Map.ofEntries(2079 Map.entry("type", "array"),2080 Map.entry(2081 "items",2082 Map.ofEntries(2083 Map.entry(2084 "$ref",2085 "#/$defs/schema_definition")))))))),2086 Map.entry(2087 "required",2088 Map.ofEntries(2089 Map.entry("type", "array"),2090 Map.entry(2091 "items", Map.ofEntries(Map.entry("type", "string"))))),2092 Map.entry(2093 "additionalProperties",2094 Map.ofEntries(Map.entry("type", "boolean"))))),2095 Map.entry("required", List.of("type")),2096 Map.entry("additionalProperties", false),2097 Map.entry(2098 "if",2099 Map.ofEntries(2100 Map.entry(2101 "properties",2102 Map.ofEntries(2103 Map.entry(2104 "type", Map.ofEntries(Map.entry("const", "object"))))))),2105 Map.entry("then", Map.ofEntries(Map.entry("required", List.of("properties")))),2106 Map.entry(2107 "$defs",2108 Map.ofEntries(2109 Map.entry(2110 "schema_definition",2111 Map.ofEntries(2112 Map.entry("type", "object"),2113 Map.entry(2114 "properties",2115 Map.ofEntries(2116 Map.entry(2117 "type",2118 Map.ofEntries(2119 Map.entry("type", "string"),2120 Map.entry(2121 "enum",2122 List.of(2123 "object", "array", "string", "number",2124 "boolean", "null")))),2125 Map.entry(2126 "properties",2127 Map.ofEntries(2128 Map.entry("type", "object"),2129 Map.entry(2130 "additionalProperties",2131 Map.ofEntries(2132 Map.entry(2133 "$ref",2134 "#/$defs/schema_definition"))))),2135 Map.entry(2136 "items",2137 Map.ofEntries(2138 Map.entry(2139 "anyOf",2140 List.of(2141 Map.ofEntries(2142 Map.entry(2143 "$ref",2144 "#/$defs/schema_definition")),2145 Map.ofEntries(2146 Map.entry("type", "array"),2147 Map.entry(2148 "items",2149 Map.ofEntries(2150 Map.entry(2151 "$ref",2152 "#/$defs/schema_definition")))))))),2153 Map.entry(2154 "required",2155 Map.ofEntries(2156 Map.entry("type", "array"),2157 Map.entry(2158 "items",2159 Map.ofEntries(2160 Map.entry("type", "string"))))),2161 Map.entry(2162 "additionalProperties",2163 Map.ofEntries(Map.entry("type", "boolean"))))),2164 Map.entry("required", List.of("type")),2165 Map.entry("additionalProperties", false),2166 Map.entry(2167 "if",2168 Map.ofEntries(2169 Map.entry(2170 "properties",2171 Map.ofEntries(2172 Map.entry(2173 "type",2174 Map.ofEntries(2175 Map.entry("const", "object"))))))),2176 Map.entry(2177 "then",2178 Map.ofEntries(2179 Map.entry("required", List.of("properties")))))))))));21802181ChatCompletionCreateParams params =2182 ChatCompletionCreateParams.builder()2183 .model("gpt-5.6-terra")2184 .addSystemMessage(metaPrompt)2185 .addUserMessage("Description:\nDescribe a calendar event.")2186 .putAdditionalBodyProperty(2187 "response_format",2188 JsonValue.from(Map.of("type", "json_schema", "json_schema", metaSchema)))2189 .build();21902191client.chat().completions().create(params).choices().stream()2192 .flatMap(choice -> choice.message().content().stream())2193 .forEach(System.out::println);2194```21952196```ruby2197require "openai"2198require "json"21992200META_SCHEMA = {2201 "name" => "metaschema",2202 "schema" => {2203 "type" => "object",2204 "properties" => {2205 "name" => {2206 "type" => "string",2207 "description" => "The name of the schema"2208 },2209 "type" => {2210 "type" => "string",2211 "enum" => ["object", "array", "string", "number", "boolean", "null"]2212 },2213 "properties" => {2214 "type" => "object",2215 "additionalProperties" => {2216 "$ref" => "#/$defs/schema_definition"2217 }2218 },2219 "items" => {2220 "anyOf" => [2221 {2222 "$ref" => "#/$defs/schema_definition"2223 }, {2224 "type" => "array",2225 "items" => {2226 "$ref" => "#/$defs/schema_definition"2227 }2228 }2229 ]2230 },2231 "required" => {2232 "type" => "array",2233 "items" => {2234 "type" => "string"2235 }2236 },2237 "additionalProperties" => {2238 "type" => "boolean"2239 }2240 },2241 "required" => ["type"],2242 "additionalProperties" => false,2243 "if" => {2244 "properties" => {2245 "type" => {2246 "const" => "object"2247 }2248 }2249 },2250 "then" => {2251 "required" => ["properties"]2252 },2253 "$defs" => {2254 "schema_definition" => {2255 "type" => "object",2256 "properties" => {2257 "type" => {2258 "type" => "string",2259 "enum" => ["object", "array", "string", "number", "boolean", "null"]2260 },2261 "properties" => {2262 "type" => "object",2263 "additionalProperties" => {2264 "$ref" => "#/$defs/schema_definition"2265 }2266 },2267 "items" => {2268 "anyOf" => [2269 {2270 "$ref" => "#/$defs/schema_definition"2271 }, {2272 "type" => "array",2273 "items" => {2274 "$ref" => "#/$defs/schema_definition"2275 }2276 }2277 ]2278 },2279 "required" => {2280 "type" => "array",2281 "items" => {2282 "type" => "string"2283 }2284 },2285 "additionalProperties" => {2286 "type" => "boolean"2287 }2288 },2289 "required" => ["type"],2290 "additionalProperties" => false,2291 "if" => {2292 "properties" => {2293 "type" => {2294 "const" => "object"2295 }2296 }2297 },2298 "then" => {2299 "required" => ["properties"]2300 }2301 }2302 }2303 }2304}23052306META_PROMPT = <<~PROMPT.strip2307 # Instructions2308 Return a valid schema for the described JSON.23092310 You must also make sure:2311 - all fields in an object are set as required2312 - I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED2313 - all objects must have additionalProperties set to false2314 - because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties2315 - all objects must have properties defined2316 - field order matters. any form of "thinking" or "explanation" should come before the conclusion2317 - $defs must be defined under the schema param23182319 Notable keywords NOT supported include:2320 - For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties2321 - For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems23222323 Other notes:2324 - definitions and recursion are supported2325 - only if necessary to include references e.g. "$defs", it must be inside the "schema" object23262327 # Examples2328 Input: Generate a math reasoning schema with steps and a final answer.2329 Output: {2330 "name": "math_reasoning",2331 "type": "object",2332 "properties": {2333 "steps": {2334 "type": "array",2335 "description": "A sequence of steps involved in solving the math problem.",2336 "items": {2337 "type": "object",2338 "properties": {2339 "explanation": {2340 "type": "string",2341 "description": "Description of the reasoning or method used in this step."2342 },2343 "output": {2344 "type": "string",2345 "description": "Result or outcome of this specific step."2346 }2347 },2348 "required": [2349 "explanation",2350 "output"2351 ],2352 "additionalProperties": false2353 }2354 },2355 "final_answer": {2356 "type": "string",2357 "description": "The final solution or answer to the math problem."2358 }2359 },2360 "required": [2361 "steps",2362 "final_answer"2363 ],2364 "additionalProperties": false2365 }23662367 Input: Give me a linked list2368 Output: {2369 "name": "linked_list",2370 "type": "object",2371 "properties": {2372 "linked_list": {2373 "$ref": "#/$defs/linked_list_node",2374 "description": "The head node of the linked list."2375 }2376 },2377 "$defs": {2378 "linked_list_node": {2379 "type": "object",2380 "description": "Defines a node in a singly linked list.",2381 "properties": {2382 "value": {2383 "type": "number",2384 "description": "The value stored in this node."2385 },2386 "next": {2387 "anyOf": [2388 {2389 "$ref": "#/$defs/linked_list_node"2390 },2391 {2392 "type": "null"2393 }2394 ],2395 "description": "Reference to the next node; null if it is the last node."2396 }2397 },2398 "required": [2399 "value",2400 "next"2401 ],2402 "additionalProperties": false2403 }2404 },2405 "required": [2406 "linked_list"2407 ],2408 "additionalProperties": false2409 }24102411 Input: Dynamically generated UI2412 Output: {2413 "name": "ui",2414 "type": "object",2415 "properties": {2416 "type": {2417 "type": "string",2418 "description": "The type of the UI component",2419 "enum": [2420 "div",2421 "button",2422 "header",2423 "section",2424 "field",2425 "form"2426 ]2427 },2428 "label": {2429 "type": "string",2430 "description": "The label of the UI component, used for buttons or form fields"2431 },2432 "children": {2433 "type": "array",2434 "description": "Nested UI components",2435 "items": {2436 "$ref": "#"2437 }2438 },2439 "attributes": {2440 "type": "array",2441 "description": "Arbitrary attributes for the UI component, suitable for any element",2442 "items": {2443 "type": "object",2444 "properties": {2445 "name": {2446 "type": "string",2447 "description": "The name of the attribute, for example onClick or className"2448 },2449 "value": {2450 "type": "string",2451 "description": "The value of the attribute"2452 }2453 },2454 "required": [2455 "name",2456 "value"2457 ],2458 "additionalProperties": false2459 }2460 }2461 },2462 "required": [2463 "type",2464 "label",2465 "children",2466 "attributes"2467 ],2468 "additionalProperties": false2469 }2470PROMPT24712472client = OpenAI::Client.new2473completion = client.chat.completions.create(2474 model: "gpt-5.6-terra",2475 response_format: {2476 type: :json_schema,2477 json_schema: META_SCHEMA2478 },2479 messages: [2480 {2481 role: :system,2482 content: META_PROMPT2483 },2484 {2485 role: :user,2486 content: "Description: Schedule a meeting with a title and start time."2487 }2488 ]2489)2490message = completion.choices.fetch(0).message2491raise "Schema generation refused: #{message.refusal}" if message.refusal24922493puts(JSON.pretty_generate(JSON.parse(message.content || raise("No schema returned"))))2494```24952496 24972498 24992500 2501Function schema25022503 Structured output meta-schema25042505```javascript2506import OpenAI from "openai";25072508const client = new OpenAI();25092510const metaSchema = {2511 name: "function-metaschema",2512 schema: {2513 type: "object",2514 properties: {2515 name: {2516 type: "string",2517 description: "The name of the function",2518 },2519 description: {2520 type: "string",2521 description: "A description of what the function does",2522 },2523 parameters: {2524 $ref: "#/$defs/schema_definition",2525 description: "A JSON schema that defines the function's parameters",2526 },2527 },2528 required: ["name", "description", "parameters"],2529 additionalProperties: false,2530 $defs: {2531 schema_definition: {2532 type: "object",2533 properties: {2534 type: {2535 type: "string",2536 enum: ["object", "array", "string", "number", "boolean", "null"],2537 },2538 properties: {2539 type: "object",2540 additionalProperties: {2541 $ref: "#/$defs/schema_definition",2542 },2543 },2544 items: {2545 anyOf: [2546 {2547 $ref: "#/$defs/schema_definition",2548 },2549 {2550 type: "array",2551 items: {2552 $ref: "#/$defs/schema_definition",2553 },2554 },2555 ],2556 },2557 required: {2558 type: "array",2559 items: {2560 type: "string",2561 },2562 },2563 additionalProperties: {2564 type: "boolean",2565 },2566 },2567 required: ["type"],2568 additionalProperties: false,2569 if: {2570 properties: {2571 type: {2572 const: "object",2573 },2574 },2575 },2576 then: {2577 required: ["properties"],2578 },2579 },2580 },2581 },2582};25832584const metaPrompt = `# Instructions2585Return a valid schema for the described function.25862587Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.2588Make sure that every property, no matter how short, has a type and description correctly nested inside it.25892590# Examples2591Input: Assign values to NN hyperparameters2592Output: {2593 "name": "set_hyperparameters",2594 "description": "Assign values to NN hyperparameters",2595 "parameters": {2596 "type": "object",2597 "required": [2598 "learning_rate",2599 "epochs"2600 ],2601 "properties": {2602 "epochs": {2603 "type": "number",2604 "description": "Number of complete passes through dataset"2605 },2606 "learning_rate": {2607 "type": "number",2608 "description": "Speed of model learning"2609 }2610 }2611 }2612}26132614Input: Plans a motion path for the robot2615Output: {2616 "name": "plan_motion",2617 "description": "Plans a motion path for the robot",2618 "parameters": {2619 "type": "object",2620 "required": [2621 "start_position",2622 "end_position"2623 ],2624 "properties": {2625 "end_position": {2626 "type": "object",2627 "properties": {2628 "x": {2629 "type": "number",2630 "description": "End X coordinate"2631 },2632 "y": {2633 "type": "number",2634 "description": "End Y coordinate"2635 }2636 }2637 },2638 "obstacles": {2639 "type": "array",2640 "description": "Array of obstacle coordinates",2641 "items": {2642 "type": "object",2643 "properties": {2644 "x": {2645 "type": "number",2646 "description": "Obstacle X coordinate"2647 },2648 "y": {2649 "type": "number",2650 "description": "Obstacle Y coordinate"2651 }2652 }2653 }2654 },2655 "start_position": {2656 "type": "object",2657 "properties": {2658 "x": {2659 "type": "number",2660 "description": "Start X coordinate"2661 },2662 "y": {2663 "type": "number",2664 "description": "Start Y coordinate"2665 }2666 }2667 }2668 }2669 }2670}26712672Input: Calculates various technical indicators2673Output: {2674 "name": "technical_indicator",2675 "description": "Calculates various technical indicators",2676 "parameters": {2677 "type": "object",2678 "required": [2679 "ticker",2680 "indicators"2681 ],2682 "properties": {2683 "indicators": {2684 "type": "array",2685 "description": "List of technical indicators to calculate",2686 "items": {2687 "type": "string",2688 "description": "Technical indicator",2689 "enum": [2690 "RSI",2691 "MACD",2692 "Bollinger_Bands",2693 "Stochastic_Oscillator"2694 ]2695 }2696 },2697 "period": {2698 "type": "number",2699 "description": "Time period for the analysis"2700 },2701 "ticker": {2702 "type": "string",2703 "description": "Stock ticker symbol"2704 }2705 }2706 }2707}`;27082709async function generateFunctionSchema(description) {2710 const completion = await client.chat.completions.create({2711 model: "gpt-5.6-terra",2712 response_format: { type: "json_schema", json_schema: metaSchema },2713 messages: [2714 { role: "system", content: metaPrompt },2715 { role: "user", content: "Description:\n" + description },2716 ],2717 });27182719 const content = completion.choices[0].message.content;2720 if (!content) throw new Error("The model did not return a schema.");2721 return JSON.parse(content);2722}27232724console.log(2725 JSON.stringify(2726 await generateFunctionSchema(2727 "Create a function that checks the weather in a city."2728 ),2729 null,2730 22731 )2732);2733```27342735```python2736from openai import OpenAI2737import json27382739client = OpenAI()27402741META_SCHEMA = {2742 "name": "function-metaschema",2743 "schema": {2744 "type": "object",2745 "properties": {2746 "name": {"type": "string", "description": "The name of the function"},2747 "description": {2748 "type": "string",2749 "description": "A description of what the function does",2750 },2751 "parameters": {2752 "$ref": "#/$defs/schema_definition",2753 "description": "A JSON schema that defines the function's parameters",2754 },2755 },2756 "required": ["name", "description", "parameters"],2757 "additionalProperties": False,2758 "$defs": {2759 "schema_definition": {2760 "type": "object",2761 "properties": {2762 "type": {2763 "type": "string",2764 "enum": [2765 "object",2766 "array",2767 "string",2768 "number",2769 "boolean",2770 "null",2771 ],2772 },2773 "properties": {2774 "type": "object",2775 "additionalProperties": {"$ref": "#/$defs/schema_definition"},2776 },2777 "items": {2778 "anyOf": [2779 {"$ref": "#/$defs/schema_definition"},2780 {2781 "type": "array",2782 "items": {"$ref": "#/$defs/schema_definition"},2783 },2784 ]2785 },2786 "required": {"type": "array", "items": {"type": "string"}},2787 "additionalProperties": {"type": "boolean"},2788 },2789 "required": ["type"],2790 "additionalProperties": False,2791 "if": {"properties": {"type": {"const": "object"}}},2792 "then": {"required": ["properties"]},2793 }2794 },2795 },2796}27972798META_PROMPT = """2799# Instructions2800Return a valid schema for the described function.28012802Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.2803Make sure that every property, no matter how short, has a type and description correctly nested inside it.28042805# Examples2806Input: Assign values to NN hyperparameters2807Output: {2808 "name": "set_hyperparameters",2809 "description": "Assign values to NN hyperparameters",2810 "parameters": {2811 "type": "object",2812 "required": [2813 "learning_rate",2814 "epochs"2815 ],2816 "properties": {2817 "epochs": {2818 "type": "number",2819 "description": "Number of complete passes through dataset"2820 },2821 "learning_rate": {2822 "type": "number",2823 "description": "Speed of model learning"2824 }2825 }2826 }2827}28282829Input: Plans a motion path for the robot2830Output: {2831 "name": "plan_motion",2832 "description": "Plans a motion path for the robot",2833 "parameters": {2834 "type": "object",2835 "required": [2836 "start_position",2837 "end_position"2838 ],2839 "properties": {2840 "end_position": {2841 "type": "object",2842 "properties": {2843 "x": {2844 "type": "number",2845 "description": "End X coordinate"2846 },2847 "y": {2848 "type": "number",2849 "description": "End Y coordinate"2850 }2851 }2852 },2853 "obstacles": {2854 "type": "array",2855 "description": "Array of obstacle coordinates",2856 "items": {2857 "type": "object",2858 "properties": {2859 "x": {2860 "type": "number",2861 "description": "Obstacle X coordinate"2862 },2863 "y": {2864 "type": "number",2865 "description": "Obstacle Y coordinate"2866 }2867 }2868 }2869 },2870 "start_position": {2871 "type": "object",2872 "properties": {2873 "x": {2874 "type": "number",2875 "description": "Start X coordinate"2876 },2877 "y": {2878 "type": "number",2879 "description": "Start Y coordinate"2880 }2881 }2882 }2883 }2884 }2885}28862887Input: Calculates various technical indicators2888Output: {2889 "name": "technical_indicator",2890 "description": "Calculates various technical indicators",2891 "parameters": {2892 "type": "object",2893 "required": [2894 "ticker",2895 "indicators"2896 ],2897 "properties": {2898 "indicators": {2899 "type": "array",2900 "description": "List of technical indicators to calculate",2901 "items": {2902 "type": "string",2903 "description": "Technical indicator",2904 "enum": [2905 "RSI",2906 "MACD",2907 "Bollinger_Bands",2908 "Stochastic_Oscillator"2909 ]2910 }2911 },2912 "period": {2913 "type": "number",2914 "description": "Time period for the analysis"2915 },2916 "ticker": {2917 "type": "string",2918 "description": "Stock ticker symbol"2919 }2920 }2921 }2922}2923""".strip()292429252926def generate_function_schema(description: str):2927 completion = client.chat.completions.create(2928 model="gpt-5.6-terra",2929 response_format={"type": "json_schema", "json_schema": META_SCHEMA},2930 messages=[2931 {2932 "role": "system",2933 "content": META_PROMPT,2934 },2935 {2936 "role": "user",2937 "content": "Description:\n" + description,2938 },2939 ],2940 )29412942 return json.loads(completion.choices[0].message.content)2943```29442945```java2946import com.openai.client.OpenAIClient;2947import com.openai.client.okhttp.OpenAIOkHttpClient;2948import com.openai.core.JsonValue;2949import com.openai.models.chat.completions.ChatCompletionCreateParams;2950import java.util.List;2951import java.util.Map;29522953String metaPrompt =2954 """2955 # Instructions2956 Return a valid schema for the described function.29572958 Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.2959 Make sure that every property, no matter how short, has a type and description correctly nested inside it.29602961 # Examples2962 Input: Assign values to NN hyperparameters2963 Output: {2964 "name": "set_hyperparameters",2965 "description": "Assign values to NN hyperparameters",2966 "parameters": {2967 "type": "object",2968 "required": [2969 "learning_rate",2970 "epochs"2971 ],2972 "properties": {2973 "epochs": {2974 "type": "number",2975 "description": "Number of complete passes through dataset"2976 },2977 "learning_rate": {2978 "type": "number",2979 "description": "Speed of model learning"2980 }2981 }2982 }2983 }29842985 Input: Plans a motion path for the robot2986 Output: {2987 "name": "plan_motion",2988 "description": "Plans a motion path for the robot",2989 "parameters": {2990 "type": "object",2991 "required": [2992 "start_position",2993 "end_position"2994 ],2995 "properties": {2996 "end_position": {2997 "type": "object",2998 "properties": {2999 "x": {3000 "type": "number",3001 "description": "End X coordinate"3002 },3003 "y": {3004 "type": "number",3005 "description": "End Y coordinate"3006 }3007 }3008 },3009 "obstacles": {3010 "type": "array",3011 "description": "Array of obstacle coordinates",3012 "items": {3013 "type": "object",3014 "properties": {3015 "x": {3016 "type": "number",3017 "description": "Obstacle X coordinate"3018 },3019 "y": {3020 "type": "number",3021 "description": "Obstacle Y coordinate"3022 }3023 }3024 }3025 },3026 "start_position": {3027 "type": "object",3028 "properties": {3029 "x": {3030 "type": "number",3031 "description": "Start X coordinate"3032 },3033 "y": {3034 "type": "number",3035 "description": "Start Y coordinate"3036 }3037 }3038 }3039 }3040 }3041 }30423043 Input: Calculates various technical indicators3044 Output: {3045 "name": "technical_indicator",3046 "description": "Calculates various technical indicators",3047 "parameters": {3048 "type": "object",3049 "required": [3050 "ticker",3051 "indicators"3052 ],3053 "properties": {3054 "indicators": {3055 "type": "array",3056 "description": "List of technical indicators to calculate",3057 "items": {3058 "type": "string",3059 "description": "Technical indicator",3060 "enum": [3061 "RSI",3062 "MACD",3063 "Bollinger_Bands",3064 "Stochastic_Oscillator"3065 ]3066 }3067 },3068 "period": {3069 "type": "number",3070 "description": "Time period for the analysis"3071 },3072 "ticker": {3073 "type": "string",3074 "description": "Stock ticker symbol"3075 }3076 }3077 }3078 }3079 """3080 .strip();3081Map<String, Object> schemaDefinition =3082 Map.of(3083 "type", "object",3084 "properties",3085 Map.of(3086 "type",3087 Map.of(3088 "type",3089 "string",3090 "enum",3091 List.of("object", "array", "string", "number", "boolean", "null")),3092 "properties",3093 Map.of(3094 "type",3095 "object",3096 "additionalProperties",3097 Map.of("$ref", "#/$defs/schema_definition")),3098 "items",3099 Map.of(3100 "anyOf",3101 List.of(3102 Map.of("$ref", "#/$defs/schema_definition"),3103 Map.of(3104 "type",3105 "array",3106 "items",3107 Map.of("$ref", "#/$defs/schema_definition")))),3108 "required", Map.of("type", "array", "items", Map.of("type", "string")),3109 "additionalProperties", Map.of("type", "boolean")),3110 "required", List.of("type"),3111 "additionalProperties", false,3112 "if", Map.of("properties", Map.of("type", Map.of("const", "object"))),3113 "then", Map.of("required", List.of("properties")));3114Map<String, Object> functionSchema =3115 Map.of(3116 "type", "object",3117 "properties",3118 Map.of(3119 "name", Map.of("type", "string", "description", "The name of the function"),3120 "description",3121 Map.of(3122 "type",3123 "string",3124 "description",3125 "A description of what the function does"),3126 "parameters",3127 Map.of(3128 "$ref",3129 "#/$defs/schema_definition",3130 "description",3131 "A JSON schema that defines the function's parameters")),3132 "required", List.of("name", "description", "parameters"),3133 "additionalProperties", false,3134 "$defs", Map.of("schema_definition", schemaDefinition));31353136ChatCompletionCreateParams params =3137 ChatCompletionCreateParams.builder()3138 .model("gpt-5.6-terra")3139 .addSystemMessage(metaPrompt)3140 .addUserMessage("Description:\nSchedule a meeting with a title and start time.")3141 .putAdditionalBodyProperty(3142 "response_format",3143 JsonValue.from(3144 Map.of(3145 "type",3146 "json_schema",3147 "json_schema",3148 Map.of("name", "function-metaschema", "schema", functionSchema))))3149 .build();31503151client.chat().completions().create(params).choices().stream()3152 .flatMap(choice -> choice.message().content().stream())3153 .forEach(System.out::println);3154```31553156```ruby3157require "openai"3158require "json"31593160META_SCHEMA = {3161 "name" => "function-metaschema",3162 "schema" => {3163 "type" => "object",3164 "properties" => {3165 "name" => {3166 "type" => "string",3167 "description" => "The name of the function"3168 },3169 "description" => {3170 "type" => "string",3171 "description" => "A description of what the function does"3172 },3173 "parameters" => {3174 "$ref" => "#/$defs/schema_definition",3175 "description" => "A JSON schema that defines the function's parameters"3176 }3177 },3178 "required" => ["name", "description", "parameters"],3179 "additionalProperties" => false,3180 "$defs" => {3181 "schema_definition" => {3182 "type" => "object",3183 "properties" => {3184 "type" => {3185 "type" => "string",3186 "enum" => ["object", "array", "string", "number", "boolean", "null"]3187 },3188 "properties" => {3189 "type" => "object",3190 "additionalProperties" => {3191 "$ref" => "#/$defs/schema_definition"3192 }3193 },3194 "items" => {3195 "anyOf" => [3196 {3197 "$ref" => "#/$defs/schema_definition"3198 }, {3199 "type" => "array",3200 "items" => {3201 "$ref" => "#/$defs/schema_definition"3202 }3203 }3204 ]3205 },3206 "required" => {3207 "type" => "array",3208 "items" => {3209 "type" => "string"3210 }3211 },3212 "additionalProperties" => {3213 "type" => "boolean"3214 }3215 },3216 "required" => ["type"],3217 "additionalProperties" => false,3218 "if" => {3219 "properties" => {3220 "type" => {3221 "const" => "object"3222 }3223 }3224 },3225 "then" => {3226 "required" => ["properties"]3227 }3228 }3229 }3230 }3231}32323233META_PROMPT = <<~PROMPT.strip3234 # Instructions3235 Return a valid schema for the described function.32363237 Pay special attention to making sure that "required" and "type" are always at the correct level of nesting. For example, "required" should be at the same level as "properties", not inside it.3238 Make sure that every property, no matter how short, has a type and description correctly nested inside it.32393240 # Examples3241 Input: Assign values to NN hyperparameters3242 Output: {3243 "name": "set_hyperparameters",3244 "description": "Assign values to NN hyperparameters",3245 "parameters": {3246 "type": "object",3247 "required": [3248 "learning_rate",3249 "epochs"3250 ],3251 "properties": {3252 "epochs": {3253 "type": "number",3254 "description": "Number of complete passes through dataset"3255 },3256 "learning_rate": {3257 "type": "number",3258 "description": "Speed of model learning"3259 }3260 }3261 }3262 }32633264 Input: Plans a motion path for the robot3265 Output: {3266 "name": "plan_motion",3267 "description": "Plans a motion path for the robot",3268 "parameters": {3269 "type": "object",3270 "required": [3271 "start_position",3272 "end_position"3273 ],3274 "properties": {3275 "end_position": {3276 "type": "object",3277 "properties": {3278 "x": {3279 "type": "number",3280 "description": "End X coordinate"3281 },3282 "y": {3283 "type": "number",3284 "description": "End Y coordinate"3285 }3286 }3287 },3288 "obstacles": {3289 "type": "array",3290 "description": "Array of obstacle coordinates",3291 "items": {3292 "type": "object",3293 "properties": {3294 "x": {3295 "type": "number",3296 "description": "Obstacle X coordinate"3297 },3298 "y": {3299 "type": "number",3300 "description": "Obstacle Y coordinate"3301 }3302 }3303 }3304 },3305 "start_position": {3306 "type": "object",3307 "properties": {3308 "x": {3309 "type": "number",3310 "description": "Start X coordinate"3311 },3312 "y": {3313 "type": "number",3314 "description": "Start Y coordinate"3315 }3316 }3317 }3318 }3319 }3320 }33213322 Input: Calculates various technical indicators3323 Output: {3324 "name": "technical_indicator",3325 "description": "Calculates various technical indicators",3326 "parameters": {3327 "type": "object",3328 "required": [3329 "ticker",3330 "indicators"3331 ],3332 "properties": {3333 "indicators": {3334 "type": "array",3335 "description": "List of technical indicators to calculate",3336 "items": {3337 "type": "string",3338 "description": "Technical indicator",3339 "enum": [3340 "RSI",3341 "MACD",3342 "Bollinger_Bands",3343 "Stochastic_Oscillator"3344 ]3345 }3346 },3347 "period": {3348 "type": "number",3349 "description": "Time period for the analysis"3350 },3351 "ticker": {3352 "type": "string",3353 "description": "Stock ticker symbol"3354 }3355 }3356 }3357 }3358PROMPT33593360client = OpenAI::Client.new3361completion = client.chat.completions.create(3362 model: "gpt-5.6-terra",3363 response_format: {3364 type: :json_schema,3365 json_schema: META_SCHEMA3366 },3367 messages: [3368 {3369 role: :system,3370 content: META_PROMPT3371 },3372 {3373 role: :user,3374 content: "Description: Schedule a meeting with a title and start time."3375 }3376 ]3377)3378message = completion.choices.fetch(0).message3379raise "Schema generation refused: #{message.refusal}" if message.refusal33803381puts(JSON.pretty_generate(JSON.parse(message.content || raise("No schema returned"))))3382```