prompt

package
v0.17.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 11 Imported by: 3 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package prompt provides a local, renderable representation of a Braintrust prompt.

A prompt is a template — messages or a completion string containing mustache placeholders — plus a model and its parameters. Prompt.Build renders the template with a set of variables and returns a Built that you can hand to any LLM client.

Prompts reach a Go program two ways. A remote eval can declare a prompt parameter, and the value chosen in the Braintrust playground arrives on the task's hooks:

p, ok := hooks.Parameters.Prompt("summary_prompt")
built, err := p.Build(map[string]any{"input": input})

Or a prompt saved in Braintrust can be loaded by slug:

p, err := bt.LoadPrompt(ctx, prompt.LoadOpts{Slug: "summarizer"})
built, err := p.Build(map[string]any{"input": article})

Index

Constants

View Source
const (
	// FormatMustache renders {{variable}} placeholders. The default.
	FormatMustache = "mustache"

	// FormatNone treats the prompt as literal text.
	FormatNone = "none"

	// FormatNunjucks is a Braintrust playground feature the Go SDK cannot
	// render. Building such a prompt returns an error.
	FormatNunjucks = "nunjucks"
)

Template formats a prompt can declare. Mustache is the default and the only one this SDK renders; see Prompt.Build.

View Source
const (
	BlockChat       = "chat"
	BlockCompletion = "completion"
)

Block types.

Variables

This section is empty.

Functions

This section is empty.

Types

type Block

type Block struct {
	Type string `json:"type"`

	// Messages is the chat message list, for Type "chat".
	Messages []Message `json:"messages,omitempty"`

	// Tools is a JSON-encoded array of tool definitions, for Type "chat". It is
	// a string because that is how Braintrust stores it: the whole array is
	// templated before being parsed.
	Tools string `json:"tools,omitempty"`

	// Content is the completion template, for Type "completion".
	Content string `json:"content,omitempty"`
}

Block is the body of a prompt. Type is either "chat", in which case Messages is set, or "completion", in which case Content is.

type BuildOption

type BuildOption func(*buildConfig)

BuildOption configures Prompt.Build.

func WithDefaults

func WithDefaults(defaults map[string]any) BuildOption

WithDefaults supplies default model parameters, used for any parameter the prompt itself does not set.

func WithStrict

func WithStrict() BuildOption

WithStrict makes Build fail when the template references a variable that was not supplied. By default a missing variable renders as an empty string, which is what the Braintrust playground does.

func WithTemplateFormat

func WithTemplateFormat(format string) BuildOption

WithTemplateFormat overrides the template format saved on the prompt.

type Built

type Built struct {
	// Model is the model to call.
	Model string

	// Messages is the rendered chat message list, for a chat prompt.
	Messages []Message

	// Prompt is the rendered completion text, for a completion prompt.
	Prompt string

	// Params are the model parameters (temperature, max_tokens, ...).
	Params map[string]any

	// Tools are the rendered tool definitions, if the prompt declares any.
	Tools []Tool

	// Metadata describes the prompt this was built from, for tracing. It is nil
	// when the prompt has no Braintrust identity. See [Built.AnnotateSpan].
	Metadata *Metadata
	// contains filtered or unexported fields
}

Built is a rendered prompt: the model to call, the rendered body, and the parameters to call it with. Get one from Prompt.Build.

It is deliberately provider-agnostic. Convert it to a request for your client — trace/contrib/openai has ChatCompletionParams for openai-go — or use Built.Map for anything that speaks OpenAI-shaped JSON.

func (*Built) AnnotateSpan

func (b *Built) AnnotateSpan(span oteltrace.Span)

AnnotateSpan records the prompt's identity and the variables it was rendered with on span, which is what links the call back to the prompt in Braintrust. It does nothing when there is no metadata to record.

Pass the span covering the model call — in an eval, hooks.TaskSpan:

built.AnnotateSpan(hooks.TaskSpan)

func (*Built) IsChat

func (b *Built) IsChat() bool

IsChat reports whether the built prompt is a chat prompt (Messages) rather than a completion (Prompt).

func (*Built) Map

func (b *Built) Map() map[string]any

Map returns the built prompt as the OpenAI-shaped map the other Braintrust SDKs return from build(): model, messages or prompt, tools, and every model parameter at the top level. Use it with clients this SDK has no adapter for.

body, err := json.Marshal(built.Map())

The values are the SDK's own types, not decoded JSON -- "messages" holds []Message, for instance -- so the map is meant for encoding rather than for type assertions. Tracing metadata is not included; it is not part of the request.

type Content

type Content struct {
	// Text is set when the content is plain text.
	Text string

	// Parts is set when the content is a list of parts.
	Parts []ContentPart
}

Content is the content of a Message. It is either plain text or a list of parts (text, images, files), because that is what the underlying API allows. Use TextContent or PartsContent to build one.

func PartsContent

