1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rails の ActionController::Live × gRPC Server Streaming で、AI の返答をリアルタイム配信する

1
Posted at

はじめに

flyingclouds.space で、Rails(画面・DB担当) と Python の AI サービス を gRPC で繋いでいます。

AI の返答は ChatGPT のように少しずつ表示したいので、

  • AI サービス → Rails:gRPC の Server Streaming
  • Rails → ブラウザ:ActionController::Live による SSE(Server-Sent Events)

という形で、受け取ったチャンクをそのままブラウザへ流しています。この記事では、その仕組みと実際に気をつけたポイントを紹介します。

環境:Rails 8.1 / Ruby 3.4 / grpc gem 1.74
コードは記事用に書き下ろした簡略版です。

全体の流れ

EventSource は GET しか使えないので、質問は先に POST で保存し、その ID を使って GET でストリームを開く、という 2 段階にしています。

1. proto:1 リクエストに対して複数回返す

assistant.proto
syntax = "proto3";
package assistant.v1;

service AssistantService {
  // 返り値に stream を付けると Server Streaming になる
  rpc StreamReply(ReplyRequest) returns (stream ReplyEvent);
}

message ReplyRequest {
  string conversation_id = 1;
  string prompt = 2;
}

// 1 メッセージにつき、どれか 1 つだけが入る
message ReplyEvent {
  oneof kind {
    TextChunk chunk = 1;
    Finished finished = 2;
    Failure failure = 3;
  }
}

message TextChunk { string text = 1; }
message Finished  { int32 output_tokens = 1; }
message Failure   { string code = 1; }

2. gRPC クライアント:fork に注意

gRPC のチャネルは fork をまたいで使えません。Puma(cluster モード)やジョブワーカーは fork するので、initializer で接続を作ると子プロセスが壊れたチャネルを引き継いでしまいます。

そこで、初回利用時に作る(遅延接続)+ PID が変わったら作り直す ようにしました。

app/services/assistant/grpc_client.rb
module Assistant
  # gRPC のメッセージを、アプリ内で扱うただの値オブジェクトに変換する
  Event = Data.define(:kind, :text, :output_tokens, :code) do
    def initialize(kind:, text: nil, output_tokens: nil, code: nil)
      super(kind:, text:, output_tokens:, code:)
    end
  end

  class GrpcClient
    LOCK = Mutex.new

    # プロセスごとに 1 つだけ。fork 後の子プロセスでは作り直す
    def self.current
      LOCK.synchronize do
        @client = nil if @pid != Process.pid
        @pid = Process.pid
        @client ||= new
      end
    end

    def stream_reply(request)
      # deadline は必ず付ける(付けないと永遠に待つことがある)
      call = stub.stream_reply(request, deadline: Time.now + 120)
      call.each { |message| yield to_event(message) }
    rescue GRPC::BadStatus => e
      # GRPC::Unavailable → "unavailable" のようなコードに変換
      yield Event.new(kind: :failure, code: e.class.name.demodulize.underscore)
    end

    private

    def stub
      @stub ||= Assistant::V1::AssistantService::Stub.new(
        ENV.fetch("ASSISTANT_GRPC_ADDR"),
        :this_channel_is_insecure,
        channel_args: {
          "grpc.keepalive_time_ms" => 30_000,   # 途中でネットワークが切れたら早めに気づく
          "grpc.keepalive_timeout_ms" => 10_000
        }
      )
    end

    def to_event(message)
      case message.kind # oneof 名で、どのフィールドが入っているかがシンボルで返る
      when :chunk    then Event.new(kind: :chunk, text: message.chunk.text)
      when :finished then Event.new(kind: :finished, output_tokens: message.finished.output_tokens)
      when :failure  then Event.new(kind: :failure, code: message.failure.code)
      end
    end
  end
end

gRPC の型は このクラスの外に出さない ようにしています。上の層は Assistant::Event だけを見ればよく、テストでは偽物のクライアントに差し替えるだけで済みます。

3. ActionController::Live で SSE を流す

include ActionController::Live すると、response.stream.write で書いた内容がその場でクライアントへ送られます。

