Skip to content

Use custom HTTP client instance - Laravel

Overview

Example

<?php
require 'examples/boot.php';

use Cognesy\Instructor\StructuredOutput;
use Cognesy\Instructor\StructuredOutputRuntime;
use Cognesy\Instructor\Enums\OutputMode;
use Cognesy\Instructor\Laravel\HttpClient\LaravelDriver;
use Cognesy\Events\Dispatchers\EventDispatcher;
use Cognesy\Http\Contracts\CanSendHttpRequests;
use Cognesy\Polyglot\Inference\LLMProvider;
use Cognesy\Http\Config\HttpClientConfig;
use Cognesy\Http\HttpClient;
use Illuminate\Http\Client\Factory;

class User {
    public int $age;
    public string $name;
}

$yourLaravelClientInstance = new Factory();
$provider = LLMProvider::using('openai')
    ->withConfigOverrides(['apiUrl' => 'https://api.openai.com/v1']);
$customClient = HttpClient::fromDriver(
    new LaravelDriver(
        config: new HttpClientConfig(),
        events: new EventDispatcher(),
        clientInstance: $yourLaravelClientInstance,
    )
);
assert($customClient instanceof CanSendHttpRequests);

$user = (new StructuredOutput(
    runtime: StructuredOutputRuntime::fromProvider(
        provider: $provider,
        httpClient: $customClient,
    )->withOutputMode(OutputMode::Tools),
))
    //->wiretap(fn($e) => $e->print())
    ->withMessages("Our user Jason is 25 years old.")
    ->withResponseClass(User::class)
    //->withStreaming()
    ->get();

dump($user);
assert(isset($user->name));
assert(isset($user->age));
?>