【OpenAI】Kotlin OkHttp で Server-Sent Events (SSE)

ChatGPT API で stream 受信したいですよね。

stream boolean Optional Defaults to false

If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message.

👉 API Reference - OpenAI API hatena-bookmark

簡単にできそうなのでやってみました。

 

📡 curl

curl で簡単に取得できる。


curl "https://api.openai.com/v1/chat/completions" \
  -H "accept: text/event-stream" \
  -H "authorization: Bearer $OPENAI_API_KEY" \
  -H "content-type: application/json" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [{"role": "user", "content": "Server-Sent Events とは"}],
    "stream": true
  }'


...

data: {"id":"chatcmpl-7OQ1xuBFfam8Ct","object":"chat.completion.chunk","created":1686054286,"model":"gpt-3.5-turbo","choices":[{"delta":{"content":"て"},"index":0,"finish_reason":null}]}

data: {"id":"chatcmpl-7OQ1xuBFfam8Ct","object":"chat.completion.chunk","created":1686054286,"model":"gpt-3.5-turbo","choices":[{"delta":{"content":"います"},"index":0,"finish_reason":null}]}

data: {"id":"chatcmpl-7OQ1xuBFfam8Ct","object":"chat.completion.chunk","created":1686054286,"model":"gpt-3.5-turbo","choices":[{"delta":{"content":"。"},"index":0,"finish_reason":null}]}

data: {"id":"chatcmpl-7OQ1xuBFfam8Ct","object":"chat.completion.chunk","created":1686054286,"model":"gpt-3.5-turbo","choices":[{"delta":{},"index":0,"finish_reason":"stop"}]}

data: [DONE]

パースはだるそうですが、取得はできてるようです!

では、いざ、Kotlin で。

 

📡 okhttp-sse

壊れてるのか何なのか微妙。


testImplementation("com.squareup.okhttp3:okhttp-sse:4.11.0")

👉 okhttp/okhttp-sse at master · square/okhttp · GitHub hatena-bookmark

現在の安定版 4.11.0 ではあやしい。

5.0.0-alpha.11 ではまあまあ動いてるのでそれで。



SSEは、日本語で表現するとサーバ送信イベントと表現されるもので、サーバからクライアントに対してリアルタイムでイベントを送信することができる機能です。 コネクションを張っておいて、サーバからイベントを好きなタイミングで送れるイメージです

 

📡 まとめ

カンファレンスでの公演資料とか、時間が経つと、まあ動かないこと多いですよね!


👉 Server-Sent Events in Android (with Node.js) | by Rahul Ray | Jun, 2023 | ProAndroidDev hatena-bookmark