261 lines
9.9 KiB
Go
261 lines
9.9 KiB
Go
package cli
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
|
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
|
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
|
|
auditaprompts "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
|
|
commandkit "go.maximumdirect.net/commandkit"
|
|
ck "go.maximumdirect.net/configkit"
|
|
pk "go.maximumdirect.net/promptkit"
|
|
)
|
|
|
|
func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
|
|
_, file, _, ok := runtime.Caller(0)
|
|
if !ok {
|
|
t.Fatal("cannot locate examples")
|
|
}
|
|
root := filepath.Join(filepath.Dir(file), "..", "..", "examples")
|
|
t.Setenv("AUDITA_EXAMPLE_KEY", "synthetic-example-key")
|
|
for _, tc := range []struct{ dir, main, overlay string }{
|
|
{"local", "config.yml", ""}, {"service", "config.yml", "testing"},
|
|
{"prompt-edit", "config.yml", ""}, {"campaigns", "first.yml", ""}, {"campaigns", "second.yml", ""},
|
|
} {
|
|
t.Run(tc.dir+"/"+tc.main, func(t *testing.T) {
|
|
main := filepath.Join(root, tc.dir, tc.main)
|
|
if tc.dir == "service" {
|
|
dir := t.TempDir()
|
|
if err := os.Mkdir(filepath.Join(dir, "overlays"), 0700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Mkdir(filepath.Join(dir, "secrets"), 0700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, name := range []string{"config.yml", "prompts.yml", "overlays/testing.yml"} {
|
|
data, err := os.ReadFile(filepath.Join(root, tc.dir, name))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if name == "config.yml" {
|
|
data = append(data, []byte("\nconfig:\n secrets_dir: secrets\n secrets_overwrite: true\n")...)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(dir, name), data, 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if err := os.WriteFile(filepath.Join(dir, "secrets", "AUDITA_EXAMPLE_KEY"), []byte("synthetic-bootstrap-key"), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("AUDITA_EXAMPLE_KEY", "")
|
|
main = filepath.Join(dir, "config.yml")
|
|
}
|
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, appconfig.Options{Overlay: tc.overlay})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
loaded.Config.Application.Reporting.Enabled = false
|
|
var calls atomic.Int32
|
|
var mu sync.Mutex
|
|
var models, prompts []string
|
|
transport := controlledTransport(func(r *http.Request) (*http.Response, error) {
|
|
if tc.dir == "service" && r.Header.Get("Authorization") != "Bearer synthetic-bootstrap-key" {
|
|
t.Errorf("bootstrap credential was not supplied")
|
|
}
|
|
calls.Add(1)
|
|
var request struct {
|
|
Model string `json:"model"`
|
|
Messages []struct {
|
|
Content string `json:"content"`
|
|
} `json:"messages"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
|
return nil, err
|
|
}
|
|
var content strings.Builder
|
|
for _, message := range request.Messages {
|
|
content.WriteString(message.Content)
|
|
}
|
|
mu.Lock()
|
|
models = append(models, request.Model)
|
|
prompts = append(prompts, content.String())
|
|
mu.Unlock()
|
|
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"model":"fixture","choices":[{"message":{"role":"assistant","content":"{\"corrections\":[]}"}}]}`)), Request: r}, nil
|
|
})
|
|
engine, err := llm.NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
raw, err := os.ReadFile(filepath.Join(root, tc.dir, "transcript.json"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
source, err := schema.ParseSourceTranscriptJSON(raw)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
inputs := &processInputs{Configuration: loaded.Result, Runtime: engine, Source: source}
|
|
prepared, err := prepareProcess(context.Background(), processInput{Transcript: filepath.Join(root, tc.dir, "transcript.json")}, inputs, &bytes.Buffer{})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer prepared.Prepared.Output.Close()
|
|
if _, err := executePipeline(context.Background(), prepared, func(error) {}, nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if int(calls.Load()) != len(loaded.Config.Application.Pipeline.Stages) {
|
|
t.Fatalf("provider calls=%d", calls.Load())
|
|
}
|
|
if tc.dir == "service" && (len(models) != 1 || models[0] != "example-testing-model") {
|
|
t.Fatalf("overlay models=%v", models)
|
|
}
|
|
if tc.dir == "prompt-edit" {
|
|
prepared, err := engine.Engine.Prepare(context.Background(), pk.RunRequest{PromptID: auditaprompts.PromptIDModuleGrammarProposal, ProfileID: "local", Vars: auditaprompts.WithSharedVariables(map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"})})
|
|
if err != nil || prepared.OutputContract.RepairAttempts != 2 || prepared.StructuredOutput == nil || len(prepared.Messages) != 2 {
|
|
t.Fatalf("replacement contract: %+v, error=%v", prepared, err)
|
|
}
|
|
}
|
|
if tc.dir == "campaigns" && tc.main == "first.yml" {
|
|
if len(prompts) != 3 || !strings.Contains(prompts[0], `"name": "Lyra"`) || strings.Contains(prompts[0], `"name": "Shield"`) || !strings.Contains(prompts[1], `"name": "Shield"`) || strings.Contains(prompts[1], `"name": "Lyra"`) {
|
|
t.Fatalf("campaign glossary selections: %v", prompts)
|
|
}
|
|
}
|
|
if tc.dir == "campaigns" && tc.main == "second.yml" {
|
|
if len(prompts) != 2 || !strings.Contains(prompts[0], `"name": "Lyra"`) || strings.Contains(prompts[0], `"name": "Shield"`) {
|
|
t.Fatalf("second campaign glossary selection: %v", prompts)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestExamplePromptEditIsCapturedOnNextLoad(t *testing.T) {
|
|
_, file, _, ok := runtime.Caller(0)
|
|
if !ok {
|
|
t.Fatal("cannot locate examples")
|
|
}
|
|
source := filepath.Join(filepath.Dir(file), "..", "..", "examples", "prompt-edit")
|
|
dir := t.TempDir()
|
|
for _, name := range []string{"config.yml", "glossary.yml", "prompts.yml"} {
|
|
raw, err := os.ReadFile(filepath.Join(source, name))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(dir, name), raw, 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
inspect := func() string {
|
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
engine, err := llm.NewRuntime(context.Background(), loaded.Result, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
prompt, err := engine.Engine.InspectPrompt(context.Background(), "audita/modules.grammar.proposal")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return prompt.Messages[0].Content
|
|
}
|
|
before := inspect()
|
|
filePath := filepath.Join(dir, "prompts.yml")
|
|
raw, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filePath, []byte(strings.Replace(string(raw), "clearly supported grammatical errors", "clearly supported punctuation errors", 1)), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
after := inspect()
|
|
if !strings.Contains(before, "grammatical errors") || !strings.Contains(after, "punctuation errors") {
|
|
t.Fatalf("before=%q after=%q", before, after)
|
|
}
|
|
}
|
|
|
|
func TestRuntimeGlossaryExampleWorkflow(t *testing.T) {
|
|
_, file, _, ok := runtime.Caller(0)
|
|
if !ok {
|
|
t.Fatal("cannot locate examples")
|
|
}
|
|
source := filepath.Join(filepath.Dir(file), "..", "..", "examples", "service")
|
|
dir := t.TempDir()
|
|
for _, name := range []string{"config.yml", "prompts.yml", "transcript.json", "runtime-glossary.yml", "overlays/runtime-glossary.yml"} {
|
|
data, err := os.ReadFile(filepath.Join(source, name))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
dest := filepath.Join(dir, name)
|
|
if err := os.MkdirAll(filepath.Dir(dest), 0700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(dest, data, 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
t.Setenv("AUDITA_EXAMPLE_KEY", "synthetic")
|
|
var seen string
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var request struct {
|
|
Messages []struct {
|
|
Content string `json:"content"`
|
|
} `json:"messages"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
|
t.Error(err)
|
|
return
|
|
}
|
|
for _, message := range request.Messages {
|
|
seen += message.Content
|
|
}
|
|
io.WriteString(w, `{"model":"fixture","choices":[{"message":{"role":"assistant","content":"{\"corrections\":[]}"}}]}`)
|
|
}))
|
|
defer server.Close()
|
|
promptsPath := filepath.Join(dir, "prompts.yml")
|
|
promptsData, err := os.ReadFile(promptsPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
promptsData = bytes.ReplaceAll(promptsData, []byte("https://example.invalid/v1"), []byte(server.URL+"/v1"))
|
|
if err := os.WriteFile(promptsPath, promptsData, 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
app, err := buildApplication()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
common := []string{"--config", filepath.Join(dir, "config.yml"), "--overlay", "runtime-glossary", "--glossary-file", filepath.Join(dir, "runtime-glossary.yml")}
|
|
var out, stderr bytes.Buffer
|
|
args := append([]string{"config", "show", "--scope=app"}, common...)
|
|
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr})
|
|
if result.Status != 0 || !strings.Contains(out.String(), "Mira Chen") || !strings.Contains(out.String(), "North Observatory") || strings.Contains(out.String(), "Placeholder Speaker") {
|
|
t.Fatalf("inspection %d %s %s", result.Status, out.String(), stderr.String())
|
|
}
|
|
out.Reset()
|
|
stderr.Reset()
|
|
args = append([]string{"process"}, common...)
|
|
args = append(args, "--output", filepath.Join(dir, "output.json"), filepath.Join(dir, "transcript.json"))
|
|
result = app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr})
|
|
if result.Status != 0 || !strings.Contains(seen, "Mira Chen") || !strings.Contains(seen, "North Observatory") || !strings.Contains(seen, "speaker's preferred spelling") || !strings.Contains(seen, "Preserve established place names") {
|
|
t.Fatalf("processing %d seen=%s stderr=%s", result.Status, seen, stderr.String())
|
|
}
|
|
if _, err := os.Stat(filepath.Join(dir, "output.json")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|