Skip to content

Commit

Permalink
Use Golines to limit line length (#17)
Browse files Browse the repository at this point in the history
* Add golines test to workflow

* run golines on project

* run golines
  • Loading branch information
WillMatthews authored Sep 6, 2024
1 parent 90102ae commit 46f46a6
Show file tree
Hide file tree
Showing 11 changed files with 248 additions and 59 deletions.
24 changes: 24 additions & 0 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,38 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Setup Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod

- name: Run tests
run: go test -race -covermode=atomic -coverprofile=coverage.out -v .

- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v4.5.0
with:
token: ${{ secrets.CODECOV_TOKEN }}
slug: liushuangls/go-anthropic

- name: Run tests
run: go test -race -covermode=atomic -coverprofile=coverage.out -v .

- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v4.0.1
with:
token: ${{ secrets.CODECOV_TOKEN }}
slug: liushuangls/go-anthropic

- name: Golines format check
run: |
go install github.com/segmentio/golines@latest
change=$(golines --dry-run .)
if [ -n "$change" ]; then
echo "::error:: golines needs to be run, and changes committed. Please run:"
echo "::error:: go install github.com/segmentio/golines@latest"
echo "::error:: golines -w ."
echo "$change"
exit 1
fi
21 changes: 18 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,12 @@ func withBetaVersion(betaVersion ...BetaVersion) requestSetter {
}
}

