Vizra.ai |

Documentation

πŸ“š

Agent Class Reference

Master the heart of Vizra ADK! πŸ’— The BaseLlmAgent class is your gateway to building incredible AI agents. Every property, method, and secret revealed - let's turn you into an agent architect extraordinaire!

πŸ—οΈ The Foundation of Intelligence

Think of BaseLlmAgent as the DNA of your AI agents! 🧬 Every intelligent behavior, every smart response, every amazing capability starts here. Ready to peek under the hood?

πŸ—οΈ The Agent Family Tree

Understanding the class hierarchy is like knowing your agent's family tree! πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ Here's how everything connects:

namespace Vizra\VizraADK\Agents;

abstract class BaseAgent
{
    // Base contract for all agents
}

abstract class BaseLlmAgent extends BaseAgent
{
    // LLM-powered agent implementation
}

βš™οΈ Agent Properties - Your Agent's DNA

These properties are like your agent's personality traits! 🎭 Set them right, and your agent will be amazing. Let's explore what makes each agent unique:

πŸ”₯ Required Properties - The Must-Haves

🏷️

$name

string (required)

Your agent's unique identifier! Like a superhero name, it should be memorable and descriptive. No two agents can share the same name! πŸ¦Έβ€β™‚οΈ

protected string $name = 'customer_support';
πŸ“

$description

string (required)

Tell everyone what your agent does! This human-readable description helps you and your team understand the agent's purpose at a glance. ✨

protected string $description = 'Helps customers with support inquiries';

✨ Optional Properties - The Customizers

These optional properties let you fine-tune your agent's behavior! πŸŽ›οΈ Mix and match to create the perfect AI personality:

Property Type Default Description
$instructions string '' System prompt for the agent
$model string '' LLM model to use (e.g., 'gpt-4o', 'claude-3-opus')
$provider ?Provider null LLM provider (OpenAI, Anthropic, Gemini)
$temperature ?float null Response creativity (0-1)
$maxTokens ?int null Maximum response tokens
$topP ?float null Nucleus sampling parameter
$streaming bool false Enable streaming responses
$tools array [] Array of tool class names

Static Methods (BaseAgent)

All static methods return an AgentExecutor instance for fluent configuration:

ask()

public static function ask(mixed $input): AgentExecutor

Create a fluent agent executor for conversational interaction.

$response = CustomerSupportAgent::ask('Where is my order?')
    ->forUser($user)
    ->execute();

trigger()

public static function trigger(mixed $event): AgentExecutor

Trigger the agent with an event or data.

$response = NotificationAgent::trigger($orderCreatedEvent)
    ->forUser($user)
    ->execute();

analyze()

public static function analyze(mixed $data): AgentExecutor

Ask the agent to analyze data or events.

$response = FraudDetectionAgent::analyze($paymentData)
    ->withContext($context)
    ->execute();

process()

public static function process(mixed $data): AgentExecutor

Process data or perform batch operations.

$response = DataProcessorAgent::process($largeDataset)
    ->async()
    ->execute();

monitor()

public static function monitor(mixed $data): AgentExecutor

Monitor metrics or conditions continuously.

$response = SystemMonitorAgent::monitor($metrics)
    ->onQueue('monitoring')
    ->execute();

generate()

public static function generate(mixed $data): AgentExecutor

Generate reports or summaries.

$response = ReportAgent::generate('daily_sales')
    ->withContext(['date' => today()])
    ->execute();

Instance Methods (BaseLlmAgent)

Core Methods

// Execute the agent's primary logic (must be implemented)
public function run(mixed $input, AgentContext $context): mixed

// Get agent properties
public function getName(): string
public function getDescription(): string

Configuration Methods

// Getters
public function getModel(): string
public function getProvider(): Provider
public function getInstructions(): string
public function getInstructionsWithMemory(AgentContext $context): string
public function getTemperature(): ?float
public function getMaxTokens(): ?int
public function getTopP(): ?float
public function getStreaming(): bool

// Setters
public function setInstructions(string $instructions): static
public function setModel(string $model): static
public function setProvider(Provider $provider): static
public function setTemperature(?float $temperature): static
public function setMaxTokens(?int $maxTokens): static
public function setTopP(?float $topP): static
public function setStreaming(bool $streaming): static

Tool Management

public function loadTools(): void
public function getLoadedTools(): array

Sub-Agent Management

public function getSubAgent(string $name): ?BaseLlmAgent
public function getLoadedSubAgents(): array

Protected Methods (Override in Your Agent)

Sub-Agent Registration

protected function registerSubAgents(): array
{
    return [
        'technical_support' => TechnicalSupportAgent::class,
        'billing_support' => BillingSupportAgent::class,
        'sales_specialist' => SalesAgent::class,
    ];
}

Lifecycle Hooks

// Called before sending messages to LLM
public function beforeLlmCall(array $inputMessages, AgentContext $context): array
{
    // Modify messages, start tracing, etc.
    return $inputMessages;
}

