Repository Public
1# Text 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.45With the OpenAI API, you can use a [large language model](https://developers.openai.com/api/docs/models) to generate text from a prompt, as you might using [ChatGPT](https://chatgpt.com). Models can generate almost any kind of text response—like code, mathematical equations, structured JSON data, or human-like prose.67Use the [Responses API](https://developers.openai.com/api/reference/resources/responses) for direct model requests like this text-generation call.89Generate text from a simple prompt1011```javascript12import OpenAI from "openai";13const client = new OpenAI();1415const response = await client.responses.create({16 model: "gpt-6-astra",17 input: "Write a one-sentence bedtime story about a unicorn.",18});1920console.log(response.output_text);21```2223```python24from openai import OpenAI2526client = OpenAI()2728response = client.responses.create(29 model="gpt-6-astra",30 input="Write a one-sentence bedtime story about a unicorn.",31)3233print(response.output_text)34```3536```go37package main3839import (40 "context"41 "fmt"4243 "github.com/openai/openai-go/v3"44 "github.com/openai/openai-go/v3/responses"45)4647func main() {48 client := openai.NewClient()4950 resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{51 Model: "gpt-6-astra",52 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},53 })54 if err != nil {55 panic(err.Error())56 }5758 fmt.Println(resp.OutputText())59}60```6162```java63import com.openai.client.OpenAIClient;64import com.openai.client.okhttp.OpenAIOkHttpClient;65import com.openai.models.responses.Response;66import com.openai.models.responses.ResponseCreateParams;6768public class Main {69 public static void main(String[] args) {70 OpenAIClient client = OpenAIOkHttpClient.fromEnv();7172 ResponseCreateParams params =73 ResponseCreateParams.builder().input("Say this is a test").model("gpt-6-astra").build();7475 Response response = client.responses().create(params);76 response.output().stream()77 .flatMap(item -> item.message().stream())78 .flatMap(message -> message.content().stream())79 .flatMap(content -> content.outputText().stream())80 .forEach(outputText -> System.out.println(outputText.text()));81 }82}83```8485```csharp86using OpenAI.Responses;87#pragma warning disable OPENAI0018889string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;90ResponsesClient client = new(key);9192ResponseResult response = await client.CreateResponseAsync(93 "gpt-6-astra",94 "Say 'this is a test.'"95);9697Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");98```99100```ruby101require "openai"102103openai = OpenAI::Client.new104105response = openai.responses.create(106 model: "gpt-6-astra",107 input: "Write a one-sentence bedtime story about a unicorn."108)109110puts(response.output_text)111```112113```bash114openai responses create \115 --model "gpt-6-astra" \116 --input "Write a one-sentence bedtime story about a unicorn." \117 --raw-output \118 --transform 'output.#(type=="message").content.0.text'119```120121```bash122curl "https://api.openai.com/v1/responses" \123 -H "Content-Type: application/json" \124 -H "Authorization: Bearer $OPENAI_API_KEY" \125 -d '{126 "model": "gpt-6-astra",127 "input": "Write a one-sentence bedtime story about a unicorn."128 }'129```130131132An array of content generated by the model is in the `output` property of the response. In this simple example, we have just one output which looks like this:133134```json135[136 {137 "id": "msg_67b73f697ba4819183a15cc17d011509",138 "type": "message",139 "role": "assistant",140 "content": [141 {142 "type": "output_text",143 "text": "Under the soft glow of the moon, Luna the unicorn danced through fields of twinkling stardust, leaving trails of dreams for every child asleep.",144 "annotations": []145 }146 ]147 }148]149```150151**The `output` array often has more than one item in it!** It can contain tool calls, data about reasoning tokens generated by [reasoning models](https://developers.openai.com/api/docs/guides/reasoning), and other items. It is not safe to assume that the model's text output is present at `output[0].content[0].text`.152153Some of our [official SDKs](https://developers.openai.com/api/docs/libraries) include an `output_text` property on model responses for convenience, which aggregates all text outputs from the model into a single string. This may be useful as a shortcut to access text output from the model.154155In addition to plain text, you can also have the model return structured data in JSON format—this feature is called [**Structured Outputs**](https://developers.openai.com/api/docs/guides/structured-outputs).156157## Prompt engineering158159**Prompt engineering** is the process of writing effective instructions for a model, such that it consistently generates content that meets your requirements.160161Because the content generated from a model is non-deterministic, prompting to get your desired output is a mix of art and science. However, you can apply techniques and best practices to get good results consistently.162163Some prompt engineering techniques work with every model, like using message roles. But different models might need to be prompted differently to produce the best results. Even different snapshots of models within the same family could produce different results. So as you build more complex applications, we strongly recommend:164165- Pinning your production applications to specific [model snapshots](https://developers.openai.com/api/docs/models) (like `gpt-5.5-2026-04-23` for example) to ensure consistent behavior166- Building tests and evaluation suites that measure prompt behavior so you can monitor performance as you iterate, or when you change and upgrade model versions167168Now, let's examine some tools and techniques available to you to construct prompts.169170## Choosing models and APIs171172OpenAI has many different [models](https://developers.openai.com/api/docs/models) and several APIs to choose from. [Reasoning models](https://developers.openai.com/api/docs/guides/reasoning), like [`gpt-6-astra`](https://developers.openai.com/api/docs/models/gpt-6-astra), behave differently from chat models and respond better to different prompts. One important note is that reasoning models perform better and demonstrate higher intelligence when used with the Responses API.173174If you're building any text generation app, we recommend using the Responses API over the older Chat Completions API. And if you're using a reasoning model, it's especially useful to [migrate to Responses](https://developers.openai.com/api/docs/guides/migrate-to-responses).175176## Message roles and instruction following177178You can provide instructions to the model with [differing levels of authority](https://model-spec.openai.com/2025-02-12.html#chain_of_command) using the `instructions` API parameter along with **message roles**.179180The `instructions` parameter gives the model high-level instructions on how it should behave while generating a response, including tone, goals, and examples of correct responses. Any instructions provided this way will take priority over a prompt in the `input` parameter.181182Generate text with instructions183184```javascript185import OpenAI from "openai";186const client = new OpenAI();187188const response = await client.responses.create({189 model: "gpt-6-astra",190 reasoning: { effort: "low" },191 instructions: "Talk like a pirate.",192 input: "Are semicolons optional in JavaScript?",193});194195console.log(response.output_text);196```197198```python199from openai import OpenAI200201client = OpenAI()202203response = client.responses.create(204 model="gpt-6-astra",205 reasoning={"effort": "low"},206 instructions="Talk like a pirate.",207 input="Are semicolons optional in JavaScript?",208)209210print(response.output_text)211```212213```go214package main215216import (217 "context"218 "fmt"219220 "github.com/openai/openai-go/v3"221 "github.com/openai/openai-go/v3/responses"222)223224func main() {225 client := openai.NewClient()226227 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{228 Model: "gpt-6-astra",229 Instructions: openai.String("Talk like a pirate."),230 Reasoning: responses.ReasoningParam{231 Effort: responses.ReasoningEffortLow,232 },233 Input: responses.ResponseNewParamsInputUnion{234 OfString: openai.String("Are semicolons optional in JavaScript?"),235 },236 })237 if err != nil {238 panic(err)239 }240241 fmt.Println(response.OutputText())242}243```244245```java246import com.openai.client.OpenAIClient;247import com.openai.client.okhttp.OpenAIOkHttpClient;248import com.openai.models.Reasoning;249import com.openai.models.ReasoningEffort;250import com.openai.models.responses.ResponseCreateParams;251252String semicolonsDevMsg = "Talk like a pirate.";253254String semicolonsPrompt = "Are semicolons optional in JavaScript?";255256ResponseCreateParams params =257 ResponseCreateParams.builder()258 .model("gpt-6-astra")259 .input(semicolonsPrompt)260 .instructions(semicolonsDevMsg)261 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())262 .build();263264client.responses().create(params).output().stream()265 .flatMap(item -> item.message().stream())266 .flatMap(message -> message.content().stream())267 .flatMap(content -> content.outputText().stream())268 .forEach(text -> System.out.println(text.text()));269```270271```csharp272using OpenAI.Responses;273#pragma warning disable OPENAI001274275string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;276ResponsesClient client = new(key);277278CreateResponseOptions options = new()279{280 Model = "gpt-6-astra",281 Instructions = "Talk like a pirate.",282 ReasoningOptions = new ResponseReasoningOptions283 {284 ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,285 },286};287options.InputItems.Add(288 ResponseItem.CreateUserMessageItem("Are semicolons optional in JavaScript?")289);290291ResponseResult response = await client.CreateResponseAsync(options);292293Console.WriteLine(response.GetOutputText());294```295296```ruby297require "openai"298299client = OpenAI::Client.new300response = client.responses.create(301 model: "gpt-6-astra",302 instructions: "Talk like a pirate.",303 reasoning: { effort: :low },304 input: "Are semicolons optional in JavaScript?"305)306307puts(response.output_text)308```309310```bash311curl "https://api.openai.com/v1/responses" \312 -H "Content-Type: application/json" \313 -H "Authorization: Bearer $OPENAI_API_KEY" \314 -d '{315 "model": "gpt-6-astra",316 "reasoning": {"effort": "low"},317 "instructions": "Talk like a pirate.",318 "input": "Are semicolons optional in JavaScript?"319 }'320```321322323The example above is roughly equivalent to using the following input messages in the `input` array:324325Generate text with messages using different roles326327```javascript328import OpenAI from "openai";329const client = new OpenAI();330331const response = await client.responses.create({332 model: "gpt-6-astra",333 reasoning: { effort: "low" },334 input: [335 {336 role: "developer",337 content: "Talk like a pirate.",338 },339 {340 role: "user",341 content: "Are semicolons optional in JavaScript?",342 },343 ],344});345346console.log(response.output_text);347```348349```python350from openai import OpenAI351352client = OpenAI()353354response = client.responses.create(355 model="gpt-6-astra",356 reasoning={"effort": "low"},357 input=[358 {"role": "developer", "content": "Talk like a pirate."},359 {"role": "user", "content": "Are semicolons optional in JavaScript?"},360 ],361)362363print(response.output_text)364```365366```go367package main368369import (370 "context"371 "fmt"372373 "github.com/openai/openai-go/v3"374 "github.com/openai/openai-go/v3/responses"375)376377func main() {378 client := openai.NewClient()379380 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{381 Model: "gpt-6-astra",382 Reasoning: responses.ReasoningParam{383 Effort: responses.ReasoningEffortLow,384 },385 Input: responses.ResponseNewParamsInputUnion{386 OfInputItemList: responses.ResponseInputParam{387 responses.ResponseInputItemParamOfMessage(388 "Talk like a pirate.",389 responses.EasyInputMessageRoleDeveloper,390 ),391 responses.ResponseInputItemParamOfMessage(392 "Are semicolons optional in JavaScript?",393 responses.EasyInputMessageRoleUser,394 ),395 },396 },397 })398 if err != nil {399 panic(err)400 }401402 fmt.Println(response.OutputText())403}404```405406```java407import com.openai.client.OpenAIClient;408import com.openai.client.okhttp.OpenAIOkHttpClient;409import com.openai.models.Reasoning;410import com.openai.models.ReasoningEffort;411import com.openai.models.responses.EasyInputMessage;412import com.openai.models.responses.ResponseCreateParams;413import com.openai.models.responses.ResponseInputItem;414import java.util.List;415416String semicolonsDevMsg = "Talk like a pirate.";417418String semicolonsPrompt = "Are semicolons optional in JavaScript?";419420ResponseCreateParams params =421 ResponseCreateParams.builder()422 .model("gpt-6-astra")423 .input(424 ResponseCreateParams.Input.ofResponse(425 List.of(426 ResponseInputItem.ofEasyInputMessage(427 EasyInputMessage.builder()428 .role(EasyInputMessage.Role.DEVELOPER)429 .content(semicolonsDevMsg)430 .build()),431 ResponseInputItem.ofEasyInputMessage(432 EasyInputMessage.builder()433 .role(EasyInputMessage.Role.USER)434 .content(semicolonsPrompt)435 .build()))))436 .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())437 .build();438439client.responses().create(params).output().stream()440 .flatMap(item -> item.message().stream())441 .flatMap(message -> message.content().stream())442 .flatMap(content -> content.outputText().stream())443 .forEach(text -> System.out.println(text.text()));444```445446```csharp447using OpenAI.Responses;448#pragma warning disable OPENAI001449450string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;451ResponsesClient client = new(key);452453CreateResponseOptions options = new()454{455 Model = "gpt-6-astra",456 ReasoningOptions = new ResponseReasoningOptions457 {458 ReasoningEffortLevel = ResponseReasoningEffortLevel.Low,459 },460};461options.InputItems.Add(462 ResponseItem.CreateDeveloperMessageItem("Talk like a pirate.")463);464options.InputItems.Add(465 ResponseItem.CreateUserMessageItem("Are semicolons optional in JavaScript?")466);467468ResponseResult response = await client.CreateResponseAsync(options);469470Console.WriteLine(response.GetOutputText());471```472473```ruby474require "openai"475476client = OpenAI::Client.new477response = client.responses.create(478 model: "gpt-6-astra",479 reasoning: { effort: :low },480 input: [481 {482 role: :developer,483 content: "Talk like a pirate."484 },485 {486 role: :user,487 content: "Are semicolons optional in JavaScript?"488 }489 ]490)491492puts(response.output_text)493```494495```bash496curl "https://api.openai.com/v1/responses" \497 -H "Content-Type: application/json" \498 -H "Authorization: Bearer $OPENAI_API_KEY" \499 -d '{500 "model": "gpt-6-astra",501 "reasoning": {"effort": "low"},502 "input": [503 {504 "role": "developer",505 "content": "Talk like a pirate."506 },507 {508 "role": "user",509 "content": "Are semicolons optional in JavaScript?"510 }511 ]512 }'513```514515516Note that the `instructions` parameter only applies to the current response generation request. If you are [managing conversation state](https://developers.openai.com/api/docs/guides/conversation-state) with the `previous_response_id` parameter, the `instructions` used on previous turns will not be present in the context.517518The [OpenAI model spec](https://model-spec.openai.com/2025-02-12.html#chain_of_command) describes how our models give different levels of priority to messages with different roles.519520<table>521 <thead>522 <tr>523 <th>developer</th>524 <th>user</th>525 <th>assistant</th>526 </tr>527 </thead>528 <tbody>529 <tr>530 <td>531 `developer` messages are instructions provided by the application532 developer, prioritized ahead of user messages.533 </td>534 <td>535 `user` messages are instructions provided by an end user, prioritized536 behind developer messages.537 </td>538 <td>539 Messages generated by the model have the `assistant` role.540 </td>541 </tr>542 </tbody>543</table>544545A multi-turn conversation may consist of several messages of these types, along with other content types provided by both you and the model. Learn more about [managing conversation state here](https://developers.openai.com/api/docs/guides/conversation-state).546547You could think about `developer` and `user` messages like a function and its arguments in a programming language.548549- `developer` messages provide the system's rules and business logic, like a function definition.550- `user` messages provide inputs and configuration to which the `developer` message instructions are applied, like arguments to a function.551552## Version prompts in code553554Store production prompts in your application code instead of creating reusable prompt objects. Code-managed prompts let you use typed inputs, code review, tests, and your normal deployment process to change model behavior.555556OpenAI is deprecating reusable prompt objects in the API. Prompt creation will557 be de-emphasized beginning June 3, 2026, and `v1/prompts` is scheduled to shut558 down on November 30, 2026. See the [deprecations559 page](https://developers.openai.com/api/docs/deprecations#2026-06-03-reusable-prompts) for the current560 timeline.561562For new text-generation work:563564- Keep prompt builders in a small module near the feature they support.565- Use typed function arguments or schemas for dynamic values such as customer data, files, or task options.566- Pass the generated `instructions` and `input` directly to the [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create).567- Add representative fixtures, tests, and evaluation checks before changing production prompts.568- Roll out prompt changes through your deployment system, using feature flags or configuration when you need staged releases.569570If your integration already calls a saved prompt with a prompt ID or version, use the [prompt object migration guide](https://developers.openai.com/api/docs/guides/prompting/migrate-from-prompt-object) to move that prompt into code.571572## Next steps573574Now that you know the basics of text inputs and outputs, you might want to check out one of these resources next.575576[Build a prompt in the Playground577578579580 Use the Playground to develop and iterate on prompts.](https://platform.openai.com/chat/edit)581582[Generate JSON data with Structured Outputs583584585586 Ensure JSON data emitted from a model conforms to a JSON schema.](https://developers.openai.com/api/docs/guides/structured-outputs)587588[Full API reference589590591592 Check out all the options for text generation in the API reference.](https://developers.openai.com/api/reference/resources/responses)