### Example Questions for LLM Agent Source: https://docs.laragent.ai/guides/rag/vector-based A list of example questions designed to test the capabilities of an LLM agent. These questions cover various topics and are intended to elicit responses based on provided documentation. ```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?" ``` -------------------------------- ### Simple Agent Response Example Source: https://docs.laragent.ai/quickstart Demonstrates how to instantiate an agent for a specific user or chat session and obtain a response. This example uses the WeatherAgent. ```php use App\AiAgents\WeatherAgent; // Create an instance for a specific user or chat session $agent = WeatherAgent::for('user-123'); ``` -------------------------------- ### Example Laragent Configuration File (PHP) Source: https://docs.laragent.ai/quickstart This is an example of the published configuration file for Laragent. It defines default drivers and other settings. Refer to the latest version on GitHub for the most up-to-date configuration. ```php // config for Maestroerror/LarAgent return [ 'default_driver' => \LarAgent\Drivers\OpenAi\OpenAiCompatible::class, ]; ``` -------------------------------- ### Example Chat Completions Request Source: https://docs.laragent.ai/v1/agents/agent-via-api A cURL example demonstrating how to send a POST request to the chat completions endpoint with a model and messages payload. ```APIDOC ## POST /v1/chat/completions ### Description This is an example request to the chat completions endpoint, typically used for initiating a conversation with an AI agent. ### Method POST ### Endpoint `/v1/chat/completions` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model** (string) - Required - The identifier of the AI model to use (e.g., "MyAgent/gpt-4o-mini"). - **messages** (array) - Required - An array of message objects, where each object has a `role` (e.g., "user", "assistant") and `content` (string). ``` ```APIDOC ### Request Example ```json { "model": "MyAgent/gpt-4o-mini", "messages": [ {"role":"user","content":"Hello"} ] } ``` ``` ```APIDOC ### Response #### Success Response (200) - **object** - The response will typically contain the AI's generated message content. ``` ```APIDOC #### Response Example ```json { "id": "chatcmpl-123", "object": "chat.completion", "created": 1700000000, "model": "MyAgent/gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! How can I help you today?" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 10, "completion_tokens": 15, "total_tokens": 25 } } ``` ``` -------------------------------- ### Context-Aware Inline Tools Example in PHP Source: https://context7_llms Provides an example of registering inline tools that are aware of runtime context, such as user authentication and permissions. This includes tools that are always available, user-specific, or conditionally available based on user capabilities. ```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; } ``` -------------------------------- ### Display Example JSON Response Source: https://docs.laragent.ai/v1/agents/agent-via-api This snippet displays an example JSON response from an AI LLM agent. It includes details such as the agent's ID, object type, creation timestamp, model used, and choices. The code is formatted for readability. ```json { "id": "MyAgent_abcd1234", "object": "chat.completion", "created": 1753357877, "model": "gpt-4o-mini", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "This is a sample response from the AI agent." }, "logprobs": null, "finish_reason": "stop" } ] } ``` -------------------------------- ### Example Queries for Agent Testing Source: https://context7_llms This section provides example queries categorized into Database, Documentation, and Combined types to test the agent's functionality. It also outlines the expected behavior, such as tool selection, query validation, and information synthesis. ```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 ``` -------------------------------- ### Complete LarAgent Example with MCP Server Registration in PHP Source: https://context7_llms This comprehensive PHP example illustrates a `ResearchAgent` that registers multiple MCP servers, including filtering specific tools and resources. It also shows how to load additional context from a resource to be used in agent instructions. ```php mcpClient ->connect('knowledge_base') ->readResource('docs://api_reference'); $context = $apiDocs['contents'][0]['text'] ?? ''; return "You are a research assistant with access to GitHub and memory storage. Use the available tools to search repositories, track information, and answer questions. API Reference: {$context}"; } } ``` -------------------------------- ### OpenAI Streaming Chunk Example (JSON) Source: https://docs.laragent.ai/v1/agents/agent-via-api An example of a JSON chunk that conforms to OpenAI's chat completion streaming format. This is sent as part of a Server-Sent Event. ```json { "id": "ApiAgent_OpenWebUi-LarAgent", "object": "chat.completion.chunk", "created": 1753446654, "model": "gpt-4.1-nano", "choices": [ { "index": 0, "delta": { "role": "assistant", "content": " can" }, "logprobs": null, "finish_reason": null } ], "usage": null } ``` -------------------------------- ### Example Questions for Agent Chat Source: https://context7_llms Provides example questions to test the agent's ability to retrieve relevant information from documentation and provide accurate answers. ```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?" ``` -------------------------------- ### Simple Agent Response Example (PHP) Source: https://docs.laragent.ai/quickstart This example illustrates a basic usage scenario for an LLM agent, focusing on generating a simple response. It assumes the agent is configured to handle chat interactions with a specified name. ```php // Example of a simple response with chat name $agent = new WeatherAgent(); $response = $agent->respond('What is the weather like today?'); echo $response; ``` -------------------------------- ### Query Agent Contexts: Count, Exists, First, All, and Get Methods in PHP Source: https://context7_llms Provides examples of various query methods for agent contexts, including counting total or filtered identities, checking for existence, retrieving the first matching identity, and fetching all matching identities as an array or a collection. These methods allow for efficient data retrieval and validation. ```php use LarAgent\Context\Storages\ChatHistoryStorage; // Count matching identities $totalChats = Context::of(SupportAgent::class)->count(); $userChats = Context::of(SupportAgent::class) ->forUser('user-123') ->count(); // Check if any identities exist $hasChats = Context::of(SupportAgent::class) ->forUser('user-123') ->exists(); // Get first matching identity $identity = Context::of(SupportAgent::class) ->forUser('user-123') ->first(); if ($identity) { echo $identity->getChatName(); echo $identity->getUserId(); echo $identity->getGroup(); } // Get first matching identity as an agent instance $agent = Context::of(SupportAgent::class) ->forUser('user-123') ->firstAgent(); if ($agent) { $response = $agent->respond('Hello!'); } // Get all matching identities as array $identities = Context::of(SupportAgent::class) ->forUser('user-123') ->all(); // Get as SessionIdentityArray collection $identities = Context::of(SupportAgent::class) ->forUser('user-123') ->getIdentities(); // Get chat-specific identities $chatIdentities = Context::of(SupportAgent::class) ->getChatIdentities(); // Get storage keys $keys = Context::of(SupportAgent::class)->getStorageKeys(); $chatKeys = Context::of(SupportAgent::class)->getChatKeys(); ``` -------------------------------- ### Custom LLM Provider Configuration Example (PHP) Source: https://docs.laragent.ai/quickstart This PHP code snippet demonstrates how to configure a custom LLM provider. It includes an example of setting a custom provider named 'custom_provider' with various potential configurations, though only the name and label are shown in this specific example. ```php // Example custom provider with all possible configurations 'custom_provider' => [ // Just name for reference, changes nothing 'label' => 'custom' ] ``` -------------------------------- ### Example cURL Request for LarAgent Chat Completions Source: https://docs.laragent.ai/v1/agents/agent-via-api An example cURL command to send a POST request to the `/v1/chat/completions` endpoint. This request specifies the model to use and provides a user message for the AI to respond to. It's a standard way to interact with chat completion APIs. ```bash curl -X POST /v1/chat/completions \ -H 'Content-Type: application/json' \ -d '{ "model": "MyAgent/gpt-4o-mini", "messages": [ {"role":"user","content":"Hello"} ], }' ``` -------------------------------- ### 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 example logs the start of a new conversation, including the agent class and the current message. ```php protected function onConversationStart() { Log::info('Starting new conversation', [ 'agent' => self::class, 'message' => $this->currentMessage() ]); } ``` -------------------------------- ### Expose Agent with Completions Class (PHP) Source: https://docs.laragent.ai/v1/agents/agent-via-api This snippet demonstrates how to expose an agent using the `Completions` class in PHP. It shows the structure for handling requests and responses, including options for streaming or JSON output. The `Completions::make()` method is central to this process. ```php self::class, 'message' => $this->currentMessage() ]); } ``` -------------------------------- ### PHP onInitialize Hook for Agent Setup Source: https://docs.laragent.ai/v1/agents/hooks The `onInitialize` hook is called when the agent is fully initialized. It's used to set up initial states or configurations. This example demonstrates checking authentication and user preferences before proceeding. ```php protected function onInitialize() { if (auth()->check() && auth()->user()->prefersCreative()) { $this->temperature = ``` -------------------------------- ### Simple Agent Response Generation (PHP) Source: https://context7_llms Demonstrates different ways to get a response from a WeatherAgent. It shows how to instantiate an agent for a specific user, create an agent with custom temperature and message, and use a shorthand method for quick responses. All examples assume the WeatherAgent class is available. ```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..." ``` -------------------------------- ### Define SearchQuery DataModel with Property Promotion Source: https://docs.laragent.ai/v1/context/data-model Illustrates defining a DataModel for search queries using PHP's constructor property promotion. This approach simplifies property declaration. It leverages the `DataModel`'s features like automatic hydration, schema generation, and serialization, with `#[Desc]` attributes for AI context. ```php use LarAgent\Core\Abstractions\DataModel; use LarAgent\Attributes\Desc; class SearchQuery extends DataModel { public function __construct( #[Desc('The search term to look for')] public string $query, #[Desc('The maximum number of results to return')] public int $limit = 10, ) {} } ``` -------------------------------- ### LarAgent Event Dispatching for Hooks (PHP) Source: https://docs.laragent.ai/v1/agents/hooks Illustrates how LarAgent dispatches Laravel events for all hook points, enabling custom logic for cross-cutting concerns like logging and analytics. This example shows the structure for event setup and agent event handling. ```php // Example of event setup (in EventServiceProvider) protected $listen = [ \LarAgent\Events\AgentHookCalled::class => [ \App\Listeners\LogAgentHook::class, ], ]; // Example of an agent event listener namespace App\Listeners; use LarAgent\Events\AgentHookCalled; class LogAgentHook { public function handle(AgentHookCalled $event) { // Log the hook call details Log::info('Agent hook called:', [ 'agent' => $event->agent::class, 'hook' => $event->hookName, 'context' => $event->context, ]); } } ``` -------------------------------- ### Initialize Banner and Configuration Source: https://docs.laragent.ai/guides/introduction This JavaScript code initializes a banner and configures the application. It checks for user preferences regarding banner visibility and sets the banner's state accordingly. It also includes configuration details for the application, such as the theme, colors, logo, and navigation links. ```javascript (function j(a,b,c,d,e){try{let f,g,h=[];try{h=window.location.pathname.split("/").filter(a=\u003e""!==a\u0026\u0026"global"!==a).slice(0,2)}catch{h=[]}let i=h.find(a=\u003ec.includes(a)),j=[];for(let c of(i?j.push(i):j.push(b),j.push("global"),j)){if(!c)continue;let b=a[c];if(b?.content){f=b.content,g=c;break}}if(!f)return void document.documentElement.setAttribute(d,"hidden");let k=!0,l=0;for(;l\u003clocalStorage.length;){let a=localStorage.key(l);if(l++,!a?.endsWith(e))continue;let b=localStorage.getItem(a);if(b\u0026\u0026b===f){k=!1;break}g\u0026\u0026(a.startsWith(`lang:${g}_`)||!a.startsWith("lang:"))\u0026\u0026(localStorage.removeItem(a),l--)}document.documentElement.setAttribute(d,k?"visible":"hidden")}catch(a){console.error(a),document.documentElement.setAttribute(d,"hidden")}})( {"global":{"content":"🔴 LarAgent is powered by Redberry. Need help building AI agents in Laravel? [Talk to us](https://redberry.international/ai-agent-development/?utm_source=documentation\u0026utm_medium=documentation_banner\u0026utm_campaign=AI+service+campaign) →"}}, "en", [], "data-banner-state", "bannerDismissed", ) ``` -------------------------------- ### Configure Single Storage Driver (PHP) Source: https://docs.laragent.ai/v1/context/overview This PHP code example demonstrates how to configure a single storage driver for all operations. It includes 'use' statements for CacheStorage and EloquentStorage, indicating their availability for use. This setup is suitable for simpler applications requiring a unified storage solution. ```php use LarAgent\\Context\\Drivers\\CacheStorage; use LarAgent\\Context\\Drivers\\EloquentStorage; class SupportAgent ``` -------------------------------- ### Get Usage Analytics Dashboard (PHP) Source: https://context7_llms Retrieves total usage, usage by provider, and estimated cost for a given date range. It takes 'from' and 'to' dates as optional request inputs, defaulting to the start of the current month and the current date respectively. The output is a JSON response containing these analytics. ```php analytics = $analytics; } 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), ]); } } ``` -------------------------------- ### Programmatic Testing of LLM Agent in PHP Source: https://docs.laragent.ai/guides/rag/vector-based A PHP code snippet demonstrating how to programmatically test an LLM agent within an application. This example shows how to instantiate and potentially interact with the agent using its namespace and class. ```php use App\\AiAgents\\SupportAgent; // Example of how to instantiate the agent (further interaction code would follow) $agent = new SupportAgent(); ``` -------------------------------- ### Initialize AI Agent Instance Source: https://docs.laragent.ai/v1/context/data-model This snippet shows how to create a new instance of an AI agent. It utilizes a 'self' object and expects an 'agentName' parameter. This is a fundamental step in setting up an AI agent for use. ```javascript return new self({ agentName }); ``` -------------------------------- ### Blade: System Prompt Instructions Source: https://docs.laragent.ai/guides/rag/vector-based This Blade template snippet demonstrates how to instruct an LLM to stay on topic. It provides specific phrasing to redirect users asking about unrelated subjects back to the intended domain or a general contact page. This helps maintain focus and relevance in LLM interactions. ```blade If the user asks about topics unrelated to HelloWorld or our services, politely redirect them: "I'm specialized in helping with HelloWorld platform questions." For other topics, please visit our general contact page." ``` -------------------------------- ### Install Project Dependencies Source: https://context7_llms Installs the necessary project dependencies using Composer. This command should be run after cloning the repository to ensure all required packages are available. ```bash composer install ``` -------------------------------- ### Agent Initialization and Listener Setup Source: https://docs.laragent.ai/v1/customization/events/setup This snippet demonstrates how an agent is initialized and how a listener is set up to react to agent events. It highlights the use of specific classes like AgentInitialized and AgentListener. ```javascript _jsx("div", { children: [ _jsx(_components.span, { style: { color: "#CF222E", "--shiki-dark": "#D4D4D4" }, children: "::" }), _jsx(_components.span, { style: { color: "#8250DF", "--shiki-dark": "#DCDCAA" }, children: "listen" }), _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: "(" }) ] }), "\n", _jsxs(_components.span, { className: "line", children: [ _jsx(_components.span, { style: { color: "#0550AE", "--shiki-dark": "#4EC9B0" }, children: " AgentInitialized" }), _jsx(_components.span, { style: { color: "#CF222E", "--shiki-dark": "#D4D4D4" }, children: "::" }), _jsx(_components.span, { style: { color: "#CF222E", "--shiki-dark": "#569CD6" }, children: "class" }), _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: "," }) ] }), "\n", _jsxs(_components.span, { className: "line", children: [ _jsx(_components.span, { style: { color: "#0550AE", "--shiki-dark": "#4EC9B0" }, children: " AgentListener" }), _jsx(_components.span, { style: { color: "#CF222E", "--shiki-dark": "#D4D4D4" }, children: "::" }), _jsx(_components.span, { style: { color: "#CF222E", "--shiki-dark": "#569CD6" }, children: "class" }) ] }), "\n", _jsx(_components.span, { className: "line", children: _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: " );" }) }), "\n", _jsx(_components.span, { className: "line", children: _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: " }" }) }), "\n", _jsx(_components.span, { className: "line", children: _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: "}" }) }), "\n"] }) ``` -------------------------------- ### Install OpenAI PHP Client Package Source: https://context7_llms Installs the openai-php/client package, which is recommended for generating embeddings and is often pre-installed with LarAgent. This package is essential for AI-related tasks. ```bash # Usually already installed with LarAgent composer require openai-php/client ``` -------------------------------- ### Programmatic Testing of Support Agent in PHP Source: https://docs.laragent.ai/guides/rag/vector-based Demonstrates how to programmatically test the Support Agent within a PHP application. This snippet shows the necessary 'use' statement for the SupportAgent class. ```php use App\\AiAgents\\SupportAgent; // For authenticated users ``` -------------------------------- ### Install LarAgent Package Source: https://docs.laragent.ai/quickstart Installs the LarAgent package using Composer. This is the first step in integrating LarAgent into your Laravel application. ```bash composer require maestroerror/laragent ``` -------------------------------- ### Configure Environment Variables for AI and Vector Database Source: https://docs.laragent.ai/guides/rag/vector-based Sets up essential environment variables for connecting to the OpenAI API and a Qdrant vector database. These variables include API keys and host configurations required for the AI agent and its data storage. ```env OPENAI_API_KEY=your_openai_api_key_here # Qdrant Configuration QDRANT_HOST=http://localhost:6333 QDRANT_API_KEY=your_qdrant_api_key ``` -------------------------------- ### Getting Tracked Storage Keys in PHP Source: https://context7_llms Retrieve all tracked storage keys associated with an agent. You can get all keys, chat history keys specifically, or 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(); ``` -------------------------------- ### LLM Storage Driver Configuration Example (JavaScript) Source: https://docs.laragent.ai/v1/context/overview This JavaScript code snippet demonstrates how to configure storage drivers for an LLM. It shows the instantiation of InMemoryStorage and EloquentStorage, likely used for chat history or other data persistence needs. The code highlights the use of specific driver names and their initialization. ```javascript const historyStorageDrivers = () => [ new InMemoryStorage() ]; const defaultStorageDrivers = () => [ new EloquentStorage() ]; ``` -------------------------------- ### ConversationStarted Event Source: https://docs.laragent.ai/v1/customization/events/agent This event is dispatched when the respond() method begins execution, marking the start of a new conversation turn. It includes the agent configuration at the start of the conversation. ```APIDOC ## POST /events/conversation-started ### Description This endpoint handles the `ConversationStarted` event, which is triggered at the beginning of a new conversation turn when the `respond()` method is called. It receives the current agent configuration. ### Method POST ### Endpoint `/events/conversation-started` ### Parameters #### Request Body - **agentDto** (AgentDTO) - Required - Current agent configuration at the start of the conversation. ### Request Example ```json { "agentDto": { "//": "AgentDTO object details would go here" } } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the event was processed. #### Response Example ```json { "message": "Conversation started event processed successfully." } ``` ``` -------------------------------- ### Call Completions::make() for Custom AI Control (PHP) Source: https://docs.laragent.ai/v1/agents/agent-via-api This PHP code demonstrates how to directly call the `Completions::make()` method for more granular control over AI interactions. It requires the 'ai-llms' package and allows for custom controller implementations. ```php use LLM\LLM;\n\n$response = LLM::make()\n ->withMessages($messages)\n ->withModel($model)\n ->withFunction($function)\n ->withFunctionJsonSchema($functionJsonSchema)\n ->withFunctionDescription($functionDescription)\n ->withTemperature($temperature)\n ->withStream($stream)\n ->call(); ``` -------------------------------- ### PHP Method Override Example Source: https://docs.laragent.ai/v1/context/history An example demonstrating method overriding in PHP. This snippet is part of a larger class structure, likely related to agent behavior or configuration. ```php protected function someMethod() { // Method implementation } ``` -------------------------------- ### Bootstrapping Event Handling in Laravel Source: https://docs.laragent.ai/v1/customization/events/setup This snippet illustrates the `boot` method within the `AppServiceProvider`. While the provided code is minimal, it indicates where application bootstrapping logic, such as event listener setup, would typically reside. ```php // ... inside AppServiceProvider class public function boot(): void { // Event::listen(...); } ``` -------------------------------- ### MDX Component Setup and Rendering (JavaScript) Source: https://docs.laragent.ai/guides/rag/vector-based This JavaScript code initializes MDX (Markdown with JSX) components for rendering content. It imports necessary components like `Fragment`, `jsx`, `jsxs`, and `useMDXComponents`. The code defines a function `_createMdxContent` that maps imported components to their JSX equivalents, ensuring that custom components like `Accordion`, `Card`, `CodeBlock`, etc., are correctly integrated and rendered within the application. It also includes checks for missing component references. ```javascript \"use strict\";\nconst {Fragment: _Fragment, jsx: _jsx, jsxs: _jsxs} = arguments[0];\nconst {useMDXComponents: _provideComponents} = arguments[0];\nfunction _createMdxContent(props) {\n const _components = {\n a: \"a\",\n code: \"code\",\n hr: \"hr\",\n li: \"li\",\n ol: \"ol\",\n p: \"p\",\n pre: \"pre\",\n span: \"span\",\n strong: \"strong\",\n ul: \"ul\",\n ..._provideComponents(),\n ...props.components\n }, {Accordion, AccordionGroup, Card, CardGroup, CodeBlock, CodeGroup, Heading, Mermaid, Note, Step, Steps, Tip, Warning} = _components;\n if (!Accordion) _missingMdxReference(\"Accordion\", true);\n if (!AccordionGroup) _missingMdxReference(\"AccordionGroup\", true);\n if (!Card) _missingMdxReference(\"Card\", true);\n if (!CardGroup) _missingMdxReference(\"CardGroup\", true);\n if (!CodeBlock) _missingMdxReference(\"CodeBlock\", true);\n if (!CodeGroup) _missingMdxReference(\"CodeGroup\", true);\n if (!Heading) _missingMdxReference(\"Heading\", true);\n if (!Mermaid) _missingMdxReference(\"Mermaid\", true);\n if (!Note) _missingMdxReference(\"Note\", true);\n if (!Step) _missingMdxReference(\"Step\", true);\n if (!Steps) _missingMdxReference(\"Steps\", true);\n if (!Tip) _missingMdxReference(\"Tip\", true);\n if (!Warning) _missingMdxRe ``` -------------------------------- ### PHP LLM Agent Initialization and Response Handling Source: https://docs.laragent.ai/v1/agents/llm-drivers This PHP code demonstrates initializing an LLM agent, retrieving its provider sequence, and handling a response. It shows how to assign an agent instance, fetch the sequence of providers, and send a response back. ```php $agent = MyAgent::make(); // Get the configured provider sequence $sequence = $agent->getProviderSequence(); // ['openai', 'gemini', 'claude'] // After a response, check which provider was used $response = $agent->respond('Hello!'); $activeProvider = $agent->activeProvider; ``` -------------------------------- ### Define and Use Functions in PHP Source: https://docs.laragent.ai/v1/context/data-model This snippet demonstrates how to define and use functions in PHP, specifically focusing on creating an array from object properties. It showcases the use of arrow functions and property access. ```php $this->agentName, 'chatKey' => $this->chatKey, 'userId' => $this->userId ]; } ?> ``` -------------------------------- ### Define Support Agent Instructions (JavaScript) Source: https://docs.laragent.ai/guides/rag/vector-based This JavaScript code defines a public function named 'instructions' that returns a formatted string. This string can be used as instructions for a support agent AI. It dynamically includes the current date and user information, formatted for clarity. The function utilizes a 'view' helper and string interpolation. ```javascript public function instructions() { return view( 'prompts.support_agent_instructions', [ 'date' => now()->format('F j, Y'), 'user' => ] ); } ``` -------------------------------- ### Create and Register Inline Tools in PHP Source: https://context7_llms Demonstrates how to create inline tools using the `Tool::create()` method and register them within an agent's `registerTools()` method. It shows examples of setting callbacks and adding properties for tool functionality. ```php use LarAgent\Tool; class MyAgent extends Agent { public function registerTools() { $user = auth()->user(); return [ Tool::create('get_user_location', "Get the current user's location") ->setCallback(fn() => $user->location->city), Tool::create('get_weather', 'Get weather for a location') ->addProperty('location', 'string', 'City name') ->addProperty('unit', 'string', 'Temperature unit', ['celsius', 'fahrenheit']) ->setRequired('location') ->setCallback(fn($location, $unit = 'celsius') => WeatherService::get($location, $unit) ), ]; } } ``` -------------------------------- ### PHP Data Model with Property Promotion Source: https://docs.laragent.ai/v1/context/data-model Demonstrates the use of property promotion in PHP for defining a data model. This approach reduces boilerplate code by declaring properties directly in the constructor. It also includes necessary 'use' statements for the Laragent framework. ```php use LarAgent\\Core\\Abstractions\\DataModel; use LarAgent\\Attributes\\ ``` -------------------------------- ### Expected Behavior of LLM Agent Source: https://docs.laragent.ai/guides/rag/vector-based Outlines the expected behavior of the LLM agent when responding to user queries. This includes retrieving relevant information, providing accurate answers, admitting limitations, and maintaining conversational context. ```text ✅ Agent retrieves relevant FAQ documents ✅ Provides accurate answers based on context ✅ Admits when information is not available ✅ Maintains conversation context across messages ``` -------------------------------- ### Get Agent Response - JavaScript Source: https://docs.laragent.ai/quickstart This JavaScript snippet demonstrates how to get a response from an AI agent. It shows the assignment of the agent's response to a variable and how to echo the response. This is useful for integrating AI agent capabilities into web applications. ```javascript import { _jsx, _jsxs } from "react/jsx-runtime"; import { _components } from "@/components/ui/code-block"; // Get a response $response = $agent->respond("What's the weather like in Boston?"); echo $response; // "The weather in Boston is currently..." ``` -------------------------------- ### LLM Agent Interaction Example (Unspecified Language) Source: https://docs.laragent.ai/quickstart This snippet demonstrates how to interact with a generic LLM agent. It shows setting parameters like temperature and passing messages. The output is then echoed. ```javascript import { _jsx, _jsxs } from "react/jsx-runtime"; import { CodeBlock } from "@/components/CodeBlock"; export function Page() { return ( <_jsx(CodeBlock, { filename: "agent.js", numberOfLines: "15", language: "javascript", children: _jsx(_components.pre, { className: "shiki shiki-themes github-light-default dark-plus", style: { backgroundColor: "#ffffff", "--shiki-dark-bg": "#0B0C0E", color: "#1f2328", "--shiki-dark": "#D4D4D4" }, language: "javascript", children: _jsxs(_components.code, { language: "javascript", numberOfLines: "15", children: [ _jsxs(_components.span, { className: "line", children: [ _jsx(_components.span, { style: { color: "#CF222E", "--shiki-dark": "#D4D4D4" }, children: " ->" }), _jsx(_components.span, { style: { color: "#8250DF", "--shiki-dark": "#DCDCAA" }, children: "withTemperature" }), _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: "(" }), _jsx(_components.span, { style: { color: "#0550AE", "--shiki-dark": "#B5CEA8" }, children: "0.7" }), _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: ")" }) ] }), "\n", _jsxs(_components.span, { className: "line", children: [ _jsx(_components.span, { style: { color: "#CF222E", "--shiki-dark": "#D4D4D4" }, children: " ->" }), _jsx(_components.span, { style: { color: "#8250DF", "--shiki-dark": "#DCDCAA" }, children: "message" }), _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: "(" }), _jsx(_components.span, { style: { color: "#0A3069", "--shiki-dark": "#CE9178" }, children: "\"What's the weather like in Boston?\"" }), _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: ")" }) ] }), "\n", _jsxs(_components.span, { className: "line", children: [ _jsx(_components.span, { style: { color: "#CF222E", "--shiki-dark": "#D4D4D4" }, children: " ->" }), _jsx(_components.span, { style: { color: "#8250DF", "--shiki-dark": "#DCDCAA" }, children: "respond" }), _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: "();" }) ] }), "\n", _jsx(_components.span, { className: "line" }), "\n", _jsxs(_components.span, { className: "line", children: [ _jsx(_components.span, { style: { color: "#0550AE", "--shiki-dark": "#DCDCAA" }, children: "echo" }), _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#9CDCFE" }, children: " $response" }), _jsx(_components.span, { style: { color: "#1F2328", "--shiki-dark": "#D4D4D4" }, children: "; " }), _jsx(_components.span, { style: { color: "#6E7781", "--shiki-dark": "#6A9955" }, children: "// \"The weather in Boston is currently...\"" }) ] }), "\n", _jsx(_components.span, { className: "line" }), "\n" ] }) }) }) ); } ``` -------------------------------- ### Tool Class Example in PHP Source: https://docs.laragent.ai/v1/tools/overview This PHP code demonstrates the creation of a 'Tool Class' for encapsulating complex or reusable tool functionalities. It serves as a structural example for organizing tool-related logic within a class, promoting modularity and maintainability in AI LLM projects. ```php name ?? 'Valued Customer' }} Email: {{ $user->email ?? 'N/A' }} Account Type: {{ $user->subscription_type ?? 'Free' }} ``` -------------------------------- ### Next Steps for Tool Implementation (Links) Source: https://docs.laragent.ai/v1/tools/overview Provides links to resources for implementing tools in LarAgent, covering attribute-based tool creation, reusable tool classes, and structured output generation. This section guides developers on how to leverage LarAgent's tool system effectively. ```markup

