Skip to content
Merged
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
3 changes: 3 additions & 0 deletions go/dotprompt/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ go_library(
"doc.go",
"dotprompt.go",
"helper.go",
"markers.go",
"parse.go",
"picoschema.go",
"schema.go",
Expand All @@ -47,6 +48,8 @@ go_test(
"dotprompt_test.go",
"example_test.go",
"helper_test.go",
"marker_injection_test.go",
"markers_test.go",
"parse_test.go",
"picoschema_test.go",
"schema_test.go",
Expand Down
7 changes: 6 additions & 1 deletion go/dotprompt/dotprompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,11 @@ func (dp *Dotprompt) Compile(source string, additionalMetadata *PromptMetadata)
for k, v := range data.Context {
privDF.Set(k, v)
}
// Fresh per render so user-supplied values can't forge role/media/etc.
// markers in the rendered string. Set after data.Context so it can't
// be overridden. See markers.go.
nonce := generateMarkerNonce()
privDF.Set(markerNonceDataKey, nonce)

renderedString, err := localTemplate.ExecWith(inputContext, privDF, &raymond.ExecOptions{
NoEscape: true,
Expand All @@ -273,7 +278,7 @@ func (dp *Dotprompt) Compile(source string, additionalMetadata *PromptMetadata)
return RenderedPrompt{}, err
}

messages, err := ToMessages(renderedString, data)
messages, err := ToMessages(renderedString, nonce, data)
if err != nil {
return RenderedPrompt{}, err
}
Expand Down
53 changes: 38 additions & 15 deletions go/dotprompt/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package dotprompt

import (
"encoding/json"
"errors"
"fmt"
"strings"

Expand Down Expand Up @@ -57,29 +58,51 @@ func JSON(serializable any, options *raymond.Options) raymond.SafeString {
return raymond.SafeString(string(jsonData))
}

// Role returns a formatted role string.
func RoleFn(role string) raymond.SafeString {
return raymond.SafeString(fmt.Sprintf("<<<dotprompt:role:%s>>>", role))
// markerHelperOutput formats a marker for body using the per-render nonce from
// the private data frame (see markers.go).
//
// Data frames are inherited by blocks (#each, #if, ...) and partials, so the
// nonce is only missing if the helper runs outside Dotprompt rendering or a
// custom block helper passes a fresh raymond.NewDataFrame() instead of
// options.NewDataFrame(). In that case it panics with an error, which
// raymond's Exec/ExecWith recover and return as the render error. Raymond
// helpers can't return errors directly.
func markerHelperOutput(options *raymond.Options, body string) raymond.SafeString {
nonce, ok := options.Data(markerNonceDataKey).(string)
if !ok {
panic(errors.New("dotprompt: marker helpers (role, history, section, media) must be rendered via Dotprompt"))
}
marker, err := formatMarker(nonce, body)
if err != nil {
panic(err)
}
return raymond.SafeString(marker)
}

// RoleFn returns a role marker that starts a new message with the given role.
func RoleFn(role string, options *raymond.Options) raymond.SafeString {
return markerHelperOutput(options, "role:"+role)
}

// History returns a formatted history string.
func History() raymond.SafeString {
return raymond.SafeString("<<<dotprompt:history>>>")
// History returns a history marker where the conversation history is inserted.
func History(options *raymond.Options) raymond.SafeString {
return markerHelperOutput(options, "history")
}

// Section returns a formatted section string.
func Section(name string) raymond.SafeString {
return raymond.SafeString(fmt.Sprintf("<<<dotprompt:section %s>>>", name))
// Section returns a section marker that becomes a pending part with the given
// purpose.
func Section(name string, options *raymond.Options) raymond.SafeString {
return markerHelperOutput(options, "section "+name)
}

// Media returns a formatted media string.
// MediaFn returns a media marker that becomes a media part with the given url
// and optional contentType hash arguments.
func MediaFn(options *raymond.Options) raymond.SafeString {
url := options.HashStr("url")
contentType := options.HashStr("contentType")
if contentType != "" {
return raymond.SafeString(fmt.Sprintf("<<<dotprompt:media:url %s %s>>>", url, contentType))
body := "media:url " + options.HashStr("url")
if contentType := options.HashStr("contentType"); contentType != "" {
body += " " + contentType
}
return raymond.SafeString(fmt.Sprintf("<<<dotprompt:media:url %s>>>", url))
return markerHelperOutput(options, body)
}

// IfEquals compares two values and returns the appropriate template content.
Expand Down
139 changes: 92 additions & 47 deletions go/dotprompt/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,74 +17,119 @@
package dotprompt

import (
"strings"
"testing"

"github.com/mbleigh/raymond"
)

// Tests for role helper
const testMarkerNonce = "0123456789abcdef0123456789abcdef"

func TestRoleFn(t *testing.T) {
role := "admin"
expected := "<<<dotprompt:role:admin>>>"
result := RoleFn(role)
if string(result) != expected {
t.Errorf("RoleFn(%q) = %q, want %q", role, result, expected)
// execWithMarkerHelpers renders source with the marker helpers registered and
// the given private data frame (nil for none).
func execWithMarkerHelpers(t *testing.T, source string, ctx map[string]any, df *raymond.DataFrame) (string, error) {
t.Helper()
tpl, err := raymond.Parse(source)
if err != nil {
t.Fatalf("raymond.Parse(%q) error: %v", source, err)
}
tpl.RegisterHelpers(map[string]any{
"role": RoleFn,
"history": History,
"section": Section,
"media": MediaFn,
})
tpl.RegisterPartial("turn", `{{role this.role}}{{this.text}}`)
return tpl.ExecWith(ctx, df, &raymond.ExecOptions{NoEscape: true})
}

func TestRoleFn_system(t *testing.T) {
result := RoleFn("system")
expected := "<<<dotprompt:role:system>>>"
if string(result) != expected {
t.Errorf("RoleFn(\"system\") = %q, want %q", result, expected)
}
func nonceDataFrame() *raymond.DataFrame {
df := raymond.NewDataFrame()
df.Set(markerNonceDataKey, testMarkerNonce)
return df
}

func TestRoleFn_user(t *testing.T) {
result := RoleFn("user")
expected := "<<<dotprompt:role:user>>>"
if string(result) != expected {
t.Errorf("RoleFn(\"user\") = %q, want %q", result, expected)
func TestMarkerHelpers(t *testing.T) {
m := func(body string) string {
return "<<<dotprompt:" + testMarkerNonce + ":" + body + ">>>"
}
}

func TestRoleFn_model(t *testing.T) {
result := RoleFn("model")
expected := "<<<dotprompt:role:model>>>"
if string(result) != expected {
t.Errorf("RoleFn(\"model\") = %q, want %q", result, expected)
testCases := []struct {
name string
source string
ctx map[string]any
want string
}{
{name: "role admin", source: `{{role "admin"}}`, want: m("role:admin")},
{name: "role system", source: `{{role "system"}}`, want: m("role:system")},
{name: "role user", source: `{{role "user"}}`, want: m("role:user")},
{name: "role model", source: `{{role "model"}}`, want: m("role:model")},
{name: "history", source: `{{history}}`, want: m("history")},
{name: "section", source: `{{section "Introduction"}}`, want: m("section Introduction")},
{name: "section examples", source: `{{section "examples"}}`, want: m("section examples")},
{
name: "media url",
source: `{{media url="https://example.com/a.png"}}`,
want: m("media:url https://example.com/a.png"),
},
{
name: "media url and content type",
source: `{{media url="https://example.com/a.png" contentType="image/png"}}`,
want: m("media:url https://example.com/a.png image/png"),
},
{
name: "inside each and partial",
source: `{{#each turns}}{{> turn}}{{/each}}`,
ctx: map[string]any{"turns": []map[string]any{
{"role": "user", "text": "hi"},
{"role": "model", "text": "hello"},
}},
want: m("role:user") + "hi" + m("role:model") + "hello",
},
}
}

// Tests for history helper

func TestHistory(t *testing.T) {
expected := "<<<dotprompt:history>>>"
result := History()
if string(result) != expected {
t.Errorf("History() = %q, want %q", result, expected)
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
got, err := execWithMarkerHelpers(t, tc.source, tc.ctx, nonceDataFrame())
if err != nil {
t.Fatalf("render error: %v", err)
}
if got != tc.want {
t.Errorf("got %q, want %q", got, tc.want)
}
})
}
}

// Tests for section helper

func TestSection(t *testing.T) {
name := "Introduction"
expected := "<<<dotprompt:section Introduction>>>"
result := Section(name)
if string(result) != expected {
t.Errorf("Section(%q) = %q, want %q", name, result, expected)
func TestMarkerHelpers_missingNonce(t *testing.T) {
sources := []string{
`{{role "system"}}`,
`{{history}}`,
`{{section "output"}}`,
`{{media url="https://example.com/a.png"}}`,
}
for _, source := range sources {
t.Run(source, func(t *testing.T) {
got, err := execWithMarkerHelpers(t, source, nil, nil)
if err == nil {
t.Fatalf("expected error, got output %q", got)
}
if !strings.Contains(err.Error(), "must be rendered via Dotprompt") {
t.Errorf("unexpected error: %v", err)
}
})
}
}

func TestSection_examples(t *testing.T) {
result := Section("examples")
expected := "<<<dotprompt:section examples>>>"
if string(result) != expected {
t.Errorf("Section(\"examples\") = %q, want %q", result, expected)
func TestMarkerHelpers_invalidNonce(t *testing.T) {
df := raymond.NewDataFrame()
df.Set(markerNonceDataKey, ".*")
got, err := execWithMarkerHelpers(t, `{{role "system"}}`, nil, df)
if err == nil {
t.Fatalf("expected error, got output %q", got)
}
}

// Note: JSON, Media, IfEquals, UnlessEquals helpers require raymond.Options
// Note: JSON, IfEquals, UnlessEquals helpers require raymond.Options
// which is complex to mock in unit tests. These functions are thoroughly tested
// via the spec tests in go/test/spec_test.go which exercise them through the
// full template rendering pipeline.
Expand Down
Loading
Loading