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 a baseline OpenAI prediction and applies an optimizer artifact.
- Provider:
openai - Env:
OPENAI_API_KEY,OPENAI_APIKEY - Level:
beginner - Run:
npm run example -- go src/examples/go/optimization/axgen_optimization.go - Source: src/examples/go/optimization/axgen_optimization.go
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
ax "github.com/ax-llm/ax/packages/go"
)
func openAIClient() *ax.OpenAICompatibleClient {
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.NewOpenAICompatibleClient(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 GEPA Optimization
Pairs a real OpenAI baseline with a local GEPA optimization pass.
- Provider:
openai - Env:
OPENAI_API_KEY,OPENAI_APIKEY - Level:
intermediate - Run:
npm run example -- go src/examples/go/optimization/gepa_optimization.go - Source: src/examples/go/optimization/gepa_optimization.go
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
ax "github.com/ax-llm/ax/packages/go"
)
type localEvaluator struct{}
func (localEvaluator) Evaluate(candidateMap map[string]ax.Value, options map[string]ax.Value) (ax.Value, error) { return ax.Object("rows", ax.Array(ax.Object("prediction", ax.Object("answer", "Ax composes typed LLM programs."), "scores", ax.Object("quality", 0.9), "scalar", 0.9)), "avg", 0.9, "count", 1), nil }
func openAIClient() *ax.OpenAICompatibleClient {
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.NewOpenAICompatibleClient(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) }
request := map[string]ax.Value{"programKind": "axgen", "components": ax.Array(ax.Object("id", "priority::instruction", "owner", "priority", "kind", "instruction", "current", "Classify priority clearly.")), "dataset": ax.Object("train", ax.Array(ax.Object("emailText", "URGENT: checkout is down"))), "options": ax.Object("numTrials", 0, "maxMetricCalls", 4, "seed", 7)}
artifact, err := ax.NewGEPA(nil, map[string]ax.Value{"seed": 7}).Optimize(request, localEvaluator{})
if err != nil { panic(err) }
printJSON(ax.Object("baseline", baseline, "artifact", artifact))
}Go Optimization Artifact Reuse
Saves and reapplies an optimizer artifact after a real OpenAI baseline.
- Provider:
openai - Env:
OPENAI_API_KEY,OPENAI_APIKEY - Level:
advanced - Run:
npm run example -- go src/examples/go/optimization/artifact_optimization.go - Source: src/examples/go/optimization/artifact_optimization.go
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
ax "github.com/ax-llm/ax/packages/go"
)
func openAIClient() *ax.OpenAICompatibleClient {
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.NewOpenAICompatibleClient(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.
- Provider:
openai - Env:
OPENAI_API_KEY,OPENAI_APIKEY - Level:
advanced - Run:
npm run example -- go src/examples/go/optimization/agent_playbook_evolve.go - Source: src/examples/go/optimization/agent_playbook_evolve.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-5.4-mini"
}
client := ax.NewOpenAICompatibleClient(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(
"contextFields", ax.Array(),
"runtime", ax.Object("language", "JavaScript"),
"playbook", ax.Object(
"seed", seed,
"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)
}
encoded, _ := json.MarshalIndent(answer, "", " ")
fmt.Println(string(encoded))
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())
}