PHP code example of thinwrap / llm

1. Go to this page and download the library: Download thinwrap/llm library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

thinwrap / llm example snippets


use Thinwrap\Llm\Chat;
use Thinwrap\Llm\DTO\Chat\ChatInput;
use Thinwrap\Llm\DTO\Chat\ChatMessage;
use Thinwrap\Llm\Enum\ChatRole;
use Thinwrap\Llm\Enum\LlmProviderId;
use Thinwrap\Llm\Exception\ConnectorError;
use Thinwrap\Llm\Providers\Shared\OpenAiCompatConfig;

$chat = new Chat(LlmProviderId::OpenAI, new OpenAiCompatConfig(apiKey: getenv('OPENAI_API_KEY')));

try {
    $res = $chat->complete(new ChatInput(
        model: 'gpt-4o-mini',
        messages: [new ChatMessage(ChatRole::User, 'Say hi in one word.')],
    ));
    echo $res->message->content;                              // → the reply
    echo $res->usage->inputTokens . '/' . $res->usage->outputTokens;
} catch (ConnectorError $e) {
    error_log($e->providerCode->value . ': ' . ($e->providerMessage ?? ''));
}

use Thinwrap\Llm\Providers\Anthropic\AnthropicConfig;
use Thinwrap\Llm\Providers\Gemini\GeminiConfig;
use Thinwrap\Llm\Providers\Bedrock\BedrockConfig;

$anthropic = new Chat(LlmProviderId::Anthropic, new AnthropicConfig(apiKey: getenv('ANTHROPIC_API_KEY')));
$gemini    = new Chat(LlmProviderId::Gemini,    new GeminiConfig(apiKey: getenv('GEMINI_API_KEY')));
$bedrock   = new Chat(LlmProviderId::Bedrock,   new BedrockConfig(
    region: 'us-east-1',
    accessKeyId: getenv('AWS_ACCESS_KEY_ID'),
    secretAccessKey: getenv('AWS_SECRET_ACCESS_KEY'),
));
// same ->complete($input) shape, same ChatResult

foreach ($chat->stream($input) as $delta) {
    if ($delta->contentDelta !== null) {
        echo $delta->contentDelta;
    }
}

use Thinwrap\Llm\Embeddings;
use Thinwrap\Llm\DTO\Embeddings\EmbeddingsInput;

$emb = new Embeddings(LlmProviderId::OpenAI, new OpenAiCompatConfig(apiKey: getenv('OPENAI_API_KEY')));
$res = $emb->create(new EmbeddingsInput(model: 'text-embedding-3-small', input: ['hello', 'world']));
$res->embeddings; // list<list<float>>, one vector per input, in input order

$chat = new Chat(
    LlmProviderId::OpenAI,
    new OpenAiCompatConfig(apiKey: getenv('OPENAI_API_KEY')),
    $myPsr18Client,          // ?ClientInterface
    $myRequestFactory,       // ?RequestFactoryInterface
    $myStreamFactory,        // ?StreamFactoryInterface
);

new ChatInput(
    model: 'gpt-4o-mini',
    messages: [new ChatMessage(ChatRole::User, 'hi')],
    _passthrough: ['body' => ['logprobs' => true], 'headers' => ['X-Trace' => 'abc']],
);