Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Api/AiClientInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,21 @@ interface AiClientInterface
* @return string|null
*/
public function generate(string $systemPrompt, string $userPrompt): ?string;

/**
* Generate content for multiple attributes in a single API call.
*
* Returns an empty array on failure (JSON parse error, missing keys, etc.)
* to signal the caller should fall back to individual generate() calls.
*
* @param string $systemPrompt
* @param string $productContext Formatted product attribute data
* @param array<string, string> $attributePrompts [attribute_code => parsed_prompt]
* @return array<string, string> [attribute_code => generated_value]
*/
public function generateBatch(
string $systemPrompt,
string $productContext,
array $attributePrompts
): array;
}
18 changes: 18 additions & 0 deletions Api/ProductContextBuilderInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace MageOS\CatalogDataAI\Api;

use Magento\Catalog\Model\Product;

interface ProductContextBuilderInterface
{
/**
* Build a text representation of product attributes for AI context.
*
* @param Product $product
* @return string
*/
public function build(Product $product): string;
}
6 changes: 6 additions & 0 deletions Model/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Config
public const XML_PATH_OPENAI_API_ADVANCED_TEMPERATURE = 'catalog_ai/advanced/temperature';
public const XML_PATH_OPENAI_API_ADVANCED_FREQUENCY_PENALTY = 'catalog_ai/advanced/frequency_penalty';
public const XML_PATH_OPENAI_API_ADVANCED_PRESENCE_PENALTY = 'catalog_ai/advanced/presence_penalty';
public const XML_PATH_CONTEXT_VALUE_MAX_LENGTH = 'catalog_ai/advanced/context_value_max_length';
public const XML_PATH_PRODUCT_ATTRIBUTE_PROMPTS = 'catalog_ai/product/attribute_prompts';

private array $attributePromptsMap = [];
Expand Down Expand Up @@ -135,6 +136,11 @@ public function getPresencePenalty(): float
);
}

public function getContextValueMaxLength(): int
{
return (int) $this->scopeConfig->getValue(self::XML_PATH_CONTEXT_VALUE_MAX_LENGTH);
}

/**
* Parse the serialized attribute_prompts config into [attribute_code => prompt].
*
Expand Down
87 changes: 87 additions & 0 deletions Model/OpenAiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,93 @@ public function generate(string $systemPrompt, string $userPrompt): ?string
return $result?->message?->content;
}

/**
* @param array<string, string> $attributePrompts
* @return array<string, mixed>
*/
public function buildBatchSchema(array $attributePrompts): array
{
$properties = [];
foreach ($attributePrompts as $code => $prompt) {
$properties[$code] = ['type' => 'string', 'description' => $prompt];
}

return [
'type' => 'object',
'properties' => $properties,
'required' => array_keys($attributePrompts),
'additionalProperties' => false,
];
}

/**
* @param string $productContext
* @param array<string, string> $attributePrompts
* @return string
*/
public function buildBatchPrompt(string $productContext, array $attributePrompts): string
{
$prompt = "Product information:\n" . $productContext . "\n\n"
. "Generate content for each of the following product attributes:\n";

foreach ($attributePrompts as $code => $instruction) {
$prompt .= "\n{$code}: {$instruction}";
}

return $prompt;
}

/**
* @param string|null $json
* @param array<string, string> $requestedKeys
* @return array<string, string>
*/
public function parseBatchResponse(?string $json, array $requestedKeys): array
{
$decoded = json_decode($json ?? '', true);

if (!is_array($decoded)) {
return [];
}

return array_intersect_key($decoded, $requestedKeys);
}

/**
* @inheritdoc
*/
public function generateBatch(
string $systemPrompt,
string $productContext,
array $attributePrompts
): array {
$response = $this->getClient()->chat()->create([
'model' => $this->config->getApiModel(),
'temperature' => $this->config->getTemperature(),
'frequency_penalty' => $this->config->getFrequencyPenalty(),
'presence_penalty' => $this->config->getPresencePenalty(),
'max_completion_tokens' => $this->config->getApiMaxTokens() * count($attributePrompts),
'response_format' => [
'type' => 'json_schema',
'json_schema' => [
'name' => 'product_enrichment',
'strict' => true,
'schema' => $this->buildBatchSchema($attributePrompts),
],
],
'messages' => [
['role' => 'developer', 'content' => $systemPrompt],
['role' => 'user', 'content' => $this->buildBatchPrompt($productContext, $attributePrompts)],
],
]);

$this->backoff($response->meta());

$content = $response->choices[0]?->message?->content;

return $this->parseBatchResponse($content, $attributePrompts);
}

private function getClient(): Client
{
if (!isset($this->client)) {
Expand Down
Loading