Created
January 1, 2024 03:35
-
-
Save vincentopensourcetaiwan/dc602601f6b3a65f3b7e6c95b84331cb to your computer and use it in GitHub Desktop.
app/controllers/chat_responses_controller.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ChatResponsesController < ApplicationController | |
include ActionController::Live | |
def show | |
response.headers['Content-Type'] = 'text/event-stream' | |
response.headers['Last-Modified'] = Time.now.httpdate | |
# handle message event | |
sse = SSE.new(response.stream, event: "message") | |
# connect to OpenAI API | |
client = OpenAI::Client.new(access_token: ENV["OPENAI_ACCESS_TOKEN"]) | |
# send prompt to OpenAI API | |
begin | |
client.chat( | |
parameters: { | |
model: "gpt-3.5-turbo", | |
messages: [{ role: "user", content: params[:prompt] }], | |
stream: proc do |chunk| | |
content = chunk.dig("choices", 0, "delta", "content") | |
if content.nil? | |
return | |
end | |
# send response to client | |
sse.write({ message: content }) | |
end | |
} | |
) | |
ensure | |
sse.close | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment