### Basic Agent Usage: Simple Response Source: https://github.com/maestroerror/docs/blob/main/quickstart.mdx Shows how to instantiate an agent and get a response to a user query. It demonstrates creating an agent instance for a specific user session and calling the `respond` method. ```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..." ``` -------------------------------- ### Install LarAgent via Composer Source: https://github.com/maestroerror/docs/blob/main/quickstart.mdx Installs the LarAgent package using Composer, the dependency manager for PHP. This is the primary step to include the library in your Laravel project. ```bash composer require maestroerror/laragent ``` -------------------------------- ### Example Custom Provider Configuration Source: https://github.com/maestroerror/docs/blob/main/quickstart.mdx Demonstrates how to configure a custom LLM provider in `config/laragent.php`. This includes all possible settings like API key, URL, model, driver, context window, temperature, and options for parallel tool calls and metadata storage. ```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_context_window' => 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 Mintlify CLI Source: https://github.com/maestroerror/docs/blob/main/README.md Installs the Mintlify command-line interface globally using npm. This is a prerequisite for using Mintlify's development and publishing features. ```bash npm i -g mintlify ``` -------------------------------- ### Example Weather Agent Implementation in PHP Source: https://github.com/maestroerror/docs/blob/main/DOCS.md Provides a practical example of a `WeatherAgent` class, showcasing how to set configuration properties and override methods for specific functionality. This demonstrates a complete agent setup. ```php class WeatherAgent extends Agent { protected $model = 'gpt-4'; protected $history = 'cache'; protected $temperature = 0.7; public function instructions() { return "You are a weather expert assistant. Provide accurate weather information."; } public function prompt(string $message) { return "Weather query: " . $message; } } ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/maestroerror/docs/blob/main/development.mdx Install the project's dependencies using Composer. This command downloads and installs all required PHP packages listed in the composer.json file. ```bash composer install ``` -------------------------------- ### Complete Agent Example with Tools and Structured Output (PHP) Source: https://github.com/maestroerror/docs/blob/main/core-concepts/usage-without-laravel.mdx A comprehensive example demonstrating the setup of LarAgent for non-Laravel projects. It includes configuring the driver and chat history, defining a tool with properties and a callback, specifying a structured output schema for responses, setting custom instructions, and running the agent with a user message. ```php use LarAgent\Drivers\OpenAi\OpenAiDriver; use LarAgent\History\InMemoryChatHistory; use LarAgent\LarAgent; use LarAgent\Message; use LarAgent\Messages\ToolCallMessage; use LarAgent\Tool; // Setup $driver = new OpenAiDriver(['api_key' => $yourApiKey]); $chatHistory = new InMemoryChatHistory('weather-chat'); $agent = LarAgent::setup($driver, $chatHistory, [ 'model' => 'gpt-4o-mini', ]); // Create a weather tool $weatherTool = Tool::create('get_current_weather', 'Get the current weather in a given location') ->addProperty('location', 'string', 'The city and state, e.g. San Francisco, CA') ->addProperty('unit', 'string', 'The unit of temperature', ['celsius', 'fahrenheit']) ->setRequired('location') ->setCallback(function ($location, $unit = 'fahrenheit') { return 'The weather in '.$location.' is 72 degrees '.$unit; }); // Define structured output schema $weatherInfoSchema = [ 'name' => 'weather_info', 'schema' => [ 'type' => 'object', 'properties' => [ 'locations' => [ 'type' => 'array', 'items' => [ 'type' => 'object', 'properties' => [ 'city' => ['type' => 'string'], 'weather' => ['type' => 'string'], ], 'required' => ['city', 'weather'], ], ], ], 'required' => ['locations'], ], 'strict' => true, ]; // Set up the agent with all components $userMessage = Message::user('What\'s the weather like in Boston and Los Angeles? I prefer celsius'); $instructions = 'You are weather assistant and always respond using celsius. If it provided as fahrenheit, convert it to celsius.'; $agent->setTools([$weatherTool]) ->structured($weatherInfoSchema) ->withInstructions($instructions) ->withMessage($userMessage); // Get the structured response $response = $agent->run(); ``` -------------------------------- ### Run Mintlify Development Server Source: https://github.com/maestroerror/docs/blob/main/README.md Starts the Mintlify development server from the root directory of your documentation project. This command allows you to preview changes locally. ```bash mintlify dev ``` -------------------------------- ### Publish LarAgent Configuration Source: https://github.com/maestroerror/docs/blob/main/quickstart.mdx Publishes the configuration file for LarAgent to your Laravel application. This command creates a `config/laragent.php` file, allowing you to customize settings. ```bash php artisan vendor:publish --tag="laragent-config" ``` -------------------------------- ### Example Tool Class Implementation Source: https://github.com/maestroerror/docs/blob/main/DOCS.md Provides an example of a custom tool class extending `LarAgent\Tool`. It defines the tool's name, description, properties, required parameters, and the `execute` method containing the tool's logic. ```php class WeatherTool extends LarAgent\Tool { protected string $name = 'get_current_weather'; protected string $description = 'Get the current weather in a given location'; protected array $properties = [ 'location' => [ 'type' => 'string', 'description' => 'The city and state, e.g. San Francisco, CA', ], 'unit' => [ 'type' => 'string', 'description' => 'The unit of temperature', 'enum' => ['celsius', 'fahrenheit'], ], ]; protected array $required = ['location']; protected array $metaData = ['sent_at' => '2024-01-01']; public function execute(array $input): mixed { // Call the weather API return 'The weather in '.$input['location'].' is '.rand(10, 60).' degrees '.$input['unit']; } } ``` -------------------------------- ### Configure OpenAI API Key Source: https://github.com/maestroerror/docs/blob/main/quickstart.mdx Sets the OpenAI API key in your application's `.env` file. This is required for LarAgent to authenticate with the OpenAI service. ```dotenv OPENAI_API_KEY=your-openai-api-key ``` -------------------------------- ### Agent Usage: Adding Tools Source: https://github.com/maestroerror/docs/blob/main/quickstart.mdx Illustrates how to define tools for an agent using PHP attributes. The `#[Tool]` attribute describes the tool's purpose and its parameters, allowing the agent to call this method when needed. ```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}."; } } ``` -------------------------------- ### Maestro Agent Chainable Syntax Examples Source: https://github.com/maestroerror/docs/blob/main/DOCS.md Demonstrates the fluent, chainable syntax for interacting with the Maestro Agent, allowing for method chaining to configure agent behavior before execution. Includes examples for setting messages, overriding parameters like temperature, and managing conversation contexts. ```php $response = WeatherAgent::for('test_chat') ->message('What is the weather like?') // Set the message ->temperature(0.7) // Optional: Override temperature ->respond(); // Get the response ``` ```php // Different histories for different users echo WeatherAgent::for('user_1_chat')->respond('What is the weather like?'); echo WeatherAgent::for('user_2_chat')->respond('How about tomorrow?'); echo WeatherAgent::forUser(auth()->user())->respond('How about tomorrow?'); ``` -------------------------------- ### Install LarAgent Package Source: https://github.com/maestroerror/docs/blob/main/DOCS.md Installs the LarAgent package using Composer. This is the primary method to add the library to your Laravel project. ```bash composer require maestroerror/laragent ``` -------------------------------- ### Default LarAgent Configuration Source: https://github.com/maestroerror/docs/blob/main/quickstart.mdx The default configuration array for LarAgent, defining the default LLM driver, chat history implementation, and namespaces for AI agents. It also lists supported providers with their specific 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_context_window' => 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_context_window' => 1000000, 'default_max_completion_tokens' => 10000, 'default_temperature' => 1, ], 'groq' => [ 'label' => 'groq', 'api_key' => env('GROQ_API_KEY'), 'api_url' => 'https://api.groq.com/openai/v1', 'model' => 'llama-3.1-8b-instant', 'driver' => \LarAgent\Drivers\Groq\GroqDriver::class, 'default_context_window' => 131072, 'default_max_completion_tokens' => 131072, 'default_temperature' => 1, ], ], 'fallback_provider' => 'default', ]; ``` -------------------------------- ### Create Agent using Artisan Command Source: https://github.com/maestroerror/docs/blob/main/quickstart.mdx Generates a new agent class file using the `make:agent` Artisan command. This command creates the necessary boilerplate code for a new AI agent in the specified namespace (defaulting to `App\AiAgents`). ```bash php artisan make:agent WeatherAgent ``` -------------------------------- ### Example Agent Configuration Source: https://github.com/maestroerror/docs/blob/main/core-concepts/agents.mdx Demonstrates how to define a custom agent class by extending the base Agent class and setting properties like model, history, and temperature, along with defining instructions and prompt formatting. ```php class WeatherAgent extends Agent { protected $model = 'gpt-4o'; protected $history = 'session'; protected $temperature = 0.7; public function instructions() { return "You are a weather expert assistant. Provide accurate weather information."; } public function prompt(string $message) { return "Weather query: " . $message; } } ``` -------------------------------- ### PHP: SingleAgentController Example Source: https://github.com/maestroerror/docs/blob/main/core-concepts/agent-via-api.mdx Provides an example of extending `SingleAgentController` to expose a single agent via an API. Key steps include setting the `$agentClass` property to the agent's class and the `$models` property to specify available models. ```php namespace App\Http\Controllers; use LarAgent\API\Completion\Controllers\SingleAgentController; class MyAgentApiController extends SingleAgentController { protected ?string $agentClass = \App\AiAgents\MyAgent::class; protected ?array $models = ['gpt-4o-mini']; } ``` -------------------------------- ### Example Structured Response in PHP Source: https://github.com/maestroerror/docs/blob/main/core-concepts/structured-output.mdx Illustrates the expected output format when a complex structured output schema is defined and an agent processes a request. ```php // Example response when using the complex schema above $response = $agent->respond("What's the weather like today?"); // Returns: [ 'temperature' => 25.5, 'conditions' => 'sunny', 'forecast' => [ ['day' => 'tomorrow', 'temp' => 28], ['day' => 'Wednesday', 'temp' => 24] ] ] ``` -------------------------------- ### Run Agent for a Specific User Source: https://github.com/maestroerror/docs/blob/main/introduction.mdx Provides an example of how to instantiate and run an AI agent for a particular user, leveraging Laravel's authentication. This ensures that the agent's context and history are tied to the specific user interacting with it. ```php Use App\AiAgents\YourAgentName; // ... YourAgentName::forUser(auth()->user())->respond($message); ``` -------------------------------- ### Initialize LarAgent with Chat History Outside Laravel Source: https://github.com/maestroerror/docs/blob/main/core-concepts/chat-history.mdx Provides an example of setting up the LarAgent outside of a Laravel framework, demonstrating how to instantiate drivers and chat history implementations like `InMemoryChatHistory` or `JsonChatHistory` and then passing them to the agent setup. ```php use LarAgent\History\InMemoryChatHistory; use LarAgent\History\JsonChatHistory; use LarAgent\Drivers\OpenAi\OpenAiDriver; use LarAgent\LarAgent; $driver = new OpenAiDriver(['api_key' => 'your-api-key']); // Stores chat history in memory (lost after each request) $history = new InMemoryChatHistory('user-123'); // Or in JSON files $history = new JsonChatHistory('user-123', ['folder' => __DIR__.'/json_History']); // Setup LarAgent $agent = LarAgent::setup($driver, $history, [ 'model' => 'gpt-4', // or any other model ]); ``` -------------------------------- ### Chainable Agent Methods Source: https://github.com/maestroerror/docs/blob/main/core-concepts/agents.mdx Illustrates using chainable syntax for more control over agent interactions, allowing sequential setting of messages, parameters, and models before getting a response. ```php $response = WeatherAgent::for('test_chat') ->message('What is the weather like?') // Set the message ->temperature(0.7) // Optional: Override temperature ->respond(); // Get the response ``` ```php // Override default settings echo WeatherAgent::for('user_1_chat') ->message('What is the weather like?') ->withModel('gpt-4o') ->withTemperature(0.7) ->withMaxTokens(2000) ->withN(3) ->withTool(new WeatherTool()) ->respond(); ``` -------------------------------- ### Example Provider Configurations Source: https://github.com/maestroerror/docs/blob/main/core-concepts/llm-drivers.mdx Demonstrates how to configure multiple LLM providers, including 'default', 'ollama', and 'gemini', within the LarAgent configuration. It shows essential settings like model names, API keys, and driver classes. ```php return [ // ... 'providers' => [ 'default' => [ 'name' => 'openai', 'model' => 'gpt-4o-mini', 'driver' => \LarAgent\Drivers\OpenAi\OpenAiCompatible::class, 'api_key' => env('OPENAI_API_KEY'), 'default_context_window' => 50000, 'default_max_completion_tokens' => 100, 'default_temperature' => 1, ], 'ollama' => [ 'name' => 'ollama-local', // Required configs for fallback provider: 'model' => 'llama3.2', 'api_key' => 'ollama', 'api_url' => "http://localhost:11434/v1", 'driver' => \LarAgent\Drivers\OpenAi\OpenAiCompatible::class, ], 'gemini' => [ 'name' => 'gemini provider', 'model' => 'model-GEMINI', 'driver' => \LarAgent\Drivers\OpenAi\GeminiDriver::class, 'api_key' => env('GEMINI_API_KEY'), 'default_context_window' => 500000, 'default_max_completion_tokens' => 10000, 'default_temperature' => 0.8, ], ], 'fallback_provider' => 'ollama', ]; ``` -------------------------------- ### API Request Example: Chat Completions Source: https://github.com/maestroerror/docs/blob/main/core-concepts/agent-via-api.mdx This bash command demonstrates how to make a POST request to the /v1/chat/completions endpoint. It includes setting the Content-Type header to application/json and providing a JSON payload with the model name and user messages. ```bash curl -X POST /v1/chat/completions \ -H 'Content-Type: application/json' \ -d '{ "model": "MyAgent/gpt-4o-mini", "messages": [ {"role":"user","content":"Hello"} ], }' ``` -------------------------------- ### Provider Driver Unit Testing Example (PHPUnit) Source: https://github.com/maestroerror/docs/blob/main/customization/custom-driver.mdx Demonstrates how to write unit tests for a custom provider driver using PHPUnit. It includes setting up the driver, mocking provider responses, and asserting the correctness of methods like `sendMessage` for both standard and tool-call responses. ```php driver = new YourProviderDriver([ 'api_key' => 'test_key', 'model' => 'test_model', ]); } public function testSendMessage() { // Mock your provider's client response $this->mockClientResponse(); $messages = [ ['role' => 'system', 'content' => 'You are a helpful assistant.'], ['role' => 'user', 'content' => 'Hello!'], ]; $response = $this->driver->sendMessage($messages); $this->assertInstanceOf(AssistantMessage::class, $response); $this->assertEquals('Hello! How can I help you today?', $response->getContent()); } public function testSendMessageWithToolCalls() { // Mock your provider's client response for tool calls $this->mockClientToolCallResponse(); $messages = [ ['role' => 'user', 'content' => 'What\'s the weather?'], ]; $response = $this->driver->sendMessage($messages); $this->assertInstanceOf(ToolCallMessage::class, $response); $this->assertEquals('get_weather', $response->getToolCalls()[0]->getToolName()); } // Add more tests for other methods } ``` -------------------------------- ### Example Structured Output Response Source: https://github.com/maestroerror/docs/blob/main/DOCS.md Presents an example of the expected array format for an AI agent's response when structured output is defined and enabled, conforming to the specified schema. ```php // Returns: [ 'temperature' => 25.5, 'conditions' => 'sunny', 'forecast' => [ ['day' => 'tomorrow', 'temp' => 28], ['day' => 'Wednesday', 'temp' => 24] ] ] ``` -------------------------------- ### Create AI Agent Source: https://github.com/maestroerror/docs/blob/main/core-concepts/commands.mdx Generates a new AI agent class with default configurations for model, chat history, provider, tools, instructions, and prompts. This command streamlines the initial setup for new agents. ```bash php artisan make:agent AgentName ``` -------------------------------- ### Configure Gemini LLM Driver (PHP) Source: https://github.com/maestroerror/docs/blob/main/core-concepts/llm-drivers.mdx Configures the Gemini driver for interacting with Google's Gemini API, often via an OpenAI-compatible endpoint. This setup includes the driver class, API key, and specific default parameters like context window and temperature for Gemini models. ```php 'gemini' => [ 'label' => 'gemini', 'model'=>'gemini-2.5-pro-preview-03-25', 'api_key' => env('GEMINI_API_KEY'), 'driver' => \LarAgent\Drivers\OpenAi\GeminiDriver::class, 'default_context_window' => 1000000, 'default_max_completion_tokens' => 10000, 'default_temperature' => 1, ], ``` -------------------------------- ### Start Interactive Agent Chat Source: https://github.com/maestroerror/docs/blob/main/core-concepts/commands.mdx Initiates an interactive command-line chat session with a specified AI agent. Users can send messages, receive real-time responses, utilize agent tools, and manage chat history by providing a history name. Type 'exit' to end the session. ```bash # Start a chat with default history name php artisan agent:chat AgentName # Start a chat with a specific history name php artisan agent:chat AgentName --history=weather_chat_1 ``` -------------------------------- ### Custom LarAgent Provider Configuration Source: https://github.com/maestroerror/docs/blob/main/DOCS.md An example of a custom provider configuration within LarAgent. This demonstrates how to define specific settings for different LLM providers, including API keys, model names, and driver classes. ```php // Example custom provider with all possible configurations 'custom_provider' => [ // Just name for reference, changes nothing 'label' => 'mini', 'model' => 'gpt-3.5-turbo', 'api_key' => env('CUSTOM_API_KEY'), 'api_url' => env('CUSTOM_API_URL'), // Default driver and chat history 'driver' => \LarAgent\Drivers\OpenAi\OpenAiDriver::class, 'chat_history' => \LarAgent\History\InMemoryChatHistory::class, 'default_context_window' => 15000, 'default_max_completion_tokens' => 100, 'default_temperature' => 1, // 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, ], ``` -------------------------------- ### Configure Ollama LLM Driver (PHP) Source: https://github.com/maestroerror/docs/blob/main/core-concepts/llm-drivers.mdx Configures the Ollama driver for local LLM interaction. This setup involves specifying the driver class, an API URL pointing to the local Ollama instance, and a placeholder API key, enabling the application to connect to and utilize local models. ```php 'providers' => [ 'ollama' => [ 'label' => 'ollama-local', 'driver' => \LarAgent\Drivers\OpenAi\OpenAiCompatible::class, 'api_key' => 'ollama', // Can be any string for Ollama 'api_url' => "http://localhost:11434/v1", 'default_context_window' => 50000, 'default_max_completion_tokens' => 100, 'default_temperature' => 1, ], ], ``` -------------------------------- ### API Response Example: Chat Completion Source: https://github.com/maestroerror/docs/blob/main/core-concepts/agent-via-api.mdx This JSON object represents a successful response from a chat completion API call. It includes a unique ID, object type, creation timestamp, model used, the assistant's message, finish reason, and token usage statistics. ```json { "id": "MyAgent_abcd1234", "object": "chat.completion", "created": 1753357877, "model": "gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hi!" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15 } } ``` -------------------------------- ### PHP: MultiAgentController Example Source: https://github.com/maestroerror/docs/blob/main/core-concepts/agent-via-api.mdx Illustrates extending `MultiAgentController` to expose multiple agents under a single API endpoint. Configuration involves setting the `$agents` property with agent class names and the `$models` property with model identifiers, potentially including agent-specific model mappings. ```php namespace App\Http\Controllers; use LarAgent\API\Completion\Controllers\MultiAgentController; class AgentsController extends MultiAgentController { protected ?array $agents = [ \App\AiAgents\ChatAgent::class, \App\AiAgents\SupportAgent::class, ]; protected ?array $models = [ 'ChatAgent/gpt-4o-mini', 'SupportAgent/gpt-4.1-mini', 'SupportAgent', ]; } ``` -------------------------------- ### PHP: Accessing Chat History Methods Source: https://github.com/maestroerror/docs/blob/main/core-concepts/chat-history.mdx Provides examples of common methods to retrieve information from the chat history instance. These include getting all messages, the last message, message count, identifier, and converting history to arrays. ```php // Get the current chat history instance $history = $agent->chatHistory(); // Get all messages in the chat history $messages = $history->getMessages(); // Get the last message (MessageInterface) $lastMessage = $history->getLastMessage(); // Count messages in history $count = $history->count(); // Get the chat history identifier $identifier = $history->getIdentifier(); // Convert messages to array $messagesArray = $history->toArray(); // Convert messages to array with metadata $messagesWithMeta = $history->toArrayWithMeta(); ``` -------------------------------- ### GET /plants API Endpoint Source: https://github.com/maestroerror/docs/blob/main/api-reference/endpoint/get.mdx This entry documents the GET request to the /plants endpoint. It is used to retrieve a list of available plants. No specific parameters are required for this basic retrieval. ```APIDOC GET /plants title: Get Plants description: Retrieves a list of plants. responses: 200: description: A list of plants. content: application/json: schema: type: array items: type: object properties: id: type: integer description: Unique identifier for the plant. name: type: string description: The name of the plant. species: type: string description: The species of the plant. ``` -------------------------------- ### Define Agent Properties and Instructions Source: https://github.com/maestroerror/docs/blob/main/introduction.mdx Demonstrates how to extend the base `Agent` class in PHP to define an AI agent. It shows setting the AI model, chat history mechanism, provider, and defining the agent's core instructions and prompt handling. ```php namespace App\AiAgents; use LarAgent\Agent; class YourAgentName extends Agent { protected $model = 'gpt-4'; protected $history = 'in_memory'; protected $provider = 'default'; protected $tools = []; public function instructions() { return "Define your agent's instructions here."; } public function prompt($message) { return $message; } } ``` -------------------------------- ### PHP: Log Conversation Start Source: https://github.com/maestroerror/docs/blob/main/customization/events.mdx This hook is triggered at the beginning of each respond method call. It's useful for preparing conversation-specific resources or implementing detailed logging for the start of a new conversation step. ```php protected function onConversationStart() { Log::info( 'Starting new conversation', [ 'agent' => self::class, 'message' => $this->currentMessage() ] ); } ``` -------------------------------- ### PHP: Create Laravel Event Listener Source: https://github.com/maestroerror/docs/blob/main/DOCS.md An example of a Laravel event listener that handles the `AgentMessageReceived` event. It logs information about the received agent message. ```php $event->message->getContent(), 'tokens' => Tokenizer::count($event->message->getContent()), 'history_id' => $event->history->getIdentifier() ]); } } ``` -------------------------------- ### Configure Chat History Storage Source: https://github.com/maestroerror/docs/blob/main/DOCS.md Example of how to specify a custom chat history storage mechanism, such as using Laravel's cache system, by providing the class name. ```php // ... protected $history = \LarAgent\History\CacheChatHistory::class; // ... ``` -------------------------------- ### Run All Tests (Bash) Source: https://github.com/maestroerror/docs/blob/main/development.mdx Execute the entire test suite using PEST. This command verifies that all existing functionality remains intact and that new changes do not introduce regressions. ```bash composer test ``` -------------------------------- ### PHP: Backup Chat History Source: https://github.com/maestroerror/docs/blob/main/customization/events.mdx Triggered before the agent's chat history is cleared, this hook allows for pre-clearance operations. This example backs up the current chat history to a JSON file. ```php protected function onClear() { // Backup chat history file_put_contents('backup.json', json_encode($this->chatHistory()->toArrayWithMeta())); } ``` -------------------------------- ### Plant Store API Authentication and Specification Source: https://github.com/maestroerror/docs/blob/main/api-reference/introduction.mdx Details the authentication method for the Plant Store API, which uses Bearer tokens. It also references the OpenAPI specification file for a complete list of endpoints and their details. ```APIDOC API Documentation Approach: - Supports OpenAPI and MDX components. - Starter kit uses an OpenAPI specification. Plant Store API: - Endpoints: Defined in openapi.json (viewable at https://github.com/mintlify/starter/blob/main/api-reference/openapi.json). - Authentication: - Method: Bearer tokens. - Configuration: Defined in the OpenAPI specification file. - Example Security Scheme: "security": [ { "bearerAuth": [] } ] ``` -------------------------------- ### Bash: Start Interactive Agent Chat Source: https://github.com/maestroerror/docs/blob/main/DOCS.md Initiates an interactive chat session with a specified agent using the `agent:chat` command. It supports specifying a custom history name for the session. ```bash # Start a chat with default history name php artisan agent:chat AgentName # Start a chat with a specific history name php artisan agent:chat AgentName --history=weather_chat_1 ``` -------------------------------- ### Product Recommendations Schema (PHP) Source: https://github.com/maestroerror/docs/blob/main/core-concepts/structured-output.mdx Defines a JSON schema for product recommendations, including a list of products with their ID, name, reason for recommendation, and score, along with a category. This schema helps structure personalized product suggestions. ```php protected $responseSchema = [ 'name' => 'product_recommendations', 'schema' => [ 'type' => 'object', 'properties' => [ 'products' => [ 'type' => 'array', 'items' => [ 'type' => 'object', 'properties' => [ 'id' => ['type' => 'string'], 'name' => ['type' => 'string'], 'reason' => ['type' => 'string'], 'score' => ['type' => 'number'], ], 'required' => ['id', 'name', 'reason'], 'additionalProperties' => false, ], ], 'category' => ['type' => 'string'], ], 'required' => ['products', 'category'], 'additionalProperties' => false, ], 'strict' => true, ]; ``` -------------------------------- ### Interact with Agent for Direct Response in PHP Source: https://github.com/maestroerror/docs/blob/main/DOCS.md Illustrates the simplest method for interacting with an agent, using the `for()` method to specify a chat history name and then calling `respond()` to get an immediate AI-generated response. ```php // Using a specific chat history name echo WeatherAgent::for('test_chat')->respond('What is the weather like?'); ``` -------------------------------- ### Clone LarAgent Repository (Bash) Source: https://github.com/maestroerror/docs/blob/main/development.mdx Clone the LarAgent repository from GitHub to your local machine. This is the first step in setting up your development environment. Ensure you replace YOUR_USERNAME with your GitHub username. ```bash git clone https://github.com/YOUR_USERNAME/LarAgent.git cd LarAgent ``` -------------------------------- ### API Security Configuration Source: https://github.com/maestroerror/docs/blob/main/api-reference/introduction.mdx This JSON snippet defines the security scheme for the API, specifying that authentication is handled using Bearer tokens. ```json { "security": [ { "bearerAuth": [] } ] } ``` -------------------------------- ### Run Tests with Coverage Report (Bash) Source: https://github.com/maestroerror/docs/blob/main/development.mdx Run the test suite and generate a code coverage report. This helps identify parts of the code that are not adequately tested. ```bash composer test-coverage ``` -------------------------------- ### PHP: Log Agent Termination Source: https://github.com/maestroerror/docs/blob/main/customization/events.mdx This hook is called when the agent is being terminated. It's the ideal place for final cleanup, saving state, or closing connections. This example logs a success message upon termination. ```php protected function onTerminate() { Log::info('Agent terminated successfully'); } ``` -------------------------------- ### PHP: Update Tool Metadata Source: https://github.com/maestroerror/docs/blob/main/customization/events.mdx This hook is triggered when a tool is added to or removed from the agent. It receives the tool instance and a boolean indicating the action. This example updates metadata for a specific tool when it's added. ```php /** * @param ToolInterface $tool * @param bool $added */ protected function onToolChange($tool, $added = true) { // If 'my_tool' tool is added if($added && $tool->getName() == 'my_tool') { // Update metadata $newMetaData = ['using_in' => self::class, ...$tool->getMetaData()]; $tool->setMetaData($newMetaData); } } ``` -------------------------------- ### Basic Streaming with respondStreamed Source: https://github.com/maestroerror/docs/blob/main/core-concepts/streaming.mdx Demonstrates the basic usage of the `respondStreamed` method to receive AI responses in chunks. It iterates through the stream and echoes the last chunk of assistant messages. ```php $agent = WeatherAgent::for('user-123'); $stream = $agent->respondStreamed('What\'s the weather like in Boston and Los Angeles?'); foreach ($stream as $chunk) { if ($chunk instanceof \LarAgent\Messages\StreamedAssistantMessage) { echo $chunk->getLastChunk(); // Output each new piece of content } } ``` -------------------------------- ### Create Plant Endpoint Source: https://github.com/maestroerror/docs/blob/main/api-reference/endpoint/create.mdx This API endpoint allows for the creation of a new plant resource. It uses the POST HTTP method to submit plant data. ```APIDOC POST /plants summary: Create a new plant operationId: createPlant tags: - Plants requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The name of the plant. example: "Ficus Benghalensis" species: type: string description: The scientific species name of the plant. example: "Ficus benghalensis" watering_frequency_days: type: integer description: How often the plant should be watered in days. example: 7 light_requirements: type: string description: The light conditions the plant prefers. example: "Bright indirect light" required: - name - species responses: '201': description: Plant created successfully content: application/json: schema: type: object properties: id: type: string description: The unique identifier for the created plant. example: "plant-12345" name: type: string description: The name of the plant. example: "Ficus Benghalensis" species: type: string description: The scientific species name of the plant. example: "Ficus benghalensis" watering_frequency_days: type: integer description: How often the plant should be watered in days. example: 7 light_requirements: type: string description: The light conditions the plant prefers. example: "Bright indirect light" '400': description: Bad Request - Invalid input provided '500': description: Internal Server Error ``` -------------------------------- ### PHP: Save Conversation History Source: https://github.com/maestroerror/docs/blob/main/customization/events.mdx Called at the end of each respond method, this hook allows for cleanup, logging, or saving data. It runs even for the last chunk in streaming scenarios. This example saves the last response to a database table. ```php /** @param MessageInterface|array|null $message */ protected function onConversationEnd($message) { // Clean the history $this->clear(); // Save the last response DB::table('chat_histories')->insert( [ 'chat_session_id' => $this->chatHistory()->getIdentifier(), 'message' => $message, ] ); } ``` -------------------------------- ### Create a New Agent Source: https://github.com/maestroerror/docs/blob/main/introduction.mdx Generates a new AI agent class file using the Artisan command-line tool. This command sets up the basic structure for a custom AI agent within your Laravel application. ```bash php artisan make:agent YourAgentName ``` -------------------------------- ### Configure OpenRouter LLM Driver (PHP) Source: https://github.com/maestroerror/docs/blob/main/core-concepts/llm-drivers.mdx Sets up the OpenRouter driver, which connects to the OpenRouter API. This configuration requires an API key from OpenRouter and specifies the API URL, enabling access to a wide range of models available through their platform. ```php 'providers' => [ 'openrouter' => [ 'label' => 'openrouter-provider', 'driver' => \LarAgent\Drivers\OpenAi\OpenAiCompatible::class, 'api_key' => env('OPENROUTER_API_KEY'), 'api_url' => "https://api.openrouter.ai/api/v1", 'default_context_window' => 50000, 'default_max_completion_tokens' => 100, 'default_temperature' => 1, ], ], ``` -------------------------------- ### Setup Agent with Chat History (PHP) Source: https://github.com/maestroerror/docs/blob/main/core-concepts/usage-without-laravel.mdx Illustrates how to initialize and configure the LarAgent outside of a Laravel environment. This requires manually creating and passing a chat history instance, such as `JsonChatHistory` or `InMemoryChatHistory`, along with the driver and model configuration. ```php use LarAgent\History\JsonChatHistory; // Setup $yourApiKey = 'your-openai-api-key'; // Replace with your actual API key $driver = new OpenAiDriver(['api_key' => $yourApiKey]); $chatHistory = new JsonChatHistory('test-chat-history'); $agent = LarAgent::setup($driver, $chatHistory, [ 'model' => 'gpt-4o-mini', ]); ``` -------------------------------- ### Basic Agent Structure (PHP) Source: https://github.com/maestroerror/docs/blob/main/core-concepts/agents.mdx Shows the boilerplate code generated by the `make:agent` command. This includes default properties for model, history, provider, and tools, along with placeholder methods for instructions and prompt handling. ```php respondStreamed( 'What\'s the weather like in Boston and Los Angeles?', function ($chunk) { if ($chunk instanceof \LarAgent\Messages\StreamedAssistantMessage) { echo $chunk->getLastChunk(); // Flush output buffer to send content to the browser immediately ob_flush(); flush(); } } ); // Consume the stream to ensure it completes foreach ($stream as $_) { // The callback handles the output } ``` -------------------------------- ### Create Custom Chat History Class Source: https://github.com/maestroerror/docs/blob/main/customization/custom-chat-history.mdx Defines a custom chat history class extending LarAgent's abstract ChatHistory and implementing the ChatHistory interface. It includes a constructor for initializing custom storage mechanisms and calls the parent constructor for common setup. ```php customStorage = $options['custom_storage'] ?? null; // Call parent constructor to handle common setup parent::__construct($name, $options); } // Implement abstract methods... } ``` -------------------------------- ### Add and Use Custom Tools Source: https://github.com/maestroerror/docs/blob/main/introduction.mdx Demonstrates how to define custom tools for an AI agent using PHP attributes and methods. These tools can be invoked by the agent to perform specific actions or retrieve information, enhancing its capabilities. ```php // ... #[Tool('Get the current weather in a given location')] public function exampleWeatherTool($location, $unit = 'celsius') { return 'The weather in '.$location.' is '.'20'.' degrees '.$unit; } // ... ``` -------------------------------- ### APIDOC: Routes for SingleAgentController Source: https://github.com/maestroerror/docs/blob/main/core-concepts/agent-via-api.mdx Defines the necessary API routes for a controller extending `SingleAgentController`. It includes routes for chat completions and listing available models, ensuring compatibility with OpenAI API endpoints. ```apidoc Route::post('/v1/chat/completions', [MyAgentApiController::class, 'completion']); Route::get('/v1/models', [MyAgentApiController::class, 'models']); ``` -------------------------------- ### PHP: Initialize Agent State Source: https://github.com/maestroerror/docs/blob/main/customization/events.mdx The onInitialize hook is called when the agent is fully initialized. Use this to set up initial state or configurations, such as dynamically adjusting parameters like temperature based on user preferences. ```php protected function onInitialize() { if (auth()->check() && auth()->user()->prefersCreative()) { $this->temperature(1.4); } } ``` -------------------------------- ### Run Specific Test File (Bash) Source: https://github.com/maestroerror/docs/blob/main/development.mdx Execute a single test file using the PEST runner. This is useful for quickly verifying changes in a specific area of the codebase. ```bash ./vendor/bin/pest tests/YourTestFile.php ``` -------------------------------- ### Create and Add Tool to Agent (PHP) Source: https://github.com/maestroerror/docs/blob/main/core-concepts/usage-without-laravel.mdx Demonstrates how to create a reusable tool for an agent. This involves defining the tool's name, description, properties (with types and constraints), required fields, metadata, and a callback function that executes when the tool is invoked. The tool is then added to the agent. ```php use LarAgent\Tool; // Create a tool $toolName = 'get_current_weather'; $tool = Tool::create($toolName, 'Get the current weather in a given location'); $tool->addProperty('location', 'string', 'The city and state, e.g. San Francisco, CA') ->addProperty('unit', 'string', 'The unit of temperature', ['celsius', 'fahrenheit']) ->setRequired('location') ->setMetaData(['sent_at' => '2024-01-01']) ->setCallback(function ($location, $unit = 'fahrenheit') { // "Call the weather API" return 'The weather in '.$location.' is 72 degrees '.$unit; }); // Add the tool to the agent $agent->setTools([$tool]); ``` -------------------------------- ### Create Tool with #[Tool] Attribute Source: https://github.com/maestroerror/docs/blob/main/DOCS.md Demonstrates creating a tool by applying the #[Tool] attribute to a PHP method. The attribute takes a description string and the method signature is used to define the tool's parameters. ```php use LarAgent\Attributes\Tool; // ... #[Tool('Get the current weather')] public function getWeather(string $city) { return WeatherService::getWeather($city); } ```