쿠키를 사용합니다. 쿠키와 브라우저 저장소는 로그인 상태를 유지하고 환경설정을 기억합니다. 동의하시면 사이트 이용 방식도 측정합니다. 언제든지 할 수 있습니다. 자세한 내용은 쿠키 정책을 참고하세요.

Ruby

SDK 가이드

Ruby

Ruby와 Rails에서 ruby-openai 젬의 uri_base를 api14로 지정하는 방법입니다. 이니셜라이저 설정, 채팅, 스트리밍, 도구 호출, 구조화된 출력, 임베딩, 백오프 재시도를 다룹니다. 게이트웨이 전용 파라미터 사용법도 있습니다.

api14에서 ruby-openai 젬을 사용하세요. uri_base를 설정하고 openai/gpt-5-mini 같은 모델 ID를 사용합니다.

설치

gem install ruby-openai
export API14_API_KEY="sk-api14-..."

설정

ruby-openai는 API 버전(v1)을 uri_base 뒤에 붙이므로 기본값은 https://api14.com/api이고, 요청은 https://api14.com/api/v1/...로 전송됩니다.

require "openai"

client = OpenAI::Client.new(
  access_token: ENV.fetch("API14_API_KEY"),
  uri_base: "https://api14.com/api",
  request_timeout: 120
)

Rails 앱에서는 initializer에서 젬을 한 번 설정하고 인수 없이 클라이언트를 만드세요.

# config/initializers/openai.rb
OpenAI.configure do |config|
  config.access_token = ENV.fetch("API14_API_KEY")
  config.uri_base = "https://api14.com/api"
  config.request_timeout = 120 # 초 단위, 기본값 120
end

client = OpenAI::Client.new

채팅

response = client.chat(
  parameters: {
    model: "openai/gpt-5-mini",
    messages: [{ role: "user", content: "Explain vector databases in two sentences." }]
  }
)
puts response.dig("choices", 0, "message", "content")

스트리밍

stream에 proc을 전달하면 청크마다 한 번씩 호출됩니다.

client.chat(
  parameters: {
    model: "anthropic/claude-sonnet-4.5",
    messages: [{ role: "user", content: "Write a haiku about APIs." }],
    stream: proc { |chunk, _bytesize| print chunk.dig("choices", 0, "delta", "content") }
  }
)

스트리밍을 참고하세요.

도구 호출

require "json"

tools = [{
  type: "function",
  function: {
    name: "get_weather",
    description: "Current weather for a city",
    parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] }
  }
}]
messages = [{ role: "user", content: "What's the weather in Istanbul?" }]

loop do
  response = client.chat(parameters: { model: "openai/gpt-5-mini", messages: messages, tools: tools })
  message = response.dig("choices", 0, "message")
  unless message["tool_calls"]
    puts message["content"]
    break
  end

  messages << message
  message["tool_calls"].each do |call|
    args = JSON.parse(call.dig("function", "arguments"))
    messages << { role: "tool", tool_call_id: call["id"], content: get_weather(args["city"]).to_json } # 직접 작성한 메서드
  end
end

도구 호출을 참고하세요.

구조화된 출력

response = client.chat(
  parameters: {
    model: "openai/gpt-5-mini",
    messages: [{ role: "user", content: "Extract: Ada Lovelace, born 1815 in London." }],
    response_format: {
      type: "json_schema",
      json_schema: {
        name: "person",
        strict: true,
        schema: {
          type: "object",
          properties: { name: { type: "string" }, born: { type: "integer" }, city: { type: "string" } },
          required: %w[name born city],
          additionalProperties: false
        }
      }
    }
  }
)
person = JSON.parse(response.dig("choices", 0, "message", "content"))

구조화된 출력을 참고하세요.

이미지 입력

require "base64"

image = Base64.strict_encode64(File.binread("photo.png"))

client.chat(
  parameters: {
    model: "google/gemini-2.5-flash",
    messages: [{
      role: "user",
      content: [
        { type: "text", text: "What is in this picture?" },
        { type: "image_url", image_url: { url: "data:image/png;base64,#{image}" } }
      ]
    }]
  }
)

비전 및 파일을 참고하세요.

게이트웨이 파라미터

젬은 parameters를 그대로 전달하므로 게이트웨이 필드를 바로 사용할 수 있습니다.

client.chat(
  parameters: {
    model: "openai/gpt-5-mini",
    models: ["anthropic/claude-sonnet-4.5"], # 폴백
    provider: { sort: "throughput" },
    reasoning: { effort: "low" },
    messages: [{ role: "user", content: "Hi" }]
  }
)

임베딩

response = client.embeddings(
  parameters: { model: "openai/text-embedding-3-small", input: ["The quick brown fox", "Lorem ipsum"] }
)
puts response.dig("data", 0, "embedding").length

오류

HTTP 오류는 Faraday::Error로 발생합니다. 응답 해시에는 상태, 헤더, OpenAI 형식의 본문이 들어 있습니다.

begin
  client.chat(parameters: { model: "openai/gpt-5-mini", messages: [{ role: "user", content: "Hi" }] })
rescue Faraday::Error => e
  case e.response&.dig(:status)
  when 402 then warn "Balance too low, add funds (insufficient_balance)"
  when 429 then warn "Rate limited, retry after #{e.response[:headers]['retry-after']}s"
  else raise
  end
end

모든 코드는 오류를 참고하세요.

백오프를 적용한 재시도

ruby-openai는 기본적으로 재시도하지 않습니다. 작은 래퍼로 rate_limited, 5xx, 타임아웃을 재시도하고 daily_limit_reached와 insufficient_balance는 그대로 둘 수 있습니다.

def with_retry(attempts: 5)
  attempts.times do |i|
    return yield
  rescue Faraday::TimeoutError, Faraday::ConnectionFailed
    raise if i == attempts - 1
    sleep([2**i, 60].min + rand)
  rescue Faraday::Error => e
    status = e.response&.dig(:status).to_i
    retryable = status >= 500 || (status == 429 && !e.response[:body].to_s.include?("daily_limit_reached"))
    raise if !retryable || i == attempts - 1
    wait = e.response.dig(:headers, "retry-after")&.to_i || 2**i
    sleep([wait, 60].min + rand)
  end
end

with_retry { client.chat(parameters: { model: "openai/gpt-5-mini", messages: [{ role: "user", content: "Hi" }] }) }

속도 제한을 참고하세요.

모든 기능

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api14.com/api/v1",
  apiKey: process.env.API14_API_KEY,
});

const result = await client.chat.completions.create({
  "model": "openai/gpt-5-mini",
  "messages": [
    {
      "role": "user",
      "content": "Explain vector databases in two sentences."
    }
  ]
});
console.log(result.choices[0].message.content);