Skip to content
Open
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
2 changes: 2 additions & 0 deletions pkg/cmd/agentstudio/agentstudio.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

"github.com/algolia/cli/pkg/cmd/agents"
"github.com/algolia/cli/pkg/cmd/conversations"
"github.com/algolia/cli/pkg/cmd/evals"
"github.com/algolia/cli/pkg/cmd/providers"
"github.com/algolia/cli/pkg/cmdutil"
)
Expand All @@ -23,6 +24,7 @@ func NewAgentStudioCmd(f *cmdutil.Factory) *cobra.Command {

cmd.AddCommand(agents.NewAgentsCmd(f))
cmd.AddCommand(conversations.NewConversationsCmd(f))
cmd.AddCommand(evals.NewEvalsCmd(f))
cmd.AddCommand(providers.NewProvidersCmd(f))
return cmd
}
14 changes: 14 additions & 0 deletions pkg/cmd/evals/evals.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package evals

import (
"github.com/algolia/cli/pkg/cmd/evals/metrics"
"github.com/algolia/cli/pkg/cmdutil"
"github.com/spf13/cobra"
)

// NewEvalsCmd returns the experimental evaluations command group.
func NewEvalsCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{Use: "evals", Short: "Experimental Agent Studio evaluations", Long: "Experimental evaluation API: availability, schema and stability are not guaranteed. An explicit Agent Studio --base-url is required."}
cmd.AddCommand(metrics.NewMetricsCmd(f))
return cmd
}
28 changes: 28 additions & 0 deletions pkg/cmd/evals/evals_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package evals_test

import (
"strings"
"testing"

"github.com/algolia/cli/pkg/cmd/agentstudio"
"github.com/algolia/cli/pkg/httpmock"
"github.com/algolia/cli/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestExperimentalMetricsCommandRegistration(t *testing.T) {
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/evals/metrics"), httpmock.StringResponse(`{"metrics":[]}`))
f, out := test.NewFactory(false, r, nil, "")
f.AgentStudioBaseURL = "http://localhost:8000"
root := agentstudio.NewAgentStudioCmd(f)
cmd, _, err := root.Find([]string{"evals", "metrics", "list"})
require.NoError(t, err)
assert.Equal(t, "settings", cmd.Annotations["acls"])
assert.Contains(t, strings.ToLower(cmd.Long), "experimental")
_, err = test.Execute(root, "--base-url http://localhost:8000 evals metrics list", out)
require.NoError(t, err)
assert.JSONEq(t, `{"metrics":[]}`, strings.TrimSpace(out.String()))
r.Verify(t)
}
81 changes: 81 additions & 0 deletions pkg/cmd/evals/internal/evalsapi/get.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Package evalsapi provides the experimental, explicitly routed evaluation transport.
package evalsapi

import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"

agentStudio "github.com/algolia/algoliasearch-client-go/v4/algolia/agent-studio"
"github.com/algolia/cli/pkg/cmdutil"
)

// Get reads an experimental evaluation endpoint with the official SDK transport.
func Get(f *cmdutil.Factory, path string, parameters map[string]any) (any, error) {
if f.AgentStudioBaseURL == "" {
return nil, fmt.Errorf("experimental evaluations require an explicit --base-url")
}
if _, err := cmdutil.ParseAgentStudioURL(f.AgentStudioBaseURL); err != nil {
return nil, err
}
client, err := f.AgentStudioClient()
if err != nil {
return nil, err
}
req := client.NewApiCustomGetRequest(path).WithParameters(parameters)
response, body, err := client.CustomGetWithHTTPInfo(req)
if err != nil {
return nil, err
}
if response == nil {
return nil, fmt.Errorf("evaluation API returned no response")
}
if response.Body != nil {
defer response.Body.Close()
}
if response.StatusCode >= 300 {
apiErr := &agentStudio.APIError{Status: response.StatusCode, Message: "evaluation request failed", CorrelationID: response.Header.Get("Correlation-ID")}
if strings.Contains(response.Header.Get("Content-Type"), "application/json") {
var parsed struct {
Message *string `json:"message"`
Detail *string `json:"detail"`
}
if json.Unmarshal(body, &parsed) == nil {
if parsed.Message != nil {
apiErr.Message = *parsed.Message
} else if parsed.Detail != nil {
apiErr.Message = *parsed.Detail
}
}
}
if f.Config != nil {
if key, keyErr := f.Config.Profile().GetAPIKey(); keyErr == nil {
apiErr.Message = cmdutil.RedactCredential(apiErr.Message, key)
}
}
return nil, apiErr
}
var output any
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.UseNumber()
if err := decoder.Decode(&output); err != nil {
return nil, fmt.Errorf("evaluation API returned invalid JSON")
}
if err := decoder.Decode(new(any)); err != io.EOF {
return nil, fmt.Errorf("evaluation API returned invalid JSON")
}
object, ok := output.(map[string]any)
if !ok {
return nil, fmt.Errorf("evaluation API returned an unexpected JSON response")
}
return safeObject(object), nil
}