// Called after receiving LLM response
public function afterLlmResponse(Response|Generator $response, AgentContext $context): mixed
{
    // Process response, access token usage, etc.
    return $response;
}

// Called before tool execution
public function beforeToolCall(string $toolName, array $arguments, AgentContext $context): array
{
    // Modify tool arguments before execution
    return $arguments;
}

// Called after tool execution
public function afterToolResult(string $toolName, string $result, AgentContext $context): string
{
    // Process tool results
    return $result;
}

Sub-Agent Delegation Hooks

// Called before delegating to sub-agent
public function beforeSubAgentDelegation(
    string $subAgentName,
    string $taskInput,
    string $contextSummary,
    AgentContext $parentContext
): array
{
    // Returns [subAgentName, taskInput, contextSummary]
    return [$subAgentName, $taskInput, $contextSummary];
}

// Called after sub-agent completes
public function afterSubAgentDelegation(
    string $subAgentName,
    string $taskInput,
    string $subAgentResult,
    AgentContext $parentContext,
    AgentContext $subAgentContext
): string
{
    // Process and return the result
    return $subAgentResult;
}

AgentExecutor Methods

The AgentExecutor provides a fluent API for configuring agent execution:

// User context
public function forUser(?Model $user): self

// Session management
public function withSession(string $sessionId): self

// Context data
public function withContext(array $context): self

// Streaming
public function streaming(bool $enabled = true): self

// Parameters
public function withParameters(array $parameters): self
public function temperature(float $temperature): self
public function maxTokens(int $maxTokens): self

// Async execution
public function async(bool $enabled = true): self
public function onQueue(string $queue): self
public function delay(int $seconds): self
public function tries(int $tries): self
public function timeout(int $seconds): self

// Multimodal support
public function withImage(string $path, ?string $mimeType = null): self
public function withImageFromBase64(string $base64Data, string $mimeType): self
public function withImageFromUrl(string $url): self
public function withDocument(string $path, ?string $mimeType = null): self
public function withDocumentFromBase64(string $base64Data, string $mimeType): self
public function withDocumentFromUrl(string $url): self

// Execute the agent
public function execute(): mixed

Complete Example

<?php

namespace App\Agents;

use Vizra\VizraADK\Agents\BaseLlmAgent;
use Vizra\VizraADK\System\AgentContext;
use Prism\Prism\Text\Response;
use Generator;

class CustomerSupportAgent extends BaseLlmAgent
{
    protected string $name = 'customer_support';

    protected string $description = 'Handles customer inquiries and support requests';

    protected string $instructions = "You are a helpful customer support agent.
        Be friendly, professional, and solution-oriented.
        Always prioritize customer satisfaction.";

    protected string $model = 'gpt-4o';

    protected ?float $temperature = 0.7;

    protected ?int $maxTokens = 1000;

    /** @var array<class-string<ToolInterface>> */
    protected array $tools = [
        OrderLookupTool::class,
        RefundProcessorTool::class,
        EmailSenderTool::class,
    ];

    // Register specialized sub-agents
    protected function registerSubAgents(): array
    {
        return [
            'technical_expert' => TechnicalSupportAgent::class,
            'billing_specialist' => BillingAgent::class,
        ];
    }

    // Customize LLM call behavior
    public function beforeLlmCall(array $inputMessages, AgentContext $context): array
    {
        // Add customer context to messages if available
        if ($userId = $context->getState('user_id')) {
            logger()->info('Processing request for user', ['user_id' => $userId]);
        }

        return parent::beforeLlmCall($inputMessages, $context);
    }

    // Process response after LLM call
    public function afterLlmResponse(Response|Generator $response, AgentContext $context): mixed
    {
        if ($response instanceof Response) {
            // Log token usage for monitoring
            if ($response->usage) {
                logger()->info('Token usage', [
                    'input_tokens' => $response->usage->inputTokens ?? 0,
                    'output_tokens' => $response->usage->outputTokens ?? 0,
                ]);
            }
        }

        return parent::afterLlmResponse($response, $context);
    }
}

Usage Examples

// Basic conversation
$response = CustomerSupportAgent::ask('How do I reset my password?')
    ->execute();

// With user context and session
$response = CustomerSupportAgent::ask('Show me my recent orders')
    ->forUser($user)
    ->withSession($sessionId)
    ->execute();

// Streaming response
$stream = CustomerSupportAgent::ask('Explain our refund policy')
    ->streaming()
    ->execute();

foreach ($stream as $chunk) {
    echo $chunk;
}

// Async processing
$job = CustomerSupportAgent::process($supportTickets)
    ->async()
    ->onQueue('support')
    ->execute();

// With images
$response = CustomerSupportAgent::ask('What\'s wrong with this product?')
    ->withImage('/path/to/product-photo.jpg')
    ->execute();

πŸ’‘ Agent Best Practices

  • Keep agent instructions focused and clear
  • Override lifecycle hooks for custom behavior
  • Use appropriate temperature settings for your use case
  • Implement error handling for robustness
  • Test agents thoroughly with evaluations
  • Monitor token usage and costs