Class: Net::Llm::OpenAI

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key: ENV.fetch("OPENAI_API_KEY"), base_url: ENV.fetch("OPENAI_BASE_URL", "https://api.openai.com/v1"), model: "gpt-4o-mini", http: Net::Llm.http) ⇒ OpenAI

Returns a new instance of OpenAI.



8
9
10
11
12
13
# File 'lib/net/llm/openai.rb', line 8

def initialize(api_key: ENV.fetch("OPENAI_API_KEY"), base_url: ENV.fetch("OPENAI_BASE_URL", "https://api.openai.com/v1"), model: "gpt-4o-mini", http: Net::Llm.http)
  @api_key = api_key
  @base_url = base_url
  @model = model
  @http = http
end

Instance Attribute Details

#api_key ⇒ Object (readonly)

Returns the value of attribute api_key.



6
7
8
# File 'lib/net/llm/openai.rb', line 6

def api_key
  @api_key
end

#base_url ⇒ Object (readonly)

Returns the value of attribute base_url.



6
7
8
# File 'lib/net/llm/openai.rb', line 6

def base_url
  @base_url
end

#http ⇒ Object (readonly)

Returns the value of attribute http.



6
7
8
# File 'lib/net/llm/openai.rb', line 6

def http
  @http
end

#model ⇒ Object (readonly)

Returns the value of attribute model.



6
7
8
# File 'lib/net/llm/openai.rb', line 6

def model
  @model
end

Instance Method Details

#chat(messages, tools) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/net/llm/openai.rb', line 15

def chat(messages, tools)
  handle_response(http.post(
    "#{base_url}/chat/completions",
    headers: headers,
    body: { model: model, messages: messages, tools: tools, tool_choice: "auto" }
  ))
end

#embeddings(input, model: "text-embedding-ada-002") ⇒ Object



35
36
37
38
39
40
41
# File 'lib/net/llm/openai.rb', line 35

def embeddings(input, model: "text-embedding-ada-002")
  handle_response(http.post(
    "#{base_url}/embeddings",
    headers: headers,
    body: { model: model, input: input },
  ))
end

#fetch(messages, tools = [], &block) ⇒ Object



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

def fetch(messages, tools = [], &block)
  if block_given?
    fetch_streaming(messages, tools, &block)
  else
    fetch_non_streaming(messages, tools)
  end
end

#models ⇒ Object



31
32
33
# File 'lib/net/llm/openai.rb', line 31

def models
  handle_response(http.get("#{base_url}/models", headers: headers))
end