// safeObject wraps a decoded response so that error paths printing it with %#v
// (for example JSONPath errors) do not leak the full evaluation payload.
type safeObject map[string]any

// GoString prevents JSONPath error messages from printing the full response.
func (safeObject) GoString() string { return "EvaluationResponse{[REDACTED]}" }
47 changes: 47 additions & 0 deletions pkg/cmd/evals/internal/evalsapi/get_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package evalsapi_test

import (
"io"
"net/http"
"strings"
"testing"

"github.com/algolia/cli/pkg/cmd/evals/internal/evalsapi"
"github.com/algolia/cli/pkg/httpmock"
"github.com/algolia/cli/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestGetUsesStringDetailFromErrorBody(t *testing.T) {
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/evals/datasets"), func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 422,
Request: req,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"detail":"not authorized for evaluations"}`)),
}, nil
})
f, _ := test.NewFactory(false, r, nil, "")
f.AgentStudioBaseURL = "http://localhost:8000"
_, err := evalsapi.Get(f, "1/evals/datasets", nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "not authorized for evaluations")
}

func TestGetPreservesQueryValues(t *testing.T) {
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/evals/datasets"), httpmock.StringResponse(`{"data":[]}`))
f, _ := test.NewFactory(false, r, nil, "")
f.AgentStudioBaseURL = "http://localhost:8000"
_, err := evalsapi.Get(f, "1/evals/datasets", map[string]any{"page": 0, "hasFlags": false, "metricSlug": "a & b+c%"})
require.NoError(t, err)
r.Verify(t)
require.Len(t, r.Requests, 1)
q := r.Requests[0].URL.Query()
assert.Equal(t, "0", q.Get("page"))
assert.Equal(t, "false", q.Get("hasFlags"))
assert.Equal(t, "a & b+c%", q.Get("metricSlug"))
assert.Len(t, q, 3)
}
32 changes: 32 additions & 0 deletions pkg/cmd/evals/metrics/list/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package list

import (
"github.com/algolia/cli/pkg/cmd/evals/internal/evalsapi"
"github.com/algolia/cli/pkg/cmdutil"
"github.com/spf13/cobra"
)

// NewListCmd returns the experimental metric catalog command.
func NewListCmd(f *cmdutil.Factory) *cobra.Command {
printFlags := cmdutil.NewPrintFlags().WithDefaultOutput("json")
cmd := &cobra.Command{
Use: "list", Short: "List evaluation metrics (experimental)",
Long: "List evaluation metrics using an experimental API. Availability, schema and stability are not guaranteed. Requires an explicit Agent Studio --base-url.",
Args: cobra.NoArgs, Annotations: map[string]string{"acls": "settings"},
RunE: func(_ *cobra.Command, _ []string) error {
printer, err := printFlags.ToPrinter()
if err != nil {
return err
}
f.IOStreams.StartProgressIndicatorWithLabel("Fetching evaluation metrics")
result, err := evalsapi.Get(f, "1/evals/metrics", nil)
f.IOStreams.StopProgressIndicator()
if err != nil {
return err
}
return printer.Print(f.IOStreams, result)
},
}
printFlags.AddFlags(cmd)
return cmd
}
81 changes: 81 additions & 0 deletions pkg/cmd/evals/metrics/list/list_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package list_test

import (
"io"
"net/http"
"strings"
"testing"

"github.com/algolia/cli/pkg/cmd/evals/metrics/list"
"github.com/algolia/cli/pkg/httpmock"
"github.com/algolia/cli/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestMetricsListExperimental(t *testing.T) {
const body = `{"metrics":[{"slug":"tone","customNumber":9007199254740993}]}`
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/evals/metrics"), httpmock.StringResponse(body))
f, out := test.NewFactory(false, r, nil, "")
f.AgentStudioBaseURL = "http://localhost:8000"
cmd := list.NewListCmd(f)
assert.Equal(t, "settings", cmd.Annotations["acls"])
_, err := test.Execute(cmd, "", out)
require.NoError(t, err)
assert.JSONEq(t, body, strings.TrimSpace(out.String()))
assert.Contains(t, out.String(), `9007199254740993`)
r.Verify(t)
}

func TestMetricsListRequiresExplicitDestination(t *testing.T) {
r := &httpmock.Registry{}
f, out := test.NewFactory(false, r, nil, "")
_, err := test.Execute(list.NewListCmd(f), "", out)
require.Error(t, err)
assert.Contains(t, err.Error(), "--base-url")
assert.Empty(t, r.Requests)
}

func TestMetricsListRejectsAPIError(t *testing.T) {
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/evals/metrics"), func(req *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 403, Request: req, Header: http.Header{"Content-Type": []string{"application/json"}, "Correlation-Id": []string{"trace-1"}}, Body: io.NopCloser(strings.NewReader(`{"message":"access denied synthetic-secret"}`))}, nil
})
f, out := test.NewFactory(false, r, nil, "")
f.AgentStudioBaseURL = "http://localhost:8000"
f.Config.Profile().APIKey = "synthetic-secret"
_, err := test.Execute(list.NewListCmd(f), "", out)
require.Error(t, err)
assert.Contains(t, err.Error(), "access denied")
assert.Contains(t, err.Error(), "trace-1")
assert.NotContains(t, err.Error(), "synthetic-secret")
assert.Empty(t, strings.TrimSpace(out.String()))
r.Verify(t)
}

func TestMetricsListRejectsMalformedResponse(t *testing.T) {
for _, body := range []string{`{"metrics":`, `{"metrics":[]} garbage`, `[]`} {
t.Run(body, func(t *testing.T) {
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/evals/metrics"), httpmock.StringResponse(body))
f, out := test.NewFactory(false, r, nil, "")
f.AgentStudioBaseURL = "http://localhost:8000"
_, err := test.Execute(list.NewListCmd(f), "", out)
require.Error(t, err)
assert.Empty(t, strings.TrimSpace(out.String()))
r.Verify(t)
})
}
}

func TestMetricsListJSONPathErrorRedactsResponse(t *testing.T) {
r := &httpmock.Registry{}
r.Register(httpmock.REST("GET", "agent-studio/1/evals/metrics"), httpmock.StringResponse(`{"metrics":[{"slug":"sensitive-content"}]}`))
f, out := test.NewFactory(false, r, nil, "")
f.AgentStudioBaseURL = "http://localhost:8000"
_, err := test.Execute(list.NewListCmd(f), "-o jsonpath={.metrics[0].slug[0]}", out)
require.Error(t, err)
assert.NotContains(t, err.Error(), "sensitive-content")
r.Verify(t)
}
14 changes: 14 additions & 0 deletions pkg/cmd/evals/metrics/metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package metrics

import (
"github.com/algolia/cli/pkg/cmd/evals/metrics/list"
"github.com/algolia/cli/pkg/cmdutil"
"github.com/spf13/cobra"
)

// NewMetricsCmd returns the experimental evaluation metrics command group.
func NewMetricsCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{Use: "metrics", Short: "Read evaluation metrics (experimental)"}
cmd.AddCommand(list.NewListCmd(f))
return cmd
}
Loading