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.

This guide takes you from a fresh Composer project to working AI generations using aisdk/core and the aisdk/openai provider. Each section builds on the one before it, progressing from a minimal text generation example through streaming, tool calling, and structured output.

Complete Working Example

1

Install the packages

Install both the core SDK and the OpenAI provider with a single Composer command:
composer require aisdk/core aisdk/openai
2

Set your API key

The OpenAI provider reads your key from the OPENAI_API_KEY environment variable. Export it in your shell before running your script:
export OPENAI_API_KEY="sk-..."
In a .env-driven application (Laravel, Symfony, etc.) add the variable to your .env file and load it through your framework’s normal bootstrap.
3

Generate text

Create a PHP file and call Generate::text() with a model and a prompt:
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;
->run() is synchronous and returns a TextResult value object.
4

Access the result

TextResult exposes the generated content and metadata as typed readonly properties:
echo $result->text;          // The generated text string
echo $result->finishReason;  // FinishReason enum (e.g. ::Stop)
print_r($result->toolCalls); // Any tool calls the model made
print_r($result->output);    // Structured output (when schema is used)

Default Model Shortcut

Calling ->model(...) on every request is verbose. Register a default model once at application boot and then use the terse single-argument form:
use AiSdk\Generate;
use AiSdk\OpenAI;

// Called once — in a service provider, bootstrap file, or index.php
Generate::model(OpenAI::model('gpt-4o'));

// Terse call site anywhere in your application
$result = Generate::text('Explain closures in PHP.')->run();

echo $result->text;
Generate::model() stores the default model on the internal Sdk runtime. Every subsequent Generate::text() or Generate::image() call picks it up automatically unless you override it on a per-request basis with ->model(...).

Streaming

Use ->stream() instead of ->run() to receive tokens as they arrive. Iterate over the chunks() generator, then call ->run() on the stream to get the final TextResult:
use AiSdk\Generate;
use AiSdk\OpenAI;

$stream = Generate::text('Tell me a story.')
    ->model(OpenAI::model('gpt-4o'))
    ->stream();

foreach ($stream->chunks() as $chunk) {
    echo $chunk;
}

$result = $stream->run();
You can also attach lifecycle hooks for logging or side-effects:
$stream
    ->onChunk(fn (string $text) => log($text))
    ->onFinish(fn (TextResult $result) => log($result->usage))
    ->onError(fn (\Throwable $e) => log($e));
Hooks are chainable and can be attached before or after you start iterating chunks(). The onFinish callback receives the same TextResult that ->run() returns.

Tool Calling

Define a tool with Tool::make(), give it an input schema, and attach it to the request with ->tool(). The model calls the tool automatically and the SDK invokes your PHP callable:
use AiSdk\Generate;
use AiSdk\OpenAI;
use AiSdk\Schema;
use AiSdk\Tool;

$weather = Tool::make('weather', 'Get current weather')
    ->input(Schema::string(name: 'city')->required())
    ->run(fn (string $city): string => "Sunny in {$city}");

$result = Generate::text()
    ->model(OpenAI::model('gpt-4o'))
    ->prompt('What is the weather in Lahore?')
    ->tool($weather)
    ->run();

echo $result->text;

Structured Output

Pass a Schema to ->output() to constrain the model’s response to a specific shape. The parsed data is available on $result->output as an associative array:
use AiSdk\Generate;
use AiSdk\OpenAI;
use AiSdk\Schema;

$result = Generate::text()
    ->model(OpenAI::model('gpt-4o'))
    ->prompt('Extract the city and country from: Lahore, Pakistan.')
    ->output(Schema::object(
        name: 'address',
        description: 'The city and country extracted from the prompt.',
        properties: [
            Schema::string(name: 'city')->required(),
            Schema::string(name: 'country')->required(),
        ],
    ))
    ->run();

echo $result->output['city'];    // "Lahore"
echo $result->output['country']; // "Pakistan"
Combine structured output with tool calling in the same request — the SDK resolves tool calls first, then enforces the output schema on the final model response.

Next Steps

Text Generation

Deep dive into prompts, system instructions, provider options, and result metadata.

Streaming

Learn all available stream hooks and how to handle errors mid-stream.

Tool Calling

Build complex multi-turn agentic flows with class-based and closure-based tools.

Structured Output

Explore the full Schema API — objects, strings, numbers, arrays, and enums.

Build docs developers (and LLMs) love