bluefly/langchain

LangChain integration and orchestration framework for Drupal, providing foundational LLM capabilities.

1.0.0 2025-05-22 23:00 UTC

This package is auto-updated.

Last update: 2025-06-06 09:57:04 UTC


README

Tests Maintenance License Packagist Downloads

The LangChain module brings LangChain-style agent orchestration and LLM workflow integration to Drupal, enabling advanced AI pipelines and composable agent systems.

Features

  • LLM Integration: Connect with various LLM providers (OpenAI, HuggingFace, etc.)
  • Chain Orchestration: Create and manage LLM workflow chains
  • Agent Management: Build and deploy AI agents with specific capabilities
  • Prompt Management: Create, store, and optimize prompts for LLMs
  • Vector Storage: Manage embeddings and vector databases
  • RAG Implementation: Build retrieval-augmented generation workflows
  • Admin Interface: Comprehensive UI for managing all LangChain components
  • API Endpoints: REST and OpenAPI-compliant endpoints for integration
  • ECA Integration: Workflow automation with Event-Condition-Action

Requirements

  • PHP 8.1 or higher
  • Drupal 10.1 or 11.0
  • Required modules:
    • System
    • Key (for secure storage of API keys)
    • Field

Recommended Modules

  • ECA: For workflow automation
  • Search API: For vector search capabilities
  • Views: For custom admin interfaces
  • Token: For enhanced prompt templating

Installation

Using Composer (recommended)

composer require drupal/langchain
drush en langchain

Manual Installation

  1. Download the module and place it in the modules/contrib directory
  2. Enable the module via the UI or using Drush:
    drush en langchain
    

Configuration

  1. Navigate to Administration > Configuration > AI > LangChain Settings
  2. Configure general settings:
    • Default LLM provider
    • API credentials (via Key module)
    • Default parameters for chains and agents
    • Advanced settings for vector storage and embeddings

Usage

Managing LLM Providers

  1. Go to Administration > Configuration > AI > LangChain > Providers
  2. Add a new provider configuration:
    • Select provider type (OpenAI, HuggingFace, etc.)
    • Configure API connection settings
    • Set default parameters

Creating Chains

  1. Go to Administration > Structure > LangChain > Chains
  2. Click "Add Chain"
  3. Configure the chain:
    • Add steps (LLM calls, tools, conditionals)
    • Configure input/output schemas
    • Set execution parameters

Building Agents

  1. Go to Administration > Structure > LangChain > Agents
  2. Click "Add Agent"
  3. Configure the agent:
    • Select agent type
    • Add tools and capabilities
    • Configure memory and state management
    • Set input/output formats

Using the API

The module provides REST endpoints for integrating with external systems:

# Execute a chain
POST /api/langchain/chains/{chain_id}/execute
Content-Type: application/json
{
  "input": {"query": "What is Drupal?"},
  "parameters": {"temperature": 0.7}
}

# Execute an agent
POST /api/langchain/agents/{agent_id}/execute
Content-Type: application/json
{
  "input": {"task": "Research Drupal modules"},
  "parameters": {"max_iterations": 5}
}

Programmatic Usage

You can use the LangChain services in your custom code:

// Get the chain manager service
$chain_manager = \Drupal::service('langchain.chain_manager');

// Execute a chain
$result = $chain_manager->executeChain('content_analysis_chain', [
  'text' => 'Analyze this content for insights',
]);

// Get the agent manager service
$agent_manager = \Drupal::service('langchain.agent_manager');

// Execute an agent
$result = $agent_manager->executeAgent('research_agent', [
  'query' => 'Find information about Drupal modules',
]);

Architecture

The LangChain module uses a modular architecture with these key components:

  • Provider System: Plugins for different LLM providers
  • Chain Manager: Manages the creation and execution of chains
  • Agent Manager: Manages the creation and execution of agents
  • Prompt Manager: Manages prompt templates and optimization
  • Tool Registry: Central registry for tools available to agents
  • Vector Store: Manages embeddings and vector storage
  • API Layer: REST and OpenAPI endpoints

Integration with ECA

The module integrates with the Event-Condition-Action (ECA) module to enable workflow automation:

Events

  • langchain.chain_executed: Triggered when a chain is executed
  • langchain.agent_executed: Triggered when an agent is executed
  • langchain.prompt_executed: Triggered when a prompt is executed

Conditions

  • langchain.chain_result_contains: Checks if a chain result contains specific text
  • langchain.agent_result_type: Checks the type of an agent result
  • langchain.execution_metrics: Checks metrics from chain or agent execution

Actions

  • langchain.execute_chain: Executes a chain
  • langchain.execute_agent: Executes an agent
  • langchain.execute_prompt: Executes a prompt

Extending the Module

Creating Custom Providers

Create a custom provider by implementing the LlmProviderInterface:

namespace Drupal\my_module\Plugin\LlmProvider;

use Drupal\langchain\Plugin\LlmProviderInterface;
use Drupal\langchain\Plugin\LlmProviderBase;

/**
 * @LlmProvider(
 *   id = "my_custom_provider",
 *   label = @Translation("My Custom Provider"),
 *   description = @Translation("Custom LLM provider implementation.")
 * )
 */
class MyCustomProvider extends LlmProviderBase implements LlmProviderInterface {

  /**
   * {@inheritdoc}
   */
  public function complete($prompt, array $options = []) {
    // Implementation logic.
  }

}

Creating Custom Tools

Create a custom tool for agents by implementing the AgentToolInterface:

namespace Drupal\my_module\Plugin\AgentTool;

use Drupal\langchain\Plugin\AgentToolInterface;
use Drupal\langchain\Plugin\AgentToolBase;

/**
 * @AgentTool(
 *   id = "my_custom_tool",
 *   label = @Translation("My Custom Tool"),
 *   description = @Translation("Custom tool implementation.")
 * )
 */
class MyCustomTool extends AgentToolBase implements AgentToolInterface {

  /**
   * {@inheritdoc}
   */
  public function execute($input, array $context = []) {
    // Implementation logic.
  }

}

Troubleshooting

Common Issues

  1. API Connection Errors: Verify API keys and endpoints in the Key module.
  2. Chain Execution Failures: Check chain configuration and step dependencies.
  3. Agent Tool Errors: Verify tool permissions and dependencies.
  4. Performance Issues: Adjust caching and optimization settings.

Logging

The module logs detailed information about chain and agent execution:

  • View logs at Administration > Reports > Recent Log Messages (filter for "langchain")
  • Enable debug logging in the module settings for more detailed information

API Reference

Contributing

Contributions to this module are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for your changes
  4. Submit a pull request

Development Setup

  1. Clone the repository
  2. Install dependencies:
    composer install
    
  3. Run tests:
    composer test
    

License

This project is licensed under the GPL v2 or later.