1. Go to this page and download the library: Download arturas88/anyllm 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/ */
arturas88 / anyllm example snippets
use AnyLLM\AnyLLM;
use AnyLLM\Enums\Provider;
// Create provider
$llm = AnyLLM::provider(Provider::OpenAI)
->apiKey($_ENV['OPENAI_API_KEY'])
->model('gpt-4o')
->build();
// Simple chat
$response = $llm->generateText('gpt-4o', 'Explain PHP in simple terms');
echo $response->text;
use AnyLLM\Messages\UserMessage;
$messages = [
new UserMessage('What is PHP?'),
];
$response = $llm->chat('gpt-4o', $messages);
echo $response->content();
use AnyLLM\Support\FileCache;
$cache = new FileCache();
// Enable retry logic
$llm->withRetry(maxRetries: 5);
// Cache expensive calls
$result = $cache->remember('llm:question:1', function() use ($llm) {
return $llm->generateText('gpt-4o', 'What is AI?');
}, 3600);
use AnyLLM\StructuredOutput\Attributes\Description;
class Person {
#[Description('Full name')]
public string $name;
#[Description('Age in years')]
public int $age;
}
$response = $llm->generateObject(
model: 'gpt-4o',
prompt: 'Extract person from: John Doe is 30 years old',
schema: Person::class
);
echo $response->object->name; // "John Doe"
echo $response->object->age; // 30
use AnyLLM\Tools\Tool;
$weatherTool = Tool::fromCallable(
name: 'get_weather',
description: 'Get current weather',
callable: function(string $location): string {
return "Sunny, 72°F in {$location}";
}
);
$response = $llm->chat('gpt-4o', [
new UserMessage('What\'s the weather in Paris?')
], tools: [$weatherTool]);
use AnyLLM\Agents\Agent;
use AnyLLM\Tools\Tool;
// Create an agent with a system prompt
$agent = Agent::create(
provider: $llm,
model: 'gpt-4o-mini',
systemPrompt: 'You are a helpful assistant that solves problems step by step.',
);
// Simple agent execution
$result = $agent->run('What are the main benefits of using PHP?');
echo $result->content;
echo "Iterations: {$result->iterations}";
// Agent with tools
$calculator = Tool::fromCallable(
name: 'calculator',
description: 'Perform calculations',
callable: function(string $expression): array {
// Safe evaluation logic
return ['result' => eval("return {$expression};")];
}
);
$agentWithTools = Agent::create($llm, 'gpt-4o-mini')
->withTools($calculator)
->withMaxIterations(10);
$result = $agentWithTools->run('Calculate 25 * 4 + 100');
echo $result->content;
foreach ($result->toolExecutions as $execution) {
echo "Tool: {$execution->name}, Result: " . json_encode($execution->result);
}
// Request approval before tool execution
$agent = Agent::create($llm, 'gpt-4o-mini')
->withTools($databaseTool)
->withBeforeToolExecution(function(string $toolName, array $arguments): bool {
// Request human approval
echo "Tool {$toolName} will be called with: " . json_encode($arguments);
return true; // or false to skip
})
->withAfterToolExecution(function(ToolExecution $execution): mixed {
// Review/modify tool result
return $execution->result; // or modified result
})
->withBeforeFinalResponse(function(string $content, array $messages, array $toolExecutions): ?string {
// Review/modify final response
return $content; // or modified content
});
use AnyLLM\Agents\Workflow\Workflow;
use AnyLLM\StructuredOutput\Schema;
use AnyLLM\StructuredOutput\Attributes\{Description, ArrayOf};
// Simple workflow with variable interpolation
$workflow = Workflow::create(
provider: $llm,
defaultModel: 'gpt-4o-mini',
)
->addStep(
name: 'analyze',
prompt: 'Analyze this text: {{input}}',
)
->addStep(
name: 'summarize',
prompt: 'Summarize the analysis: {{analyze}}',
)
->addStep(
name: 'recommend',
prompt: 'Provide recommendations based on: {{summarize}}',
);
$result = $workflow->run(['input' => 'Your text here']);
echo $result->finalOutput;
foreach ($result->stepResults as $stepName => $stepResult) {
echo "{$stepName}: {$stepResult->output}\n";
}
class ProductAnalysis
{
#[Description('Product name')]
public string $productName;
#[Description('Key features')]
#[ArrayOf('string')]
public array $features;
}
$workflow = Workflow::create($llm, 'gpt-4o-mini')
->addStep(
name: 'analyze_product',
prompt: 'Analyze: {{product_description}}',
outputSchema: Schema::fromClass(ProductAnalysis::class),
)
->addStep(
name: 'create_marketing_plan',
prompt: 'Create marketing plan for: {{analyze_product.productName}}',
);
$result = $workflow->run(['product_description' => 'A mobile app...']);
$analysis = $result->stepResults['analyze_product']->output;
echo $analysis->productName;
$workflow = Workflow::create($llm, 'gpt-4o-mini')
->addStep(name: 'draft', prompt: 'Create draft: {{topic}}')
->addStep(name: 'review', prompt: 'Review: {{draft}}')
->withBeforeStep(function(string $stepName, string $prompt, WorkflowContext $context): bool {
// Request approval before executing step
if ($stepName === 'review') {
echo "Approve review step? (yes/no): ";
return true; // or false to skip
}
return true;
})
->withAfterStep(function(string $stepName, StepResult $result, WorkflowContext $context): ?StepResult {
// Review/modify step result
if ($stepName === 'draft') {
// Allow modifications
return $result; // or modified StepResult
}
return null; // Use original
});
$texts = [
'The cat sat on the mat',
'A feline rested on a rug',
];
$embeddings = $llm->embed('text-embedding-3-small', $texts);
// Check similarity
$similarity = $embeddings->similarity(0, 1);
echo "Similarity: " . number_format($similarity, 4); // 0.9234
// Or find similar texts
$queryEmbedding = $llm->embed('text-embedding-3-small', 'What is AI?');
$results = \AnyLLM\Support\VectorMath::kNearest(
$queryEmbedding->getEmbedding(0),
$embeddings->embeddings,
k: 3
);
use AnyLLM\Middleware\MiddlewarePipeline;
use AnyLLM\Middleware\CachingMiddleware;
use AnyLLM\Middleware\LoggingMiddleware;
use AnyLLM\Middleware\RateLimitMiddleware;
$pipeline = new MiddlewarePipeline([
new RateLimitMiddleware($limiter),
new CachingMiddleware($cache),
new LoggingMiddleware($logger),
]);
// All requests go through middleware automatically
// Estimate tokens before calling
use AnyLLM\Support\TokenCounter;
$tokens = TokenCounter::estimate($text, 'gpt-4');
// Enable debugging (logs to stdout by default)
$llm = $llm->withDebugging();
// With custom logger
$llm = $llm->withDebugging(function(string $type, array $data) {
// $type is 'REQUEST', 'RESPONSE', or 'CHUNK'
error_log(json_encode(['type' => $type, 'data' => $data]));
});
// Show full base64 content (default: truncated for readability)
$llm = $llm->withDebugging(showFullBase64: true);
// Disable debugging
$llm = $llm->withoutDebugging();
// Enable via config
$llm = AnyLLM::provider(Provider::OpenAI)
->apiKey($key)
->option('debug', true)
->build();
bash
php examples/basic-usage.php
=== Example 1: Simple Text Generation ===
Response: PHP is a server-side scripting language...
Tokens used: 37
=== Example 2: Chat Conversation ===
Assistant: PHP 8.2 introduced several new features...
bash
# Run tests
composer test
# Check code style
composer cs-fix -- --dry-run
# Run static analysis
composer phpstan
# View test coverage
composer test-coverage
open coverage/index.html
# Run specific example
php examples/embeddings-example.php
php examples/streaming-advanced.php
php examples/middleware-example.php
bash
# Run migrations
php artisan migrate
# Or run SQL directly
mysql database < database/migrations/create_llm_logs_table.php
mysql database < database/migrations/create_llm_conversations_table.php
mysql database < database/migrations/create_llm_messages_table.php
bash
composer dump-autoload
bash
# Test basic connectivity
php -r "
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.