go-chatgpt
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

107 lines
2.5 KiB

  1. package gogpt
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "io"
  8. "net/http"
  9. )
  10. type ChatCompletionStreamChoiceDelta struct {
  11. Content string `json:"content"`
  12. }
  13. type ChatCompletionStreamChoice struct {
  14. Index int `json:"index"`
  15. Delta ChatCompletionStreamChoiceDelta `json:"delta"`
  16. FinishReason string `json:"finish_reason"`
  17. }
  18. type ChatCompletionStreamResponse struct {
  19. ID string `json:"id"`
  20. Object string `json:"object"`
  21. Created int64 `json:"created"`
  22. Model string `json:"model"`
  23. Choices []ChatCompletionStreamChoice `json:"choices"`
  24. }
  25. // ChatCompletionStream
  26. // Note: Perhaps it is more elegant to abstract Stream using generics.
  27. type ChatCompletionStream struct {
  28. emptyMessagesLimit uint
  29. isFinished bool
  30. reader *bufio.Reader
  31. response *http.Response
  32. }
  33. func (stream *ChatCompletionStream) Recv() (response ChatCompletionStreamResponse, err error) {
  34. if stream.isFinished {
  35. err = io.EOF
  36. return
  37. }
  38. var emptyMessagesCount uint
  39. waitForData:
  40. line, err := stream.reader.ReadBytes('\n')
  41. if err != nil {
  42. return
  43. }
  44. var headerData = []byte("data: ")
  45. line = bytes.TrimSpace(line)
  46. if !bytes.HasPrefix(line, headerData) {
  47. emptyMessagesCount++
  48. if emptyMessagesCount > stream.emptyMessagesLimit {
  49. err = ErrTooManyEmptyStreamMessages
  50. return
  51. }
  52. goto waitForData
  53. }
  54. line = bytes.TrimPrefix(line, headerData)
  55. if string(line) == "[DONE]" {
  56. stream.isFinished = true
  57. err = io.EOF
  58. return
  59. }
  60. err = json.Unmarshal(line, &response)
  61. return
  62. }
  63. func (stream *ChatCompletionStream) Close() {
  64. stream.response.Body.Close()
  65. }
  66. // CreateChatCompletionStream — API call to create a chat completion w/ streaming
  67. // support. It sets whether to stream back partial progress. If set, tokens will be
  68. // sent as data-only server-sent events as they become available, with the
  69. // stream terminated by a data: [DONE] message.
  70. func (c *Client) CreateChatCompletionStream(
  71. ctx context.Context,
  72. request ChatCompletionRequest,
  73. ) (stream *ChatCompletionStream, err error) {
  74. request.Stream = true
  75. req, err := c.newStreamRequest(ctx, "POST", "/chat/completions", request)
  76. if err != nil {
  77. return
  78. }
  79. resp, err := c.config.HTTPClient.Do(req) //nolint:bodyclose // body is closed in stream.Close()
  80. if err != nil {
  81. return
  82. }
  83. stream = &ChatCompletionStream{
  84. emptyMessagesLimit: c.config.EmptyMessagesLimit,
  85. reader: bufio.NewReader(resp.Body),
  86. response: resp,
  87. }
  88. return
  89. }