func PartsContent(parts ...ContentPart) Content

PartsContent returns multi-part content.

func TextContent

func TextContent(text string) Content

TextContent returns plain text content.

func (Content) IsZero

func (c Content) IsZero() bool

IsZero reports whether the content is empty. It also makes `omitzero` work on Message.Content.

func (Content) MarshalJSON

func (c Content) MarshalJSON() ([]byte, error)

MarshalJSON encodes content as a string or an array of parts, matching the Braintrust API.

func (Content) String

func (c Content) String() string

String returns the content as text. Multi-part content is joined from its text parts; non-text parts are skipped.

func (*Content) UnmarshalJSON

func (c *Content) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a string, an array of parts, or null.

type ContentPart

type ContentPart struct {
	Type     string    `json:"type"`
	Text     string    `json:"text,omitempty"`
	ImageURL *ImageURL `json:"image_url,omitempty"`
	File     *File     `json:"file,omitempty"`
}

ContentPart is one part of multi-part message content.

type Data

type Data struct {
	// Prompt is the prompt body: chat messages or a completion string.
	Prompt *Block `json:"prompt,omitempty"`

	// Options holds the model and its parameters.
	Options *Options `json:"options,omitempty"`

	// TemplateFormat is one of [FormatMustache], [FormatNone] or
	// [FormatNunjucks]. Empty means mustache.
	TemplateFormat string `json:"template_format,omitempty"`

	// Origin identifies the saved prompt this data came from, when it was sent
	// by the Braintrust playground.
	Origin *Origin `json:"origin,omitempty"`

	// Parser, ToolFunctions and MCP are server-side features the Go SDK does
	// not act on. They are preserved so prompt data survives a round trip.
	Parser        json.RawMessage `json:"parser,omitempty"`
	ToolFunctions json.RawMessage `json:"tool_functions,omitempty"`
	MCP           json.RawMessage `json:"mcp,omitempty"`
}

Data is the prompt payload Braintrust stores and the playground sends: the prompt body, the model and its parameters, and how the body should be templated. It mirrors the PromptData object in the Braintrust API.

type Definition

type Definition struct {
	// Model is the model the prompt targets. Required.
	Model string

	// Messages is the chat message list. Mutually exclusive with Prompt.
	Messages []Message

	// Prompt is the completion template. Mutually exclusive with Messages.
	Prompt string

	// Params are model parameters such as temperature or max_tokens.
	Params map[string]any

	// Tools are tool definitions offered to the model. Chat prompts only.
	Tools []Tool

	// TemplateFormat is [FormatMustache] (the default) or [FormatNone].
	TemplateFormat string
}

Definition declares a prompt in Go code. It is the shape you write when giving a prompt eval parameter a default:

Default: prompt.Definition{
	Model: "gpt-4o-mini",
	Messages: []prompt.Message{
		prompt.System("You summarize articles in one sentence."),
		prompt.User("Summarize this:\n\n{{input}}"),
	},
	Params: map[string]any{"temperature": 0},
}

Set either Messages (a chat prompt) or Prompt (a completion prompt). Definition serializes to the prompt data format Braintrust expects, so it can be used anywhere prompt data is accepted.

func (Definition) Data

func (d Definition) Data() Data

Data converts the definition to prompt data.

func (Definition) MarshalJSON

func (d Definition) MarshalJSON() ([]byte, error)

MarshalJSON encodes the definition as prompt data, so a Definition used as a parameter default reaches Braintrust in the format the playground expects.

type File

type File struct {
	FileData string `json:"file_data,omitempty"`
	FileID   string `json:"file_id,omitempty"`
	Filename string `json:"filename,omitempty"`
}

File is the file payload of a content part.

type ImageURL

type ImageURL struct {
	URL    string `json:"url"`
	Detail string `json:"detail,omitempty"`
}

ImageURL is the image payload of a content part.

type LoadOpts

type LoadOpts struct {
	// Slug is the prompt's slug. Required unless ID is set.
	Slug string

	// Project is the name of the project holding the prompt. Ignored when ID or
	// ProjectID is set. [braintrust.Client.LoadPrompt] fills this in with the
	// client's project when it is empty.
	Project string

	// ProjectID identifies the project by ID instead of by name.
	ProjectID string

	// ID loads a prompt by its Braintrust ID, ignoring Slug and project.
	ID string

	// Version pins to a specific prompt version. Defaults to the latest.
	Version string

	// Environment loads the prompt deployed to an environment, for example
	// "production". Ignored when Version is set.
	Environment string
}

LoadOpts selects the prompt Load fetches.

type Message

type Message struct {
	Role       string     `json:"role"`
	Content    Content    `json:"content,omitzero"`
	Name       string     `json:"name,omitempty"`
	ToolCalls  []ToolCall `json:"tool_calls,omitempty"`
	ToolCallID string     `json:"tool_call_id,omitempty"`
}

