Skip to main content

Documentation Index

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

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

The Generate class is a static facade that acts as the single entry point for all AI generation tasks in the PHP AI SDK. It holds a shared Sdk instance (or builds one lazily), and returns fluent PendingTextRequest or PendingImageRequest builders that let you configure every aspect of a request before dispatching it.

Generate static methods

text()

Start a text generation request. If $prompt is provided, it is immediately added as a user message.
public static function text(?string $prompt = null): PendingTextRequest
prompt
string | null
default:"null"
An optional prompt string. When provided, it is appended as a user message on the returned PendingTextRequest.
$result = Generate::text('Explain the theory of relativity.')
    ->model($model)
    ->run();

echo $result->text;

image()

Start an image generation request. If $prompt is provided, it is immediately set on the returned builder.
public static function image(?string $prompt = null): PendingImageRequest
prompt
string | null
default:"null"
An optional prompt string. When provided, it is pre-set on the returned PendingImageRequest.
$result = Generate::image('A sunset over the ocean, oil painting style')
    ->model($imageModel)
    ->size('1024x1024')
    ->run();

echo $result->output->url;

model()

Set the default model used by subsequent text() and image() calls when no model is specified on the request itself.
public static function model(Model $model): void
model
Model
required
A model instance implementing the Model contract. Must also implement TextModelInterface or ImageModelInterface to be useful as a default.
Generate::model(new OpenAiModel('gpt-4o'));

$result = Generate::text('Hello!')->run();

configure()

Provide a fully constructed Sdk instance to the facade. All subsequent requests will use this SDK for model resolution and container access.
public static function configure(Sdk $sdk): void
sdk
Sdk
required
A configured Sdk value object that carries the default model and optional container.
$sdk = Sdk::build()->withDefaultModel(new OpenAiModel('gpt-4o'))->make();
Generate::configure($sdk);

sdk()

Return the current Sdk instance. If one has not been configured explicitly, a default instance is constructed lazily.
public static function sdk(): Sdk
return
Sdk
The active Sdk instance used for model resolution.
$sdk = Generate::sdk();

reset()

Clear the stored Sdk instance and the internal runtime factory. Primarily useful in tests to reset state between runs.
public static function reset(): void
Generate::reset(); // Clears all configured state

PendingTextRequest

PendingTextRequest is a fluent builder returned by Generate::text(). It composes four traits — ConfiguresGeneration, HasMessages, HasTools, and HasProviderOptions — in addition to its own methods.

model()

Override the model for this request only.
public function model(TextModelInterface $model): self
model
TextModelInterface
required
A model instance that implements TextModelInterface.
Generate::text()->model(new OpenAiModel('gpt-4o'))->prompt('Hello')->run();

instructions()

Set a system-level instruction string that is sent as the system prompt.
public function instructions(string $instructions): self
instructions
string
required
The system prompt / instructions for the model.
Generate::text()
    ->instructions('You are a helpful assistant that only answers in haiku.')
    ->prompt('What is PHP?')
    ->run();

prompt()

Append a user message to the conversation.
public function prompt(string $prompt): self
prompt
string
required
The user prompt text. Each call appends an additional user Message.
Generate::text()->prompt('Tell me a joke.')->run();

messages()

Replace the full message history with an explicit array of Message objects.
public function messages(array $messages): self
messages
Message[]
required
An array of Message instances. Replaces any previously set messages.
Generate::text()
    ->messages([
        Message::system('You are a travel guide.'),
        Message::user('What should I see in Tokyo?'),
    ])
    ->run();

tool()

Register a single tool for this request. Accepts a Tool instance, a class name string, or an invokable object.
public function tool(mixed $tool): self
tool
Tool | string | object
required
A single tool. Can be a Tool instance, a fully-qualified class name, or an invokable object resolved via ToolResolver.
$weatherTool = Tool::make('get_weather', 'Get current weather')
    ->input(Schema::string('location', 'City name')->required())
    ->run(fn(string $location) => "Sunny in {$location}");

Generate::text()->prompt('Weather in Paris?')->tool($weatherTool)->run();

tools()

Register multiple tools at once. Accepts variadic arguments or a single array.
public function tools(mixed ...$tools): self
tools
Tool | string | object | array
required
One or more tools, or a single array of tools. Each tool must have a unique name.
Generate::text()
    ->prompt('What can you do?')
    ->tools($weatherTool, $calculatorTool)
    ->run();

toolChoice()

Control how the model selects tools for this request.
public function toolChoice(ToolChoice|string $choice): self
choice
ToolChoice | string
required
A ToolChoice instance or one of the string constants 'auto', 'none', 'required', or a specific tool name.
Generate::text()
    ->prompt('Calculate 2+2')
    ->tool($calculatorTool)
    ->toolChoice(ToolChoice::required())
    ->run();

output()

Request structured output. The model will be instructed to return a JSON object matching the given schema.
public function output(Output|Schema $output): self
output
Output | Schema
required
An Output instance or a Schema. A bare Schema is automatically wrapped in Output::schema().
$schema = Schema::object('response', properties: [
    Schema::string('summary', 'Brief summary')->required(),
    Schema::integer('confidence', 'Confidence score 0-100')->required(),
]);

$result = Generate::text()
    ->prompt('Summarize the PHP AI SDK.')
    ->output($schema)
    ->run();

var_dump($result->output); // ['summary' => '...', 'confidence' => 95]

maxTokens()

