|
| 1 | +package gogpt |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "errors" |
| 8 | + "net/http" |
| 9 | +) |
| 10 | + |
| 11 | +var ( |
| 12 | + ErrChatCompletionInvalidModel = errors.New("currently, only gpt-3.5-turbo and gpt-3.5-turbo-0301 are supported") |
| 13 | +) |
| 14 | + |
| 15 | +type ChatCompletionMessage struct { |
| 16 | + Role string `json:"role"` |
| 17 | + Content string `json:"content"` |
| 18 | +} |
| 19 | + |
| 20 | +// ChatCompletionRequest represents a request structure for chat completion API. |
| 21 | +type ChatCompletionRequest struct { |
| 22 | + Model string `json:"model"` |
| 23 | + Messages []ChatCompletionMessage `json:"messages"` |
| 24 | +} |
| 25 | + |
| 26 | +type ChatCompletionChoice struct { |
| 27 | + Index int `json:"index"` |
| 28 | + Message ChatCompletionMessage `json:"message"` |
| 29 | + FinishReason string `json:"finish_reason"` |
| 30 | +} |
| 31 | + |
| 32 | +// ChatCompletionResponse represents a response structure for chat completion API. |
| 33 | +type ChatCompletionResponse struct { |
| 34 | + ID string `json:"id"` |
| 35 | + Object string `json:"object"` |
| 36 | + Created int64 `json:"created"` |
| 37 | + Model string `json:"model"` |
| 38 | + Choices []ChatCompletionChoice `json:"choices"` |
| 39 | + Usage Usage `json:"usage"` |
| 40 | +} |
| 41 | + |
| 42 | +// CreateChatCompletion — API call to Creates a completion for the chat message. |
| 43 | +func (c *Client) CreateChatCompletion( |
| 44 | + ctx context.Context, |
| 45 | + request ChatCompletionRequest, |
| 46 | +) (response ChatCompletionResponse, err error) { |
| 47 | + model := request.Model |
| 48 | + if model != GPT3Dot5Turbo0301 && model != GPT3Dot5Turbo { |
| 49 | + err = ErrChatCompletionInvalidModel |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + var reqBytes []byte |
| 54 | + reqBytes, err = json.Marshal(request) |
| 55 | + if err != nil { |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + urlSuffix := "/chat/completions" |
| 60 | + req, err := http.NewRequest("POST", c.fullURL(urlSuffix), bytes.NewBuffer(reqBytes)) |
| 61 | + if err != nil { |
| 62 | + return |
| 63 | + } |
| 64 | + |
| 65 | + req = req.WithContext(ctx) |
| 66 | + err = c.sendRequest(req, &response) |
| 67 | + return |
| 68 | +} |
0 commit comments