Message is a single chat message.

func Assistant

func Assistant(text string) Message

Assistant returns an assistant message with the given template text.

func System

func System(text string) Message

System returns a system message with the given template text.

func User

func User(text string) Message

User returns a user message with the given template text.

type Metadata

type Metadata struct {
	ID        string         `json:"id,omitempty"`
	ProjectID string         `json:"project_id,omitempty"`
	Version   string         `json:"version,omitempty"`
	Variables map[string]any `json:"variables,omitempty"`
}

Metadata identifies the prompt a Built came from and the variables it was rendered with. Recording it on a span is what links a model call back to the prompt in Braintrust.

type Options

type Options struct {
	Model string `json:"model,omitempty"`

	// Params are model parameters such as temperature or max_tokens. They are
	// untyped because the shape differs per provider and Braintrust accepts
	// provider-specific keys.
	Params map[string]any `json:"params,omitempty"`

	Position string `json:"position,omitempty"`
}

Options holds the model a prompt targets and the parameters to call it with.

type Origin

type Origin struct {
	PromptID      string `json:"prompt_id,omitempty"`
	ProjectID     string `json:"project_id,omitempty"`
	PromptVersion string `json:"prompt_version,omitempty"`
}

Origin identifies the saved prompt a Data value came from.

type Prompt

type Prompt struct {
	// ID is the prompt's Braintrust ID.
	ID string

	// Name is the prompt's display name.
	Name string

	// Slug is the prompt's slug.
	Slug string

	// ProjectID is the ID of the project holding the prompt.
	ProjectID string

	// Version is the transaction ID of the loaded version.
	Version string

	// Data is the prompt payload: body, model, options.
	Data Data
}

Prompt is a renderable Braintrust prompt: a template, a model, and the parameters to call it with. Build it with Prompt.Build.

The identity fields are set when the prompt was loaded from Braintrust; a prompt constructed from raw data with FromData has none.

func FromData

func FromData(name string, data Data) *Prompt

FromData returns a prompt built from raw prompt data, named name. Use it when prompt data arrives from somewhere other than a Braintrust API call — a playground parameter, a config file, a test fixture.

func FromValue

func FromValue(name string, value any) (*Prompt, error)

FromValue converts a value into a prompt, named name.

It accepts anything a prompt can arrive as: a *Prompt, a Definition or Data declared in Go, or prompt data decoded from JSON (a map[string]any or json.RawMessage, which is how the Braintrust playground sends a prompt parameter). This is what makes a prompt parameter's Go default and its playground value end up as the same type.

func Load

func Load(ctx context.Context, client *api.API, opts LoadOpts) (*Prompt, error)

Load fetches a prompt from Braintrust and returns it ready to render.

Most callers want [braintrust.Client.LoadPrompt], which supplies the API client and the default project. Use Load directly when you already hold an API client:

p, err := prompt.Load(ctx, client.API(), prompt.LoadOpts{Slug: "summarizer"})
if err != nil {
	return err
}
built, err := p.Build(map[string]any{"input": article})

The prompt is fetched every time; nothing is cached.

func (*Prompt) Build

func (p *Prompt) Build(vars map[string]any, opts ...BuildOption) (*Built, error)

Build renders the prompt with vars and returns the result.

Variables are addressed by name ({{name}}); the whole map is also bound to "input", so a prompt written against {{input}} in the playground works without wrapping. Values that are not strings are interpolated as JSON.

built, err := p.Build(map[string]any{"article": text})
if err != nil {
	return err
}
resp, err := client.Chat.Completions.New(ctx, traceopenai.ChatCompletionParams(built))

Build fails if the prompt has no body or no model, if the template is malformed, or if the prompt uses a template format the SDK cannot render.

func (*Prompt) Messages

func (p *Prompt) Messages() []Message

Messages returns the prompt's unrendered chat messages, or nil for a completion prompt.

func (*Prompt) Model

func (p *Prompt) Model() string

Model returns the model the prompt targets, or "" if it declares none.

func (*Prompt) TemplateFormat

func (p *Prompt) TemplateFormat() string

TemplateFormat returns the prompt's template format, defaulting to FormatMustache.

type Tool

type Tool struct {
	Type     string       `json:"type"`
	Function ToolFunction `json:"function"`
}

Tool is a tool definition offered to the model.

type ToolCall

type ToolCall struct {
	ID       string           `json:"id"`
	Type     string           `json:"type"`
	Function ToolCallFunction `json:"function"`
}

ToolCall is a tool call recorded on an assistant message.

type ToolCallFunction

type ToolCallFunction struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ToolCallFunction is the function a ToolCall invokes.

type ToolFunction

type ToolFunction struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	Parameters  map[string]any `json:"parameters,omitempty"`
	Strict      *bool          `json:"strict,omitempty"`
}

ToolFunction describes the function a Tool exposes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL