Skip to content

Commit

Permalink
unexport unneeded fields
Browse files Browse the repository at this point in the history
  • Loading branch information
conneroisu committed Sep 6, 2024
1 parent 9c89519 commit 1277d0b
Show file tree
Hide file tree
Showing 6 changed files with 122 additions and 120 deletions.
6 changes: 3 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ func sendRequestStream[T streamer](
emptyMessagesLimit: client.EmptyMessagesLimit,
reader: bufio.NewReader(resp.Body),
response: resp,
errAccumulator: NewErrorAccumulator(),
errAccumulator: newErrorAccumulator(),
Header: resp.Header,
}, nil
}
Expand Down Expand Up @@ -273,10 +273,10 @@ func withModel(model Model) fullURLOption {
}

func (c *Client) handleErrorResp(resp *http.Response) error {
var errRes ErrorResponse
var errRes errorResponse
err := json.NewDecoder(resp.Body).Decode(&errRes)
if err != nil || errRes.Error == nil {
reqErr := &RequestError{
reqErr := &requestError{
HTTPStatusCode: resp.StatusCode,
Err: err,
}
Expand Down
215 changes: 104 additions & 111 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,96 @@ import (
"strings"
)

// Helper is an interface for error helpers
type Helper interface {
error
Advice() string
// DefaultErrorAccumulator is a default implementation of ErrorAccumulator
type DefaultErrorAccumulator struct {
Buffer errorBuffer
}

// APIError provides error information returned by the Groq API.
type APIError struct {
Code any `json:"code,omitempty"` // Code is the code of the error.
Message string `json:"message"` // Message is the message of the error.
Param *string `json:"param,omitempty"` // Param is the param of the error.
Type string `json:"type"` // Type is the type of the error.
HTTPStatusCode int `json:"-"` // HTTPStatusCode is the status code of the error.
}

// ErrorAccumulator is an interface for accumulating errors
type ErrorAccumulator interface {
// ErrChatCompletionInvalidModel is an error that occurs when the model is not supported with the CreateChatCompletion method.
type ErrChatCompletionInvalidModel struct {
Model Model
Endpoint Endpoint
}

// Error implements the error interface.
func (e ErrChatCompletionInvalidModel) Error() string {
return fmt.Errorf(
"this model (%s) is not supported with this method of interaction over %s, please use CreateCompletion client method instead",
e.Endpoint,
e.Model,
).
Error()
}

// ErrChatCompletionStreamNotSupported is an error that occurs when streaming is not supported with the CreateChatCompletionStream method.
type ErrChatCompletionStreamNotSupported struct {
model Model
}

// Error implements the error interface.
func (e ErrChatCompletionStreamNotSupported) Error() string {
return fmt.Errorf("streaming is not supported with this method, please use CreateChatCompletionStream client method instead").
Error()
}

// ErrContentFieldsMisused is an error that occurs when both Content and MultiContent properties are set.
type ErrContentFieldsMisused struct {
field string
}

// Error implements the error interface.
func (e ErrContentFieldsMisused) Error() string {
return fmt.Errorf("can't use both Content and MultiContent properties simultaneously").
Error()
}

// ErrCompletionUnsupportedModel is an error that occurs when the model is not
// supported with the CreateCompletion method.
type ErrCompletionUnsupportedModel struct{ Model Model }

// Error implements the error interface.
func (e ErrCompletionUnsupportedModel) Error() string {
return fmt.Errorf("this model (%s) is not supported with this method, please use CreateCompletion client method instead", e.Model).
Error()
}

// ErrCompletionStreamNotSupported is an error that occurs when streaming is not supported with the CreateCompletionStream method.
type ErrCompletionStreamNotSupported struct{}

// Error implements the error interface.
func (e ErrCompletionStreamNotSupported) Error() string {
return fmt.Errorf("streaming is not supported with this method, please use CreateCompletionStream client method instead").
Error()
}

// ErrCompletionRequestPromptTypeNotSupported is an error that occurs when the type of CompletionRequest.Prompt only supports string and []string.
type ErrCompletionRequestPromptTypeNotSupported struct{}

// Error implements the error interface.
func (e ErrCompletionRequestPromptTypeNotSupported) Error() string {
return fmt.Errorf("the type of CompletionRequest.Prompt only supports string and []string").
Error()
}

// ErrTooManyEmptyStreamMessages is returned when the stream has sent too many empty messages.
type ErrTooManyEmptyStreamMessages struct{}

// Error returns the error message.
func (e ErrTooManyEmptyStreamMessages) Error() string {
return "stream has sent too many empty messages"
}

// errorAccumulator is an interface for accumulating errors
type errorAccumulator interface {
// Write writes bytes to the error accumulator
//
// It implements the io.Writer interface.
Expand All @@ -30,19 +112,26 @@ type errorBuffer interface {
Bytes() []byte
}

// DefaultErrorAccumulator is a default implementation of ErrorAccumulator
type DefaultErrorAccumulator struct {
Buffer errorBuffer
// requestError provides information about generic request errors.
type requestError struct {
HTTPStatusCode int
Err error
}

// errorResponse is a response from the error endpoint.
type errorResponse struct {
Error *APIError `json:"error,omitempty"`
}

// NewErrorAccumulator creates a new error accumulator
func NewErrorAccumulator() ErrorAccumulator {
// Error implements the error interface.
// newErrorAccumulator creates a new error accumulator
func newErrorAccumulator() errorAccumulator {
return &DefaultErrorAccumulator{
Buffer: &bytes.Buffer{},
}
}

// Write writes bytes to the error accumulator
// Write writes bytes to the error accumulator.
func (e *DefaultErrorAccumulator) Write(p []byte) error {
_, err := e.Buffer.Write(p)
if err != nil {
Expand All @@ -51,7 +140,7 @@ func (e *DefaultErrorAccumulator) Write(p []byte) error {
return nil
}

// Bytes returns the bytes of the error accumulator
// Bytes returns the bytes of the error accumulator.
func (e *DefaultErrorAccumulator) Bytes() (errBytes []byte) {
if e.Buffer.Len() == 0 {
return
Expand All @@ -60,26 +149,6 @@ func (e *DefaultErrorAccumulator) Bytes() (errBytes []byte) {
return
}

// APIError provides error information returned by the Groq API.
type APIError struct {
Code any `json:"code,omitempty"` // Code is the code of the error.
Message string `json:"message"` // Message is the message of the error.
Param *string `json:"param,omitempty"` // Param is the param of the error.
Type string `json:"type"` // Type is the type of the error.
HTTPStatusCode int `json:"-"` // HTTPStatusCode is the status code of the error.
}

// RequestError provides information about generic request errors.
type RequestError struct {
HTTPStatusCode int
Err error
}

// ErrorResponse is a response from the error endpoint.
type ErrorResponse struct {
Error *APIError `json:"error,omitempty"`
}

// Error implements the error interface.
func (e *APIError) Error() string {
if e.HTTPStatusCode > 0 {
Expand Down Expand Up @@ -129,90 +198,14 @@ func (e *APIError) UnmarshalJSON(data []byte) (err error) {
return json.Unmarshal(rawMap["code"], &e.Code)
}

// Error implements the error interface.
func (e *RequestError) Error() string {
func (e *requestError) Error() string {
return fmt.Sprintf(
"error, status code: %d, message: %s",
e.HTTPStatusCode,
e.Err,
)
}

// Unwrap returns the underlying error
func (e *RequestError) Unwrap() error {
func (e *requestError) Unwrap() error {
return e.Err
}

// ErrChatCompletionInvalidModel is an error that occurs when the model is not supported with the CreateChatCompletion method.
type ErrChatCompletionInvalidModel struct {
Model Model
Endpoint Endpoint
}

// Error implements the error interface.
func (e ErrChatCompletionInvalidModel) Error() string {
return fmt.Errorf(
"this model (%s) is not supported with this method of interaction over %s, please use CreateCompletion client method instead",
e.Endpoint,
e.Model,
).
Error()
}

// ErrChatCompletionStreamNotSupported is an error that occurs when streaming is not supported with the CreateChatCompletionStream method.
type ErrChatCompletionStreamNotSupported struct {
model Model
}

// Error implements the error interface.
func (e ErrChatCompletionStreamNotSupported) Error() string {
return fmt.Errorf("streaming is not supported with this method, please use CreateChatCompletionStream client method instead").
Error()
}

// ErrContentFieldsMisused is an error that occurs when both Content and MultiContent properties are set.
type ErrContentFieldsMisused struct {
field string
}

// Error implements the error interface.
func (e ErrContentFieldsMisused) Error() string {
return fmt.Errorf("can't use both Content and MultiContent properties simultaneously").
Error()
}

// ErrCompletionUnsupportedModel is an error that occurs when the model is not
// supported with the CreateCompletion method.
type ErrCompletionUnsupportedModel struct{ Model Model }

// Error implements the error interface.
func (e ErrCompletionUnsupportedModel) Error() string {
return fmt.Errorf("this model (%s) is not supported with this method, please use CreateCompletion client method instead", e.Model).
Error()
}

// ErrCompletionStreamNotSupported is an error that occurs when streaming is not supported with the CreateCompletionStream method.
type ErrCompletionStreamNotSupported struct{}

// Error implements the error interface.
func (e ErrCompletionStreamNotSupported) Error() string {
return fmt.Errorf("streaming is not supported with this method, please use CreateCompletionStream client method instead").
Error()
}

// ErrCompletionRequestPromptTypeNotSupported is an error that occurs when the type of CompletionRequest.Prompt only supports string and []string.
type ErrCompletionRequestPromptTypeNotSupported struct{}

// Error implements the error interface.
func (e ErrCompletionRequestPromptTypeNotSupported) Error() string {
return fmt.Errorf("the type of CompletionRequest.Prompt only supports string and []string").
Error()
}

// ErrTooManyEmptyStreamMessages is returned when the stream has sent too many empty messages.
type ErrTooManyEmptyStreamMessages struct{}

// Error returns the error message.
func (e ErrTooManyEmptyStreamMessages) Error() string {
return "stream has sent too many empty messages"
}
5 changes: 4 additions & 1 deletion moderation.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,10 @@ func (c *Client) Moderate(
response.Flagged = true
split := strings.Split(strings.Split(content, "\n")[1], ",")
for _, s := range split {
response.Categories = append(response.Categories, SectionMap[strings.TrimSpace(s)])
response.Categories = append(
response.Categories,
SectionMap[strings.TrimSpace(s)],
)
}
}
return
Expand Down
8 changes: 7 additions & 1 deletion moderation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,13 @@ func TestModerate(t *testing.T) {
a := assert.New(t)
a.NoError(err, "Moderation error")
a.Equal(true, mod.Flagged)
a.Equal(mod.Categories, []groq.HarmfulCategory{groq.CategoryViolentCrimes, groq.CategoryNonviolentCrimes})
a.Equal(
mod.Categories,
[]groq.HarmfulCategory{
groq.CategoryViolentCrimes,
groq.CategoryNonviolentCrimes,
},
)
}

func handleModerationEndpoint(w http.ResponseWriter, r *http.Request) {
Expand Down
4 changes: 2 additions & 2 deletions stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ type streamReader[T streamer] struct {

reader *bufio.Reader
response *http.Response
errAccumulator ErrorAccumulator
errAccumulator errorAccumulator

Header http.Header // Header is the header of the response.
}
Expand Down Expand Up @@ -127,7 +127,7 @@ func (stream *streamReader[T]) processLines() (T, error) {
}
}

func (stream *streamReader[T]) unmarshalError() (errResp *ErrorResponse) {
func (stream *streamReader[T]) unmarshalError() (errResp *errorResponse) {
errBytes := stream.errAccumulator.Bytes()
if len(errBytes) == 0 {
return
Expand Down
4 changes: 2 additions & 2 deletions stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
// TestStreamReaderReturnsUnmarshalerErrors tests the stream reader returns an unmarshaler error.
func TestStreamReaderReturnsUnmarshalerErrors(t *testing.T) {
stream := &streamReader[ChatCompletionStreamResponse]{
errAccumulator: NewErrorAccumulator(),
errAccumulator: newErrorAccumulator(),
}

respErr := stream.unmarshalError()
Expand All @@ -39,7 +39,7 @@ func TestStreamReaderReturnsErrTooManyEmptyStreamMessages(t *testing.T) {
reader: bufio.NewReader(
bytes.NewReader([]byte("\n\n\n\n")),
),
errAccumulator: NewErrorAccumulator(),
errAccumulator: newErrorAccumulator(),
}
_, err := stream.Recv()
a.ErrorIs(
Expand Down

0 comments on commit 1277d0b

Please sign in to comment.