1. Go to this page and download the library: Download helgesverre/pagent 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/ */
helgesverre / pagent example snippets
// Configure an agent
agent('assistant')
->provider('anthropic')
->system('You are a helpful assistant')
->temperature(0.7);
// Use the agent
$response = agent('assistant')->prompt('Hello!');
echo $response->content;
// Or stream responses in real-time
agent('assistant')->streamTo('Tell me a story', function ($chunk) {
if ($chunk->isText()) {
echo $chunk->content;
flush();
}
});
// Persist conversations across sessions
agent('support')
->memory('sqlite', ['path' => 'storage/conversations.db'])
->sessionId('user-123')
->contextWindow(100000)
->prompt('Hello');
// Define an agent
agent('support')
->provider('anthropic')
->system('You are a customer support agent')
->model('claude-3-haiku-20240307')
->temperature(0.3);
// Have a conversation
$agent = agent('support');
$agent->prompt('I need help with my order');
$agent->prompt('Order number is 12345');
// Access conversation history
foreach ($agent->messages as $message) {
echo "[{$message['role']}]: {$message['content']}\n";
}
agent('assistant')
->provider('anthropic') // String name
->system('You are helpful');
// With config options
agent('custom')
->provider('ollama', ['base_url' => 'http://custom:11434', 'timeout' => 180])
->model('qwen3:8b');
// Using helper functions
agent('assistant')
->provider(anthropic(['api_key' => 'custom-key']))
->prompt('Hello');
agent('local')
->provider(ollama(['timeout' => 300, 'base_url' => 'http://10.0.0.5:11434']))
->model('llama3.1');
// Direct instantiation
use Pagent\Providers\OpenAI;
agent('custom')
->provider(new OpenAI(['api_key' => getenv('CUSTOM_KEY')]))
->prompt('Hello');
use Pagent\Tool\Tool;
// Create a tool from a closure
$weatherTool = Tool::fromClosure(
'get_weather',
'Get the current weather for a location',
fn(string $location, bool $', 'Get current time', fn(string $tz = 'UTC') => date('H:i:s'));
// Execute tools
$result = $agent->executeTool('calculate', [10, 5]); // 15
// Generate provider-specific schemas
$anthropicSchema = $weatherTool->toAnthropicSchema();
$openaiSchema = $weatherTool->toOpenAISchema();
use Pagent\Tools\FileRead;
use Pagent\Tools\FileWrite;
use Pagent\Tools\WebFetch;
use Pagent\Tools\Bash;
use Pagent\Tools\Grep;
use Pagent\Tools\Glob;
use Pagent\Tools\PdfReader;
use Pagent\Tools\DataExtract;
use Pagent\Tools\SearchTool;
// Use class-based tools with agents
$agent = agent('assistant')
->provider('anthropic')
->tool(new FileRead())
->tool(new WebFetch())
->prompt('Read the file data.json and fetch https://api.example.com/data');
// Add multiple tools at once
$agent = agent('file-assistant')
->provider('anthropic')
->tools([
new FileRead(baseDir: '/project'),
new FileWrite(baseDir: '/project'),
new Glob(baseDir: '/project'),
new Grep(baseDir: '/project'),
])
->prompt('List all PHP files and show me the config');
// Create custom class-based tools
use Pagent\Tools\Tool;
class DatabaseQuery extends Tool
{
public function name(): string
{
return 'query_database';
}
public function description(): string
{
return 'Execute a database query and return results';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'query' => ['type' => 'string', 'description' => 'SQL query to execute'],
'limit' => ['type' => 'integer', 'description' => 'Maximum rows to return'],
],
'
use Pagent\Tools\SearchTool;
// Search through an array of documents (RAG pattern)
$documents = [
['id' => 1, 'title' => 'PHP Guide', 'content' => 'Learn PHP programming...'],
['id' => 2, 'title' => 'Laravel Tutorial', 'content' => 'Build web apps with Laravel...'],
];
agent('docs-assistant')
->tools([searchDocuments($documents)])
->prompt('Find information about PHP');
// Search through files in a directory
agent('codebase-helper')
->tools([new SearchTool(paths: ['docs/', 'src/'])])
->prompt('Find all documentation about API endpoints');
// Use a pre-built search index
agent('knowledge-bot')
->tools([searchIndex('knowledge/docs.index')])
->prompt('Search the knowledge base for deployment guides');
// Database-backed search
agent('db-search')
->tools([
new SearchTool(
query: 'SELECT id, title, content FROM articles',
connection: ['driver' => 'mysql', 'host' => 'localhost', 'database' => 'mydb']
)
])
->prompt('Find articles about Laravel');
new SearchTool(
documents: $docs, // Array of documents to index
returnContent: true, // Return full documents vs just IDs
fuzzy: true, // Enable fuzzy search
fuzziness: 2, // Levenshtein distance (1-3)
maxResults: 20, // Max results to return
storage: ':memory:', // Index storage location
stemmer: PorterStemmer::class // Custom stemmer class
);
use function Pagent\{agent, telemetry_console};
// Enable console telemetry for debugging
telemetry_console(verbose: true);
agent('assistant')
->provider('anthropic')
->telemetry(true) // Enable tracing for this agent
->prompt('Hello!');
// Console shows:
// ┌─ Span: agent.prompt
// │ Duration: 1.23s
// │ Attributes:
// │ - gen_ai.system: anthropic
// │ - gen_ai.usage.total_tokens: 125
// └─
use function Pagent\{agent, telemetry_jaeger};
// Export to Jaeger
telemetry_jaeger('http://localhost:14268/api/traces');
// All operations automatically traced
agent('support')
->telemetry(true)
->tool('search', 'Search knowledge base', $searchFn)
->prompt('Help me find documentation');
// View traces at http://localhost:16686