Optimization Optimization — Go examples backed by real provider calls. go examples examples/optimization src/examples/go/optimization example Optimization

These Go examples are real runnable files. Edit the source file first; this page is rebuilt from the checked-in example and its metadata header.

Go AxGen Optimization

Runs an OpenAI prediction, applies an optimizer artifact, and scores novel rationale overlap.

Go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"time"

	ax "github.com/ax-llm/ax/packages/go"
)

func openAIClient() ax.AIClient {
	apiKey := os.Getenv("OPENAI_API_KEY")
	if apiKey == "" { apiKey = os.Getenv("OPENAI_APIKEY") }
	if apiKey == "" { panic("Set OPENAI_API_KEY or OPENAI_APIKEY to run this example.") }
	model := os.Getenv("AX_OPENAI_MODEL")
	if model == "" { model = "gpt-6-luna" }
	return ax.NewAI("openai", map[string]ax.Value{"api_key": apiKey, "model": model, "model_config": ax.Object("temperature", 0)})
}

func printJSON(value ax.Value) {
	data, err := json.MarshalIndent(value, "", "  ")
	if err != nil { panic(err) }
	fmt.Println(string(data))
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()
	client := openAIClient()
	program := ax.NewAx("emailText:string -> priority:class \"high, normal, low\", rationale:string", map[string]ax.Value{"id": "priority", "instruction": "Classify the email priority."})
	baseline, err := program.Forward(ctx, client, map[string]ax.Value{"emailText": "Production checkout is failing for enterprise customers."}, nil)
	if err != nil { panic(err) }
	artifact := ax.Object("componentMap", ax.Object("priority::instruction", "Classify operational risk. Use high for production-impacting urgency."), "metadata", ax.Object("source", "local"))
	program.ApplyOptimizedComponents(map[string]ax.Value{"priority::instruction": "Classify operational risk. Use high for production-impacting urgency."})
	after, err := program.Forward(ctx, client, map[string]ax.Value{"emailText": "Production checkout is failing for enterprise customers."}, nil)
	if err != nil { panic(err) }
	values := after.(map[string]ax.Value)
	score := ax.NovelF1Score("", fmt.Sprint(values["rationale"]), "Production checkout is failing for enterprise customers.", false)
	printJSON(ax.Object("baseline", baseline, "artifact", artifact, "after", after, "rationaleNovelF1", score))
}

Go GEPA Optimization

Scores real OpenAI predictions before and after GEPA instruction search.

Go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"time"

	ax "github.com/ax-llm/ax/packages/go"
)

type priorityEvaluator struct {
	program *ax.AxGen
	client  ax.AIClient
}

func (e priorityEvaluator) Evaluate(candidateMap map[string]ax.Value, options map[string]ax.Value) (ax.Value, error) {
	result := e.program.EvaluateOptimization(e.client, options["dataset"], candidateMap, options).(map[string]ax.Value)
	rows := result["rows"].(*ax.AxArray).Items
	sum := 0.0
	for _, item := range rows {
		row := item.(map[string]ax.Value)
		expected := row["input"].(map[string]ax.Value)["expectedOutput"].(map[string]ax.Value)
		output, _ := row["prediction"].(map[string]ax.Value)["output"].(map[string]ax.Value)
		score := 0.0
		if output["priority"] == expected["priority"] {
			score = 1
		}
		row["scores"], row["scalar"] = ax.Object("accuracy", score), score
		sum += score
	}
	result["avg"] = sum / float64(len(rows))
	return result, nil
}
func task(text, priority string) ax.Value {
	return ax.Object("input", ax.Object("emailText", text), "expectedOutput", ax.Object("priority", priority))
}

func openAIClient() ax.AIClient {
	apiKey := os.Getenv("OPENAI_API_KEY")
	if apiKey == "" {
		apiKey = os.Getenv("OPENAI_APIKEY")
	}
	if apiKey == "" {
		panic("Set OPENAI_API_KEY or OPENAI_APIKEY to run this example.")
	}
	model := os.Getenv("AX_OPENAI_MODEL")
	if model == "" {
		model = "gpt-6-luna"
	}
	return ax.NewAI("openai", map[string]ax.Value{"api_key": apiKey, "model": model})
}

