### Simple Agent Response Generation in PHP Source: https://docs.laragent.ai/quickstart Demonstrates various ways to get a simple text response from an agent. It covers creating an agent instance for a specific user, using default settings, and a shorthand method for quick interactions. These examples assume the `WeatherAgent` class is set up. ```php use App\AiAgents\WeatherAgent; // Create an instance for a specific user or chat session $agent = WeatherAgent::for('user-123'); // Get a response $response = $agent->respond("What's the weather like in Boston?"); echo $response; // "The weather in Boston is currently..." ``` ```php use App\AiAgents\WeatherAgent; // Create instance with random chat history name $response = WeatherAgent::make() ->withTemperature(0.7) ->message("What's the weather like in Boston?") ->respond(); echo $response; // "The weather in Boston is currently..." ``` ```php use App\AiAgents\WeatherAgent; // Create instance with random chat history name $response = WeatherAgent::ask("What's the weather like in Boston?"); echo $response; // "The weather in Boston is currently..." ``` -------------------------------- ### LarAgent Custom Provider Configuration Example Source: https://docs.laragent.ai/quickstart An example of how to configure a custom LLM provider in LarAgent, including all possible settings like API key, URL, model, driver, and more. ```php // Example custom provider with all possible configurations 'custom_provider' => [ // Just name for reference, changes nothing 'label' => 'custom', 'api_key' => env('PROVIDER_API_KEY'), 'api_url' => env('PROVIDER_API_URL'), // Defaults (Can be overriden per agent) 'model' => 'your-provider-model', 'driver' => \LarAgent\Drivers\OpenAi\OpenAiDriver::class, 'chat_history' => \LarAgent\History\InMemoryChatHistory::class, 'default_truncation_threshold' => 15000, 'default_max_completion_tokens' => 100, 'default_temperature' => 0.7, // Enable/disable parallel tool calls 'parallel_tool_calls' => true, // Store metadata with messages 'store_meta' => true, // Save chat keys to memory via chatHistory 'save_chat_keys' => true, ], ``` -------------------------------- ### Install LarAgent via Composer Source: https://docs.laragent.ai/quickstart Installs the LarAgent package using Composer. This is the primary method for adding LarAgent to your Laravel project. ```bash composer require maestroerror/laragent ``` -------------------------------- ### Example Test Queries for Agent Chat Source: https://docs.laragent.ai/guides/rag/retrieval-as-tool Presents example queries categorized into Database, Documentation, and Combined types to test the agent's ability to use different tools and synthesize information. Also includes expected behavior outcomes. ```text Database Queries "Show me details for user with email john@example.com" "What are my recent orders?" "List all active products in the electronics category" "How many users registered this month?" Documentation Queries "What is the return policy?" "How do I reset my password?" "What are the available pricing plans?" "How does the referral program work?" Combined Queries "Show me user Sarah's order history and explain the return policy" "What are the requirements for premium features and how many premium users do we have?" Expected Behavior ✅ Agent decides which tool(s) to use ✅ SQL queries are validated by guardrail agent ✅ Unsafe queries are rejected ✅ Document search returns relevant results ✅ Agent synthesizes information from multiple sources ``` -------------------------------- ### Adding a Tool to an Agent in PHP Source: https://docs.laragent.ai/quickstart Illustrates how to add a tool to an agent class. Tools enable agents to perform actions or access external data. This example defines a `getCurrentWeather` tool with location and unit parameters, using PHP attributes for definition. ```php namespace App\AiAgents; use LarAgent\Agent; use LarAgent\Attributes\Tool; class WeatherAgent extends Agent { // ... other properties #[Tool('Get the current weather in a given location')] public function getCurrentWeather($location, $unit = 'celsius') { // Call a weather API or service return "The weather in {$location} is 22 degrees {$unit}."; } } ``` -------------------------------- ### Install OpenAI PHP Client Source: https://docs.laragent.ai/guides/rag/retrieval-as-tool Installs the OpenAI PHP client library, recommended for generating embeddings within LarAgent. This is often installed as a dependency of LarAgent. ```bash # Usually already installed with LarAgent composer require openai-php/client ``` -------------------------------- ### Example Questions for Testing (Text) Source: https://docs.laragent.ai/guides/rag/vector-based A list of example questions to use when interactively testing the Support Agent. These questions cover various topics like user creation, historical facts, and pricing plans. ```text "How do I create a new user?" "Who has invented the lightbulb?" "What are the pricing plans available?" "What's the difference between Basic and Pro plans?" ``` -------------------------------- ### PHP: Simple Storage Configuration Source: https://docs.laragent.ai/v1/context/overview Example of a simple PHP configuration where a single set of storage drivers is applied to all storage types. This is useful for basic setups. ```php use LarAgent\Context\Drivers\CacheStorage; use LarAgent\Context\Drivers\EloquentStorage; class SupportAgent extends Agent { protected $instructions = 'You are a helpful support agent.'; // All storages use cache and database drivers protected $storage = [ CacheStorage::class, EloquentStorage::class, ]; } ``` -------------------------------- ### Interact with an Agent in PHP Source: https://docs.laragent.ai/v1/agents/overview These PHP examples demonstrate how to interact with a LarAgent Agent. The first shows how to start or continue a conversation with a specific user, maintaining context. The second shows a one-off interaction for a simple query without persisting history. ```php // Start or continue a conversation $response = AssistantAgent::for('user-123')->respond('Hello, how can you help me?'); // Or for one-off interactions without persisted history $response = AssistantAgent::ask('What is 2 + 2?'); ``` -------------------------------- ### Install Project Dependencies Source: https://docs.laragent.ai/guides/development Installs the necessary project dependencies using Composer. This command should be run after cloning the repository. ```bash composer install ``` -------------------------------- ### Publish LarAgent Configuration Source: https://docs.laragent.ai/quickstart Publishes the LarAgent configuration file to your Laravel application. This creates the `config/laragent.php` file. ```bash php artisan vendor:publish --tag="laragent-config" ``` -------------------------------- ### Create New Agent with Artisan Command Source: https://docs.laragent.ai/quickstart Generates a new agent class using the provided Artisan command. This command creates the necessary boilerplate code for a new agent in the `App\AiAgents` directory. ```bash php artisan make:agent WeatherAgent ``` -------------------------------- ### LarAgent Default Configuration Source: https://docs.laragent.ai/quickstart The default configuration file for LarAgent, specifying default drivers, chat history, namespaces, and various LLM provider settings. ```php // config for Maestroerror/LarAgent return [ 'default_driver' => \LarAgent\Drivers\OpenAi\OpenAiCompatible::class, 'default_chat_history' => \LarAgent\History\InMemoryChatHistory::class, 'namespaces' => [ 'App\\AiAgents\\', 'App\\Agents\\', ], 'providers' => [ 'default' => [ 'label' => 'openai', 'api_key' => env('OPENAI_API_KEY'), 'driver' => \LarAgent\Drivers\OpenAi\OpenAiDriver::class, 'default_truncation_threshold' => 50000, 'default_max_completion_tokens' => 10000, 'default_temperature' => 1, ], 'gemini' => [ 'label' => 'gemini', 'api_key' => env('GEMINI_API_KEY'), 'driver' => \LarAgent\Drivers\OpenAi\GeminiDriver::class, 'default_truncation_threshold' => 1000000, 'default_max_completion_tokens' => 10000, 'default_temperature' => 1, ], 'gemini_native' => [ 'label' => 'gemini', 'api_key' => env('GEMINI_API_KEY'), 'driver' => \LarAgent\Drivers\Gemini\GeminiDriver::class, 'default_truncation_threshold' => 1000000, 'default_max_completion_tokens' => 10000, 'default_temperature' => 1, ], 'groq' => [ 'label' => 'groq', 'api_key' => env('GROQ_API_KEY'), 'driver' => \LarAgent\Drivers\Groq\GroqDriver::class, 'default_truncation_threshold' => 131072, 'default_max_completion_tokens' => 131072, 'default_temperature' => 1, ], 'claude' => [ 'label' => 'claude', 'api_key' => env('ANTHROPIC_API_KEY'), 'model' => 'claude-3-7-sonnet-latest', 'driver' => \LarAgent\Drivers\Anthropic\ClaudeDriver::class, 'default_truncation_threshold' => 200000, 'default_max_completion_tokens' => 8192, 'default_temperature' => 1, ], 'openrouter' => [ 'label' => 'openrouter', 'api_key' => env('OPENROUTER_API_KEY'), 'model' => 'openai/gpt-oss-20b:free', 'driver' => \LarAgent\Drivers\OpenAi\OpenRouter::class, 'default_truncation_threshold' => 200000, 'default_max_completion_tokens' => 8192, 'default_temperature' => 1, ], 'ollama' => [ 'label' => 'ollama', 'driver' => \LarAgent\Drivers\OpenAi\OllamaDriver::class, 'default_truncation_threshold' => 131072, 'default_max_completion_tokens' => 131072, 'default_temperature' => 0.8, ], ], 'fallback_provider' => null, ]; ``` -------------------------------- ### Bash: Example API Request for Chat Completions Source: https://docs.laragent.ai/v1/agents/agent-via-api This bash script provides an example of how to make a POST request to the `/v1/chat/completions` endpoint using `curl`. It includes the necessary headers and a JSON payload specifying the model and user message. ```bash curl -X POST /v1/chat/completions \ -H 'Content-Type: application/json' \ -d '{ "model": "MyAgent/gpt-4o-mini", "messages": [ {"role":"user","content":"Hello"} ], }' ``` -------------------------------- ### Configure OpenAI API Key Source: https://docs.laragent.ai/quickstart Sets the OpenAI API key in the `.env` file for LarAgent to use. This is a simple way to configure API access for OpenAI. ```dotenv OPENAI_API_KEY=your-openai-api-key ``` -------------------------------- ### Simple Eloquent Storage Configuration Example Source: https://docs.laragent.ai/v1/context/storage-drivers Shows how to configure the SimpleEloquentStorage driver. It illustrates using the default model or specifying a custom Eloquent model for storing data as JSON blobs. ```php use LarAgent\Context\Drivers\SimpleEloquentStorage; protected function defaultStorageDrivers(): array { return [ // Use default model new SimpleEloquentStorage(), // Or use custom model new SimpleEloquentStorage(\App\Models\CustomStorage::class), ]; } ``` -------------------------------- ### Create a LarAgent Event Listener in Laravel Source: https://docs.laragent.ai/v1/customization/events/setup Generates a new listener class for handling LarAgent events using the Artisan command. This listener will contain the logic to process specific agent events. ```bash php artisan make:listener AgentListener ``` -------------------------------- ### Instance Method Tool Example Source: https://docs.laragent.ai/v1/tools/attribute-tools An example of defining a tool using an instance method in PHP. This method accesses agent context via `$this->context` to retrieve user preferences. ```php #[Tool('Get user preferences')] public function getUserPreferences(): array { // Access agent properties or methods return $this->context->get('user_preferences', []); } ``` -------------------------------- ### Interactive Agent Testing Command Source: https://docs.laragent.ai/guides/rag/retrieval-as-tool Provides the Artisan command to launch an interactive chat session with the SmartSupportAgent. This allows for testing the implemented tools with various query types. ```bash php artisan agent:chat SmartSupportAgent ``` -------------------------------- ### Test SQL Guardrails with Safe and Unsafe Queries Source: https://docs.laragent.ai/guides/rag/retrieval-as-tool Demonstrates safe queries that should pass guardrail validation and unsafe queries that should be rejected. This helps ensure the integrity of database interactions. ```text ✅ "SELECT * FROM users WHERE email = 'test@example.com'" ✅ "SELECT COUNT(*) FROM orders WHERE created_at > '2024-01-01'" ✅ "SELECT u.name, o.total FROM users u JOIN orders o ON u.id = o.user_id" ``` ```text ❌ "DELETE FROM users WHERE id = 1" ❌ "UPDATE users SET role = 'admin' WHERE id = 1" ❌ "DROP TABLE users" ❌ "INSERT INTO users (name) VALUES ('hacker')" ❌ "SELECT * FROM users; DROP TABLE users;" ``` -------------------------------- ### Replace Chat Key Management with Context Facade (PHP) Source: https://docs.laragent.ai/guides/upgrade-to-v1 Provides examples of how to manage chat history keys and storage after the removal of related methods from the ChatHistory interface. It shows how to use the new `Context` facade and Agent methods to retrieve chat keys, storage keys, and chat identities, offering multiple options for accessing this data. ```php use LarAgent\Facades\Context; use App\AiAgents\MyAgent; // Option 1: Inside Agent - get chat keys via Agent methods $agent = MyAgent::for('user-123'); $chatKeys = $agent->getChatKeys(); // Get all chat history keys $allStorageKeys = $agent->getStorageKeys(); // Get all storage keys $chatIdentities = $agent->getChatIdentities(); // Get chat identities // Option 2: Inside Agent - get current session key $sessionKey = $this->context()->getIdentity()->getKey(); $chatName = $this->context()->getIdentity()->getChatName(); // Option 3: Outside Agent - use Context facade with agent class $chatKeys = Context::of(MyAgent::class)->getChatKeys(); $storageKeys = Context::of(MyAgent::class)->getStorageKeys(); // Option 4: Outside Agent - use Context facade with agent name $chatKeys = Context::named('MyAgent')->getChatKeys(); $storageKeys = Context::named('MyAgent')->getStorageKeys(); ``` -------------------------------- ### LarAgent MCP Tool Caching Usage Example Source: https://docs.laragent.ai/v1/tools/mcp Provides a practical example of how LarAgent's MCP tool caching works. The first agent instantiation triggers a network call to fetch and cache tools, while subsequent instantiations load tools directly from the cache, significantly improving performance. ```php use App\Agents\ResearchAgent; // First call: fetches from MCP server + caches tools $agent = ResearchAgent::for('user_123'); $response = $agent->respond('Hello'); // Tools fetched & cached // Subsequent calls: uses cache (no network call) $agent2 = ResearchAgent::for('user_456'); $response2 = $agent2->respond('Hi'); // Tools loaded from cache ⚡ ``` -------------------------------- ### Manual Tool Access via mcpClient (PHP) Source: https://docs.laragent.ai/v1/tools/mcp Provides an example of manually calling an MCP tool using the `mcpClient`'s `callTool` method. This allows for custom tool descriptions and the ability to hard-code or restrict arguments, reducing potential errors. The example demonstrates calling a 'get_issue' tool for a specific GitHub repository and issue number. ```php use Attribute; // Assuming Attribute is available for #[Tool] #[Tool("Get issue details from LarAgent repository")] public function readTheIssue(int $issue_number) { $args = [ "issue_number" => $issue_number, "owner" => "maestroerror", "repo" => "LarAgent" ]; return $this->mcpClient->connect("github")->callTool("get_issue", $args); } ``` -------------------------------- ### Create Smart Support Agent Class Source: https://docs.laragent.ai/guides/rag/retrieval-as-tool Generates a new agent class file for the 'SmartSupportAgent' using the Artisan command-line tool. This command scaffolds the basic structure for a custom AI agent. ```bash php artisan make:agent SmartSupportAgent ``` -------------------------------- ### Manage Individual Agent Configurations (PHP) Source: https://docs.laragent.ai/v1/agents/creation Provides methods to set, get, check for the existence of, and remove individual configuration values for an agent at runtime. This allows for fine-grained control over agent settings. ```php // Set single config $agent->setConfig('custom_key', 'value'); // Get config $value = $agent->getConfig('custom_key'); // Check existence if ($agent->hasConfig('custom_key')) { // ... } // Remove config $agent->removeConfig('custom_key'); ``` -------------------------------- ### Create SQL Guardrail Agent using Artisan (PHP) Source: https://docs.laragent.ai/guides/rag/retrieval-as-tool This command generates a new agent class for SQL query validation using the Artisan command-line tool. It sets up the basic structure for the `SqlGuardAgent`. ```bash php artisan make:agent SqlGuardAgent ``` -------------------------------- ### LarAgent AgentDTO Structure Definition Source: https://docs.laragent.ai/v1/customization/events/setup Defines the structure of the `AgentDTO` class used by LarAgent events. This DTO contains information about the agent, including its provider, message, tools, and configuration. ```php namespace LarAgent\Core\DTO; class AgentDTO { public function __construct( public readonly string $provider, public readonly string $providerName, public readonly ?string $message, public readonly array $tools = [], public readonly ?string $instructions = null, public readonly ?array $responseSchema = [], public readonly array $configuration = [] ) {} public function toArray(): array { return [ 'provider' => $this->provider, 'providerName' => $this->providerName, 'message' => $this->message, 'tools' => $this->tools, 'instructions' => $this->instructions, 'responseSchema' => $this->responseSchema, 'configuration' => $this->configuration, ]; } } ``` -------------------------------- ### Register LarAgent Event Listener in Laravel Service Provider Source: https://docs.laragent.ai/v1/customization/events/setup Registers a custom listener for a specific LarAgent event within the `AppServiceProvider`. This ensures that your listener is invoked when the registered event is dispatched. ```php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Event; use LarAgent\Events\AgentInitialized; use App\Listeners\AgentListener; class AppServiceProvider extends ServiceProvider { public function register(): void { // } public function boot(): void { Event::listen( AgentInitialized::class, AgentListener::class ); } } ``` -------------------------------- ### Implement LarAgent Event Handling in Laravel Listener Source: https://docs.laragent.ai/v1/customization/events/setup Defines the `handle` method within a Laravel listener to process a specific LarAgent event, such as `AgentInitialized`. It shows how to access event data like the `agentDto`. ```php namespace App\Listeners; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; use LarAgent\Events\AgentInitialized; class AgentListener { public function __construct() { // } public function handle(AgentInitialized $event): void { // Access the agent DTO dd('Agent has been initialized:', $event->agentDto); } } ``` -------------------------------- ### Eloquent Storage Configuration Example Source: https://docs.laragent.ai/v1/context/storage-drivers Demonstrates how to configure the Eloquent storage driver within a Laravel Agent context. It shows how to use the default model or specify a custom model and customize column names for session keys and item ordering. ```php use LarAgent\Context\Drivers\EloquentStorage; protected function historyStorageDrivers(): string|array { // Use default model $storage = new EloquentStorage(); // Or use custom model $storage = new EloquentStorage(\App\Models\ChatMessage::class); // With custom column names $storage = (new EloquentStorage(\App\Models\ChatMessage::class)) ->setKeyColumn('chat_session_id') ->setPositionColumn('order'); return [$storage]; } ``` -------------------------------- ### Customize Agent Instructions with instructions() Method Source: https://docs.laragent.ai/v1/agents/creation The `instructions()` method allows you to define the system prompt for your agent, shaping its personality, role, and operational guidelines. This method returns a string that serves as the core instruction set for the LLM. ```php public function instructions() { return "You are an expert financial advisor. Provide clear, actionable advice while always recommending users consult with a certified professional for major decisions."; } ``` -------------------------------- ### Set and Get Message Extras (PHP) Source: https://docs.laragent.ai/guides/upgrade-to-v1 Shows how to use the `setExtra` and `getExtra` methods to store and retrieve custom or driver-specific data within a `Message` object. The `getExtras` method retrieves all stored extra data. ```php $message->setExtra('custom_field', 'value'); $value = $message->getExtra('custom_field'); $all = $message->getExtras(); ``` -------------------------------- ### Programmatic Testing of SmartSupportAgent in PHP Source: https://docs.laragent.ai/guides/rag/retrieval-as-tool Shows how to programmatically test the SmartSupportAgent in PHP for different scenarios, including authenticated user queries, documentation searches, and combined retrieval tasks. It utilizes the 'respond' method and checks for expected string content in the response. ```php use App\AiAgents\SmartSupportAgent; // Test with authenticated user $response = SmartSupportAgent::forUser(auth()->user()) ->respond('Show me my order history'); str_contains($response, "test_string"); // Test documentation search $response = SmartSupportAgent::for('test_session') ->respond('What is your refund policy?'); str_contains($response, "test_string"); // Test combined retrieval $response = SmartSupportAgent::forUser(auth()->user()) ->respond('Show my account details and explain how to upgrade to premium'); str_contains($response, "test_string"); ``` -------------------------------- ### Monitoring Token Usage with Context Window Size in PHP Source: https://docs.laragent.ai/guides/rag/vector-based Illustrates how to monitor token usage by setting a context window size. This is crucial for managing API costs and performance, especially when dealing with large amounts of context. The `$contextWindowSize` property can be adjusted as needed. ```php protected $contextWindowSize = 4000; // Adjust based on your needs ``` -------------------------------- ### Create Custom StorageDriver (PHP) Source: https://docs.laragent.ai/guides/upgrade-to-v1 Provides an example of creating a custom `StorageDriver` for custom storage logic within LarAgent. This class implements the `StorageDriver` contract, defining methods for reading, writing, and removing data from memory. ```php use LarAgent\Context\Contracts\StorageDriver; use LarAgent\Context\Contracts\SessionIdentity; class MyStorageDriver implements StorageDriver { public function readFromMemory(SessionIdentity $identity): ?array { // Your read logic } public function writeToMemory(SessionIdentity $identity, array $data): bool { // Your write logic } public function removeFromMemory(SessionIdentity $identity): bool { // Your remove logic } public static function make(?array $config = null): static { return new static(); } } ``` -------------------------------- ### Update ChatHistory getMessages() Usage (PHP) Source: https://docs.laragent.ai/guides/upgrade-to-v1 Shows the difference in using the `getMessages()` method from the ChatHistory interface. In v0.8, it returned a standard array, while in v1.0, it returns a `MessageArray` object. The example demonstrates how to iterate and access messages using both versions, highlighting new methods available on `MessageArray`. ```php $messages = $chatHistory->getMessages(); // returns array foreach ($messages as $msg) { ... } ``` ```php $messages = $chatHistory->getMessages(); // returns MessageArray foreach ($messages as $msg) { ... } // Still iterable count($messages); // Still countable $messages->all(); // Get as array if needed $messages->first(); // Get first message $messages->last(); // Get last message ``` -------------------------------- ### Update ToolCallMessage Constructor Calls (PHP) Source: https://docs.laragent.ai/guides/upgrade-to-v1 Illustrates how to update calls to the ToolCallMessage constructor. The first example shows the old v0.8 syntax, while the second shows the new v1.0 syntax. It also recommends using the `Message::toolCall` factory method for creating tool call messages. ```php new ToolCallMessage($toolCalls, $messageArray, $metadata); // $messageArray was typically the raw API response array ``` ```php new ToolCallMessage($toolCalls, $metadata); // Or use the factory method (recommended): Message::toolCall($toolCalls, $metadata); ``` -------------------------------- ### Implement Queueable Listener for Asynchronous Event Handling (PHP) Source: https://docs.laragent.ai/v1/customization/events/setup This snippet shows how to implement a queueable listener in PHP using LarAgent's `ShouldQueue` interface. It handles the `ConversationEnded` event asynchronously, logging conversation metrics. This approach is suitable for heavy processing tasks that should not block the main request thread. ```php namespace App\Listeners; use Illuminate\Contracts\Queue\ShouldQueue; use LarAgent\Events\ConversationEnded; class LogConversationMetrics implements ShouldQueue { public function handle(ConversationEnded $event): void { // This runs in the background $metrics = [ 'provider' => $event->agentDto->provider, 'tools_used' => count($event->agentDto->tools), 'response_length' => strlen($event->message?->getContent() ?? ''), ]; Analytics::track('conversation_completed', $metrics); } } ``` -------------------------------- ### Publish and Run Migrations for Simple Eloquent Storage Source: https://docs.laragent.ai/v1/context/storage-drivers This command publishes the migration files for the SimpleEloquentStorage driver and then executes them to prepare the database for simple JSON blob storage. ```bash # Publish and run migrationphp artisan la:publish simple-eloquent-storage php artisan migrate ``` -------------------------------- ### Get AI Usage Analytics Dashboard Data (PHP) Source: https://docs.laragent.ai/v1/context/usage-tracking This function retrieves usage data for a specified date range and returns it as a JSON response. It utilizes a UsageAnalyticsService to fetch total usage, usage by provider, and estimated costs. The date range can be specified via request parameters 'from' and 'to', defaulting to the start and end of the current month respectively. ```php public function dashboard(Request $request) { $from = $request->input('from', now()->startOfMonth()->format('Y-m-d')); $to = $request->input('to', now()->format('Y-m-d')); return response()->json([ 'total_usage' => $this->analytics->getTotalUsage($from, $to), 'by_provider' => $this->analytics->getUsageByProvider(), 'estimated_cost' => $this->analytics->estimateCost($from, $to), ]); } ``` -------------------------------- ### Configuring Multiple Drivers for Named Contexts in PHP Source: https://docs.laragent.ai/v1/context/facade Demonstrates how to specify multiple storage drivers for a named context using the `withDrivers()` method in PHP. This allows for flexible storage configurations when using `Context::named()` for administrative or cleanup tasks. ```php withDrivers([CacheStorage::class]) ->clearAllChats(); // Multiple drivers Context::named('SupportAgent') ->withDrivers([CacheStorage::class, FileStorage::class]) ->clearAllChats(); ?> ``` -------------------------------- ### Configuring Named Contexts and Drivers in PHP Source: https://docs.laragent.ai/v1/context/facade Explains how to use `Context::named()` to create a `NamedContextManager` in PHP, which is useful for administrative tasks. It details how to explicitly configure storage drivers using `withDrivers()` for operations that don't involve agent initialization. ```php withDrivers([CacheStorage::class]) ->clearAllChats(); ?> ``` -------------------------------- ### Static Method Tool Example Source: https://docs.laragent.ai/v1/tools/attribute-tools An example of defining a tool using a static method in PHP. This method is self-contained and performs a tax calculation without needing agent instance context. ```php #[Tool('Calculate tax')] public static function calculateTax(float $amount, string $state): float { return TaxService::calculate($amount, $state); } ``` -------------------------------- ### Log Conversation Start - PHP Source: https://docs.laragent.ai/v1/agents/hooks The onConversationStart hook is triggered at the beginning of each `respond` method call. This snippet logs the start of a new conversation, including the agent class and the initial message. ```php protected function onConversationStart() { Log::info('Starting new conversation', [ 'agent' => self::class, 'message' => $this->currentMessage() ]); } ``` -------------------------------- ### Handle Conversation Start Event Source: https://docs.laragent.ai/v1/customization/events/agent Listens for the ConversationStarted event, dispatched at the beginning of a new conversation turn. It provides the agent's configuration at the start of the conversation, useful for logging or initializing metrics. ```php use LarAgent\Events\ConversationStarted; public function handle(ConversationStarted $event): void { $message = $event->agentDto->message; // Log conversation start, initialize metrics, etc. ``` -------------------------------- ### Publish and Run Migrations for Eloquent Storage Source: https://docs.laragent.ai/v1/context/storage-drivers This command publishes the necessary migration files for the Eloquent storage driver and then runs the migrations to set up the database table. ```bash php artisan la:publish eloquent-storage php artisan migrate ``` -------------------------------- ### Getting Tracked Storage Keys and Identities Source: https://docs.laragent.ai/v1/context/identity Shows how to retrieve keys and identities associated with agent storages. This includes getting all tracked storage keys, filtering for chat history keys, and retrieving chat history identities. ```php // Get all tracked storage keys $keys = $agent->getStorageKeys(); // ['chatHistory_SupportAgent_user-123', 'usage_SupportAgent_user-123', ...] // Get chat history keys only $chatKeys = $agent->getChatKeys(); // Get chat history identities $chatIdentities = $agent->getChatIdentities(); ``` -------------------------------- ### Implement Document Search Tool in PHP Source: https://docs.laragent.ai/guides/rag/retrieval-as-tool Adds a document search tool to a SmartSupportAgent class. This tool uses semantic vector search via QdrantSearchService to find relevant documentation based on a query and a constrained limit. It handles cases where no documents are found and returns results as pretty-printed JSON. ```php use App\Enums\DocumentLimit; use App\Services\QdrantSearchService; // Add this method to your SmartSupportAgent class /** * Search documentation for unstructured information * * This tool searches through documentation, FAQs, guides, and policies * using semantic vector search. */ #[Tool( 'Search the documentation for unstructured information like FAQs, guides, policies, and procedures. Use this for conceptual questions or how-to queries.', [ 'query' => 'The search query or question to find relevant documentation for.', 'limit' => 'Number of documents to retrieve. Choose based on query complexity.', ] )] public function searchDocumentation(string $query, DocumentLimit $limit = DocumentLimit::THREE): string { try { // Search using Qdrant $searchService = new QdrantSearchService(); $documents = $searchService->search($query, $limit->value); // Check if we found any relevant documents if (empty($documents)) { return "No relevant documentation found for the query: {$query}"; } // Format and return results directly return json_encode($documents, JSON_PRETTY_PRINT); } catch (\Exception $e) { return "Error searching documentation: " . $e->getMessage(); } } ``` -------------------------------- ### Write Clear Tool Descriptions (PHP) Source: https://docs.laragent.ai/v1/tools/attribute-tools Provides examples of vague versus clear tool descriptions for LLM integration. Clear descriptions specify what the tool does, expected input formats, and return values, improving LLM's ability to select and use the tool correctly. This example uses PHP attributes for tool definition. ```php // ❌ Vague #[Tool('Get data')] public function getData($id) { ... } // ✅ Clear #[Tool('Retrieve customer order history by customer ID')] public function getOrderHistory( string $customerId ): array { ... } ``` -------------------------------- ### Configure Driver Chain for Storage Source: https://docs.laragent.ai/v1/context/storage-drivers Demonstrates how to configure multiple storage drivers in a chain for fallback functionality. The primary driver is used first, and subsequent drivers act as fallbacks for reading if the primary fails. Writing and removing operations are performed on all drivers in the chain. ```php protected $history = [ CacheStorage::class, // Primary: read first, write first FileStorage::class, // Fallback: used if primary fails on read ]; ``` -------------------------------- ### Programmatic Testing with SupportAgent in PHP Source: https://docs.laragent.ai/guides/rag/vector-based Demonstrates how to programmatically test the SupportAgent for both authenticated users and named sessions. It shows how to get responses and check for specific strings within those responses. This requires the App\AiAgents\SupportAgent class. ```php use App\AiAgents\SupportAgent; // For authenticated users $response = SupportAgent::forUser(auth()->user()) ->respond('How do I create a new email campaign?'); str_contains($response, "test_string"); // For named sessions $response = SupportAgent::for('test_session') ->respond('What are the pricing plans?'); str_contains($response, "test_string"); ``` -------------------------------- ### Implement Context-Aware Tools in PHP Source: https://docs.laragent.ai/v1/tools/other-tools Shows how to register tools dynamically based on runtime context, such as user authentication and permissions, in PHP. This allows for tools that are only available or relevant under specific conditions. ```php public function registerTools() { $user = auth()->user(); $tools = []; // Always available $tools[] = Tool::create('get_time', 'Get current server time') ->setCallback(fn() => now()->toIso8601String()); // User-specific tool $tools[] = Tool::create('get_my_orders', 'Get my recent orders') ->addProperty('limit', 'integer', 'Number of orders to return') ->setCallback(fn($limit = 5) => $user->orders()->latest()->take($limit)->get()->toArray() ); // Permission-based tool if ($user->can('view_reports')) { $tools[] = Tool::create('get_sales_report', 'Get sales report') ->addProperty('period', 'string', 'Time period', ['day', 'week', 'month']) ->setCallback(fn($period) => ReportService::sales($period)); } return $tools; } ``` -------------------------------- ### Registering Resources as Tools (PHP) Source: https://docs.laragent.ai/v1/tools/mcp Shows how to make resources available as callable tools by specifying them in the `$mcpServers` property with a ':resources' suffix. When registered this way, resources can be invoked by the agent, and their descriptions are automatically prefixed with 'Read the resource: '. ```php protected $mcpServers = [ 'mcp_everything:resources', ]; ``` -------------------------------- ### Debugging LarAgent: Monitor Tool Calls in PHP Source: https://docs.laragent.ai/guides/rag/retrieval-as-tool Provides a PHP code snippet demonstrating how to add logging to monitor tool calls, specifically for a 'queryDatabase' function. This helps in understanding which tools are being invoked during agent execution. ```php public function queryDatabase(string $query): string { \Log::info('Database query tool called', ['query' => $query]); // ... rest of implementation } ``` -------------------------------- ### Execute Review Analysis with AI Agent (PHP) Source: https://docs.laragent.ai/v1/responses/structured-output This PHP snippet demonstrates how to use the `ReviewAnalyzerAgent` to analyze a block of text containing product reviews. It shows how to instantiate the agent, call its `ask` method with the reviews, and then access the structured analysis results, including product name, average score, recommendation, and individual review sentiments. ```php $reviews = <<productName}\n"; echo "Average Score: {$analysis->averageScore}\n"; echo "Recommendation: {$analysis->recommendation}\n"; foreach ($analysis->reviews as $review) { echo "- {$review->sentiment} ({$review->confidence})\n"; } ``` -------------------------------- ### Log Agent Termination - PHP Source: https://docs.laragent.ai/v1/agents/hooks The onTerminate hook is called when the agent is being terminated. This example logs a success message upon agent termination, useful for monitoring and debugging. ```php protected function onTerminate() { Log::info('Agent terminated successfully'); } ``` -------------------------------- ### Find ToolCallMessage Usages (Bash) Source: https://docs.laragent.ai/guides/upgrade-to-v1 A bash command to recursively search for all occurrences of 'new ToolCallMessage' within PHP files in the current directory and its subdirectories. ```bash grep -rn "new ToolCallMessage" --include="*.php" ``` -------------------------------- ### Define API Routes for Multiple Agents in Laravel Source: https://docs.laragent.ai/v1/agents/agent-via-api Define POST and GET routes for chat completions and models respectively, pointing to the methods in your `MultiAgentController` implementation. ```php Route::post('/v1/chat/completions', [AgentsController::class, 'completion']); Route::get('/v1/models', [AgentsController::class, 'models']); ``` -------------------------------- ### PHP: Using String Aliases for Storage Source: https://docs.laragent.ai/v1/context/overview Demonstrates how to use convenient string aliases for `$usageStorage` and `$history` properties in PHP. These aliases map to specific driver classes for storage management. ```php class SupportAgent extends Agent { // Using alias for usage protected $usageStorage = 'cache'; // Using alias for history protected $history = 'database'; } ``` -------------------------------- ### Define API Routes for Single Agent in Laravel Source: https://docs.laragent.ai/v1/agents/agent-via-api Define POST and GET routes for chat completions and models respectively, pointing to the methods in your `SingleAgentController` implementation. ```php Route::post('/v1/chat/completions', [MyAgentApiController::class, 'completion']); Route::get('/v1/models', [MyAgentApiController::class, 'models']); ``` -------------------------------- ### Environment Variables Configuration (.env) Source: https://docs.laragent.ai/guides/rag/vector-based Specifies the necessary environment variables for configuring the OpenAI API key and Qdrant connection details, including host and API key. These are essential for the AI agent and vector database integration. ```env OPENAI_API_KEY=your_openai_api_key_here # Qdrant Configuration QDRANT_HOST=http://localhost:6333 QDRANT_API_KEY=your_qdrant_api_key ``` -------------------------------- ### Configure Anthropic (Claude) Provider in Laragent Source: https://docs.laragent.ai/v1/agents/llm-drivers Configures the Anthropic Claude driver for Laragent. Requires an ANTHROPIC_API_KEY in the .env file. This setup is done within the config/laragent.php file. ```php 'claude' => [ 'label' => 'anthropic', 'api_key' => env('ANTHROPIC_API_KEY'), 'driver' => \LarAgent\Drivers\Anthropic\ClaudeDriver::class, 'model' => 'claude-sonnet-4-20250514', ], ``` -------------------------------- ### Add Inline Tools at Runtime with PHP Source: https://docs.laragent.ai/v1/tools/other-tools Demonstrates how to add custom tools to an agent at runtime using the `withTool()` method in PHP. This is useful for dynamic or context-dependent tool creation, such as for quick prototypes. ```php $tool = Tool::create('custom_tool', 'Do something custom') ->addProperty('input', 'string', 'The input value') ->setCallback(fn($input) => processInput($input)); $response = MyAgent::for('user-123') ->withTool($tool) ->respond('Use the custom tool'); ``` -------------------------------- ### LarAgent Fluent API Reference for Tool Creation in PHP Source: https://docs.laragent.ai/v1/tools/other-tools Provides a reference for the fluent API used to create inline tools in LarAgent. Key methods include `Tool::create()` to initialize a tool, `addProperty()` to define parameters, `setRequired()` to specify mandatory parameters, and `setCallback()` to assign the tool's execution logic. ```php Tool::create(string $name, string $description) ->addProperty(string $name, string $type, string $description, ?array $enum = null) ->setRequired(string|array $properties) ->setCallback(callable $callback); ``` -------------------------------- ### Laravel Streaming with Structured Output Source: https://docs.laragent.ai/v1/responses/streaming Example of handling streamed responses that eventually resolve to structured data in Laravel. It iterates through chunks, identifying partial messages and the final structured array. ```php $agent = ProfileAgent::for('user-123'); $stream = $agent->respondStreamed('Generate a profile for John Doe'); $finalStructuredData = null; foreach ($stream as $chunk) { if ($chunk instanceof \LarAgent\Messages\StreamedAssistantMessage) { echo $chunk->getLastChunk(); // Part of JSON } elseif (is_array($chunk)) { // This is the final structured data $finalStructuredData = $chunk; } } // Now $finalStructuredData is array which contains the structured output // For example: ['name' => 'John Doe', 'age' => 30, 'interests' => [...]] ```