Files
go-openai/chat_stream.go
渡邉祐一 / Yuichi Watanabe f1b66967a4 refactor: refactoring http request creation and sending (#395)
* refactoring http request creation and sending

* fix lint error

* increase the test coverage of client.go

* refactor: Change the style of HTTPRequestBuilder.Build func to one-argument-per-line.
2023-06-22 13:57:52 +04:00

63 lines
1.9 KiB
Go

package openai
import (
"context"
"net/http"
)
type ChatCompletionStreamChoiceDelta struct {
Content string `json:"content,omitempty"`
Role string `json:"role,omitempty"`
FunctionCall *FunctionCall `json:"function_call,omitempty"`
}
type ChatCompletionStreamChoice struct {
Index int `json:"index"`
Delta ChatCompletionStreamChoiceDelta `json:"delta"`
FinishReason FinishReason `json:"finish_reason"`
}
type ChatCompletionStreamResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []ChatCompletionStreamChoice `json:"choices"`
}
// ChatCompletionStream
// Note: Perhaps it is more elegant to abstract Stream using generics.
type ChatCompletionStream struct {
*streamReader[ChatCompletionStreamResponse]
}
// CreateChatCompletionStream — API call to create a chat completion w/ streaming
// support. It sets whether to stream back partial progress. If set, tokens will be
// sent as data-only server-sent events as they become available, with the
// stream terminated by a data: [DONE] message.
func (c *Client) CreateChatCompletionStream(
ctx context.Context,
request ChatCompletionRequest,
) (stream *ChatCompletionStream, err error) {
urlSuffix := chatCompletionsSuffix
if !checkEndpointSupportsModel(urlSuffix, request.Model) {
err = ErrChatCompletionInvalidModel
return
}
request.Stream = true
req, err := c.newRequest(ctx, http.MethodPost, c.fullURL(urlSuffix, request.Model), withBody(request))
if err != nil {
return nil, err
}
resp, err := sendRequestStream[ChatCompletionStreamResponse](c, req)
if err != nil {
return
}
stream = &ChatCompletionStream{
streamReader: resp,
}
return
}