Class: Braintrust::Prompt

Inherits:
Object
  • Object
show all
Defined in:
lib/braintrust/prompt.rb

Overview

Prompt class for loading and building prompts from Braintrust

Examples:

Load and use a prompt

prompt = Braintrust::Prompt.load(project: "my-project", slug: "summarizer")
params = prompt.build(text: "Article to summarize...")
client.messages.create(**params)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, defaults: {}) ⇒ Prompt

Initialize a Prompt from function data

Parameters:

  • data (Hash)

    Function data from API

  • defaults (Hash) (defaults to: {})

    Default variable values for build()



47
48
49
50
51
52
53
54
55
56
# File 'lib/braintrust/prompt.rb', line 47

def initialize(data, defaults: {})
  @data = data
  @defaults = Internal::Template.stringify_keys(defaults)

  @id = data["id"]
  @name = data["name"]
  @slug = data["slug"]
  @project_id = data["project_id"]
  @version = data["_xact_id"]
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



14
15
16
# File 'lib/braintrust/prompt.rb', line 14

def id
  @id
end

#nameObject (readonly)

Returns the value of attribute name.



14
15
16
# File 'lib/braintrust/prompt.rb', line 14

def name
  @name
end

#project_idObject (readonly)

Returns the value of attribute project_id.



14
15
16
# File 'lib/braintrust/prompt.rb', line 14

def project_id
  @project_id
end

#slugObject (readonly)

Returns the value of attribute slug.



14
15
16
# File 'lib/braintrust/prompt.rb', line 14

def slug
  @slug
end

#versionObject (readonly)

Returns the value of attribute version.



14
15
16
# File 'lib/braintrust/prompt.rb', line 14

def version
  @version
end

Class Method Details

.load(slug:, project: nil, project_id: nil, version: nil, defaults: {}, api: nil) ⇒ Prompt

Load a prompt from Braintrust

Parameters:

  • project (String, nil) (defaults to: nil)

    Project name (provide either project or project_id)

  • project_id (String, nil) (defaults to: nil)

    Project ID (UUID, provide either project or project_id)

  • slug (String)

    Prompt slug

  • version (String, nil) (defaults to: nil)

    Specific version (default: latest)

  • defaults (Hash) (defaults to: {})

    Default variable values for build()

  • api (API, nil) (defaults to: nil)

    Braintrust API client (default: creates one using global state)

Returns:

Raises:

  • (ArgumentError)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/braintrust/prompt.rb', line 25

def self.load(slug:, project: nil, project_id: nil, version: nil, defaults: {}, api: nil)
  raise ArgumentError, "Either project or project_id is required" unless project || project_id

  api ||= API.new

  # Find the function by project + slug
  result = api.functions.list(project_name: project, project_id: project_id, slug: slug)
  function = result.dig("objects")&.first

  identifier = project ? "project '#{project}'" : "project_id '#{project_id}'"
  raise Error, "Prompt '#{slug}' not found in #{identifier}" unless function

  # Fetch full function data including prompt_data
  full_data = api.functions.get(id: function["id"], version: version)

  new(full_data, defaults: defaults)
end

Instance Method Details

#build(variables = nil, strict: false, **kwargs) ⇒ Hash

Build the prompt with variable substitution

Returns a hash ready to pass to an LLM client:

{model: "...", messages: [...], temperature: ..., ...}

Examples:

With keyword arguments

prompt.build(name: "Alice", task: "coding")

With explicit hash

prompt.build({name: "Alice"}, strict: true)

Parameters:

  • variables (Hash) (defaults to: nil)

    Variables to substitute (e.g., “Alice”)

  • strict (Boolean) (defaults to: false)

    Raise error on missing variables (default: false)

Returns:

  • (Hash)

    Built prompt ready for LLM client



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/braintrust/prompt.rb', line 113

def build(variables = nil, strict: false, **kwargs)
  # Support both explicit hash and keyword arguments
  variables_hash = variables.is_a?(Hash) ? variables : {}
  vars = @defaults
    .merge(Internal::Template.stringify_keys(variables_hash))
    .merge(Internal::Template.stringify_keys(kwargs))

  # Render Mustache templates in messages
  built_messages = messages.map do |msg|
    {
      role: msg["role"].to_sym,
      content: Internal::Template.render(msg["content"], vars, format: template_format, strict: strict)
    }
  end

  # Build result with model and messages
  result = {
    model: model,
    messages: built_messages
  }

  # Add tools if defined
  parsed_tools = tools
  result[:tools] = parsed_tools if parsed_tools

  # Add params (temperature, max_tokens, etc.) to top level
  params = options.dig("params")
  if params.is_a?(Hash)
    params.each do |key, value|
      result[key.to_sym] = value
    end
  end

  result
end

#messagesArray<Hash>

Get the prompt messages

Returns:

  • (Array<Hash>)


66
67
68
# File 'lib/braintrust/prompt.rb', line 66

def messages
  prompt&.dig("messages") || []
end

#modelString?

Get the model name

Returns:

  • (String, nil)


83
84
85
# File 'lib/braintrust/prompt.rb', line 83

def model
  @data.dig("prompt_data", "options", "model")
end

#optionsHash

Get model options

Returns:

  • (Hash)


89
90
91
# File 'lib/braintrust/prompt.rb', line 89

def options
  @data.dig("prompt_data", "options") || {}
end

#promptHash?

Get the raw prompt definition

Returns:

  • (Hash, nil)


60
61
62
# File 'lib/braintrust/prompt.rb', line 60

def prompt
  @data.dig("prompt_data", "prompt")
end

#template_formatString

Get the template format

Returns:

  • (String)

    “mustache” (default), “nunjucks”, or “none”



95
96
97
# File 'lib/braintrust/prompt.rb', line 95

def template_format
  @data.dig("prompt_data", "template_format") || "mustache"
end

#toolsArray<Hash>?

Get the tools definition (parsed from JSON string)

Returns:

  • (Array<Hash>, nil)


72
73
74
75
76
77
78
79
# File 'lib/braintrust/prompt.rb', line 72

def tools
  tools_json = prompt&.dig("tools")
  return nil unless tools_json.is_a?(String) && !tools_json.empty?

  JSON.parse(tools_json)
rescue JSON::ParserError
  nil
end