update
This commit is contained in:
1 parent
3bfeb6b61e
commit
7537a41955
30 files changed
+1441
-85
No files matched your search
@@ -0,0 +1,43 @@
|
||||
package aiprompts
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A1's historical content sometimes repeats the exact same H2/paragraph pair.
|
||||
// Remove only identical pairs; different benefits, paragraph inclusion rules,
|
||||
// technical specifications and all non-description instructions stay intact.
|
||||
var a1HeadingParagraph = regexp.MustCompile(`(?is)<\s*h[1-4]\s*>.*?<\s*/\s*h[1-4]\s*>\s*<\s*p\s*>.*?<\s*/\s*p\s*>`)
|
||||
var a1Whitespace = regexp.MustCompile(`\s+`)
|
||||
|
||||
func DedupeA1DescriptionBlocks(source string) (string, int) {
|
||||
blocks := a1HeadingParagraph.FindAllStringIndex(source, -1)
|
||||
if len(blocks) < 2 {
|
||||
return source, 0
|
||||
}
|
||||
seen := make(map[string]bool, len(blocks))
|
||||
var out strings.Builder
|
||||
out.Grow(len(source))
|
||||
cursor, removed := 0, 0
|
||||
for _, b := range blocks {
|
||||
part := source[b[0]:b[1]]
|
||||
key := strings.ToLower(a1Whitespace.ReplaceAllString(strings.TrimSpace(part), " "))
|
||||
// Keep non-description content exactly as it was. Removing an exact
|
||||
// repeated pair must not also delete the next section or specs.
|
||||
out.WriteString(source[cursor:b[0]])
|
||||
if seen[key] {
|
||||
removed++
|
||||
} else {
|
||||
seen[key] = true
|
||||
out.WriteString(part)
|
||||
}
|
||||
cursor = b[1]
|
||||
}
|
||||
out.WriteString(source[cursor:])
|
||||
if removed == 0 {
|
||||
return source, 0
|
||||
}
|
||||
// Do not rewrite punctuation/case/brand-specific rules.
|
||||
return out.String(), removed
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package aiprompts
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDedupeA1DescriptionBlocks(t *testing.T) {
|
||||
input := `--- Title ---
|
||||
Napiši ime v slovenščini
|
||||
--- End Title ---
|
||||
--- Description ---
|
||||
<H2>{Benefit one}</H2><p>{No title}</p>
|
||||
<H2>{Benefit two}</H2><p>{Include title}</p>
|
||||
<H2>{Benefit one}</H2><p>{No title}</p>
|
||||
<H2>{Benefit two}</H2><p>{Exclude title}</p>
|
||||
<H2>{Benefit two}</H2><p>{Include title}</p>
|
||||
<b>{Tehnične specifikacije}</b><ul><li>{3-10}</li></ul>
|
||||
--- End Description ---
|
||||
--- Meta ---
|
||||
140 znakov
|
||||
--- End Meta ---`
|
||||
got, n := DedupeA1DescriptionBlocks(input)
|
||||
if n != 2 {
|
||||
t.Fatalf("removed=%d want 2", n)
|
||||
}
|
||||
if strings.Count(got, "<H2>") != 3 {
|
||||
t.Fatalf("H2 count changed incorrectly: %s", got)
|
||||
}
|
||||
for _, want := range []string{"Napiši ime", "140 znakov", "Tehnične specifikacije", "Exclude title"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("lost %q", want)
|
||||
}
|
||||
}
|
||||
again, n := DedupeA1DescriptionBlocks(got)
|
||||
if n != 0 || again != got {
|
||||
t.Fatal("cleanup not idempotent")
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package aiprompts
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
@@ -27,7 +28,27 @@ var defaultCategoryPromptsJSON []byte
|
||||
// GenericDefaultCategoryPrompt is the English formula applied to any category the
|
||||
// seed does not name. Same shape as the A1 template: naming formula, meta rule, two
|
||||
// heading/paragraph pairs, technical specifications list.
|
||||
const GenericDefaultCategoryPrompt = `Create a new product description in {{language}} using the following variables:
|
||||
// GenericDefaultCategoryPrompt is the A1-inspired standard platform template.
|
||||
// Each paragraph focuses on a distinct benefit; no duplicated headings/pairs.
|
||||
const GenericDefaultCategoryPrompt = `Create an accurate product listing in {{language}} from {{name}}, {{description}}, {{attrs}} and {{category}}. Use only supported facts.
|
||||
Product template:
|
||||
<name>{Write the new product name in this order: brand correctly capitalized, product type in lowercase, complete model with official capitalization and uppercase model ID, and color as one word if known. Do not use commas. Omit unavailable parts.}</name>
|
||||
<metaDescription>{Start with the new product name and continue to a maximum of 140 characters including spaces. Be natural, factual and do not cut words in half.}</metaDescription>
|
||||
<H2>{Write the new product name without the color and highlight the first verified benefit.}</H2>
|
||||
<p>{Write approximately 100 words about the first benefit WITHOUT repeating the complete new product name. Avoid unsupported claims.}</p>
|
||||
<H2>{Highlight a different second verified benefit WITHOUT using the new product name.}</H2>
|
||||
<p>{Write approximately 100 words about the second benefit and INCLUDE the new product name naturally once.}</p>
|
||||
<H2>{Highlight a different third verified benefit, without the new product name.}</H2>
|
||||
<p>{Write approximately 100 words about the third benefit WITHOUT repeating the complete new product name.}</p>
|
||||
<H2>{Highlight a different fourth verified benefit, without the new product name.}</H2>
|
||||
<p>{Write approximately 100 words about the fourth benefit and INCLUDE the new product name naturally once.}</p>
|
||||
<H2>{Highlight a different fifth verified benefit, without the new product name.}</H2>
|
||||
<p>{Write approximately 100 words about the fifth benefit WITHOUT repeating the complete new product name.}</p>
|
||||
<b>{Technical specifications}</b><ul><li>{List 3–10 sourced technical specifications as bullet points. If fewer than 3 are verified, list only those available. Never invent specifications.}</li></ul>`
|
||||
|
||||
// Previous generic default, kept only to safely identify untouched old values
|
||||
// when migrating existing companies to the new platform default.
|
||||
const LegacyGenericDefaultCategoryPrompt = `Create a new product description in {{language}} using the following variables:
|
||||
|
||||
Old_product_description: {"PRODUCT DESCRIPTION"};
|
||||
Old_product_name: {"OLD PRODUCT NAME"};
|
||||
@@ -85,13 +106,17 @@ type defaultCategoryPromptsFile struct {
|
||||
var (
|
||||
defaultFormulaOnce sync.Once
|
||||
defaultFormulaByKey map[string]CategoryFormulaDefaults
|
||||
legacyFormulaByKey map[string]CategoryFormulaDefaults
|
||||
legacyFormulaGeneric CategoryFormulaDefaults
|
||||
defaultFormulaGeneric CategoryFormulaDefaults
|
||||
defaultFormulaCount int
|
||||
)
|
||||
|
||||
func loadDefaultCategoryFormulas() {
|
||||
defaultFormulaGeneric = buildCategoryFormulaDefaults("", GenericDefaultCategoryPrompt)
|
||||
legacyFormulaGeneric = buildCategoryFormulaDefaults("", LegacyGenericDefaultCategoryPrompt)
|
||||
defaultFormulaByKey = map[string]CategoryFormulaDefaults{}
|
||||
legacyFormulaByKey = map[string]CategoryFormulaDefaults{}
|
||||
|
||||
var f defaultCategoryPromptsFile
|
||||
if err := json.Unmarshal(defaultCategoryPromptsJSON, &f); err != nil {
|
||||
@@ -104,7 +129,17 @@ func loadDefaultCategoryFormulas() {
|
||||
if prompt == "" {
|
||||
continue
|
||||
}
|
||||
res := buildCategoryFormulaDefaults(strings.TrimSpace(e.Name), prompt)
|
||||
legacy := buildCategoryFormulaDefaults(strings.TrimSpace(e.Name), prompt)
|
||||
// Retain category-specific naming instructions but standardize the
|
||||
// description and meta structure across the platform defaults.
|
||||
parts := ParseLegacyCombinedEnhancePrompt(prompt)
|
||||
base := ParseLegacyCombinedEnhancePrompt(GenericDefaultCategoryPrompt)
|
||||
parts.DescriptionRules = base.DescriptionRules
|
||||
parts.MetaRules = base.MetaRules
|
||||
if parts.TitleRules == "" {
|
||||
parts.TitleRules = base.TitleRules
|
||||
}
|
||||
res := buildCategoryFormulaDefaultsFromParts(strings.TrimSpace(e.Name), parts)
|
||||
if res.Overlay == "" {
|
||||
continue
|
||||
}
|
||||
@@ -112,6 +147,7 @@ func loadDefaultCategoryFormulas() {
|
||||
for _, key := range append([]string{e.Name, e.UniqueID}, e.Aliases...) {
|
||||
if k := NormalizeCategoryKey(key); k != "" {
|
||||
defaultFormulaByKey[k] = res
|
||||
legacyFormulaByKey[k] = legacy
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,6 +158,10 @@ func buildCategoryFormulaDefaults(name, legacyPrompt string) CategoryFormulaDefa
|
||||
if !parts.WasLegacy {
|
||||
return CategoryFormulaDefaults{}
|
||||
}
|
||||
return buildCategoryFormulaDefaultsFromParts(name, parts)
|
||||
}
|
||||
|
||||
func buildCategoryFormulaDefaultsFromParts(name string, parts LegacyEnhanceParts) CategoryFormulaDefaults {
|
||||
out := CategoryFormulaDefaults{
|
||||
MatchedName: name,
|
||||
Overlay: BuildCategoryEnhanceOverlay(parts),
|
||||
@@ -161,6 +201,19 @@ func DefaultCategoryFormula(uniqueID, name string) CategoryFormulaDefaults {
|
||||
return defaultFormulaGeneric
|
||||
}
|
||||
|
||||
// LegacyDefaultCategoryFormula is used exclusively by the migration seed to
|
||||
// recognize previously generated platform defaults. It MUST NOT be used for
|
||||
// creating new category instructions.
|
||||
func LegacyDefaultCategoryFormula(uniqueID, name string) CategoryFormulaDefaults {
|
||||
defaultFormulaOnce.Do(loadDefaultCategoryFormulas)
|
||||
for _, key := range []string{uniqueID, name} {
|
||||
if def, ok := legacyFormulaByKey[NormalizeCategoryKey(key)]; ok {
|
||||
return def
|
||||
}
|
||||
}
|
||||
return legacyFormulaGeneric
|
||||
}
|
||||
|
||||
// GenericCategoryFormula is DefaultCategoryFormula's fallback on its own — used
|
||||
// when only the shape matters and the category is unknown.
|
||||
func GenericCategoryFormula() CategoryFormulaDefaults {
|
||||
@@ -208,3 +261,24 @@ func NormalizeCategoryKey(s string) string {
|
||||
}
|
||||
return strings.TrimSpace(b.String())
|
||||
}
|
||||
|
||||
// AllDefaultCategoryPrompts returns every bundled English default enhance overlay,
|
||||
// including the generic fallback. Seed these once globally so future categories
|
||||
// never require an AI request during creation.
|
||||
func AllDefaultCategoryPrompts() []string {
|
||||
defaultFormulaOnce.Do(loadDefaultCategoryFormulas)
|
||||
unique := map[string]bool{defaultFormulaGeneric.Overlay: true}
|
||||
for _, def := range defaultFormulaByKey {
|
||||
if def.Overlay != "" {
|
||||
unique[def.Overlay] = true
|
||||
}
|
||||
}
|
||||
out := make([]string, 0, len(unique))
|
||||
for source := range unique {
|
||||
if source != "" {
|
||||
out = append(out, source)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
@@ -49,8 +49,8 @@ func TestDefaultCategoryFormula_matchesA1Shape(t *testing.T) {
|
||||
for _, s := range f.Sections {
|
||||
types = append(types, s.Type)
|
||||
}
|
||||
if strings.Join(types, ",") != "h2,p,h2,p,ul" {
|
||||
t.Fatalf("description sections = %v want h2,p,h2,p,ul", types)
|
||||
if strings.Join(types, ",") != "h2,p,h2,p,h2,p,h2,p,h2,p,ul" {
|
||||
t.Fatalf("description sections = %v want h2,p,h2,p,h2,p,h2,p,h2,p,ul", types)
|
||||
}
|
||||
if f.MetaTitle == "" || f.MetaDescription == "" {
|
||||
t.Fatalf("meta rules missing: %+v", f)
|
||||
|
||||
@@ -30,7 +30,7 @@ const applyDefaultCategoryFormulasSQL = `
|
||||
UPDATE categories AS c SET
|
||||
prompt = CASE
|
||||
WHEN c.prompt IS NULL OR c.prompt = '{}'::jsonb
|
||||
THEN v.prompt::jsonb ELSE c.prompt END,
|
||||
THEN v.prompt::jsonb || v.translations ELSE c.prompt END,
|
||||
title_template = CASE
|
||||
WHEN c.title_template IS NULL OR c.title_template::text IN ('null', '{}')
|
||||
THEN NULLIF(v.title_template, '')::jsonb ELSE c.title_template END,
|
||||
@@ -39,13 +39,16 @@ const applyDefaultCategoryFormulasSQL = `
|
||||
THEN NULLIF(v.description_template, '')::jsonb ELSE c.description_template END,
|
||||
updated_at = now()
|
||||
FROM (
|
||||
SELECT * FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[])
|
||||
AS t(id, prompt, title_template, description_template)
|
||||
SELECT t.id, t.prompt, t.title_template, t.description_template,
|
||||
COALESCE(cache.translations, '{}'::jsonb) AS translations
|
||||
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[])
|
||||
AS t(id, prompt, title_template, description_template, source_hash)
|
||||
LEFT JOIN default_category_prompt_translations cache ON cache.source_hash = t.source_hash
|
||||
) AS v
|
||||
WHERE c.id = v.id AND c.company_id = $1`
|
||||
|
||||
// ApplyDefaultCategoryFormulas gives newly created categories the platform-default
|
||||
// formulas (English, same style as the A1 legacy templates) when they have none.
|
||||
// formulas and any seeded translations when they have none.
|
||||
//
|
||||
// New categories get a working title/description/meta formula out of the box
|
||||
// instead of falling through to generic "1-3 paragraphs" copy. Existing rows are
|
||||
@@ -56,6 +59,7 @@ func ApplyDefaultCategoryFormulas(ctx context.Context, db pgxExecer, companyID u
|
||||
return nil
|
||||
}
|
||||
ids := make([]uuid.UUID, 0, len(targets))
|
||||
hashes := make([]string, 0, len(targets))
|
||||
prompts := make([]string, 0, len(targets))
|
||||
titles := make([]string, 0, len(targets))
|
||||
descs := make([]string, 0, len(targets))
|
||||
@@ -67,12 +71,13 @@ func ApplyDefaultCategoryFormulas(ctx context.Context, db pgxExecer, companyID u
|
||||
if def.Overlay == "" {
|
||||
continue
|
||||
}
|
||||
// "*" applies to every content language: the formula text is English while
|
||||
// {{language}} still selects the output language at render time.
|
||||
// Keep the English wildcard for an explicit fallback if a translation
|
||||
// is missing; the seed's language variants take precedence.
|
||||
promptJSON, err := company.EncodeLangPromptMap(company.LangPromptMap{"*": def.Overlay})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hashes = append(hashes, DefaultPromptHash(def.Overlay))
|
||||
ids = append(ids, t.ID)
|
||||
prompts = append(prompts, string(promptJSON))
|
||||
titles = append(titles, def.TitleTemplateJSON)
|
||||
@@ -81,6 +86,6 @@ func ApplyDefaultCategoryFormulas(ctx context.Context, db pgxExecer, companyID u
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := db.Exec(ctx, applyDefaultCategoryFormulasSQL, companyID, ids, prompts, titles, descs)
|
||||
_, err := db.Exec(ctx, applyDefaultCategoryFormulasSQL, companyID, ids, prompts, titles, descs, hashes)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||
)
|
||||
|
||||
// DefaultPromptHash versions platform translations by the exact English formula.
|
||||
// Editing a built-in formula therefore cannot accidentally apply stale translations.
|
||||
func DefaultPromptHash(source string) string {
|
||||
sum := sha256.Sum256([]byte(source))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// IsUntouchedDefaultPrompt ensures tenant-authored prompts are NEVER translated,
|
||||
// modified, or mistaken for the platform's default. A language override is
|
||||
// eligible only when it is an exact copy of a previously seeded default.
|
||||
func IsUntouchedDefaultPrompt(prompts company.LangPromptMap, source string, seeded company.LangPromptMap) bool {
|
||||
if strings.TrimSpace(source) == "" {
|
||||
return false
|
||||
}
|
||||
for code, value := range prompts {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
if code == "*" || code == "en" {
|
||||
if value != source {
|
||||
return false
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !company.IsAllowedLanguage(code) || strings.TrimSpace(seeded[code]) != value {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/aiprompts"
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||
)
|
||||
|
||||
func TestIsUntouchedDefaultPrompt(t *testing.T) {
|
||||
source := aiprompts.GenericCategoryFormula().Overlay
|
||||
seeded := company.LangPromptMap{"de": "Vorgabe", "sl": "Predloga"}
|
||||
for name, prompts := range map[string]company.LangPromptMap{
|
||||
"no stored prompt": {},
|
||||
"shared default": {"*": source},
|
||||
"existing translated default": {"*": source, "de": "Vorgabe", "sl": "Predloga"},
|
||||
"english default": {"en": source},
|
||||
} {
|
||||
if !IsUntouchedDefaultPrompt(prompts, source, seeded) {
|
||||
t.Errorf("%s should be default", name)
|
||||
}
|
||||
}
|
||||
for name, prompts := range map[string]company.LangPromptMap{
|
||||
"custom shared": {"*": "My shop-specific instructions"},
|
||||
"custom english": {"en": "Custom"},
|
||||
"custom german override": {"*": source, "de": "Our custom German copy"},
|
||||
"custom extra language": {"*": source, "fr": "custom"},
|
||||
"unsupported override": {"*": source, "xx": "custom"},
|
||||
} {
|
||||
if IsUntouchedDefaultPrompt(prompts, source, seeded) {
|
||||
t.Errorf("%s must stay custom", name)
|
||||
}
|
||||
}
|
||||
if DefaultPromptHash(source) == DefaultPromptHash("changed "+source) {
|
||||
t.Fatal("hash not versioned by source")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultPromptSourcesCoverGenericAndTaxonomy(t *testing.T) {
|
||||
all := aiprompts.AllDefaultCategoryPrompts()
|
||||
if len(all) < 100 {
|
||||
t.Fatalf("expected embedded taxonomy + generic, got %d", len(all))
|
||||
}
|
||||
generic := aiprompts.GenericCategoryFormula().Overlay
|
||||
found := false
|
||||
for _, s := range all {
|
||||
if s == generic {
|
||||
found = true
|
||||
}
|
||||
if s == "" {
|
||||
t.Fatal("empty default")
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("generic default not included")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user