Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/phpaisdk/openai/llms.txt

Use this file to discover all available pages before exploring further.

The aisdk/openai package routes every text generation request through OpenAI’s /chat/completions endpoint. The SDK converts your high-level Generate::text() builder call into a properly authenticated HTTP request, parses the response into a normalized TextModelResponse, and exposes typed fields for text content, token usage, finish reason, and raw provider metadata — all without you touching a single curl handle.

Basic Usage

Install the package, set your OPENAI_API_KEY environment variable, then call Generate::text():
use AiSdk\Generate;
use AiSdk\OpenAI;

$result = Generate::text()
    ->model(OpenAI::model('gpt-4o'))
    ->instructions('Write short, clear answers.')
    ->prompt('Explain closures in PHP.')
    ->run();

echo $result->text;
You can also register a default model once so that subsequent calls do not repeat it:
Generate::model(OpenAI::model('gpt-4o'));

$result = Generate::text('Explain closures in PHP.')->run();

Request Options

ChatRequestBuilder::build() assembles the body sent to /chat/completions. The following parameters are recognized.
model
string
required
The OpenAI model ID to use — for example gpt-4o, gpt-4.1, o3, or gpt-5. Passed directly to the API as the model field.
messages
array
required
The conversation history as an ordered array of message objects. The SDK converts each Message value to the OpenAI {role, content} wire format, prepending a system message when instructions are provided.
temperature
float
Sampling temperature between 0 and 2. Higher values produce more varied output; lower values produce more deterministic output. Maps directly to the OpenAI temperature field.
max_tokens
integer
Hard cap on the number of completion tokens the model may generate. Maps to the OpenAI max_tokens field. When null, the API uses its own default.
top_p
float
Nucleus sampling probability mass. Only included in the request body when a non-null value is provided — OpenAI recommends setting either temperature or top_p, not both.
stream
bool
Managed internally by the SDK. Set to false for ->run() and true for ->stream(). When true, stream_options: {include_usage: true} is also appended so usage statistics are available after the stream ends.

Response Fields

Generate::text()->run() returns a TextModelResponse. All fields below are available on the returned object.
text
string
The complete generated text. This is the concatenation of all TextPart content in the response.
parts
array
The typed parts that make up the response. For text generation this contains TextPart instances; when the model issues tool calls it contains ToolCallPart instances instead (or in addition). Inspect this array when you need per-part detail rather than the concatenated text string.
rawResponse
array
The complete, unmodified JSON payload returned by the OpenAI API. Use this as an escape hatch when you need fields that the SDK does not surface through normalized accessors.
usage
object
Token consumption for the request.
finishReason
string
Normalized reason the model stopped generating. Possible values:
ValueMeaning
stopThe model reached a natural end or a stop sequence.
lengthThe max_tokens limit was reached.
tool_callsThe model issued one or more tool calls.
content_filterContent was blocked by OpenAI’s content policy.
providerMetadata['openai']
array
Raw metadata extracted directly from the OpenAI response body. Useful for logging, debugging, and advanced routing decisions.

Multi-turn Conversations

Pass an explicit messages array to maintain conversation history. Use Message::user() for user turns and Message::assistant() for model turns:
use AiSdk\Generate;
use AiSdk\Message;
use AiSdk\OpenAI;

$result = Generate::text()
    ->model(OpenAI::model('gpt-4o'))
    ->messages([
        Message::user('What is a closure in PHP?'),
        Message::assistant('A closure is an anonymous function that can capture variables from its surrounding scope.'),
        Message::user('Can you show me a short example?'),
    ])
    ->run();

echo $result->text;
Each Message is converted by ChatMessageConverter::convert() into the OpenAI {role, content} wire format before the request is sent. A system message is prepended automatically when you call ->instructions().

Model Compatibility

The table below lists which model patterns in resources/models.json support text generation along with their additional capabilities.
Model / PatternText GenStreamingTool CallingStructured OutputReasoningImage InputFile Input
gpt-4o
gpt-4o*
gpt-4.1*
o* (o-series)
gpt-5*
gpt-*-audio*
openai/gpt-oss-20b
Unknown model IDs not listed in models.json are still allowed for text generation. For advanced capabilities (tool calling, structured output), opt in explicitly using ->assume([Capability::ToolCalling, ...]) on the model handle, or register the model with OpenAI::registerModel().

Build docs developers (and LLMs) love