Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions pkg/cmd/agents/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package create
import (
"encoding/json"
"fmt"
"io"

"github.com/MakeNowJust/heredoc"
agentStudio "github.com/algolia/algoliasearch-client-go/v4/algolia/agent-studio"
Expand All @@ -21,6 +22,7 @@ type CreateOptions struct {
PrintFlags *cmdutil.PrintFlags

JSON string
JSONFile string
Name string
Instructions string
}
Expand All @@ -47,10 +49,26 @@ func NewCreateCmd(f *cmdutil.Factory) *cobra.Command {
# Create from a JSON object
$ algolia agentstudio agents create --json '{"name":"support-bot","instructions":"You are a helpful assistant."}'

# Create from a file, or use --json-file - to read standard input
$ algolia agentstudio agents create --json-file agent.json

# Create with a provider and model so the agent can be published
$ algolia agentstudio agents create --json '{"name":"support-bot","instructions":"You are a helpful assistant.","providerId":"22222222-2222-4222-8222-222222222222","model":"gpt-4o"}'
`),
RunE: func(cmd *cobra.Command, args []string) error {
if cmd.Flags().Changed("json-file") {
if cmd.Flags().Changed("json") || cmd.Flags().Changed("name") || cmd.Flags().Changed("instructions") {
return cmdutil.FlagErrorf("--json-file cannot be combined with --json, --name or --instructions")
}
data, err := cmdutil.ReadFile(opts.JSONFile, opts.IO.In)
if err != nil {
return fmt.Errorf("reading agent JSON file: %w", err)
}
if len(data) == 0 {
return fmt.Errorf("parsing agent JSON: %w", io.EOF)
}
opts.JSON = string(data)
}
if opts.JSON != "" {
if opts.Name != "" || opts.Instructions != "" {
return cmdutil.FlagErrorf("--json cannot be combined with --name or --instructions")
Expand All @@ -64,6 +82,7 @@ func NewCreateCmd(f *cmdutil.Factory) *cobra.Command {
}

cmd.Flags().StringVar(&opts.JSON, "json", "", "Agent JSON object (include providerId and model to publish later)")
cmd.Flags().StringVar(&opts.JSONFile, "json-file", "", "Read agent JSON from a file (or - for standard input)")
cmd.Flags().StringVar(&opts.Name, "name", "", "Agent name")
cmd.Flags().StringVar(&opts.Instructions, "instructions", "", "Agent prompt")

Expand Down
72 changes: 72 additions & 0 deletions pkg/cmd/agents/create/create_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package create_test

import (
"errors"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"

agentStudio "github.com/algolia/algoliasearch-client-go/v4/algolia/agent-studio"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -71,6 +75,37 @@
r.Verify(t)
}

func TestCreateAgent_FromJSONFile(t *testing.T) {
file := filepath.Join(t.TempDir(), "agent.json")
require.NoError(t, os.WriteFile(file, []byte(`{"name":"cli-test-agent","instructions":"Hello","providerId":"22222222-2222-4222-8222-222222222222","model":"gpt-4o","config":{"temperature":0.2}}`), 0600))

Check failure on line 80 in pkg/cmd/agents/create/create_test.go

View workflow job for this annotation

GitHub Actions / lint

File is not properly formatted (gofumpt)
r := &httpmock.Registry{}
var gotBody []byte
r.Register(httpmock.REST("POST", "agent-studio/1/agents"), func(req *http.Request) (*http.Response, error) {
gotBody, _ = io.ReadAll(req.Body)
return httpmock.StringResponse(createdAgentBody)(req)
})
f, out := test.NewFactory(false, r, nil, "")
_, err := test.Execute(create.NewCreateCmd(f), "--json-file "+file, out)
require.NoError(t, err)
assert.JSONEq(t, `{"name":"cli-test-agent","instructions":"Hello","providerId":"22222222-2222-4222-8222-222222222222","model":"gpt-4o","config":{"temperature":0.2}}`, string(gotBody))
r.Verify(t)
}

func TestCreateAgent_FromStdin(t *testing.T) {
r := &httpmock.Registry{}
var gotBody []byte
r.Register(httpmock.REST("POST", "agent-studio/1/agents"), func(req *http.Request) (*http.Response, error) {
gotBody, _ = io.ReadAll(req.Body)
return httpmock.StringResponse(createdAgentBody)(req)
})
f, out := test.NewFactory(false, r, nil, "")
f.IOStreams.In = io.NopCloser(strings.NewReader(`{"name":"cli-test-agent","instructions":"Hello"}`))
_, err := test.Execute(create.NewCreateCmd(f), "--json-file -", out)
require.NoError(t, err)
assert.JSONEq(t, `{"name":"cli-test-agent","instructions":"Hello"}`, string(gotBody))
r.Verify(t)
}

func TestCreateAgent_MissingInput(t *testing.T) {
r := &httpmock.Registry{}
f, out := test.NewFactory(false, r, nil, "")
Expand Down Expand Up @@ -106,3 +141,40 @@
require.Error(t, err)
assert.Contains(t, err.Error(), "requires `name` and `instructions`")
}

func TestCreateAgent_JSONFileValidationBeforeClient(t *testing.T) {
valid := filepath.Join(t.TempDir(), "valid.json")
empty := filepath.Join(t.TempDir(), "empty.json")
invalid := filepath.Join(t.TempDir(), "invalid.json")
missingFields := filepath.Join(t.TempDir(), "missing-fields.json")
require.NoError(t, os.WriteFile(valid, []byte(`{"name":"test","instructions":"hello"}`), 0600))

Check failure on line 150 in pkg/cmd/agents/create/create_test.go

View workflow job for this annotation

GitHub Actions / lint

File is not properly formatted (gofumpt)
require.NoError(t, os.WriteFile(empty, nil, 0600))
require.NoError(t, os.WriteFile(invalid, []byte(`{invalid`), 0600))
require.NoError(t, os.WriteFile(missingFields, []byte(`{"name":"test"}`), 0600))

cases := []struct{ name, args, want string }{
{"empty file", "--json-file " + empty, "parsing agent JSON"},
{"empty stdin", "--json-file -", "parsing agent JSON"},
{"invalid JSON", "--json-file " + invalid, "parsing agent JSON"},
{"missing fields", "--json-file " + missingFields, "requires `name` and `instructions`"},
{"missing file", "--json-file " + filepath.Join(t.TempDir(), "absent"), "reading agent JSON file"},
{"conflicting empty json", "--json-file " + valid + " --json ''", "cannot be combined"},
{"conflicting json", "--json-file " + valid + " --json '{}'", "cannot be combined"},
{"conflicting empty name", "--json-file " + valid + " --name ''", "cannot be combined"},
{"conflicting instructions", "--json-file " + valid + " --instructions hello", "cannot be combined"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f, out := test.NewFactory(false, &httpmock.Registry{}, nil, "")
called := false
f.AgentStudioClient = func() (*agentStudio.APIClient, error) {
called = true
return nil, errors.New("unexpected client creation")
}
_, err := test.Execute(create.NewCreateCmd(f), tc.args, out)
require.Error(t, err)
assert.Contains(t, err.Error(), tc.want)
assert.False(t, called, "invalid input must be rejected before creating a client")
})
}
}
Loading