func (c *Client) newRequest(ctx context.Context, method, urlSuffix string, body any, requestSetters ...requestSetter) (req *http.Request, err error) {
func (c *Client) newRequest(
ctx context.Context,
method, urlSuffix string,
body any,
requestSetters ...requestSetter,
) (req *http.Request, err error) {
var reqBody []byte
if body != nil {
reqBody, err = json.Marshal(body)
Expand All @@ -102,7 +107,12 @@ func (c *Client) newRequest(ctx context.Context, method, urlSuffix string, body
}
}

req, err = http.NewRequestWithContext(ctx, method, c.fullURL(urlSuffix), bytes.NewBuffer(reqBody))
req, err = http.NewRequestWithContext(
ctx,
method,
c.fullURL(urlSuffix),
bytes.NewBuffer(reqBody),
)
if err != nil {
return nil, err
}
Expand All @@ -119,7 +129,12 @@ func (c *Client) newRequest(ctx context.Context, method, urlSuffix string, body
return req, nil
}

func (c *Client) newStreamRequest(ctx context.Context, method, urlSuffix string, body any, requestSetters ...requestSetter) (req *http.Request,
func (c *Client) newStreamRequest(
ctx context.Context,
method, urlSuffix string,
body any,
requestSetters ...requestSetter,
) (req *http.Request,
err error) {
req, err = c.newRequest(ctx, method, urlSuffix, body, requestSetters...)
if err != nil {
Expand Down
5 changes: 4 additions & 1 deletion complete.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ type CompleteResponse struct {
Model Model `json:"model"`
}

func (c *Client) CreateComplete(ctx context.Context, request CompleteRequest) (response CompleteResponse, err error) {
func (c *Client) CreateComplete(
ctx context.Context,
request CompleteRequest,
) (response CompleteResponse, err error) {
request.Stream = false

urlSuffix := "/complete"
Expand Down
5 changes: 4 additions & 1 deletion complete_stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ type CompleteStreamPingData struct {
Type string `json:"type"`
}

func (c *Client) CreateCompleteStream(ctx context.Context, request CompleteStreamRequest) (response CompleteResponse, err error) {
func (c *Client) CreateCompleteStream(
ctx context.Context,
request CompleteStreamRequest,
) (response CompleteResponse, err error) {
request.Stream = true

urlSuffix := "/complete"
Expand Down
33 changes: 28 additions & 5 deletions complete_stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,18 @@ func TestCompleteStream(t *testing.T) {

expected := strings.Join(testCompletionStreamContent, "")
if receivedContent != expected {
t.Fatalf("CreateCompleteStream content not match expected: %s, got: %s", expected, receivedContent)
t.Fatalf(
"CreateCompleteStream content not match expected: %s, got: %s",
expected,
receivedContent,
)
}
if resp.Completion != expected {
t.Fatalf("CreateCompleteStream content not match expected: %s, got: %s", expected, resp.Completion)
t.Fatalf(
"CreateCompleteStream content not match expected: %s, got: %s",
expected,
resp.Completion,
)
}
t.Logf("CreateCompleteStream resp: %+v", resp)
}
Expand Down Expand Up @@ -114,16 +122,31 @@ func handlerCompleteStream(w http.ResponseWriter, r *http.Request) {

if request.Temperature != nil && *request.Temperature > 1 {
dataBytes = append(dataBytes, []byte("event: error\n")...)
dataBytes = append(dataBytes, []byte(`data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}`+"\n\n")...)
dataBytes = append(
dataBytes,
[]byte(
`data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}`+"\n\n",
)...)
}

for _, t := range testCompletionStreamContent {
dataBytes = append(dataBytes, []byte("event: completion\n")...)
dataBytes = append(dataBytes, []byte(fmt.Sprintf(`data: {"type":"completion","id":"compl_01GatBXF5t5K51mYzbVgRJfZ","completion":"%s","stop_reason":null,"model":"claude-instant-1.2","stop":null,"log_id":"compl_01GatBXF5t5K51mYzbVgRJfZ"}`, t)+"\n\n")...)
dataBytes = append(
dataBytes,
[]byte(
fmt.Sprintf(
`data: {"type":"completion","id":"compl_01GatBXF5t5K51mYzbVgRJfZ","completion":"%s","stop_reason":null,"model":"claude-instant-1.2","stop":null,"log_id":"compl_01GatBXF5t5K51mYzbVgRJfZ"}`,
t,
)+"\n\n",
)...)
}

dataBytes = append(dataBytes, []byte("event: completion\n")...)
dataBytes = append(dataBytes, []byte(`data: {"type":"completion","id":"compl_01GatBXF5t5K51mYzbVgRJfZ","completion":"","stop_reason":"stop_sequence","model":"claude-instant-1.2","stop":null,"log_id":"compl_01GatBXF5t5K51mYzbVgRJfZ"}`+"\n\n")...)
dataBytes = append(
dataBytes,
[]byte(
`data: {"type":"completion","id":"compl_01GatBXF5t5K51mYzbVgRJfZ","completion":"","stop_reason":"stop_sequence","model":"claude-instant-1.2","stop":null,"log_id":"compl_01GatBXF5t5K51mYzbVgRJfZ"}`+"\n\n",
)...)

_, _ = w.Write(dataBytes)
}
5 changes: 4 additions & 1 deletion integrationtest/messages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ func TestIntegrationMessages(t *testing.T) {
}

t.Run("CreateMessages on real API", func(t *testing.T) {
betaOpts := anthropic.WithBetaVersion(anthropic.BetaTools20240404, anthropic.BetaMaxTokens35Sonnet20240715)
betaOpts := anthropic.WithBetaVersion(
anthropic.BetaTools20240404,
anthropic.BetaMaxTokens35Sonnet20240715,
)
newClient := anthropic.NewClient(APIKey, betaOpts)

resp, err := newClient.CreateMessages(ctx, request)
Expand Down
34 changes: 18 additions & 16 deletions internal/test/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,22 @@ func (ts *ServerTest) RegisterHandler(path string, handler Handler) {

// AnthropicTestServer Creates a mocked Anthropic server which can pretend to handle requests during testing.
func (ts *ServerTest) AnthropicTestServer() *httptest.Server {
return httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("received request at path %q\n", r.URL.Path)

// check auth
if r.Header.Get("X-Api-Key") != GetTestToken() {
w.WriteHeader(http.StatusUnauthorized)
return
}

handlerCall, ok := ts.handlers[r.URL.Path]
if !ok {
http.Error(w, "the resource path doesn't exist", http.StatusNotFound)
return
}
handlerCall(w, r)
}))
return httptest.NewUnstartedServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("received request at path %q\n", r.URL.Path)

// check auth
if r.Header.Get("X-Api-Key") != GetTestToken() {
w.WriteHeader(http.StatusUnauthorized)
return
}

handlerCall, ok := ts.handlers[r.URL.Path]
if !ok {
http.Error(w, "the resource path doesn't exist", http.StatusNotFound)
return
}
handlerCall(w, r)
}),
)
}
20 changes: 16 additions & 4 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,10 @@ type MessageContentToolResult struct {
IsError *bool `json:"is_error,omitempty"`
}

func NewMessageContentToolResult(toolUseID, content string, isError bool) *MessageContentToolResult {
func NewMessageContentToolResult(
toolUseID, content string,
isError bool,
) *MessageContentToolResult {
return &MessageContentToolResult{
ToolUseID: &toolUseID,
Content: []MessageContent{
Expand All @@ -263,7 +266,10 @@ type MessageContentImageSource struct {
Data any `json:"data"`
}

func NewMessageContentImageSource(imageSourceType, mediaType string, data any) MessageContentImageSource {
func NewMessageContentImageSource(
imageSourceType, mediaType string,
data any,
) MessageContentImageSource {
return MessageContentImageSource{
Type: imageSourceType,
MediaType: mediaType,
Expand All @@ -277,7 +283,10 @@ type MessageContentToolUse struct {
Input json.RawMessage `json:"input,omitempty"`
}

func NewMessageContentToolUse(toolUseId, name string, input json.RawMessage) *MessageContentToolUse {
func NewMessageContentToolUse(
toolUseId, name string,
input json.RawMessage,
) *MessageContentToolUse {
return &MessageContentToolUse{
ID: toolUseId,
Name: name,
Expand Down Expand Up @@ -337,7 +346,10 @@ type ToolChoice struct {
Name string `json:"name,omitempty"`
}

func (c *Client) CreateMessages(ctx context.Context, request MessagesRequest) (response MessagesResponse, err error) {
func (c *Client) CreateMessages(
ctx context.Context,
request MessagesRequest,
) (response MessagesResponse, err error) {
request.Stream = false

var setters []requestSetter
Expand Down
5 changes: 4 additions & 1 deletion message_stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ type MessagesEventMessageStopData struct {
Type string `json:"type"`
}

func (c *Client) CreateMessagesStream(ctx context.Context, request MessagesStreamRequest) (response MessagesResponse, err error) {
func (c *Client) CreateMessagesStream(
ctx context.Context,
request MessagesStreamRequest,
) (response MessagesResponse, err error) {
request.Stream = true

var setters []requestSetter
Expand Down
Loading

0 comments on commit 46f46a6

Please sign in to comment.