func printJSON(value ax.Value) {
	data, err := json.MarshalIndent(value, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()
	client := openAIClient()
	program := ax.NewAx("emailText:string -> priority:class \"high, normal, low\", rationale:string", map[string]ax.Value{"id": "priority", "instruction": "Classify the email priority."})
	baseline, err := program.Forward(ctx, client, map[string]ax.Value{"emailText": "Production checkout is failing for enterprise customers."}, nil)
	if err != nil {
		panic(err)
	}
	request := map[string]ax.Value{
		"programKind": "axgen", "components": program.GetOptimizableComponents(),
		"dataset": ax.Object("train", ax.Array(task("URGENT: checkout is down", "high"), task("Weekly product newsletter", "low")),
			"validation", ax.Array(task("Production payments are failing", "high"), task("Optional community meetup invite", "low"))),
		"options": ax.Object("numTrials", 1, "minibatchSize", 2, "maxMetricCalls", 12, "bootstrap", false, "seed", 7),
	}
	artifact, err := ax.NewGEPA(client, map[string]ax.Value{"seed": 7}).Optimize(request, priorityEvaluator{program, client})
	if err != nil {
		panic(err)
	}
	result := artifact.(map[string]ax.Value)
	original := result["baselineScore"].(float64)
	best := result["metadata"].(map[string]ax.Value)["bestScore"].(float64)
	printJSON(ax.Object("baselinePrediction", baseline, "baselineScore", original, "baselineScores", result["baselineScores"], "optimizedScore", best, "delta", best-original))
}

Go Optimization Artifact Reuse

Saves and reapplies an optimizer artifact after a real OpenAI baseline.

Go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"time"

	ax "github.com/ax-llm/ax/packages/go"
)

func openAIClient() ax.AIClient {
	apiKey := os.Getenv("OPENAI_API_KEY")
	if apiKey == "" { apiKey = os.Getenv("OPENAI_APIKEY") }
	if apiKey == "" { panic("Set OPENAI_API_KEY or OPENAI_APIKEY to run this example.") }
	model := os.Getenv("AX_OPENAI_MODEL")
	if model == "" { model = "gpt-5.4-mini" }
	return ax.NewAI("openai", map[string]ax.Value{"api_key": apiKey, "model": model, "model_config": ax.Object("temperature", 0)})
}

func printJSON(value ax.Value) {
	data, err := json.MarshalIndent(value, "", "  ")
	if err != nil { panic(err) }
	fmt.Println(string(data))
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()
	client := openAIClient()
	program := ax.NewAx("emailText:string -> priority:class \"high, normal, low\", rationale:string", map[string]ax.Value{"id": "priority", "instruction": "Classify the email priority."})
	baseline, err := program.Forward(ctx, client, map[string]ax.Value{"emailText": "Production checkout is failing for enterprise customers."}, nil)
	if err != nil { panic(err) }
	artifact := ax.Object("componentMap", ax.Object("priority::instruction", "Classify operational risk. Use high for production-impacting urgency."), "metadata", ax.Object("source", "local"))
	program.ApplyOptimizedComponents(map[string]ax.Value{"priority::instruction": "Classify operational risk. Use high for production-impacting urgency."})
	after, err := program.Forward(ctx, client, map[string]ax.Value{"emailText": "Production checkout is failing for enterprise customers."}, nil)
	if err != nil { panic(err) }
	printJSON(ax.Object("baseline", baseline, "artifact", artifact, "after", after))
}

Go Agent Playbook — Learn And Verify

Attach a persistent playbook, add validated hidden citations and stage guidance, then mine a task set into playbook rules with a verification gate.

