Skip to content

How do I respond to stream results via API - Grape #2367

Closed
@datpmt

Description

@datpmt

Recently I have been using the ChatGPT API and I've found a very useful method of sending information called streaming. Instead of sending a long piece of text all at once, ChatGPT sends it in small chunks until it's finished. For example, the text "Hello! How can I assist you today?" would be divided as follows:
0.1s: Hello
0.2s: !
0.3s: How
...
0.9s: today
1s: ?
Thank you for everyone's contributions!

# /api/v1/chat_gpt
module API
  module V1
    class AttachmentStream
      attr_reader :response
      def initialize(response)
        @response = response
      end

      def each
        yield response.read_body
      end
    end
    class ChatGpt < Grape::API
      helpers API::V1::Helpers::Authentication
      helpers API::V1::Helpers::ChatGpt
      resource :chat_gpt do
        desc 'Chat with ChatGPT'
        params do
          use :authorization_token
          requires :messages, type: Array[Hash], desc: 'Chat Content'
          optional :max_tokens, type: Integer
          optional :stream, type: Boolean, default: false
        end
        post do
          content_type 'text/event-stream'
          url = 'https://api.openai.com/v1/chat/completions'
          uri = URI(url)

          data = {
            model: 'gpt-3.5-turbo',
            stream: true,
            messages: [
              {
                  "role": "user",
                  "content": "hi"
              }
            ]
          }

          Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
            request = Net::HTTP::Post.new(uri.path)

            # Set any request headers if required
            request['Content-Type'] = 'application/json'
            request['Authorization'] = "Bearer #{ENV.fetch('GPT_KEY')}"
            # Set the request body if required
            request.body = data.to_json

            http.request(request) do |response|
              stream AttachmentStream.new(response)
            end
          end
        end
      end
    end
  end
end
  • They seem to be returning at the same time :<
    image
  • Via OPENAI
    image

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions