
public function reviewsMakeModel(): void {
$fields = ['title', 'body'];
foreach ($review_nodes as $review_node) {
$data = [];
foreach ($fields as $field) {
$data[] = $review_node->get($field)->value;
}
$text = implode("n", $data);
$makeAndModel = $this->getMakeAndModel($text);
}
}
The provider
public function reviewsMakeModel(): void {
$fields = ['title', 'body'];
foreach ($review_nodes as $review_node) {
$data = [];
foreach ($fields as $field) {
$data[] = $review_node->get($field)->value;
}
$text = implode("n", $data);
$makeAndModel = $this->getMakeAndModel($text);
if (!empty($makeAndModel['make'])) {
$review_node->set('field_make', $makeAndModel['make']);
}
if (!empty($makeAndModel['model'])) {
$review_node->set('field_model', $makeAndModel['model']);
}
$review_node->save();
}
}
The disclaimer
Do not use markdown in responsesOnly respond with the make and model
The prompt
Respond with json
The specifics
I can’t speak for other AI providers, but Google Gemini is wont to deliver a response formatted in markdown, to get plain text I added:
The joy of AI’s natural language processing is that the core of the prompt is simply “What is the make and model discussed in this text?” followed by the content of the Title and Body fields of a review node.
I was working on a large website with plenty of content dating back years, including numerous product reviews that required improved categorisation. The goal was to tag all of these review nodes with the relevant Make and Model.
Artificial Intelligence has arrived in the Drupal ecosystem and it is already making huge waves. This is the first in a series of articles about my experiences as I dip a toe into these exciting waters.
protected function getManufacturerAndModel(string $text): string {
$message_texts = [
'Do not use markdown in responses',
'Only respond with the make and model',
'Respond with json',
'What is the make and model being talked about in this text',
$text,
];
$json = $this->aiChat->makeAiRequest($message_texts);
return Json::decode($json);
}
I chose to write a custom Drush script to loop through all of the review nodes, using Artificial Intelligence to parse the Title and Body fields and return the make and model discussed therein.
{
make: BMW,
model: M5
}
The processing
In conjunction with the rest of the prompt, this causes Google Gemini to respond in the form:Of course AI prompts are never quite that simple; they need refinement to return the specific data in the required format. I did not want any extraneous information so I prefaced the prompt withRather than trying to parse the response to separate the make from the model I added: