Class: DSPy::LM::OpenAIAdapter

Inherits:
Adapter
  • Object
show all
Defined in:
lib/dspy/lm/adapters/openai_adapter.rb

Instance Attribute Summary

Attributes inherited from Adapter

#api_key, #model

Instance Method Summary collapse

Constructor Details

#initialize(model:, api_key:, structured_outputs: false) ⇒ OpenAIAdapter

Returns a new instance of OpenAIAdapter.



9
10
11
12
13
14
# File 'lib/dspy/lm/adapters/openai_adapter.rb', line 9

def initialize(model:, api_key:, structured_outputs: false)
  super(model: model, api_key: api_key)
  validate_api_key!(api_key, 'openai')
  @client = OpenAI::Client.new(api_key: api_key)
  @structured_outputs_enabled = structured_outputs
end

Instance Method Details

#chat(messages:, signature: nil, response_format: nil, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/dspy/lm/adapters/openai_adapter.rb', line 16

def chat(messages:, signature: nil, response_format: nil, &block)
  request_params = {
    model: model,
    messages: normalize_messages(messages),
    temperature: 0.0 # DSPy default for deterministic responses
  }

  # Add response format if provided by strategy
  if response_format
    request_params[:response_format] = response_format
  elsif @structured_outputs_enabled && signature && supports_structured_outputs?
    # Legacy behavior for backward compatibility
    response_format = DSPy::LM::Adapters::OpenAI::SchemaConverter.to_openai_format(signature)
    request_params[:response_format] = response_format
  end

  # Add streaming if block provided
  if block_given?
    request_params[:stream] = proc do |chunk, _bytesize|
      block.call(chunk) if chunk.dig("choices", 0, "delta", "content")
    end
  end

  begin
    response = @client.chat.completions.create(**request_params)
    
    if response.respond_to?(:error) && response.error
      raise AdapterError, "OpenAI API error: #{response.error}"
    end

    message = response.choices.first.message
    content = message.content
    usage = response.usage

    # Handle structured output refusals
    if message.respond_to?(:refusal) && message.refusal
      raise AdapterError, "OpenAI refused to generate output: #{message.refusal}"
    end

    Response.new(
      content: content,
      usage: usage.respond_to?(:to_h) ? usage.to_h : usage,
      metadata: {
        provider: 'openai',
        model: model,
        response_id: response.id,
        created: response.created,
        structured_output: @structured_outputs_enabled && signature && supports_structured_outputs?
      }
    )
  rescue => e
    raise AdapterError, "OpenAI adapter error: #{e.message}"
  end
end