<p><strong>ruby-openai</strong> は GitHub で10,000スター以上を獲得している人気の OpenAI クライアント gem です。<br>
GPT-4o はもちろん、GPT-5 や Realtime API にも対応しています。<br>
本記事では Rails で実用的なチャットボットを作る手順を解説します。</p>

<h3 id="install">インストール</h3>
<pre><code># Gemfile
gem 'ruby-openai'</code></pre>
<pre><code>bundle install</code></pre>
<p><code>config/initializers/openai.rb</code> に API キーを設定します。</p>
<pre><code>OpenAI.configure do |config|
config.access_token = ENV['OPENAI_API_KEY']
end</code></pre>

<h3 id="basic-chat">基本的なチャット</h3>
<pre><code>client = OpenAI::Client.new

response = client.chat(
parameters: {
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'あなたは親切なアシスタントです。' },
{ role: 'user', content: 'Rubyの魅力を教えてください' }
]
}
)
puts response.dig('choices', 0, 'message', 'content')</code></pre>

<h3 id="streaming">ストリーミング対応(リアルタイム表示)</h3>
<p>長い回答をリアルタイムで表示するには <code>stream</code> オプションを使います。</p>
<pre><code>client.chat(
parameters: {
model: 'gpt-4o',
stream: proc { |chunk, _bytesize|
content = chunk.dig('choices', 0, 'delta', 'content')
print content if content
},
messages: [{ role: 'user', content: '長い文章を書いてください' }]
}
)</code></pre>
<p>Rails + ActionCable と組み合わせると、WebSocket 経由でリアルタイム表示ができます。</p>

<h3 id="conversation-history">会話履歴の管理</h3>
<p>複数ターンの会話を扱うには、messages 配列に履歴を蓄積します。</p>
<pre><code>class ConversationService
def initialize
@messages = [
{ role: 'system', content: 'あなたは親切なアシスタントです。' }
]
@client = OpenAI::Client.new
end

def chat(user_input)
@messages << { role: 'user', content: user_input }

response = @client.chat(
parameters: { model: 'gpt-4o', messages: @messages }
)

answer = response.dig('choices', 0, 'message', 'content')
@messages << { role: 'assistant', content: answer }
answer
end
end</code></pre>

<h3 id="function-calling">Function Calling(ツール使用)</h3>
<p>AI に外部関数を呼ばせることもできます。天気取得の例です。</p>
<pre><code>response = client.chat(
parameters: {
model: 'gpt-4o',
messages: [{ role: 'user', content: '東京の天気は?' }],
tools: [{
type: 'function',
function: {
name: 'get_weather',
description: '指定した都市の天気を取得する',
parameters: {
type: 'object',
properties: {
city: { type: 'string', description: '都市名' }
},
required: ['city']
}
}
}]
}
)</code></pre>

<h3 id="image-generation">画像生成(DALL-E)</h3>
<pre><code>response = client.images.generate(
parameters: {
model: 'dall-e-3',
prompt: 'Rubyのロゴをサイバーパンク風に描いてください',
size: '1024x1024'
}
)
puts response.dig('data', 0, 'url')</code></pre>

<h3 id="summary">まとめ</h3>
<p>ruby-openai は薄いラッパーなので OpenAI の公式ドキュメントをそのまま参照しながら実装できます。<br>
ストリーミング・Function Calling・画像生成まで1つの gem で対応できるのが強みです。</p>

<h3 id="related">関連記事</h3>
<ul>
<li><a href="/blog/javascript/rubyllm-rails-intro">RubyLLM gem 入門|Rails に ChatGPT・Claude を1時間で組み込む方法</a></li>
<li><a href="/blog/javascript/rails-claude-api">Rails で Claude API を使う|anthropic-sdk-ruby で AI 機能を実装する方法</a></li>
</ul>