Class: Spacy::OpenAIClient

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-spacy/openai_client.rb

Overview

A lightweight OpenAI API client with tools support for GPT-5 series models. This client implements the chat completions and embeddings endpoints without external dependencies.

Defined Under Namespace

Classes: APIError

Constant Summary collapse

API_ENDPOINT =
"https://api.openai.com/v1"
DEFAULT_TIMEOUT =
120
MAX_RETRIES =
3
RETRY_DELAY =
1

Instance Method Summary collapse

Constructor Details

#initialize(access_token:, timeout: DEFAULT_TIMEOUT) ⇒ OpenAIClient

Returns a new instance of OpenAIClient.



28
29
30
31
# File 'lib/ruby-spacy/openai_client.rb', line 28

def initialize(access_token:, timeout: DEFAULT_TIMEOUT)
  @access_token = access_token
  @timeout = timeout
end

Instance Method Details

#chat(model:, messages:, max_completion_tokens: 1000, temperature: nil, tools: nil, tool_choice: nil) ⇒ Hash

Sends a chat completion request with optional tools support. Note: GPT-5 series models do not support the temperature parameter.

Parameters:

  • model (String)

    The model to use (e.g., “gpt-5-mini”)

  • messages (Array<Hash>)

    The conversation messages

  • max_completion_tokens (Integer) (defaults to: 1000)

    Maximum tokens in the response

  • temperature (Float, nil) (defaults to: nil)

    Sampling temperature (ignored for GPT-5 models)

  • tools (Array<Hash>, nil) (defaults to: nil)

    Tool definitions for function calling

  • tool_choice (String, Hash, nil) (defaults to: nil)

    Tool selection strategy

Returns:

  • (Hash)

    The API response



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ruby-spacy/openai_client.rb', line 43

def chat(model:, messages:, max_completion_tokens: 1000, temperature: nil, tools: nil, tool_choice: nil)
  body = {
    model: model,
    messages: messages,
    max_completion_tokens: max_completion_tokens
  }

  # GPT-5 series models do not support temperature parameter
  unless gpt5_model?(model)
    body[:temperature] = temperature || 0.7
  end

  if tools && !tools.empty?
    body[:tools] = tools
    body[:tool_choice] = tool_choice || "auto"
  end

  post("/chat/completions", body)
end

#embeddings(model:, input:) ⇒ Hash

Sends an embeddings request.

Parameters:

  • model (String)

    The embeddings model (e.g., “text-embedding-3-small”)

  • input (String)

    The text to embed

Returns:

  • (Hash)

    The API response



74
75
76
77
78
79
80
81
# File 'lib/ruby-spacy/openai_client.rb', line 74

def embeddings(model:, input:)
  body = {
    model: model,
    input: input
  }

  post("/embeddings", body)
end

#gpt5_model?(model) ⇒ Boolean

Checks if the model is a GPT-5 series model. GPT-5 models have different parameter requirements (no temperature support).

Returns:

  • (Boolean)


65
66
67
# File 'lib/ruby-spacy/openai_client.rb', line 65

def gpt5_model?(model)
  model.to_s.start_with?("gpt-5")
end