Learn how to create tools using the #[Tool] attribute on agent methods.

Build reusable tool classes or create tools dynamically.

Get type-safe responses using DataModels and schemas.

``` -------------------------------- ### GET /v1/models Source: https://docs.laragent.ai/v1/agents/agent-via-api Retrieves a list of available models that can be used with the LLM Agent. ```APIDOC ## GET /v1/models ### Description Retrieves a list of available models that can be used with the LLM Agent. ### Method GET ### Endpoint /v1/models ### Parameters None ### Request Body None ### Response #### Success Response (200) - **models** (array) - A list of available model names. #### Response Example ```json { "example": "{\"models\": [\"gpt-3.5-turbo\", \"llama-2-7b\"]}" } ``` ``` -------------------------------- ### PHP Class Definition with Property Promotion Source: https://docs.laragent.ai/v1/context/data-model This snippet shows a PHP class `SearchQuery` that extends `DataModel`. It uses constructor property promotion to define public properties `$query` (string) and `$limit` (int) with default values. This syntax simplifies class definitions by combining property declaration and initialization within the constructor. ```php class SearchQuery extends DataModel { public function __construct( #["Desc"("The search term to look for")] public string $query, #["Desc"("The maximum number of results to return")] public int $limit = 10 ) {} } ``` -------------------------------- ### LarAgent Long-Running Process Configuration Example (PHP) Source: https://docs.laragent.ai/v1/context/history This example illustrates the configuration for LarAgent in long-running environments like Laravel Octane, FrankenPHP, or Swoole. It emphasizes the use of both `$forceReadHistory` and `$forceSaveHistory` flags to ensure data freshness when agent instances persist across requests. ```php protected $forceReadHistory = true; protected $forceSaveHistory = true; ``` -------------------------------- ### Define Support Agent Instructions (Blade) Source: https://docs.laragent.ai/guides/rag/vector-based This Blade template defines the instructions for the SupportAgent. It uses Blade syntax for templating and can include dynamic content. The template is saved as a .blade.php file. ```blade # Purpose You a ```