Limit the number of tokens in the model’s response.
public function maxTokens(int $maxTokens): self
maxTokens
int
required
Maximum token count for the completion. Defaults to 1024 if not set.
Generate::text()->prompt('Write a poem.')->maxTokens(256)->run();

temperature()

Control the randomness of the model’s output.
public function temperature(float $temperature): self
temperature
float
required
Sampling temperature. Defaults to 1.0. Lower values produce more deterministic output.
Generate::text()->prompt('Give me a creative story.')->temperature(1.2)->run();

topP()

Nucleus sampling parameter. Only tokens comprising the top $topP probability mass are considered.
public function topP(float $topP): self
topP
float
required
Nucleus sampling threshold, between 0.0 and 1.0.
Generate::text()->prompt('Write a short story.')->topP(0.9)->run();

maxSteps()

Allow multi-step agentic loops. Each step may produce tool calls; the loop continues until no tool calls remain or the step limit is reached.
public function maxSteps(int $maxSteps): self
maxSteps
int
required
Maximum number of generation steps. Minimum effective value is 1.
Generate::text()
    ->prompt('Find the weather in London and summarize it.')
    ->tool($weatherTool)
    ->maxSteps(5)
    ->run();

reasoning()

Enable extended reasoning / chain-of-thought for models that support it.
public function reasoning(string|Reasoning $reasoning = Reasoning::EFFORT_MEDIUM): self
reasoning
string | Reasoning
default:"Reasoning::EFFORT_MEDIUM"
A Reasoning instance or an effort-level string such as 'low', 'medium', or 'high'.
Generate::text()
    ->prompt('Solve this math problem step by step: ...')
    ->reasoning('high')
    ->run();

providerOptions()

Pass provider-specific options that are forwarded verbatim to the underlying model driver.
public function providerOptions(string $provider, array $options): self
provider
string
required
The provider key, e.g. 'openai' or 'anthropic'.
options
array
required
An associative array of provider-specific key-value pairs. Merged recursively with any previously set options for this provider.
Generate::text()
    ->prompt('Hello')
    ->providerOptions('openai', ['logprobs' => true, 'top_logprobs' => 3])
    ->run();

providerOption()

Set a single provider-specific key-value option.
public function providerOption(string $provider, string $key, mixed $value): self
provider
string
required
The provider key, e.g. 'openai' or 'anthropic'.
key
string
required
The option key to set for the given provider.
value
mixed
required
The option value. Stored under $provider[$key] and merged with any previously set options.
Generate::text()
    ->prompt('Hello')
    ->providerOption('openai', 'logprobs', true)
    ->run();

run()

Execute the request synchronously and return a TextResult.
public function run(): TextResult
return
TextResult
The completed generation result, including text, output, toolCalls, toolResults, finishReason, usage, reasoning, rawResponse, and providerMetadata.
$result = Generate::text('What is the capital of France?')->run();
echo $result->text; // "The capital of France is Paris."

stream()

Execute the request and return a Stream for incremental consumption.
public function stream(): Stream
return
Stream
A Stream object that yields text chunks as they arrive from the model. Requires the resolved model to support Capability::Streaming.
$stream = Generate::text('Tell me a long story.')->stream();

foreach ($stream as $chunk) {
    echo $chunk;
}

PendingImageRequest

PendingImageRequest is the fluent builder returned by Generate::image(). All methods return self for chaining.

model()

Override the image model for this request.
public function model(ImageModelInterface $model): self
model
ImageModelInterface
required
An image model instance implementing ImageModelInterface.
Generate::image()->model(new OpenAiImageModel('dall-e-3'))->prompt('A cat in space')->run();

prompt()

Set the generation prompt.
public function prompt(string $prompt): self
prompt
string
required
The textual description of the image to generate. Required before calling run().
Generate::image()->prompt('An impressionist painting of a harbour at dusk')->run();

count()

Request multiple images in a single call.
public function count(int $count): self
count
int
required
Number of images to generate. Must be at least 1. Defaults to 1.
Generate::image('Product photo on white background')->count(4)->run();

size()

Specify the pixel dimensions of the generated image.
public function size(string $size): self
size
string
required
Image dimensions in {width}x{height} format, e.g. '1024x1024' or '1792x1024'.
Generate::image('Landscape photograph')->size('1792x1024')->run();

aspectRatio()

Specify an aspect ratio instead of exact pixel dimensions.
public function aspectRatio(string $aspectRatio): self
aspectRatio
string
required
Aspect ratio in {width}:{height} format, e.g. '16:9' or '1:1'.
Generate::image('Portrait photo')->aspectRatio('9:16')->run();

seed()

Set a reproducibility seed so the same prompt produces consistent results.
public function seed(int $seed): self
seed
int
required
An integer seed value. Provider support varies.
Generate::image('Abstract geometric art')->seed(42)->run();

providerOptions() (image)

Pass provider-specific options to the image model driver.
public function providerOptions(string $provider, array $options): self
provider
string
required
The provider key, e.g. 'openai'.
options
array
required
An associative array of provider-specific key-value pairs.
Generate::image('Photorealistic cat')
    ->providerOptions('openai', ['quality' => 'hd', 'style' => 'natural'])
    ->run();

run() (image)

Execute the image request and return an ImageResult.
public function run(): ImageResult
return
ImageResult
Contains output (the first ImageData), images (all generated images), usage, rawResponse, and providerMetadata.
$result = Generate::image('A futuristic city skyline')->size('1024x1024')->run();

echo $result->output->url;

Build docs developers (and LLMs) love