app/controllers/reply_streams_controller.rb
class ReplyStreamsController < ApplicationController
  include ActionController::Live

  def show
    question = current_user.messages.find(params[:message_id])

    response.headers["Content-Type"] = "text/event-stream"
    response.headers["Cache-Control"] = "no-cache"
    response.headers["X-Accel-Buffering"] = "no" # nginx に溜め込ませない
    response.headers.delete("Content-Length")

    Assistant::StreamReply.new.call(question) do |event|
      case event.kind
      when :chunk    then sse("delta", event.text)
      when :finished then sse("done", "ok")
      when :failure  then sse("error", t("assistant.errors.#{event.code}", default: t("assistant.errors.generic")))
      end
    end
  rescue ActionController::Live::ClientDisconnected, IOError
    # もう誰も聞いていない。何もしない
  ensure
    response.stream.close # これを忘れるとスレッドが解放されない
  end

  private

  # JSON にしておくと、改行を含むチャンクでも SSE の形式が崩れない
  def sse(name, data)
    response.stream.write("event: #{name}\ndata: #{data.to_json}\n\n")
  end
end

4. タブを閉じられても、生成は止めない

ここが一番大事なポイントです。

ユーザーが途中でタブを閉じると stream.write が ClientDisconnected を投げます。そのまま処理を止めると、途中まで生成された返答が消えてしまいます(AI の料金もかかっているのに)。

そこで、書き込みの失敗だけを握りつぶし、gRPC のストリームは最後まで読み切って保存 するようにしました。

app/services/assistant/stream_reply.rb
module Assistant
  class StreamReply
    def initialize(client: GrpcClient.current)
      @client = client
    end

    def call(question)
      buffer = +""
      finished = false
      listening = true

      request = Assistant::V1::ReplyRequest.new(
        conversation_id: question.conversation_id.to_s,
        prompt: question.body
      )

      @client.stream_reply(request) do |event|
        buffer << event.text if event.kind == :chunk
        finished = true if event.kind == :finished

        next unless listening

        begin
          yield event
        rescue ActionController::Live::ClientDisconnected, IOError
          # タブを閉じられても生成は止めない。最後まで受け取って保存する
          listening = false
        end
      end

      return if buffer.empty?

      question.conversation.messages.create!(
        role: :assistant,
        body: buffer,
        interrupted: !finished # 途中で切れた返答も捨てずに残す
      )
    end
  end
end

次にページを開いたときには、完成した返答がちゃんと表示されます。

5. フロント側:close() を忘れない

app/javascript/controllers/reply_stream_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["bubble"]
  static values = { url: String }

  connect() {
    this.source = new EventSource(this.urlValue)

    this.source.addEventListener("delta", (e) => {
      this.bubbleTarget.textContent += JSON.parse(e.data)
    })

    // サーバーが正常に閉じても EventSource は自動で再接続しにいくので、自分で閉じる
    this.source.addEventListener("done", () => this.source.close())

    // サーバーの event: error と接続エラーは、どちらも "error" で届く。data の有無で見分ける
    this.source.addEventListener("error", (e) => {
      if (e.data) this.bubbleTarget.textContent = JSON.parse(e.data)
      this.source.close()
    })
  }

  disconnect() {
    this.source?.close()
  }
}

実際にハマったポイント

  • Live は返答が終わるまで Puma のスレッドを 1 本占有する
    Puma のスレッド数は多くないので、Redis の SET key NX EX で「1 ユーザーにつき同時 1 ストリーム」に制限しています。
  • 再接続は冪等にする
    EventSource は勝手に再接続することがあります。すでに返答が保存済みなら、AI を呼び直さずに保存済みの内容を返すようにしました。
  • エラーは HTTP ステータスではなく event: error で返す
    EventSource の onerror からはステータスコードもレスポンスボディも読めません。レート制限なども 200 で開いて event: error を送ると、ちゃんとした文言を表示してから close() できます。
  • nginx のバッファリング
    X-Accel-Buffering: no がないと、チャンクが溜められてまとめて届き、「ストリーミングしているのに一気に表示される」状態になります。

まとめ

  • gRPC の Server Streaming と ActionController::Live を組み合わせると、Rails 側の実装はかなりシンプルに書けます
  • gRPC の型はクライアントクラスの中に閉じ込めて、上の層はただの値オブジェクトだけを扱う
  • 「ブラウザとの接続」と「AI の生成」のライフサイクルを分けて考える のが一番のポイントでした

WebSocket(Action Cable)を使わなくても、一方向のストリーミングなら SSE で十分です。同じような構成を考えている方の参考になれば嬉しいです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?