### Provider-Specific Configuration Examples Source: https://docs.vizra.ai/integrations/providers Examples of setting the provider and model for various supported services. ```php protected ?Provider $provider = Provider::OpenAI; protected string $model = 'gpt-4-turbo'; ``` ```php protected ?Provider $provider = Provider::Anthropic; protected string $model = 'claude-3-opus-20240229'; ``` ```php protected ?Provider $provider = Provider::Gemini; protected string $model = 'gemini-1.5-flash'; ``` ```php protected ?Provider $provider = Provider::Groq; protected string $model = 'mixtral-8x7b-32768'; ``` ```php protected ?Provider $provider = Provider::Ollama; protected string $model = 'llama2'; ``` -------------------------------- ### Configuration Priority Examples Source: https://docs.vizra.ai/installation/configuration Examples of configuration sources ordered by their priority level. ```php $agent->setTemperature(0.2) ``` ```php protected ?float $temperature = 0.7; ``` ```bash VIZRA_ADK_DEFAULT_TEMPERATURE=0.5 ``` ```text config/vizra-adk.php ``` -------------------------------- ### Tool Execution Implementation Source: https://docs.vizra.ai/api-reference/tool-class Examples of the execute method, including a full implementation example. ```php public function execute(array $arguments, AgentContext $context, AgentMemory $memory): string ``` ```php public function execute(array $arguments, AgentContext $context): string { $order = Order::find($arguments['order_id']); if (!$order) { return json_encode([ 'status' => 'error', 'message' => 'Order not found', ]); } return json_encode([ 'status' => 'success', 'order' => $order->toArray(), ]); } ``` -------------------------------- ### Prompt Management Examples Source: https://docs.vizra.ai/api-reference/artisan-commands Practical examples of managing agent prompts, including creation, listing, activation, and file-based sharing. ```bash # Create friendly customer support prompt php artisan vizra:prompt create customer_support friendly \ --content="You are a warm and friendly support agent. Use casual language." # List all weather reporter prompts php artisan vizra:prompt list weather_reporter # Switch to professional version in production php artisan vizra:prompt activate customer_support professional # Share prompts between projects php artisan vizra:prompt export my_agent v2 --file=awesome_prompt.txt php artisan vizra:prompt import other_agent v1 --file=awesome_prompt.txt ``` -------------------------------- ### Complete configuration example Source: https://docs.vizra.ai/agents/image-agent Combine multiple configuration methods into a single fluent chain. ```php $image = ImageAgent::run('An oil painting of flowers') ->using('openai', 'dall-e-3') ->landscape() ->hd() ->style('natural') ->storeAs('flowers.png') ->go(); ``` -------------------------------- ### Install Vizra ADK Source: https://docs.vizra.ai/api-reference/artisan-commands Run the installation command to publish necessary configuration files and database migrations. ```bash php artisan vizra:install # This command: # - Publishes configuration files # - Publishes database migrations # - Shows post-installation information ``` -------------------------------- ### Run Vizra Installation Command Source: https://docs.vizra.ai/installation/getting-started Execute the installation command to publish configuration files, run migrations, and initialize the web interface. ```bash php artisan vizra:install ``` -------------------------------- ### Install and Initialize Vizra ADK Source: https://docs.vizra.ai/index Use these terminal commands to install the package, configure the environment, and generate a new agent class. ```bash # Install the package composer require vizra/vizra-adk # Set up everything with one command php artisan vizra:install # Create your first agent php artisan vizra:make:agent CustomerSupportAgent ``` -------------------------------- ### Install MCP Filesystem Server Source: https://docs.vizra.ai/integrations/mcp Install the filesystem MCP server globally using npm. ```bash npm install -g @modelcontextprotocol/server-filesystem ``` -------------------------------- ### vizra:install Source: https://docs.vizra.ai/api-reference Initializes the Vizra ADK environment by publishing configuration files and database migrations. ```APIDOC ## vizra:install ### Description One command to rule them all. Install everything you need to start building agents. ### Usage `php artisan vizra:install` ``` -------------------------------- ### Install GitHub MCP Server Source: https://docs.vizra.ai/integrations/mcp Global installation command for the GitHub MCP server via npm. ```bash npm install -g @modelcontextprotocol/server-github ``` -------------------------------- ### Install PostgreSQL MCP Server Source: https://docs.vizra.ai/integrations/mcp Global installation command for the PostgreSQL MCP server via npm. ```bash npm install -g @modelcontextprotocol/server-postgres ``` -------------------------------- ### Implement a complete media agent workflow Source: https://docs.vizra.ai/advanced/agent-queuing A comprehensive example demonstrating agent configuration, queuing parameters, and post-generation storage. ```php use Vizra\VizraADK\Agents\ImageAgent; $result = ImageAgent::run('Professional headshot of a business executive') ->forUser($user) ->withSession('avatar-generation') ->using('openai', 'dall-e-3') ->size('1024x1024') ->quality('hd') ->style('natural') ->onQueue('media') ->delay(5) ->tries(3) ->timeout(180) ->then(function ($image) use ($user) { $image->storeAs("avatars/{$user->id}.png"); $user->update(['avatar_path' => $image->path()]); }) ->go(); ``` -------------------------------- ### ImageAgent::run(string $prompt) Source: https://docs.vizra.ai/agents/image-agent Starts a fluent generation chain for image creation. ```APIDOC ## ImageAgent::run(string $prompt) ### Description Starts a fluent generation chain for image creation. ### Parameters - **prompt** (string) - Required - The text prompt to generate the image from. ``` -------------------------------- ### Install Vizra ADK Guidelines Source: https://docs.vizra.ai/integrations/laravel-boost Run the artisan command to copy Vizra ADK guidelines into the project's resources directory. ```bash php artisan vizra:boost:install ``` -------------------------------- ### Tool Definition Implementation Source: https://docs.vizra.ai/api-reference/tool-class Example of returning a JSON Schema to describe tool parameters to the AI. ```php public function definition(): array { return [ 'name' => 'order_lookup', 'description' => 'Look up order information by ID', 'parameters' => [ 'type' => 'object', 'properties' => [ 'order_id' => [ 'type' => 'string', 'description' => 'The order ID to look up', ], 'include_items' => [ 'type' => 'boolean', 'description' => 'Include order items in response', ], ], 'required' => ['order_id'], ], ]; } ``` -------------------------------- ### vizra:boost:install Source: https://docs.vizra.ai/api-reference Installs Vizra ADK guidelines for Laravel Boost integration to provide AI agent development context. ```APIDOC ## vizra:boost:install ### Description Install Vizra ADK guidelines for Laravel Boost integration. This adds AI agent development context to your Boost configuration. ### Usage `php artisan vizra:boost:install [--force]` ### Options - **--force** - Optional - Overwrite existing Boost guidelines ``` -------------------------------- ### Install Laravel Boost Source: https://docs.vizra.ai/integrations/laravel-boost Install the Laravel Boost package as a development dependency. ```bash composer require laravel/boost --dev ``` -------------------------------- ### Define Prompt Versions Source: https://docs.vizra.ai/concepts/dynamic-prompts Example of how prompt content evolves across sequential versions. ```text v1: "You are a helpful assistant" v2: "You are a helpful assistant. Be concise." v3: "You are a helpful assistant. Be concise and cite sources." ``` -------------------------------- ### Database Storage Setup Commands Source: https://docs.vizra.ai/concepts/dynamic-prompts Terminal commands to run migrations, update environment variables, and activate specific prompt versions. ```bash # Run migrations php artisan migrate # Update .env VIZRA_ADK_PROMPTS_USE_DATABASE=true # Activate a version php artisan vizra:prompt activate weather_reporter v2 ``` -------------------------------- ### Install Laravel Boost integration Source: https://docs.vizra.ai/api-reference/artisan-commands Configure Laravel Boost with Vizra ADK guidelines. Use the --force flag to overwrite existing configurations. ```bash # Install Boost integration php artisan vizra:boost:install # Force overwrite existing configuration php artisan vizra:boost:install --force ``` -------------------------------- ### Environment-Based MCP Setup Source: https://docs.vizra.ai/integrations/mcp Manage MCP server availability and credentials using environment variables and the corresponding configuration file. ```bash # Enable/disable servers per environment MCP_FILESYSTEM_ENABLED=true MCP_GITHUB_ENABLED=true MCP_POSTGRES_ENABLED=false # Server-specific configuration GITHUB_TOKEN=your_github_token_here DATABASE_URL=postgresql://user:pass@localhost/db BRAVE_API_KEY=your_brave_search_key MCP_NPX_PATH="/path/to/npx" # Optional: specify npx path if not in PATH ``` ```php 'mcp_servers' => [ 'filesystem' => [ 'command' => 'npx', 'args' => ['@modelcontextprotocol/server-filesystem', storage_path('app')], 'enabled' => env('MCP_FILESYSTEM_ENABLED', false), 'timeout' => 30, ], 'github' => [ 'command' => 'npx', 'args' => ['@modelcontextprotocol/server-github', '--token', env('GITHUB_TOKEN')], 'enabled' => env('MCP_GITHUB_ENABLED', false) && !empty(env('GITHUB_TOKEN')), 'timeout' => 45, ], 'postgres' => [ 'command' => 'npx', 'args' => ['@modelcontextprotocol/server-postgres', '--connection-string', env('DATABASE_URL')], 'enabled' => env('MCP_POSTGRES_ENABLED', false) && !empty(env('DATABASE_URL')), 'timeout' => 30, ], ], ``` -------------------------------- ### Batch Processing Patterns Source: https://docs.vizra.ai/api-reference/agent-class Usage examples for asynchronous batch operations and progress tracking. ```php // Process batch data $response = DataProcessorAgent::run($largeDataset) ->async() ->onQueue('processing') ->go(); // Import data with progress tracking $response = ImportAgent::run($csvFile) ->withContext(['notify_on_complete' => true]) ->async() ->go(); ``` -------------------------------- ### Custom Agent Implementation Example Source: https://docs.vizra.ai/api-reference/agent-class A complete implementation of a customer support agent extending BaseLlmAgent, including tool definitions, sub-agent delegation, and lifecycle hooks. ```php > */ protected array $tools = [ OrderLookupTool::class, RefundProcessorTool::class, EmailSenderTool::class, ]; // Sub-agents available for delegation protected array $subAgents = [ TechnicalSupportAgent::class, // Becomes: technical_support BillingAgent::class, // Becomes: billing ]; // 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); } } ``` -------------------------------- ### Configure PostgreSQL with pgvector Source: https://docs.vizra.ai/concepts/vector-rag Install the pgvector extension and set the environment variables to enable PostgreSQL as the vector storage driver. ```sql # Install pgvector extension CREATE EXTENSION IF NOT EXISTS vector; # Configure in .env VIZRA_ADK_VECTOR_DRIVER=pgvector DB_CONNECTION=pgsql ``` -------------------------------- ### Horizon Tag Filtering Examples Source: https://docs.vizra.ai/advanced/agent-queuing Examples of how tags appear and are used for filtering within the Horizon dashboard. ```php // In your Horizon config, jobs will appear with tags like: // vizra:my_agent, session:user_123_abc // Search for all jobs from a specific agent // Filter: vizra:analysis_agent // Search for all media generation jobs // Filter: vizra:media ``` -------------------------------- ### Create a Basic Pipeline Source: https://docs.vizra.ai/tools/tool-pipelines Initializes a new ToolChain and pipes multiple tools for sequential execution. ```php use Vizra\VizraADK\Tools\Chaining\ToolChain; $result = ToolChain::create() ->pipe(FetchUserTool::class) ->pipe(EnrichUserTool::class) ->pipe(ValidateUserTool::class) ->execute(['user_id' => 123], $context, $memory); // Access the final result $userData = $result->value(); ``` -------------------------------- ### Configure Workflow Step Parameters Source: https://docs.vizra.ai/api-reference/workflow-class Demonstrates adding agents with static inputs, dynamic closures, and step-specific options like retries and conditions. ```php // Static parameters $workflow->addAgent('agent_name', 'Static input'); // Dynamic parameters with closure $workflow->addAgent( 'processor', fn($input, $results, $context) => [ 'data' => $results['previous_agent'], 'mode' => $context->getState('processing_mode') ] ); // Step options $workflow->addAgent('risky_agent', 'Input', [ 'retries' => 5, 'timeout' => 60, 'condition' => fn() => config('app.env') === 'production' ]); ``` -------------------------------- ### Report Generation Patterns Source: https://docs.vizra.ai/api-reference/agent-class Usage examples for generating formatted reports and summaries. ```php // Generate daily report $response = ReportAgent::run('daily_sales') ->withContext(['date' => today()]) ->go(); // Create summary with specific format $response = SummaryAgent::run($quarterlyData) ->withContext(['format' => 'executive_summary']) ->go(); ``` -------------------------------- ### Execute Dynamic Prompts in PHP Source: https://docs.vizra.ai/concepts/dynamic-prompts Demonstrates how to invoke the SupportAgent with different version and variant configurations. ```php // Use latest version, default variant SupportAgent::run('Help')->go(); // Use specific variant SupportAgent::run('Help') ->withPromptVersion('formal') ->go(); // Use specific version & variant SupportAgent::run('Help') ->withPromptVersion('v1/casual') ->go(); ``` -------------------------------- ### Executing Agent Tasks with the run() Method Source: https://docs.vizra.ai/api-reference/agent-class Demonstrates various configurations for the run() method, including streaming, async processing, multimodal inputs, and context management. ```php // Basic conversation $response = CustomerSupportAgent::run('How do I reset my password?') ->go(); // With user context and session $response = CustomerSupportAgent::run('Show me my recent orders') ->forUser($user) ->withSession($sessionId) ->go(); // Streaming response for real-time output $stream = CustomerSupportAgent::run('Explain our refund policy') ->streaming() ->go(); foreach ($stream as $chunk) { echo $chunk; // Display as it streams } // Async processing for heavy workloads $job = DataProcessorAgent::run($supportTickets) ->async() ->onQueue('support') ->timeout(3600) // 1 hour timeout ->go(); // Multimodal with images $response = ProductAnalysisAgent::run('What\'s wrong with this product?') ->withImage('/path/to/product-photo.jpg') ->go(); // Complex analysis with multiple inputs $response = FinancialAdvisorAgent::run('Analyze my portfolio') ->withDocument('/path/to/portfolio.pdf') ->withContext([ 'risk_tolerance' => 'moderate', 'investment_horizon' => '10_years' ]) ->temperature(0.3) // Lower temperature for financial advice ->go(); // Event-driven processing $response = OrderProcessingAgent::run($orderEvent) ->withContext(['priority' => 'high']) ->forUser($customer) ->go(); // Scheduled monitoring $response = SystemHealthAgent::run($systemMetrics) ->onQueue('monitoring') ->delay(300) // Check every 5 minutes ->tries(3) // Retry up to 3 times ->go(); ``` -------------------------------- ### Define Prompt Variants Source: https://docs.vizra.ai/concepts/dynamic-prompts Example of how prompt content varies based on style or context. ```text formal: "I shall assist you with utmost professionalism" casual: "Hey! Happy to help out" technical: "Initiating support protocol. State your query." ``` -------------------------------- ### Create Prompts via CLI Source: https://docs.vizra.ai/concepts/dynamic-prompts Use interactive mode for multi-line content or quick mode for inline content creation. ```bash # Interactive mode - enter multi-line content php artisan vizra:prompt create weather_reporter friendly # Quick mode - inline content php artisan vizra:prompt create weather_reporter v2 --content="You are a helpful weather assistant." ``` -------------------------------- ### Initialize Image Tool via Factory Method Source: https://docs.vizra.ai/agents/image-agent Uses the bootTools method to dynamically add the image generation tool to the agent. ```php // In your agent's tools array protected array $tools = []; protected function bootTools(): void { $this->tools[] = DelegateToMediaAgentTool::forImage(); } ``` -------------------------------- ### Event Processing Patterns Source: https://docs.vizra.ai/api-reference/agent-class Usage examples for handling application events and webhook payloads. ```php // Process an event $response = NotificationAgent::run($orderCreatedEvent) ->forUser($user) ->go(); // Handle webhook data $response = WebhookAgent::run($webhookPayload) ->withContext(['source' => 'stripe']) ->go(); ``` -------------------------------- ### Streaming Response Format Source: https://docs.vizra.ai/integrations/openai-compatibility Example of a streaming response using Server-Sent Events (SSE) format. ```text data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677858242,"model":"your-agent","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]} data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677858242,"model":"your-agent","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]} data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677858242,"model":"your-agent","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]} data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677858242,"model":"your-agent","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]} data: [DONE] ``` -------------------------------- ### Handle media.job.completed Notification Source: https://docs.vizra.ai/api-reference/events Example listener that sends a notification to the user once a media job is completed. ```php Event::listen('media.job.completed', function (array $payload) { $url = $payload['response']->url(); // Notify user that their image is ready Notification::send($user, new MediaReadyNotification($url)); }); ``` -------------------------------- ### Agent::ask() Source: https://docs.vizra.ai/advanced/agent-queuing Initiates an agent task with fluent configuration for queuing and execution. ```APIDOC ## Agent::ask() ### Description Initiates a request to an agent. When chained with queue methods, the task is processed asynchronously. ### Parameters - **prompt** (string) - Required - The task or question for the agent. ### Example ```php $result = AnalysisAgent::ask('Analyze data') ->onQueue('analysis') ->delay(30) ->tries(5) ->timeout(600) ->go(); ``` ### Response - **job_id** (string) - The unique identifier for the queued job. ``` -------------------------------- ### Monitoring and Alerting Patterns Source: https://docs.vizra.ai/api-reference/agent-class Usage examples for continuous system monitoring and scheduled health checks. ```php // Monitor system metrics $response = SystemMonitorAgent::run($metrics) ->onQueue('monitoring') ->withContext(['alert_threshold' => 90]) ->go(); // Health checks $response = HealthCheckAgent::run($serviceEndpoints) ->delay(60) // Check every minute ->go(); ``` -------------------------------- ### Data Analysis Patterns Source: https://docs.vizra.ai/api-reference/agent-class Usage examples for agents performing data analysis or insight generation. ```php // Analyze payment data $response = FraudDetectionAgent::run($paymentData) ->withContext(['risk_threshold' => 0.7]) ->go(); // Generate insights $response = AnalyticsAgent::run($salesData) ->withContext(['period' => 'last_quarter']) ->go(); ``` -------------------------------- ### Agent run() Method Signature Source: https://docs.vizra.ai/api-reference/agent-class The static entry point for initializing an agent execution flow. ```php public static function run(mixed $input): AgentExecutor ``` -------------------------------- ### Manage Span Lifecycle Source: https://docs.vizra.ai/api-reference/tracing-class Methods for starting, completing, and failing spans within the tracing system. ```php // Start a new span $spanId = $tracer->startSpan( type: 'tool_call', name: 'database_query', input: ['query' => 'SELECT * FROM users'], metadata: ['database' => 'mysql'] ); // End the span successfully $tracer->endSpan($spanId, [ 'rows_returned' => 42, 'cache_hit' => false ]); // Mark span as failed $tracer->failSpan($spanId, $exception); ``` -------------------------------- ### Initialize Database for Vector Memory Source: https://docs.vizra.ai/concepts/vector-rag Run migrations to set up necessary tables and ensure the pgvector extension is enabled for PostgreSQL databases. ```bash # Run migrations for vector memory tables php artisan migrate # For PostgreSQL, ensure pgvector extension is installed CREATE EXTENSION IF NOT EXISTS vector; ``` -------------------------------- ### AudioAgent::run() Source: https://docs.vizra.ai/agents/audio-agent Initiates an audio generation task. This is the entry point for all audio generation requests, supporting fluent configuration for queues, callbacks, and user context. ```APIDOC ## AudioAgent::run(string $prompt) ### Description Starts the audio generation process. Returns an instance of the AudioAgent builder. ### Methods - **onQueue(string $queue)**: Specifies the queue name for background processing. - **delay(int $seconds)**: Sets a delay in seconds before the job is processed. - **tries(int $attempts)**: Sets the number of retry attempts for the job. - **timeout(int $seconds)**: Sets the timeout in seconds for the job. - **format(string $format)**: Specifies the output audio format (e.g., 'mp3'). - **forUser($user)**: Associates the generation task with a specific user. - **withSession(string $sessionId)**: Associates the task with a specific session ID. - **then(callable $callback)**: Defines a callback to execute upon successful completion. - **go()**: Dispatches the job or executes the generation task. ``` -------------------------------- ### Standard JSON Response Format Source: https://docs.vizra.ai/integrations/openai-compatibility Example of a non-streaming chat completion response matching the OpenAI schema. ```json { "id": "chatcmpl-AbCdEfGhIjKlMnOpQrStUvWxYz", "object": "chat.completion", "created": 1677858242, "model": "your-agent-name", "system_fingerprint": null, "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! I'm your Vizra agent, ready to help!" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 12, "completion_tokens": 15, "total_tokens": 27 } } ``` -------------------------------- ### AudioAgent::run Source: https://docs.vizra.ai/agents/audio-agent Initializes the text-to-speech generation process with the provided text. ```APIDOC ## AudioAgent::run(string $text) ### Description Initiates a new audio generation task with the specified input text. ### Signature `public static function run(string $text): AudioAgent` ### Parameters - **$text** (string) - Required - The text content to be converted into speech. ``` -------------------------------- ### Conversational Interaction Patterns Source: https://docs.vizra.ai/api-reference/agent-class Usage examples for chat-based agents requiring user context or session management. ```php // Ask a question $response = CustomerSupportAgent::run('Where is my order?') ->forUser($user) ->go(); // Have a conversation with context $response = CustomerSupportAgent::run('I need help with shipping') ->withSession($sessionId) ->withContext(['order_id' => $orderId]) ->go(); ``` -------------------------------- ### Install Vizra ADK via Composer Source: https://docs.vizra.ai/installation/getting-started Add the Vizra ADK package to your Laravel project dependencies. ```bash composer require vizra/vizra-adk ``` -------------------------------- ### Configure auto-storage options Source: https://docs.vizra.ai/advanced/agent-queuing Use store() or storeAs() within the fluent chain to automatically save generated media to a disk. ```php // Store with auto-generated filename (ULID) ImageAgent::run('A landscape photo') ->onQueue('media') ->store() ->go(); // Store with specific filename ImageAgent::run('A portrait photo') ->onQueue('media') ->storeAs('portraits/user-avatar.png') ->go(); // Store to a specific disk ImageAgent::run('A banner image') ->onQueue('media') ->storeAs('banners/hero.png', 's3') ->go(); ``` -------------------------------- ### Monitor Agent Performance with PHP Source: https://docs.vizra.ai/api-reference/events Tracks agent execution duration by listening to starting and finished events. ```php use Vizra\VizraADK\Events\{AgentExecutionStarting, AgentExecutionFinished}; use Illuminate\Support\Facades\Event; class AgentPerformanceMonitor { private array $startTimes = []; public function register(): void { Event::listen(AgentExecutionStarting::class, [$this, 'handleStart']); Event::listen(AgentExecutionFinished::class, [$this, 'handleFinish']); } public function handleStart(AgentExecutionStarting $event): void { $this->startTimes[$event->context->getSessionId()] = microtime(true); } public function handleFinish(AgentExecutionFinished $event): void { $sessionId = $event->context->getSessionId(); $duration = microtime(true) - $this->startTimes[$sessionId]; Log::info('Agent execution completed', [ 'agent' => $event->agentName, 'duration' => round($duration, 2) . 's' ]); } } ``` -------------------------------- ### Create a new tool Source: https://docs.vizra.ai/api-reference/artisan-commands Scaffolds a new tool class for agent capabilities. ```bash # Create a new tool interactively php artisan vizra:make:tool # The command will prompt for the tool name # Creates: app/Tools/YourTool.php ``` -------------------------------- ### Configure API Keys Source: https://docs.vizra.ai/installation/configuration Add provider-specific API keys to the .env file for authentication. ```bash # OpenAI OPENAI_API_KEY=your-openai-api-key # Anthropic Claude ANTHROPIC_API_KEY=your-anthropic-api-key # Google Gemini GOOGLE_API_KEY=your-google-api-key ``` -------------------------------- ### Define Evaluation Test Data Source: https://docs.vizra.ai/testing/evaluations Example CSV structure for defining test prompts, expected responses, and descriptions. ```csv prompt,expected_response,description "Hello, I need help",help,"Greeting test - should offer assistance" "Where is my order #12345?",order,"Order inquiry - should help track order" "I want to return this product",return,"Return request - should explain process" "This is terrible service!",sorry,"Complaint - should be empathetic" ``` -------------------------------- ### Agent::run() Source: https://docs.vizra.ai/api-reference/agent-class The run() method is the universal entry point for all agents, returning an AgentExecutor instance that supports fluent configuration methods before calling go() to execute. ```APIDOC ## public static function run(mixed $input): AgentExecutor ### Description Initializes an agent executor with the provided input. This method serves as the entry point for all agent interactions, allowing for fluent configuration of context, user association, and execution settings. ### Parameters - **input** (mixed) - Required - The data, query, or event payload to be processed by the agent. ### Fluent Configuration Methods - **forUser($user)** - Associates the execution with a specific user. - **withSession($sessionId)** - Sets the session identifier for conversational context. - **withContext(array $context)** - Provides additional metadata or context for the agent task. - **async()** - Configures the execution to run asynchronously. - **onQueue($queueName)** - Specifies the queue for asynchronous processing. - **delay($seconds)** - Sets a delay before execution. ### Execution - **go()** - Finalizes the configuration and triggers the agent execution. ``` -------------------------------- ### Evaluation Console Output Source: https://docs.vizra.ai/testing/evaluations Example of the terminal output generated during an evaluation run, including progress tracking and a summary table. ```text Running evaluation: customer_support_eval Description: Evaluate customer support agent responses Processing 4 rows from CSV using agent 'customer_support'... ████████████████████████████████████████ 4/4 Evaluation processing complete. ┌─────┬──────────────┬──────────────────────────┬─────────────────┬───────┐ │ Row │ Final Status │ LLM Response Summary │ Assertions Count│ Error │ ├─────┼──────────────┼──────────────────────────┼─────────────────┼───────┤ │ 1 │ ✅ pass │ Hello! I'd be happy to...│ 2 │ │ │ 2 │ ✅ pass │ I can help you track... │ 1 │ │ │ 3 │ ❌ fail │ Sure, let me assist... │ 2 │ │ │ 4 │ ✅ pass │ I understand your... │ 3 │ │ └─────┴──────────────┴──────────────────────────┴─────────────────┴───────┘ Summary: Total Rows: 4, Passed: 3 (75%), Failed: 1 (25%), Errors: 0 ``` -------------------------------- ### Prompt Configuration Settings Source: https://docs.vizra.ai/concepts/dynamic-prompts Configures prompt storage and analytics tracking within the vizra-adk.php configuration file. ```php 'prompts' => [ // Enable database storage (optional) 'use_database' => env('VIZRA_ADK_PROMPTS_USE_DATABASE', false), // Custom storage path 'storage_path' => env('VIZRA_ADK_PROMPTS_PATH', resource_path('prompts')), // Track usage analytics 'track_usage' => env('VIZRA_ADK_PROMPTS_TRACK_USAGE', false), ], ``` -------------------------------- ### Agent::run() Source: https://docs.vizra.ai/api-reference/agent-class The entry point for initiating an agent task. Returns a builder instance that supports various configuration methods before calling go() to execute. ```APIDOC ## Agent::run(mixed $input) ### Description Initiates an agent task with the provided input. This method returns a builder object that allows for chaining configuration methods. ### Parameters - **$input** (mixed) - Required - The primary input or query for the agent. ### Configuration Methods - **forUser($user)** - Optional - Sets the user context for the request. - **withSession($sessionId)** - Optional - Associates the request with a specific session. - **streaming()** - Optional - Enables streaming mode for real-time output. - **async()** - Optional - Queues the task for asynchronous processing. - **onQueue($queueName)** - Optional - Specifies the queue name for async jobs. - **timeout($seconds)** - Optional - Sets a timeout duration for the task. - **withImage($path)** - Optional - Attaches an image for multimodal processing. - **withDocument($path)** - Optional - Attaches a document for analysis. - **withContext(array $data)** - Optional - Provides additional metadata or context. - **temperature(float $value)** - Optional - Adjusts the creativity/randomness of the output. - **delay($seconds)** - Optional - Delays execution by the specified time. - **tries($count)** - Optional - Sets the number of retry attempts. ### Execution - **go()** - Required - Executes the configured agent task and returns the result or stream. ``` -------------------------------- ### List and test MCP servers Source: https://docs.vizra.ai/api-reference/artisan-commands Use these commands to view configured MCP servers and verify their connectivity status. ```bash # List all configured MCP servers php artisan vizra:mcp:servers # Test connectivity to all servers php artisan vizra:mcp:servers --test ``` -------------------------------- ### Progressive Disclosure API Examples Source: https://docs.vizra.ai/concepts/vector-rag Illustrates the flexible API design allowing for simple or advanced configurations when adding chunks or searching. ```php class KnowledgeAgent extends BaseLlmAgent { public function demonstrateAPI(): void { // 1. SIMPLE: Just content (perfect for quick prototyping) $this->vector()->addChunk('Laravel is awesome!'); // 2. COMMON: Content + metadata (most typical usage) $this->vector()->addChunk( 'Eloquent is Laravel\'s ORM', ['category' => 'database', 'difficulty' => 'beginner'] ); // 3. ADVANCED: Full control with array (when you need everything) $this->vector()->addChunk([ 'content' => 'Advanced Laravel patterns and practices', 'metadata' => ['category' => 'advanced', 'priority' => 'high'], 'namespace' => 'tutorials', 'source' => 'expert-guide', 'source_id' => 'guide-123', 'chunk_index' => 0 ]); } public function searchExamples(): void { // Simple search $results = $this->rag()->search('Laravel ORM'); // With limit $results = $this->rag()->search('Laravel patterns', 10); // Full control $results = $this->rag()->search([ 'query' => 'advanced Laravel', 'namespace' => 'tutorials', 'limit' => 5, 'threshold' => 0.8 ]); } } ``` -------------------------------- ### Manage Prompt Versions Source: https://docs.vizra.ai/api-reference/artisan-commands Commands for creating, listing, activating, exporting, and importing prompt versions for agents. ```bash # Create a new prompt version php artisan vizra:prompt create {agent} {version} [--content="..."] # List all prompt versions php artisan vizra:prompt list [agent] # Activate a version (database only) php artisan vizra:prompt activate {agent} {version} # Export prompt to file php artisan vizra:prompt export {agent} {version} [--file=output.txt] # Import prompt from file php artisan vizra:prompt import {agent} {version} --file=input.txt ``` -------------------------------- ### Artisan Command: vizra:make:toolbox Source: https://docs.vizra.ai/tools/toolbox CLI command to generate a new toolbox class. ```APIDOC ## php artisan vizra:make:toolbox {name} [options] ### Description Generates a new toolbox class with optional authorization and tool configurations. ### Options - **-g, --gate** (string) - Optional - Laravel Gate name for authorization - **-p, --policy** (string) - Optional - Laravel Policy class for authorization - **-t, --tools** (string) - Optional - Comma-separated list of tool class names ``` -------------------------------- ### Chat Completions API Integration Source: https://docs.vizra.ai/integrations/openai-compatibility Examples of how to send requests to the Vizra ADK chat completions endpoint using various programming languages. ```bash curl -X POST http://your-app.com/api/vizra-adk/chat/completions \ -H "Content-Type: application/json" \ -d '{ "model": "your-agent-name", "messages": [ {"role": "user", "content": "Hello! Tell me about yourself."} ], "temperature": 0.7, "max_tokens": 500 }' ``` ```php use Illuminate\Support\Facades\Http; $response = Http::post('http://your-app.com/api/vizra-adk/chat/completions', [ 'model' => 'your-agent-name', 'messages' => [ ['role' => 'user', 'content' => 'Hello! Tell me about yourself.'] ], 'temperature' => 0.7, 'max_tokens' => 500 ]); $result = $response->json(); echo $result['choices'][0]['message']['content']; ``` ```javascript const response = await fetch('http://your-app.com/api/vizra-adk/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'your-agent-name', messages: [ { role: 'user', content: 'Hello! Tell me about yourself.' } ], temperature: 0.7, max_tokens: 500 }) }); const data = await response.json(); console.log(data.choices[0].message.content); ``` ```python import requests response = requests.post( 'http://your-app.com/api/vizra-adk/chat/completions', json={ 'model': 'your-agent-name', 'messages': [ {'role': 'user', 'content': 'Hello! Tell me about yourself.'} ], 'temperature': 0.7, 'max_tokens': 500 } ) result = response.json() print(result['choices'][0]['message']['content']) ``` -------------------------------- ### Agent Memory API Methods Source: https://docs.vizra.ai/concepts/sessions-memory Provides examples of specialized methods for interacting with agent memory, including adding data and retrieving context. ```php // Inside any agent method, access memory via $this->memory() // Learnings - Insights gained from interactions $this->memory()->addLearning('User works in healthcare', [ 'confidence' => 'high', 'source' => 'direct_mention' ]); // Facts - Immutable truths about the user $this->memory()->addFact('Located in New York', 1.0); // confidence score // Preferences - User likes and dislikes $this->memory()->addPreference('Detailed explanations', 'communication_style'); // Summary - Overall user profile (replaces previous) $this->memory()->updateSummary('Tech-savvy healthcare professional in NYC'); // Recall - Search through memories $learnings = $this->memory()->getLearnings(); $facts = $this->memory()->getFacts(); $preferences = $this->memory()->getPreferences('communication_style'); $summary = $this->memory()->getSummary(); // Context - Get formatted memory for prompts $context = $this->memory()->getContext(1500); // max tokens ``` -------------------------------- ### startSpan(string $type, string $name, array $input, array $metadata) Source: https://docs.vizra.ai/api-reference/tracing-class Starts a new span within the current trace context. ```APIDOC ## startSpan ### Description Starts a new span for tracking operations like tool calls or LLM interactions. ### Parameters - **type** (string) - Required - The category of the span (e.g., 'agent_run', 'llm_call', 'tool_call', 'sub_agent_delegation'). - **name** (string) - Required - The name of the operation. - **input** (array) - Required - Input data for the operation. - **metadata** (array) - Optional - Additional context metadata. ### Returns - **spanId** (string) - The unique identifier for the created span. ``` -------------------------------- ### Publish Configuration File Source: https://docs.vizra.ai/installation/configuration Command to publish the configuration file if it has not been generated yet. ```bash php artisan vendor:publish --tag=vizra-adk-config ``` -------------------------------- ### Define a Data Analysis Agent Source: https://docs.vizra.ai/integrations/mcp An example of an LLM agent configured to use Postgres and filesystem MCP servers for database querying and report generation. ```php class DataAnalystAgent extends BaseLlmAgent { protected string $name = 'data_analyst'; protected string $instructions = 'You are a data analysis expert. You can: 1. Query databases to extract insights 2. Generate reports and save them as files 3. Create data visualizations and charts 4. Identify trends and anomalies in data Always explain your analysis methodology and findings clearly.'; protected array $mcpServers = ['postgres', 'filesystem']; } ``` -------------------------------- ### Enable MCP Servers via Environment Variables Source: https://docs.vizra.ai/installation/configuration Enable and configure various MCP servers by setting the appropriate environment variables. ```bash MCP_FILESYSTEM_ENABLED=true MCP_FILESYSTEM_PATH=/path/to/allowed/dir ``` ```bash MCP_GITHUB_ENABLED=true GITHUB_TOKEN=your-github-token ``` ```bash MCP_POSTGRES_ENABLED=true MCP_POSTGRES_URL=postgresql://... ``` ```bash MCP_BRAVE_SEARCH_ENABLED=true BRAVE_API_KEY=your-brave-api-key ``` -------------------------------- ### Define a Code Review Agent Source: https://docs.vizra.ai/integrations/mcp An example of an LLM agent configured to use filesystem and GitHub MCP servers for code analysis and issue tracking. ```php class CodeReviewAgent extends BaseLlmAgent { protected string $name = 'code_reviewer'; protected string $instructions = 'You are an expert code reviewer. You can: 1. Read code files to understand implementations 2. Search for patterns and potential issues 3. Create GitHub issues for problems found 4. Suggest improvements and best practices Always provide constructive feedback with specific examples.'; protected array $mcpServers = ['filesystem', 'github']; } ``` -------------------------------- ### Configure Audio Agent in config/vizra-adk.php Source: https://docs.vizra.ai/agents/audio-agent Define audio provider settings and storage paths within the application configuration file. ```php 'media' => [ 'audio' => [ 'provider' => env('VIZRA_ADK_AUDIO_PROVIDER', 'openai'), 'model' => env('VIZRA_ADK_AUDIO_MODEL', 'tts-1'), 'default_voice' => env('VIZRA_ADK_AUDIO_VOICE', 'alloy'), 'default_format' => env('VIZRA_ADK_AUDIO_FORMAT', 'mp3'), 'default_speed' => env('VIZRA_ADK_AUDIO_SPEED', 1.0), ], 'storage' => [ 'disk' => env('VIZRA_ADK_MEDIA_DISK', 'public'), 'path' => env('VIZRA_ADK_MEDIA_PATH', 'vizra-adk/generated'), ], ], ``` -------------------------------- ### Stream chat completions with OpenAI-compatible API Source: https://docs.vizra.ai/integrations/openai-compatibility Use these examples to handle real-time streaming responses from the chat completions endpoint by setting the stream parameter to true. ```javascript async function streamResponse() { const response = await fetch('/api/vizra-adk/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'my-agent', messages: [{ role: 'user', content: 'Tell me a long story' }], stream: true, temperature: 0.8 }) }); const reader = response.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value); const lines = chunk.split('\n'); for (const line of lines) { if (line.startsWith('data: ')) { const data = line.slice(6); if (data === '[DONE]') return; try { const parsed = JSON.parse(data); const content = parsed.choices[0]?.delta?.content; if (content) { process.stdout.write(content); // Stream to console // Or update your UI in real-time } } catch (e) { // Handle parsing errors } } } } } streamResponse(); ``` ```python import requests import json def stream_completion(): response = requests.post( 'http://your-app.com/api/vizra-adk/chat/completions', json={ 'model': 'my-agent', 'messages': [{'role': 'user', 'content': 'Write a poem'}], 'stream': True, 'temperature': 0.7 }, stream=True ) for line in response.iter_lines(): if line.startswith(b'data: '): data = line[6:].decode('utf-8') if data == '[DONE]': break try: chunk = json.loads(data) content = chunk['choices'][0]['delta'].get('content') if content: print(content, end='', flush=True) except json.JSONDecodeError: continue stream_completion() ``` -------------------------------- ### AudioAgent::run Source: https://docs.vizra.ai/agents/audio-agent The primary entry point for initiating an audio generation task. It supports chaining configuration methods before executing the request with the go() method. ```APIDOC ## AudioAgent::run ### Description Initiates the audio generation process with the provided text string. ### Methods - **format(string $format)**: Sets the output audio format (mp3, wav, opus, aac, flac). - **speed(float $rate)**: Adjusts the speaking rate between 0.25x and 4.0x. - **using(string $provider, string $model)**: Overrides the default model with a specific provider and model identifier. - **go()**: Executes the audio generation request. ### Example ```php $audio = AudioAgent::run('Text to convert') ->format('wav') ->speed(1.0) ->using('openai', 'tts-1-hd') ->go(); ``` ``` -------------------------------- ### Launch Vizra dashboard Source: https://docs.vizra.ai/api-reference/artisan-commands Access the web-based dashboard for agent testing and monitoring. Use the --open flag to automatically launch the browser. ```bash # Display dashboard URL php artisan vizra:dashboard # Open dashboard in browser php artisan vizra:dashboard --open ```