Module: DSPy
- Extended by:
- Dry::Configurable
- Defined in:
- lib/dspy/utils/serialization.rb,
lib/dspy.rb,
lib/dspy/lm.rb,
lib/dspy/evals.rb,
lib/dspy/field.rb,
lib/dspy/image.rb,
lib/dspy/tools.rb,
lib/dspy/errors.rb,
lib/dspy/events.rb,
lib/dspy/module.rb,
lib/dspy/prompt.rb,
lib/dspy/re_act.rb,
lib/dspy/scores.rb,
lib/dspy/context.rb,
lib/dspy/example.rb,
lib/dspy/predict.rb,
lib/dspy/version.rb,
lib/dspy/document.rb,
lib/dspy/lm/usage.rb,
lib/dspy/callbacks.rb,
lib/dspy/lm/errors.rb,
lib/dspy/signature.rb,
lib/dspy/lm/adapter.rb,
lib/dspy/lm/message.rb,
lib/dspy/prediction.rb,
lib/dspy/tools/base.rb,
lib/dspy/lm/response.rb,
lib/dspy/events/types.rb,
lib/dspy/tools/schema.rb,
lib/dspy/evals/version.rb,
lib/dspy/reflection_lm.rb,
lib/dspy/tools/toolset.rb,
lib/dspy/schema/version.rb,
lib/dspy/error_formatter.rb,
lib/dspy/schema_adapters.rb,
lib/dspy/type_serializer.rb,
lib/dspy/chain_of_thought.rb,
lib/dspy/few_shot_example.rb,
lib/dspy/lm/chat_strategy.rb,
lib/dspy/lm/json_strategy.rb,
lib/dspy/lm/vision_models.rb,
lib/dspy/ruby_llm/version.rb,
lib/dspy/scores/data_type.rb,
lib/dspy/teleprompt/utils.rb,
lib/dspy/scores/evaluators.rb,
lib/dspy/lm/adapter_factory.rb,
lib/dspy/lm/message_builder.rb,
lib/dspy/scores/score_event.rb,
lib/dspy/mixins/type_coercion.rb,
lib/dspy/mixins/struct_builder.rb,
lib/dspy/ext/struct_descriptions.rb,
lib/dspy/storage/program_storage.rb,
lib/dspy/storage/storage_manager.rb,
lib/dspy/support/warning_filters.rb,
lib/dspy/teleprompt/data_handler.rb,
lib/dspy/teleprompt/teleprompter.rb,
lib/dspy/tools/github_cli_toolset.rb,
lib/dspy/propose/grounded_proposer.rb,
lib/dspy/registry/registry_manager.rb,
lib/dspy/schema/sorbet_json_schema.rb,
lib/dspy/structured_outputs_prompt.rb,
lib/dspy/schema/sorbet_toon_adapter.rb,
lib/dspy/support/openai_sdk_warning.rb,
lib/dspy/registry/signature_registry.rb,
lib/dspy/mixins/instruction_updatable.rb,
lib/dspy/teleprompt/bootstrap_strategy.rb,
lib/dspy/tools/text_processing_toolset.rb,
lib/dspy/teleprompt/instruction_updates.rb,
lib/dspy/propose/dataset_summary_generator.rb,
lib/dspy/ruby_llm/lm/adapters/ruby_llm_adapter.rb
Overview
typed: strict frozen_string_literal: true
Defined Under Namespace
Modules: Callbacks, Events, Ext, Metrics, Mixins, Propose, Registry, RubyLLM, Schema, SchemaAdapters, Scores, Storage, Support, Teleprompt, Tools, TypeSystem, Utils
Classes: ChainOfThought, ConfigurationError, Context, DeserializationError, Document, Error, ErrorFormatter, Evals, EventRegistry, Example, FewShotExample, HistoryEntry, Image, InputField, InstructionUpdateError, LM, Module, NextStep, OutputField, Predict, Prediction, PredictionInvalidError, Prompt, ReAct, ReflectionLM, Signature, StructuredOutputsPrompt, TypeSerializer, UnsupportedSchemaError, ValidationError
Constant Summary
collapse
- ToolInput =
Type alias for tool input parameters - provides semantic meaning in schemas
T.type_alias { T.nilable(T::Hash[String, T.untyped]) }
- VERSION =
"1.0.1"
Class Method Summary
collapse
-
.create_event_span(event_name, attributes) ⇒ Object
-
.create_logger ⇒ Object
-
.current_lm ⇒ Object
-
.emit_log(event_name, attributes) ⇒ Object
-
.event(event_name_or_object, attributes = {}) ⇒ Object
Emits a structured event that flows through DSPy’s event bus, fires any subscribed listeners, and creates OpenTelemetry spans when observability is enabled.
-
.events ⇒ Object
-
.flatten_attributes(attributes, parent_key = '', result = {}) ⇒ Object
-
.homogeneous_primitive_array?(value) ⇒ Boolean
-
.log(event_name, **attributes) ⇒ Object
Writes structured output to the configured logger.
-
.logger ⇒ Object
-
.normalize_event_json_value(value) ⇒ Object
-
.primitive_event_attribute_value?(value) ⇒ Boolean
-
.sanitize_event_attribute_value(value) ⇒ Object
-
.score(name, value, data_type: Scores::DataType::Numeric, comment: nil, span: nil, trace_id: nil, observation_id: nil) ⇒ Object
Top-level convenience method for creating scores.
-
.with_lm(lm) ⇒ Object
Class Method Details
.create_event_span(event_name, attributes) ⇒ Object
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
|
# File 'lib/dspy.rb', line 133
def self.create_event_span(event_name, attributes)
return unless DSPy::Observability.enabled?
return if INTERNAL_EVENTS.include?(event_name)
begin
flattened_attributes = flatten_attributes(attributes)
span = DSPy::Observability.start_span(event_name, flattened_attributes)
DSPy::Observability.finish_span(span) if span
rescue StandardError => e
emit_log('event.span_creation_error', {
error_class: e.class.name,
error_message: e.message,
event_name: event_name
})
end
end
|
.create_logger ⇒ Object
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
|
# File 'lib/dspy.rb', line 218
def self.create_logger
env = ENV['RACK_ENV'] || ENV['RAILS_ENV'] || 'development'
log_output = ENV['DSPY_LOG']
case env
when 'test'
Dry.Logger(:dspy, formatter: :string) do |config|
config.add_backend(stream: log_output || "log/test.log")
end
when 'development'
Dry.Logger(:dspy, formatter: :string) do |config|
config.add_backend(stream: log_output || "log/development.log")
end
when 'production', 'staging'
Dry.Logger(:dspy, formatter: :json) do |config|
config.add_backend(stream: log_output || $stdout)
end
else
Dry.Logger(:dspy, formatter: :string) do |config|
config.add_backend(stream: log_output || $stdout)
end
end
end
|
.current_lm ⇒ Object
249
250
251
|
# File 'lib/dspy.rb', line 249
def self.current_lm
Fiber[FIBER_LM_KEY] || config.lm
end
|
.emit_log(event_name, attributes) ⇒ Object
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
# File 'lib/dspy.rb', line 105
def self.emit_log(event_name, attributes)
return unless logger
context = Context.current.dup
context.delete(:span_stack)
context.delete(:otel_span_stack)
context.delete(:module_stack)
attributes = context.merge(attributes)
attributes[:event] = event_name
logger.info(attributes)
end
|
.event(event_name_or_object, attributes = {}) ⇒ Object
Emits a structured event that flows through DSPy’s event bus, fires any subscribed listeners, and creates OpenTelemetry spans when observability is enabled. Use this for anything that should be tracked, instrumented, or forwarded to Langfuse.
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
# File 'lib/dspy.rb', line 56
def self.event(event_name_or_object, attributes = {})
if event_name_or_object.respond_to?(:name) && event_name_or_object.respond_to?(:to_attributes)
event_obj = event_name_or_object
event_name = event_obj.name
attributes = event_obj.to_attributes
if event_obj.is_a?(DSPy::Events::LLMEvent)
otel_attributes = event_obj.to_otel_attributes
create_event_span(event_name, otel_attributes)
else
create_event_span(event_name, attributes)
end
else
event_name = event_name_or_object
raise ArgumentError, "Event name cannot be nil" if event_name.nil?
attributes = {} if attributes.nil?
create_event_span(event_name, attributes)
end
attributes = attributes.dup
module_metadata = DSPy::Context.module_context_attributes
attributes.merge!(module_metadata) unless module_metadata.empty?
events.notify(event_name, attributes)
end
|
.events ⇒ Object
93
94
95
96
97
98
99
100
101
|
# File 'lib/dspy.rb', line 93
def self.events
@event_registry ||= DSPy::EventRegistry.new.tap do |registry|
registry.subscribe('*') { |event_name, attributes|
emit_log(event_name, attributes) if logger
}
end
end
|
.flatten_attributes(attributes, parent_key = '', result = {}) ⇒ Object
156
157
158
159
160
161
162
163
164
165
166
167
168
|
# File 'lib/dspy.rb', line 156
def self.flatten_attributes(attributes, parent_key = '', result = {})
attributes.each do |key, value|
new_key = parent_key.empty? ? key.to_s : "#{parent_key}.#{key}"
if value.is_a?(Hash)
flatten_attributes(value, new_key, result)
else
result[new_key] = sanitize_event_attribute_value(value)
end
end
result
end
|
.homogeneous_primitive_array?(value) ⇒ Boolean
195
196
197
198
199
200
|
# File 'lib/dspy.rb', line 195
def self.homogeneous_primitive_array?(value)
return true if value.empty?
return false unless value.all? { |item| primitive_event_attribute_value?(item) }
value.map(&:class).uniq.size == 1
end
|
.log(event_name, **attributes) ⇒ Object
Writes structured output to the configured logger. Use this for human-readable logs only—listeners and telemetry exporters are not triggered by ‘DSPy.log`. Prefer `DSPy.event` whenever you want consumers (or Langfuse/OpenTelemetry) to react to what happened.
41
42
43
44
45
46
47
48
49
50
|
# File 'lib/dspy.rb', line 41
def self.log(event_name, **attributes)
return nil unless logger
emit_log(event_name, attributes)
nil
end
|
.logger ⇒ Object
33
34
35
|
# File 'lib/dspy.rb', line 33
def self.logger
@logger ||= create_logger
end
|
.normalize_event_json_value(value) ⇒ Object
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
|
# File 'lib/dspy.rb', line 202
def self.normalize_event_json_value(value)
if primitive_event_attribute_value?(value)
value
elsif value.is_a?(Array)
value.map { |item| normalize_event_json_value(item) }
elsif value.is_a?(Hash)
value.each_with_object({}) do |(k, v), acc|
acc[k.to_s] = normalize_event_json_value(v)
end
elsif value.respond_to?(:to_h)
normalize_event_json_value(value.to_h)
else
value.to_s
end
end
|
.primitive_event_attribute_value?(value) ⇒ Boolean
191
192
193
|
# File 'lib/dspy.rb', line 191
def self.primitive_event_attribute_value?(value)
value.nil? || value.is_a?(String) || value.is_a?(Integer) || value.is_a?(Float) || value.is_a?(TrueClass) || value.is_a?(FalseClass)
end
|
.sanitize_event_attribute_value(value) ⇒ Object
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
|
# File 'lib/dspy.rb', line 170
def self.sanitize_event_attribute_value(value)
return value if primitive_event_attribute_value?(value)
if value.is_a?(Array)
return value if homogeneous_primitive_array?(value)
return JSON.generate(value.map { |item| normalize_event_json_value(item) })
end
if value.is_a?(Hash)
return JSON.generate(normalize_event_json_value(value))
end
if value.respond_to?(:to_h)
return JSON.generate(normalize_event_json_value(value.to_h))
end
value.respond_to?(:to_json) ? value.to_json : value.to_s
rescue StandardError
value.to_s
end
|
.score(name, value, data_type: Scores::DataType::Numeric, comment: nil, span: nil, trace_id: nil, observation_id: nil) ⇒ Object
Top-level convenience method for creating scores
124
125
126
127
128
129
130
131
132
133
134
|
# File 'lib/dspy/scores.rb', line 124
def self.score(name, value, data_type: Scores::DataType::Numeric, comment: nil, span: nil, trace_id: nil, observation_id: nil)
Scores.create(
name: name,
value: value,
data_type: data_type,
comment: ,
span: span,
trace_id: trace_id,
observation_id: observation_id
)
end
|
.with_lm(lm) ⇒ Object
253
254
255
256
257
258
259
|
# File 'lib/dspy.rb', line 253
def self.with_lm(lm)
previous_lm = Fiber[FIBER_LM_KEY]
Fiber[FIBER_LM_KEY] = lm
yield
ensure
Fiber[FIBER_LM_KEY] = previous_lm
end
|