97 return completion.choices[0].message.content97 return completion.choices[0].message.content
98````98````
99 99
100````java
101import com.openai.client.OpenAIClient;
102import com.openai.client.okhttp.OpenAIOkHttpClient;
103import com.openai.models.chat.completions.ChatCompletionCreateParams;
104
105String metaPrompt =
106 """
107 Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.
108
109 # Guidelines
110
111 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
112 - 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.
113 - 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!
114 - 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.
115 - Conclusion, classifications, or results should ALWAYS appear last.
116 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
117 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
118 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
119 - Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
120 - 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.
121 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
122 - Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
123 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
124 - JSON should never be wrapped in code blocks (```) unless explicitly requested.
125
126 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 "---")
127
128 [Concise instruction describing the task - this should be the first line in the prompt, no section header]
129
130 [Additional details as needed.]
131
132 [Optional sections with headings or bullet points for detailed steps.]
133
134 # Steps [optional]
135
136 [optional: a detailed breakdown of the steps necessary to accomplish the task]
137
138 # Output Format
139
140 [Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
141
142 # Examples [optional]
143
144 [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.]
145 [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! ]
146
147 # Notes [optional]
148
149 [optional: edge cases, details, and an area to call or repeat out specific important considerations]
150 """
151 .strip();
152
153ChatCompletionCreateParams params =
154 ChatCompletionCreateParams.builder()
155 .model("gpt-5.6")
156 .addSystemMessage(metaPrompt)
157 .addUserMessage(
158 "Task, Goal, or Current Prompt:\nWrite a concise product launch announcement.")
159 .build();
160
161client.chat().completions().create(params).choices().stream()
162 .flatMap(choice -> choice.message().content().stream())
163 .forEach(System.out::println);
164````
165
100 166
101 167
102 168
167 return completion.choices[0].message.content233 return completion.choices[0].message.content
168```234```
169 235
236```java
237import com.openai.client.OpenAIClient;
238import com.openai.client.okhttp.OpenAIOkHttpClient;
239import com.openai.models.chat.completions.ChatCompletionCreateParams;
240
241String metaPrompt =
242 """
243 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.
244
245 # Guidelines
246
247 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
248 - 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.
249 - Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
250 - 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.
251 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
252 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
253 - It is very important that any examples included reflect the short, conversational output responses of the model.
254 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.
255 - 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.
256 - 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.
257 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
258 - 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.
259 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
260
261 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 "---")
262
263 [Concise instruction describing the task - this should be the first line in the prompt, no section header]
264
265 [Additional details as needed.]
266
267 [Optional sections with headings or bullet points for detailed steps.]
268
269 # Examples [optional]
270
271 [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.]
272 [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! ]
273
274 # Notes [optional]
275
276 [optional: edge cases, details, and an area to call or repeat out specific important considerations]
277 """
278 .strip();
279
280ChatCompletionCreateParams params =
281 ChatCompletionCreateParams.builder()
282 .model("gpt-5.6")
283 .addSystemMessage(metaPrompt)
284 .addUserMessage(
285 "Task, Goal, or Current Prompt:\n"
286 + "Create a friendly voice assistant for a bike shop.")
287 .build();
288
289client.chat().completions().create(params).choices().stream()
290 .flatMap(choice -> choice.message().content().stream())
291 .forEach(System.out::println);
292```
293
170 294
171 295
172### Prompt edits296### Prompt edits
268 return completion.choices[0].message.content392 return completion.choices[0].message.content
269````393````
270 394
395````java
396import com.openai.client.OpenAIClient;
397import com.openai.client.okhttp.OpenAIOkHttpClient;
398import com.openai.models.chat.completions.ChatCompletionCreateParams;
399
400String metaPrompt =
401 """
402 Given a current prompt and a change description, produce a detailed system prompt to guide a language model in completing the task effectively.
403
404 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:
405 <reasoning>
406 - Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
407 - Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
408 - Identify: (max 10 words) if so, which section(s) utilize reasoning?
409 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
410 - Ordering: (before/after) is the chain of though located before or after
411 - Structure: (yes/no) does the input prompt have a well defined structure
412 - Examples: (yes/no) does the input prompt have few-shot examples
413 - Representative: (1-5) if present, how representative are the examples?
414 - Complexity: (1-5) how complex is the input prompt?
415 - Task: (1-5) how complex is the implied task?
416 - Necessity: ()
417 - Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
418 - Prioritization: (list) what 1-3 categories are the MOST important to address.
419 - 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 listed
420 </reasoning>
421
422 # Guidelines
423
424 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
425 - 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.
426 - 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!
427 - 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.
428 - Conclusion, classifications, or results should ALWAYS appear last.
429 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
430 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
431 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
432 - Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
433 - 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.
434 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
435 - Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
436 - For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
437 - JSON should never be wrapped in code blocks (```) unless explicitly requested.
438
439 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 "---")
440
441 [Concise instruction describing the task - this should be the first line in the prompt, no section header]
442
443 [Additional details as needed.]
444
445 [Optional sections with headings or bullet points for detailed steps.]
446
447 # Steps [optional]
448
449 [optional: a detailed breakdown of the steps necessary to accomplish the task]
450
451 # Output Format
452
453 [Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
454
455 # Examples [optional]
456
457 [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.]
458 [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! ]
459
460 # Notes [optional]
461
462 [optional: edge cases, details, and an area to call or repeat out specific important considerations]
463 [NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]
464 """
465 .strip();
466
467ChatCompletionCreateParams params =
468 ChatCompletionCreateParams.builder()
469 .model("gpt-5.6")
470 .addSystemMessage(metaPrompt)
471 .addUserMessage(
472 "Task, Goal, or Current Prompt:\nMake this product launch announcement clearer and more concise.")
473 .build();
474
475client.chat().completions().create(params).choices().stream()
476 .flatMap(choice -> choice.message().content().stream())
477 .forEach(System.out::println);
478````
479
271 480
272 481
273 482
357 return completion.choices[0].message.content566 return completion.choices[0].message.content
358```567```
359 568
569```java
570import com.openai.client.OpenAIClient;
571import com.openai.client.okhttp.OpenAIOkHttpClient;
572import com.openai.models.chat.completions.ChatCompletionCreateParams;
573
574String metaPrompt =
575 """
576 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.
577
578 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:
579 <reasoning>
580 - Simple Change: (yes/no) Is the change description explicit and simple? (If so, skip the rest of these questions.)
581 - Reasoning: (yes/no) Does the current prompt use reasoning, analysis, or chain of thought?
582 - Identify: (max 10 words) if so, which section(s) utilize reasoning?
583 - Conclusion: (yes/no) is the chain of thought used to determine a conclusion?
584 - Ordering: (before/after) is the chain of though located before or after
585 - Structure: (yes/no) does the input prompt have a well defined structure
586 - Examples: (yes/no) does the input prompt have few-shot examples
587 - Representative: (1-5) if present, how representative are the examples?
588 - Complexity: (1-5) how complex is the input prompt?
589 - Task: (1-5) how complex is the implied task?
590 - Necessity: ()
591 - Specificity: (1-5) how detailed and specific is the prompt? (not to be confused with length)
592 - Prioritization: (list) what 1-3 categories are the MOST important to address.
593 - 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 listed
594 </reasoning>
595
596 # Guidelines
597
598 - Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
599 - 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.
600 - Audio Output Constraints: Because the model is outputting audio, the responses should be short and conversational.
601 - 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.
602 - Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
603 - What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
604 - It is very important that any examples included reflect the short, conversational output responses of the model.
605 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.
606 - 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.
607 - 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.
608 - Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
609 - 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.
610 - Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
611
612 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 "---")
613
614 [Concise instruction describing the task - this should be the first line in the prompt, no section header]
615
616 [Additional details as needed.]
617
618 [Optional sections with headings or bullet points for detailed steps.]
619
620 # Examples [optional]
621
622 [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.]
623 [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! ]
624
625 # Notes [optional]
626
627 [optional: edge cases, details, and an area to call or repeat out specific important considerations]
628 [NOTE: you must start with a <reasoning> section. the immediate next token you produce should be <reasoning>]
629 """
630 .strip();
631
632ChatCompletionCreateParams params =
633 ChatCompletionCreateParams.builder()
634 .model("gpt-5.6")
635 .addSystemMessage(metaPrompt)
636 .addUserMessage(
637 "Task, Goal, or Current Prompt:\nMake this voice assistant prompt warmer and more direct.")
638 .build();
639
640client.chat().completions().create(params).choices().stream()
641 .flatMap(choice -> choice.message().content().stream())
642 .forEach(System.out::println);
643```
644
360 645
361 646
362## Schemas647## Schemas
676 return json.loads(completion.choices[0].message.content)961 return json.loads(completion.choices[0].message.content)
677```962```
678 963
964```java
965import com.openai.client.OpenAIClient;
966import com.openai.client.okhttp.OpenAIOkHttpClient;
967import com.openai.core.JsonValue;
968import com.openai.models.chat.completions.ChatCompletionCreateParams;
969import java.util.List;
970import java.util.Map;
971
972String metaPrompt =
973 """
974 # Instructions
975 Return a valid schema for the described JSON.
976
977 You must also make sure:
978 - all fields in an object are set as required
979 - I REPEAT, ALL FIELDS MUST BE MARKED AS REQUIRED
980 - all objects must have additionalProperties set to false
981 - because of this, some cases like "attributes" or "metadata" properties that would normally allow additional properties should instead have a fixed set of properties
982 - all objects must have properties defined
983 - field order matters. any form of "thinking" or "explanation" should come before the conclusion
984 - $defs must be defined under the schema param
985
986 Notable keywords NOT supported include:
987 - For objects: unevaluatedProperties, propertyNames, minProperties, maxProperties
988 - For arrays: unevaluatedItems, contains, minContains, maxContains, uniqueItems
989
990 Other notes:
991 - definitions and recursion are supported
992 - only if necessary to include references e.g. "$defs", it must be inside the "schema" object
993
994 # Examples
995 Input: Generate a math reasoning schema with steps and a final answer.
996 Output: {
997 "name": "math_reasoning",
998 "type": "object",
999 "properties": {
1000 "steps": {
1001 "type": "array",
1002 "description": "A sequence of steps involved in solving the math problem.",
1003 "items": {
1004 "type": "object",
1005 "properties": {
1006 "explanation": {
1007 "type": "string",
1008 "description": "Description of the reasoning or method used in this step."
1009 },
1010 "output": {
1011 "type": "string",
1012 "description": "Result or outcome of this specific step."
1013 }
1014 },
1015 "required": [
1016 "explanation",
1017 "output"
1018 ],
1019 "additionalProperties": false
1020 }
1021 },
1022 "final_answer": {
1023 "type": "string",
1024 "description": "The final solution or answer to the math problem."
1025 }
1026 },
1027 "required": [
1028 "steps",
1029 "final_answer"
1030 ],
1031 "additionalProperties": false
1032 }
1033
1034 Input: Give me a linked list
1035 Output: {
1036 "name": "linked_list",
1037 "type": "object",
1038 "properties": {
1039 "linked_list": {
1040 "$ref": "#/$defs/linked_list_node",
1041 "description": "The head node of the linked list."
1042 }
1043 },
1044 "$defs": {
1045 "linked_list_node": {
1046 "type": "object",
1047 "description": "Defines a node in a singly linked list.",
1048 "properties": {
1049 "value": {
1050 "type": "number",
1051 "description": "The value stored in this node."
1052 },
1053 "next": {
1054 "anyOf": [
1055 {
1056 "$ref": "#/$defs/linked_list_node"
1057 },
1058 {
1059 "type": "null"
1060 }
1061 ],
1062 "description": "Reference to the next node; null if it is the last node."
1063 }
1064 },
1065 "required": [
1066 "value",
1067 "next"
1068 ],
1069 "additionalProperties": false
1070 }
1071 },
1072 "required": [
1073 "linked_list"
1074 ],
1075 "additionalProperties": false
1076 }
1077
1078 Input: Dynamically generated UI
1079 Output: {
1080 "name": "ui",
1081 "type": "object",
1082 "properties": {
1083 "type": {
1084 "type": "string",
1085 "description": "The type of the UI component",
1086 "enum": [
1087 "div",
1088 "button",
1089 "header",
1090 "section",
1091 "field",
1092 "form"
1093 ]
1094 },
1095 "label": {
1096 "type": "string",
1097 "description": "The label of the UI component, used for buttons or form fields"
1098 },
1099 "children": {
1100 "type": "array",
1101 "description": "Nested UI components",
1102 "items": {
1103 "$ref": "#"
1104 }
1105 },
1106 "attributes": {
1107 "type": "array",
1108 "description": "Arbitrary attributes for the UI component, suitable for any element",
1109 "items": {
1110 "type": "object",
1111 "properties": {
1112 "name": {
1113 "type": "string",
1114 "description": "The name of the attribute, for example onClick or className"
1115 },
1116 "value": {
1117 "type": "string",
1118 "description": "The value of the attribute"
1119 }
1120 },
1121 "required": [
1122 "name",
1123 "value"
1124 ],
1125 "additionalProperties": false
1126 }
1127 }
1128 },
1129 "required": [
1130 "type",
1131 "label",
1132 "children",
1133 "attributes"
1134 ],
1135 "additionalProperties": false
1136 }
1137 """
1138 .strip();
1139Map<String, Object> metaSchema =
1140 Map.ofEntries(
1141 Map.entry("name", "metaschema"),
1142 Map.entry(
1143 "schema",
1144 Map.ofEntries(
1145 Map.entry("type", "object"),
1146 Map.entry(
1147 "properties",
1148 Map.ofEntries(
1149 Map.entry(
1150 "name",
1151 Map.ofEntries(
1152 Map.entry("type", "string"),
1153 Map.entry("description", "The name of the schema"))),
1154 Map.entry(
1155 "type",
1156 Map.ofEntries(
1157 Map.entry("type", "string"),
1158 Map.entry(
1159 "enum",
1160 List.of(
1161 "object", "array", "string", "number", "boolean",
1162 "null")))),
1163 Map.entry(
1164 "properties",
1165 Map.ofEntries(
1166 Map.entry("type", "object"),
1167 Map.entry(
1168 "additionalProperties",
1169 Map.ofEntries(
1170 Map.entry("$ref", "#/$defs/schema_definition"))))),
1171 Map.entry(
1172 "items",
1173 Map.ofEntries(
1174 Map.entry(
1175 "anyOf",
1176 List.of(
1177 Map.ofEntries(
1178 Map.entry("$ref", "#/$defs/schema_definition")),
1179 Map.ofEntries(
1180 Map.entry("type", "array"),
1181 Map.entry(
1182 "items",
1183 Map.ofEntries(
1184 Map.entry(
1185 "$ref",
1186 "#/$defs/schema_definition")))))))),
1187 Map.entry(
1188 "required",
1189 Map.ofEntries(
1190 Map.entry("type", "array"),
1191 Map.entry(
1192 "items", Map.ofEntries(Map.entry("type", "string"))))),
1193 Map.entry(
1194 "additionalProperties",
1195 Map.ofEntries(Map.entry("type", "boolean"))))),
1196 Map.entry("required", List.of("type")),
1197 Map.entry("additionalProperties", false),
1198 Map.entry(
1199 "if",
1200 Map.ofEntries(
1201 Map.entry(
1202 "properties",
1203 Map.ofEntries(
1204 Map.entry(
1205 "type", Map.ofEntries(Map.entry("const", "object"))))))),
1206 Map.entry("then", Map.ofEntries(Map.entry("required", List.of("properties")))),
1207 Map.entry(
1208 "$defs",
1209 Map.ofEntries(
1210 Map.entry(
1211 "schema_definition",
1212 Map.ofEntries(
1213 Map.entry("type", "object"),
1214 Map.entry(
1215 "properties",
1216 Map.ofEntries(
1217 Map.entry(
1218 "type",
1219 Map.ofEntries(
1220 Map.entry("type", "string"),
1221 Map.entry(
1222 "enum",
1223 List.of(
1224 "object", "array", "string", "number",
1225 "boolean", "null")))),
1226 Map.entry(
1227 "properties",
1228 Map.ofEntries(
1229 Map.entry("type", "object"),
1230 Map.entry(
1231 "additionalProperties",
1232 Map.ofEntries(
1233 Map.entry(
1234 "$ref",
1235 "#/$defs/schema_definition"))))),
1236 Map.entry(
1237 "items",
1238 Map.ofEntries(
1239 Map.entry(
1240 "anyOf",
1241 List.of(
1242 Map.ofEntries(
1243 Map.entry(
1244 "$ref",
1245 "#/$defs/schema_definition")),
1246 Map.ofEntries(
1247 Map.entry("type", "array"),
1248 Map.entry(
1249 "items",
1250 Map.ofEntries(
1251 Map.entry(
1252 "$ref",
1253 "#/$defs/schema_definition")))))))),
1254 Map.entry(
1255 "required",
1256 Map.ofEntries(
1257 Map.entry("type", "array"),
1258 Map.entry(
1259 "items",
1260 Map.ofEntries(
1261 Map.entry("type", "string"))))),
1262 Map.entry(
1263 "additionalProperties",
1264 Map.ofEntries(Map.entry("type", "boolean"))))),
1265 Map.entry("required", List.of("type")),
1266 Map.entry("additionalProperties", false),
1267 Map.entry(
1268 "if",
1269 Map.ofEntries(
1270 Map.entry(
1271 "properties",
1272 Map.ofEntries(
1273 Map.entry(
1274 "type",
1275 Map.ofEntries(
1276 Map.entry("const", "object"))))))),
1277 Map.entry(
1278 "then",
1279 Map.ofEntries(
1280 Map.entry("required", List.of("properties")))))))))));
1281
1282ChatCompletionCreateParams params =
1283 ChatCompletionCreateParams.builder()
1284 .model("gpt-5.6-terra")
1285 .addSystemMessage(metaPrompt)
1286 .addUserMessage("Description:\nDescribe a calendar event.")
1287 .putAdditionalBodyProperty(
1288 "response_format",
1289 JsonValue.from(Map.of("type", "json_schema", "json_schema", metaSchema)))
1290 .build();
1291
1292client.chat().completions().create(params).choices().stream()
1293 .flatMap(choice -> choice.message().content().stream())
1294 .forEach(System.out::println);
1295```
1296
679 1297
680 1298
681 1299
894 1512
895 return json.loads(completion.choices[0].message.content)1513 return json.loads(completion.choices[0].message.content)
896```1514```
1515
1516```java
1517import com.openai.client.OpenAIClient;
1518import com.openai.client.okhttp.OpenAIOkHttpClient;
1519import com.openai.core.JsonValue;
1520import com.openai.models.chat.completions.ChatCompletionCreateParams;
1521import java.util.List;
1522import java.util.Map;
1523
1524String metaPrompt =
1525 """
1526 # Instructions
1527 Return a valid schema for the described function.
1528
1529 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.
1530 Make sure that every property, no matter how short, has a type and description correctly nested inside it.
1531
1532 # Examples
1533 Input: Assign values to NN hyperparameters
1534 Output: {
1535 "name": "set_hyperparameters",
1536 "description": "Assign values to NN hyperparameters",
1537 "parameters": {
1538 "type": "object",
1539 "required": [
1540 "learning_rate",
1541 "epochs"
1542 ],
1543 "properties": {
1544 "epochs": {
1545 "type": "number",
1546 "description": "Number of complete passes through dataset"
1547 },
1548 "learning_rate": {
1549 "type": "number",
1550 "description": "Speed of model learning"
1551 }
1552 }
1553 }
1554 }
1555
1556 Input: Plans a motion path for the robot
1557 Output: {
1558 "name": "plan_motion",
1559 "description": "Plans a motion path for the robot",
1560 "parameters": {
1561 "type": "object",
1562 "required": [
1563 "start_position",
1564 "end_position"
1565 ],
1566 "properties": {
1567 "end_position": {
1568 "type": "object",
1569 "properties": {
1570 "x": {
1571 "type": "number",
1572 "description": "End X coordinate"
1573 },
1574 "y": {
1575 "type": "number",
1576 "description": "End Y coordinate"
1577 }
1578 }
1579 },
1580 "obstacles": {
1581 "type": "array",
1582 "description": "Array of obstacle coordinates",
1583 "items": {
1584 "type": "object",
1585 "properties": {
1586 "x": {
1587 "type": "number",
1588 "description": "Obstacle X coordinate"
1589 },
1590 "y": {
1591 "type": "number",
1592 "description": "Obstacle Y coordinate"
1593 }
1594 }
1595 }
1596 },
1597 "start_position": {
1598 "type": "object",
1599 "properties": {
1600 "x": {
1601 "type": "number",
1602 "description": "Start X coordinate"
1603 },
1604 "y": {
1605 "type": "number",
1606 "description": "Start Y coordinate"
1607 }
1608 }
1609 }
1610 }
1611 }
1612 }
1613
1614 Input: Calculates various technical indicators
1615 Output: {
1616 "name": "technical_indicator",
1617 "description": "Calculates various technical indicators",
1618 "parameters": {
1619 "type": "object",
1620 "required": [
1621 "ticker",
1622 "indicators"
1623 ],
1624 "properties": {
1625 "indicators": {
1626 "type": "array",
1627 "description": "List of technical indicators to calculate",
1628 "items": {
1629 "type": "string",
1630 "description": "Technical indicator",
1631 "enum": [
1632 "RSI",
1633 "MACD",
1634 "Bollinger_Bands",
1635 "Stochastic_Oscillator"
1636 ]
1637 }
1638 },
1639 "period": {
1640 "type": "number",
1641 "description": "Time period for the analysis"
1642 },
1643 "ticker": {
1644 "type": "string",
1645 "description": "Stock ticker symbol"
1646 }
1647 }
1648 }
1649 }
1650 """
1651 .strip();
1652Map<String, Object> schemaDefinition =
1653 Map.of(
1654 "type", "object",
1655 "properties",
1656 Map.of(
1657 "type",
1658 Map.of(
1659 "type",
1660 "string",
1661 "enum",
1662 List.of("object", "array", "string", "number", "boolean", "null")),
1663 "properties",
1664 Map.of(
1665 "type",
1666 "object",
1667 "additionalProperties",
1668 Map.of("$ref", "#/$defs/schema_definition")),
1669 "items",
1670 Map.of(
1671 "anyOf",
1672 List.of(
1673 Map.of("$ref", "#/$defs/schema_definition"),
1674 Map.of(
1675 "type",
1676 "array",
1677 "items",
1678 Map.of("$ref", "#/$defs/schema_definition")))),
1679 "required", Map.of("type", "array", "items", Map.of("type", "string")),
1680 "additionalProperties", Map.of("type", "boolean")),
1681 "required", List.of("type"),
1682 "additionalProperties", false,
1683 "if", Map.of("properties", Map.of("type", Map.of("const", "object"))),
1684 "then", Map.of("required", List.of("properties")));
1685Map<String, Object> functionSchema =
1686 Map.of(
1687 "type", "object",
1688 "properties",
1689 Map.of(
1690 "name", Map.of("type", "string", "description", "The name of the function"),
1691 "description",
1692 Map.of(
1693 "type",
1694 "string",
1695 "description",
1696 "A description of what the function does"),
1697 "parameters",
1698 Map.of(
1699 "$ref",
1700 "#/$defs/schema_definition",
1701 "description",
1702 "A JSON schema that defines the function's parameters")),
1703 "required", List.of("name", "description", "parameters"),
1704 "additionalProperties", false,
1705 "$defs", Map.of("schema_definition", schemaDefinition));
1706
1707ChatCompletionCreateParams params =
1708 ChatCompletionCreateParams.builder()
1709 .model("gpt-5.6-terra")
1710 .addSystemMessage(metaPrompt)
1711 .addUserMessage("Description:\nSchedule a meeting with a title and start time.")
1712 .putAdditionalBodyProperty(
1713 "response_format",
1714 JsonValue.from(
1715 Map.of(
1716 "type",
1717 "json_schema",
1718 "json_schema",
1719 Map.of("name", "function-metaschema", "schema", functionSchema))))
1720 .build();
1721
1722client.chat().completions().create(params).choices().stream()
1723 .flatMap(choice -> choice.message().content().stream())
1724 .forEach(System.out::println);
1725```