Skip to content

Commit

Permalink
feat: use interface to export method and initiate request with ctx
Browse files Browse the repository at this point in the history
  • Loading branch information
northes committed Apr 22, 2024
1 parent 24d2f89 commit bd6880b
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 37 deletions.
11 changes: 8 additions & 3 deletions api_chat_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,16 @@ import (
"github.com/northes/go-moonshot/internal/httpx"
)

type IChat interface {
Completions(ctx context.Context, req *ChatCompletionsRequest) (*ChatCompletionsResponse, error)
CompletionsStream(ctx context.Context, req *ChatCompletionsRequest) (*ChatCompletionsStreamResponse, error)
}

type chat struct {
client *Client
}

func (c *Client) Chat() *chat {
func (c *Client) Chat() IChat {
return &chat{
client: c,
}
Expand Down Expand Up @@ -70,7 +75,7 @@ func (c *chat) Completions(ctx context.Context, req *ChatCompletionsRequest) (*C
const path = "/v1/chat/completions"
req.Stream = false
chatCompletionsResp := new(ChatCompletionsResponse)
resp, err := c.client.HTTPClient().SetPath(path).SetBody(req).Post()
resp, err := c.client.HTTPClient().SetPath(path).SetBody(req).Post(ctx)
if err != nil {
return chatCompletionsResp, err
}
Expand Down Expand Up @@ -100,7 +105,7 @@ func (c *chat) CompletionsStream(ctx context.Context, req *ChatCompletionsReques

req.Stream = true

resp, err := c.client.HTTPClient().SetPath(path).SetBody(req).Post()
resp, err := c.client.HTTPClient().SetPath(path).SetBody(req).Post(ctx)
if err != nil {
return nil, err
}
Expand Down
40 changes: 26 additions & 14 deletions api_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,28 @@ package moonshot

import (
"bytes"
"context"
"fmt"
"os"

utils "github.com/northes/go-moonshot/internal/builder"
)

type IFiles interface {
Upload(ctx context.Context, req *FilesUploadRequest) (resp *FilesUploadResponse, err error)
UploadBytes(ctx context.Context, req *FilesUploadBytesRequest) (resp *FilesUploadBytesResponse, err error)
List(ctx context.Context) (res *FilesListResponse, err error)
Delete(ctx context.Context, fileID string) (resp *FilesDeleteResponse, err error)
BatchDelete(ctx context.Context, req *FilesBatchDeleteRequest) (resp *FilesBatchDeleteResponse, err error)
Info(ctx context.Context, fileID string) (resp *FilesInfoResponse, err error)
Content(ctx context.Context, fileID string) (resp *FileContentResponse, err error)
}

type files struct {
client *Client
}

func (c *Client) Files() *files {
func (c *Client) Files() IFiles {
return &files{
client: c,
}
Expand All @@ -34,7 +45,7 @@ type FilesUploadResponse struct {
StatusDetails string `json:"status_details"`
}

func (f *files) Upload(req *FilesUploadRequest) (*FilesUploadResponse, error) {
func (f *files) Upload(ctx context.Context, req *FilesUploadRequest) (*FilesUploadResponse, error) {
const path = "/v1/files"

var b bytes.Buffer
Expand Down Expand Up @@ -98,7 +109,7 @@ type FilesUploadBytesResponse struct {
StatusDetails string `json:"status_details"`
}

func (f *files) UploadBytes(req *FilesUploadBytesRequest) (*FilesUploadBytesResponse, error) {
func (f *files) UploadBytes(ctx context.Context, req *FilesUploadBytesRequest) (*FilesUploadBytesResponse, error) {
const path = "/v1/files"

var b bytes.Buffer
Expand Down Expand Up @@ -157,9 +168,9 @@ type FilesListResponseData struct {
StatusDetail string `json:"status_detail"`
}

func (f *files) Lists() (*FilesListResponse, error) {
func (f *files) List(ctx context.Context) (*FilesListResponse, error) {
const path = "/v1/files"
resp, err := f.client.HTTPClient().SetPath(path).Get()
resp, err := f.client.HTTPClient().SetPath(path).Get(ctx)
if err != nil {
return nil, err
}
Expand All @@ -181,10 +192,10 @@ type FilesDeleteResponse struct {
Object string `json:"object"`
}

func (f *files) Delete(fileID string) (*FilesDeleteResponse, error) {
func (f *files) Delete(ctx context.Context, fileID string) (*FilesDeleteResponse, error) {
const path = "/v1/files/%s"
fullPath := fmt.Sprintf(path, fileID)
resp, err := f.client.HTTPClient().SetPath(fullPath).Delete()
resp, err := f.client.HTTPClient().SetPath(fullPath).Delete(ctx)
if err != nil {
return nil, err
}
Expand All @@ -203,10 +214,11 @@ type FilesBatchDeleteRequest struct {
FileIDList []string `json:"file_ids"`
}
type FilesBatchDeleteResponse struct {
RespList []*FilesDeleteResponse `json:"resp_list"`
RespList []*FilesDeleteResponse `json:"resp_list"`
ErrorList []error `json:"error_list"`
}

func (f *files) BatchDelete(req *FilesBatchDeleteRequest) (*FilesBatchDeleteResponse, error) {
func (f *files) BatchDelete(ctx context.Context, req *FilesBatchDeleteRequest) (*FilesBatchDeleteResponse, error) {
if req == nil || len(req.FileIDList) == 0 {
return nil, fmt.Errorf("batch delete request must contain at least one file id")
}
Expand All @@ -216,7 +228,7 @@ func (f *files) BatchDelete(req *FilesBatchDeleteRequest) (*FilesBatchDeleteResp
}

for _, fileID := range req.FileIDList {
deleteResp, err := f.Delete(fileID)
deleteResp, err := f.Delete(ctx, fileID)
if err != nil {
return nil, err
}
Expand All @@ -237,10 +249,10 @@ type FilesInfoResponse struct {
StatusDetails string `json:"status_details"`
}

func (f *files) Info(fileID string) (*FilesInfoResponse, error) {
func (f *files) Info(ctx context.Context, fileID string) (*FilesInfoResponse, error) {
const path = "/v1/files/%s"
fullPath := fmt.Sprintf(path, fileID)
resp, err := f.client.HTTPClient().SetPath(fullPath).Get()
resp, err := f.client.HTTPClient().SetPath(fullPath).Get(ctx)
if err != nil {
return nil, err
}
Expand All @@ -263,10 +275,10 @@ type FileContentResponse struct {
Type string `json:"type"`
}

func (f *files) Content(fileID string) (*FileContentResponse, error) {
func (f *files) Content(ctx context.Context, fileID string) (*FileContentResponse, error) {
const path = "/v1/files/%s/content"
fullPath := fmt.Sprintf(path, fileID)
resp, err := f.client.HTTPClient().SetPath(fullPath).Get()
resp, err := f.client.HTTPClient().SetPath(fullPath).Get(ctx)
if err != nil {
return nil, err
}
Expand Down
21 changes: 11 additions & 10 deletions api_files_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package moonshot_test

import (
"context"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -30,7 +31,7 @@ func TestFilesUpload(t *testing.T) {
if err != nil {
t.Fatal(err)
}
resp, err := cli.Files().Upload(&moonshot.FilesUploadRequest{
resp, err := cli.Files().Upload(context.Background(), &moonshot.FilesUploadRequest{
Name: filepath.Base(filePath),
Path: filePath,
Purpose: moonshot.FilePurposeExtract,
Expand All @@ -54,7 +55,7 @@ func TestFilesUploadBytes(t *testing.T) {
if err != nil {
t.Fatal(err)
}
uploadResp, err := cli.Files().UploadBytes(&moonshot.FilesUploadBytesRequest{
uploadResp, err := cli.Files().UploadBytes(context.Background(), &moonshot.FilesUploadBytesRequest{
Name: "byteFile.txt",
Bytes: content,
Purpose: moonshot.FilePurposeExtract,
Expand All @@ -65,14 +66,14 @@ func TestFilesUploadBytes(t *testing.T) {
require.Equal(uploadResp.Bytes, len(content))

// check content
contentResp, err := cli.Files().Content(uploadResp.ID)
contentResp, err := cli.Files().Content(context.Background(), uploadResp.ID)
if err != nil {
t.Fatal(err)
}
require.Equal(string(content), contentResp.Content)

// remove
deleteResp, err := cli.Files().Delete(uploadResp.ID)
deleteResp, err := cli.Files().Delete(context.Background(), uploadResp.ID)
if err != nil {
t.Fatal(err)
}
Expand All @@ -85,7 +86,7 @@ func TestFilesList(t *testing.T) {
if err != nil {
t.Fatal(err)
}
resp, err := cli.Files().Lists()
resp, err := cli.Files().List(context.Background())
if err != nil {
t.Fatal(err)
}
Expand All @@ -98,7 +99,7 @@ func TestFilesInfo(t *testing.T) {
if err != nil {
t.Fatal(err)
}
resp, err := cli.Files().Info(fileID)
resp, err := cli.Files().Info(context.Background(), fileID)
if err != nil {
t.Fatal(err)
}
Expand All @@ -110,7 +111,7 @@ func TestFilesContent(t *testing.T) {
if err != nil {
t.Fatal(err)
}
resp, err := cli.Files().Content(fileID)
resp, err := cli.Files().Content(context.Background(), fileID)
if err != nil {
t.Fatal(err)
}
Expand All @@ -125,7 +126,7 @@ func TestFilesDelete(t *testing.T) {
if err != nil {
t.Fatal(err)
}
resp, err := cli.Files().Delete(fileID)
resp, err := cli.Files().Delete(context.Background(), fileID)
if err != nil {
t.Fatal(err)
}
Expand All @@ -142,7 +143,7 @@ func TestFilesBatchDelete(t *testing.T) {

for i := 0; i < 10; i++ {
fp, _ := test.GenerateTestFile(test.GenerateTestContent())
uploadResp, err := cli.Files().Upload(&moonshot.FilesUploadRequest{
uploadResp, err := cli.Files().Upload(context.Background(), &moonshot.FilesUploadRequest{
Name: filepath.Base(fp),
Path: fp,
Purpose: moonshot.FilePurposeExtract,
Expand All @@ -156,7 +157,7 @@ func TestFilesBatchDelete(t *testing.T) {

t.Logf("file id to delete: %v", fileIdList)

deleteAllResp, err := cli.Files().BatchDelete(&moonshot.FilesBatchDeleteRequest{
deleteAllResp, err := cli.Files().BatchDelete(context.Background(), &moonshot.FilesBatchDeleteRequest{
FileIDList: fileIdList,
})
if err != nil {
Expand Down
8 changes: 6 additions & 2 deletions api_models.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ import (
"context"
)

type IModels interface {
List(ctx context.Context) (*ListModelsResponse, error)
}

type models struct {
client *Client
}

func (c *Client) Models() *models {
func (c *Client) Models() IModels {
return &models{
client: c,
}
Expand Down Expand Up @@ -50,7 +54,7 @@ type ListModelsResponseDataPermission struct {

func (m *models) List(ctx context.Context) (*ListModelsResponse, error) {
const path = "/v1/models"
resp, err := m.client.HTTPClient().SetPath(path).Get()
resp, err := m.client.HTTPClient().SetPath(path).Get(ctx)
if err != nil {
return nil, err
}
Expand Down
8 changes: 6 additions & 2 deletions api_tokenizers_estimate_token_count.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ import (
"context"
)

type ITokenizers interface {
EstimateTokenCount(ctx context.Context, req *TokenizersEstimateTokenCountRequest) (resp *TokenizersEstimateTokenCountResponse, err error)
}

type tokenizersEstimateTokenCount struct {
client *Client
}

func (c *Client) Tokenizers() *tokenizersEstimateTokenCount {
func (c *Client) Tokenizers() ITokenizers {
return &tokenizersEstimateTokenCount{
client: c,
}
Expand All @@ -31,7 +35,7 @@ type TokenizersEstimateTokenCountResponseData struct {
func (t *tokenizersEstimateTokenCount) EstimateTokenCount(ctx context.Context, req *TokenizersEstimateTokenCountRequest) (*TokenizersEstimateTokenCountResponse, error) {
const path = "/v1/tokenizers/estimate-token-count"
estimateTokenCountResp := new(TokenizersEstimateTokenCountResponse)
resp, err := t.client.HTTPClient().SetPath(path).SetBody(req).Post()
resp, err := t.client.HTTPClient().SetPath(path).SetBody(req).Post(ctx)
if err != nil {
return nil, err
}
Expand Down
13 changes: 7 additions & 6 deletions client.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package moonshot

import (
"errors"

"github.com/northes/go-moonshot/internal/httpx"
"github.com/northes/go-moonshot/internal/httpx/tools"
)
Expand All @@ -12,27 +10,30 @@ type Client struct {
}

func NewClient(key string) (*Client, error) {
if len(key) == 0 {
return nil, errors.New("key is required")
}

cfg := NewConfig(
WithAPIKey(key),
)

if err := cfg.PreCheck(); err != nil {
return nil, err
}

return NewClientWithConfig(cfg)
}

func NewClientWithConfig(cfg *Config) (*Client, error) {
if cfg == nil {
cfg = newConfigDefault()
}

if err := cfg.PreCheck(); err != nil {
return nil, err
}

c := &Client{
cfg: cfg,
}

return c, nil
}

Expand Down

0 comments on commit bd6880b

Please sign in to comment.