$messages = [];
foreach ($message_texts as $message_text) {
$messages[] = new ChatMessage('user', $message_text);
}
$input = new ChatInput($messages);

1b) Obtain Provider and Model

Struggling with repetitive code when using Drupal’s AI module for chat operations? Discover how the AI Helper module simplifies your development by streamlining common tasks, letting you focus on unique solutions instead of boilerplate.

Code Stages

It made sense to me to separate the code into three stages, each of which will be explained below:

  1. Pre-processing
  2. Processing
  3. Post-processing

1) Pre-processing

I will be writing more articles about my use of the AI module so watch this space.

1a) Prepare input

public function makeAiRequest(array $message_texts, array $tags = []): string {
$messages = [];
foreach ($message_texts as $message_text) {
$messages[] = new ChatMessage('user', $message_text);
}
$input = new ChatInput($messages);

$provider = $this->getProvider();
$output = $provider->chat($input, $this->getModel(), $tags);
return trim($output->getNormalized()->getText());
}

Final words

I opted to combine the remaining stages into a single function makeAiRequest():$output = $provider->chat($input, $model);

3) Post-processing

interface AiInterface {

function getOperationType(): string;
}

From that I wrote the following code:The first stage consists of converting the input into the format required for the Chat request and obtaining the Provider and Model.$operation_type = 'chat';
$default = $this->aiProvider->getDefaultProviderForOperationType($operation_type);
if (empty($default['provider_id'])) {
throw new AiSetupFailureException('No provider set, please check the AI Default Settings');
}
$provider = $this->aiProvider->createInstance($default['provider_id']);
$model = $default['model_id'];

2) Processing

Having written a couple of Drush scripts that utilise the Chat operation of the Drupal AI module (e.g. see part 1 in this series of Drupal AI articles) it was clear that certain operations were repeated in each task. I wrote a module, AI Helper, to provide a service that would avoid the need for repeated code.Working back from the parameters of the Chat request to the simplest input to the service, the logic was as follows:return trim($output->getNormalized()->getText());

Service code structure

I intend for this module to eventually handle other AI calls (e.g. textToImage() ), not just chat(), therefore I extracted common code into a class called AiBase. The only (sub-)stage that could be detached from the specific operation is 1b) Obtain Provider and Model as long as the $operation_type can be provided. This is achieved with the following Interface:

Similar Posts