Skip to main content

Creating a Custom LLM Driver

LarAgent allows you to integrate with various LLM providers by creating custom drivers. This guide will walk you through the process of creating a custom LLM driver for a new provider, similar to the existing OpenAI driver but tailored to your specific LLM provider.

Understanding the LLM Driver Architecture

The LarAgent framework uses a driver-based architecture for LLM integrations:
  • LlmDriver Interface (LarAgent\Core\Contracts\LlmDriver): Defines the contract all LLM drivers must implement
  • Abstract LlmDriver (LarAgent\Core\Abstractions\LlmDriver): Provides common functionality for all drivers
  • Concrete Drivers: Implement provider-specific logic (e.g., OpenAiDriver)

Creating Your Custom Driver

The code bellow is a simplified example of a custom driver implementation. It is not a complete implementation and is intended for educational purposes only. Check the real drivers here.

Step 1: Create the Driver Class

First, create a new directory for your provider, then create your driver class:

Step 2: Implement Required Methods

2.1 Send Message Method

This is the core method for sending messages to the LLM and receiving responses:

2.2 Tool Result to Message Method

This method formats tool results for the LLM:

2.3 Tool Calls to Message Method

This method formats tool calls for the LLM:

Step 2.4 Tool Call to Content Method

This method formats a tool call for the LLM:

2.5 Streamed Message Method

For providers that support streaming:

Step 3: Implement Helper Methods

These methods help with the core functionality:

Step 4: Implement Provider-Specific Methods

These are methods specific to your provider’s API:

Testing Your Driver

Create tests for your driver to ensure it works correctly:

Registering Your Driver

To make your driver available in the LarAgent framework, you’ll need to register it:

In Laravel

Add your driver to the configuration file:

In Agent Class

Best Practices

  1. Error Handling: Implement robust error handling for API calls
  2. Rate Limiting: Consider implementing rate limiting or retry logic
  3. Logging: Add logging for debugging purposes
  4. Configuration: Make your driver configurable with sensible defaults
  5. Documentation: Document your driver’s capabilities and limitations

Complete Example Implementation

Here’s a simplified example of a complete driver implementation:

Conclusion

By following this guide, you can create a custom LLM driver for any provider and integrate it with the LarAgent framework. This allows you to leverage the full power of LarAgent with your preferred LLM provider while maintaining compatibility with the existing architecture. For more details, see the real drivers here.