Class: Rixie::LLM::Adapter::OpenAI

Inherits:
Object
  • Object
show all
Defined in:
lib/rixie/llm/adapter/openai.rb

Instance Method Summary collapse

Constructor Details

#initialize(model:, base_url:, api_key:, request_timeout: nil, max_tokens: nil, temperature: nil, parallel_tool_calls: true) ⇒ OpenAI

Returns a new instance of OpenAI.



13
14
15
16
17
18
19
20
21
# File 'lib/rixie/llm/adapter/openai.rb', line 13

def initialize(model:, base_url:, api_key:, request_timeout: nil, max_tokens: nil, temperature: nil, parallel_tool_calls: true)
  @model = model
  @max_tokens = max_tokens
  @temperature = temperature
  @parallel_tool_calls = parallel_tool_calls
  params = {api_key: api_key, base_url: base_url}
  params[:timeout] = request_timeout if request_timeout
  @client = ::OpenAI::Client.new(**params)
end

Instance Method Details

#chat(messages, tools:) ⇒ Object



23
24
25
26
27
28
# File 'lib/rixie/llm/adapter/openai.rb', line 23

def chat(messages, tools:)
  result = @client.chat.completions.create(**build_params(encode_messages(messages), tools))
  Rixie::LLM::Response.from_openai_wire(normalize(result))
rescue ::OpenAI::Errors::Error => e
  raise Rixie::LLM::Error, e.message
end

#stream(messages, tools:, &block) ⇒ Object



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
# File 'lib/rixie/llm/adapter/openai.rb', line 30

def stream(messages, tools:, &block)
  params = build_params(encode_messages(messages), tools)

  content = +""
  accumulated_tool_calls = {}
  finish_reason = nil

  @client.chat.completions.stream_raw(**params).each do |chunk|
    choice = chunk.choices&.first
    next unless choice

    finish_reason = choice.finish_reason if choice.finish_reason
    delta = choice.delta
    next unless delta

    if (text = delta.content) && !text.empty?
      block.call(Event::Token.new(delta: text))
      content << text
    end

    delta.tool_calls&.each do |tc|
      i = tc.index
      accumulated_tool_calls[i] ||= {
        "id" => +"",
        "function" => {"name" => +"", "arguments" => +""}
      }
      accumulated_tool_calls[i]["id"] << tc.id.to_s
      accumulated_tool_calls[i]["function"]["name"] << tc.function&.name.to_s
      accumulated_tool_calls[i]["function"]["arguments"] << tc.function&.arguments.to_s
    end
  end

  Rixie::LLM::Response.from_openai_wire(build_stream_raw(content, accumulated_tool_calls, finish_reason))
rescue ::OpenAI::Errors::Error => e
  raise Rixie::LLM::Error, e.message
end