openai_codex_instructions_template.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package service
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strings"
  6. "text/template"
  7. )
  8. type forcedCodexInstructionsTemplateData struct {
  9. ExistingInstructions string
  10. OriginalModel string
  11. NormalizedModel string
  12. BillingModel string
  13. UpstreamModel string
  14. }
  15. func applyForcedCodexInstructionsTemplate(
  16. reqBody map[string]any,
  17. templateText string,
  18. data forcedCodexInstructionsTemplateData,
  19. ) (bool, error) {
  20. rendered, err := renderForcedCodexInstructionsTemplate(templateText, data)
  21. if err != nil {
  22. return false, err
  23. }
  24. if rendered == "" {
  25. return false, nil
  26. }
  27. existing, _ := reqBody["instructions"].(string)
  28. if strings.TrimSpace(existing) == rendered {
  29. return false, nil
  30. }
  31. reqBody["instructions"] = rendered
  32. return true, nil
  33. }
  34. func renderForcedCodexInstructionsTemplate(
  35. templateText string,
  36. data forcedCodexInstructionsTemplateData,
  37. ) (string, error) {
  38. tmpl, err := template.New("forced_codex_instructions").Option("missingkey=zero").Parse(templateText)
  39. if err != nil {
  40. return "", fmt.Errorf("parse forced codex instructions template: %w", err)
  41. }
  42. var buf bytes.Buffer
  43. if err := tmpl.Execute(&buf, data); err != nil {
  44. return "", fmt.Errorf("render forced codex instructions template: %w", err)
  45. }
  46. return strings.TrimSpace(buf.String()), nil
  47. }