Go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"time"

	ax "github.com/ax-llm/ax/packages/go"
	axgoja "github.com/ax-llm/ax/packages/go/runtime/goja"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()
	apiKey := os.Getenv("OPENAI_API_KEY")
	if apiKey == "" {
		apiKey = os.Getenv("OPENAI_APIKEY")
	}
	if apiKey == "" {
		panic("Set OPENAI_API_KEY or OPENAI_APIKEY to run this example.")
	}
	model := os.Getenv("AX_OPENAI_MODEL")
	if model == "" {
		model = "gpt-6-luna"
	}
	client := ax.NewAI("openai", map[string]ax.Value{"api_key": apiKey, "model": model})

	bullet := ax.Object(
		"id", "failures-to-avoid-00001",
		"section", "failures_to_avoid",
		"content", "Check the available evidence before answering.",
		"helpfulCount", 0,
		"harmfulCount", 0,
		"createdAt", "2026-07-15T00:00:00.000Z",
		"updatedAt", "2026-07-15T00:00:00.000Z",
	)
	seed := ax.Object(
		"playbook", ax.Object(
			"version", 1,
			"sections", ax.Object("failures_to_avoid", ax.Array(bullet)),
			"updatedAt", "2026-07-15T00:00:00.000Z",
		),
		"artifact", ax.Object("feedback", ax.Array(), "history", ax.Array()),
	)

	var observedCitations []ax.Value
	var playbookUpdates []ax.Value
	assistant := ax.NewAgent(
		"question:string -> answer:string",
		ax.Object(
			// The playbook learns with the agent's own client.
			"ai", client,
			"contextFields", ax.Array(),
			"runtime", ax.Object("language", "JavaScript"),
			"playbook", ax.Object(
				"playbook", seed, "seed", 7,
				"onUpdate", func(value ax.Value) { playbookUpdates = append(playbookUpdates, value) },
			),
			"citations", ax.Object(
				"surface", "hidden",
				"onCitations", func(value []ax.Value) { observedCitations = value },
			),
		),
	)
	assistant.
		SetInstruction("Answer from evidence and state uncertainty plainly.").
		AddActorInstruction("Before finishing, verify the answer against the collected evidence.")

	runtime := axgoja.NewRuntime()
	answer, err := assistant.Forward(
		ctx,
		client,
		map[string]ax.Value{"question": "What should a support agent verify before answering?"},
		map[string]ax.Value{"runtime": runtime, "max_actor_steps": 8},
	)
	if err != nil {
		panic(err)
	}

	dataset := ax.Object(
		"train", ax.Array(ax.Object(
			"input", ax.Object("question", "Give a concise evidence-first answer."),
			"score", 0,
		)),
	)
	evolution, err := assistant.GetPlaybook().EvolveAgent(
		ctx,
		dataset,
		map[string]ax.Value{"verify": true, "maxProposals": 1, "runtime": runtime},
	)
	if err != nil {
		panic(err)
	}

	// Each train task replays on the runtime. A replay that fails scores 0 and
	// would be mined as the weakness, so stop instead.
	replays := []ax.Value{}
	records, _ := evolution.(map[string]ax.Value)["records"].([]ax.Value)
	for _, raw := range records {
		record, _ := raw.(map[string]ax.Value)
		prediction, _ := record["prediction"].(map[string]ax.Value)
		if record["error"] != nil || prediction["completionType"] == "error" {
			panic(fmt.Sprintf("evolve replay failed: %v %v", record["error"], prediction["error"]))
		}
		replays = append(replays, prediction["completionType"])
	}

	encoded, _ := json.MarshalIndent(answer, "", "  ")
	fmt.Println(string(encoded))
	fmt.Println("replays:", replays)
	fmt.Println("citations:", observedCitations)
	fmt.Println("run-end updates:", len(playbookUpdates))
	fmt.Println("outcomes:", evolution.(map[string]ax.Value)["outcomes"])
	fmt.Println(assistant.GetPlaybook().Render())
}
Docs