Advanced Start
Advanced Start is built from runnable Go examples. The story below follows the same source files that appear under Examples, so code changes start in src/examples/go/.
Go Typed Generation
Start with a typed contract: the model receives named inputs and Ax parses named outputs.
Runs a small typed generation program against OpenAI.
- Level:
beginner - Run:
npm run example -- go src/examples/go/generation/basic_generation.go - Source: src/examples/go/generation/basic_generation.go
- More in this group: Generation examples
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("question:string -> answer:string", nil)
output, err := program.Forward(ctx, client, map[string]ax.Value{"question": "In one sentence, explain Ax as a language-agnostic LLM programming library."}, nil)
if err != nil { panic(err) }
printJSON(output)
}Go Grounded Support Agent
Move to an agent when the model needs a runtime loop and a final typed answer.
Answers a support question grounded in a handbook that is kept out of the model prompt via contextFields.
- Level:
beginner - Run:
npm run example -- go src/examples/go/short-agents/basic_agent.go - Source: src/examples/go/short-agents/basic_agent.go
- More in this group: Agents examples
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
"time"
ax "github.com/ax-llm/ax/packages/go"
axgoja "github.com/ax-llm/ax/packages/go/runtime/goja"
)
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))
}
// The handbook can be arbitrarily large. Listing it in `contextFields` keeps it
// in the agent's runtime so it never inflates the model prompt -- the agent reads
// it through code, not through tokens. That is the whole point of an Ax agent
// over a plain gen() call: the source material stays out of the context window.
var handbook = strings.TrimSpace(`
# Acme Cloud -- Support Handbook
## Billing
- Invoices are issued on the 1st of each month and are due net-15.
- Plan downgrades take effect at the END of the current billing cycle, not immediately.
- Refunds are issued to the original payment method within 5 business days.
## Access
- Seats can be added by any workspace Owner under Settings -> Members.
- SSO (SAML) is available on Enterprise; SCIM provisioning is Owner-only.
## Incidents
- Status and uptime are published at status.acme.example.
- Sev-1 incidents page the on-call within 5 minutes; updates post every 30 minutes.
## Data
- Exports are available in CSV and JSON from Settings -> Data.
- Deleted workspaces are recoverable for 30 days, then permanently purged.
`)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
client := openAIClient()
// Keep the handbook in the runtime, out of the prompt.
assistant := ax.NewAgent(
`question:string, handbook:string -> answer:string, citations:string[] "Handbook sections the answer relies on"`,
map[string]ax.Value{"contextFields": ax.Array("handbook"), "runtime": ax.Object("language", "JavaScript")},
)
output, err := assistant.Forward(
ctx,
client,
map[string]ax.Value{
"question": "A customer downgraded their plan today. When does it take effect, and can they get a refund for the current cycle?",
"handbook": handbook,
},
map[string]ax.Value{"runtime": axgoja.NewRuntime(), "max_actor_steps": 12},
)
if err != nil {
panic(err)
}
printJSON(output)
}Go Sequential Flow
Use a flow when the application should own the order of multi-step work.
Runs a two-step Ax flow against OpenAI.
- Level:
beginner - Run:
npm run example -- go src/examples/go/flows/sequential_flow.go - Source: src/examples/go/flows/sequential_flow.go
- More in this group: Flows examples
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()
step := ax.NewAx("documentText:string -> summaryText:string", nil)
program := ax.NewFlow(map[string]ax.Value{"id": "examples.sequentialFlow"}).
Execute("step", step, nil).
Returns(map[string]ax.Value{"step": "step"})
output, err := program.Forward(ctx, client, map[string]ax.Value{"documentText": "Ax gives developers signatures, provider clients, agents, flows, tracing, and optimization."}, nil)
if err != nil { panic(err) }
printJSON(output)
}Go Text To Speech
Add audio when the same provider-backed contract should accept or produce speech.
Generates speech audio through OpenAI.
- Level:
beginner - Run:
npm run example -- go src/examples/go/audio/speech_audio.go - Source: src/examples/go/audio/speech_audio.go
- More in this group: Audio examples
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()
speech, err := client.Speak(ctx, map[string]ax.Value{"text": "Ax turns LLM prompts into typed programs.", "voice": "alloy", "format": "mp3"}, nil)
if err != nil { panic(err) }
sp := speech.(map[string]ax.Value)
audio, _ := sp["audio"].(string)
printJSON(ax.Object("format", sp["format"], "audioBytesBase64", len(audio)))
}Go Adaptive Provider Balancing
Start with a typed contract: the model receives named inputs and Ax parses named outputs.
Routes equivalent chat traffic using shared reliability, latency, and cost statistics.
- Level:
advanced - Run:
npm run example -- go src/examples/go/generation/adaptive_balancer.go - Source: src/examples/go/generation/adaptive_balancer.go
- More in this group: Generation examples
package main
import (
"context"
"fmt"
"os"
ax "github.com/ax-llm/ax/packages/go"
)
func main() {
key := os.Getenv("OPENAI_API_KEY")
if key == "" {
key = os.Getenv("OPENAI_APIKEY")
}
if key == "" {
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"
}
services := []ax.AxAIService{
ax.NewOpenAICompatibleClient(map[string]ax.Value{"api_key": key, "model": model}),
ax.NewOpenAICompatibleClient(map[string]ax.Value{"api_key": key, "model": model}),
}
store := ax.NewAxInMemoryBalancerStatsStore()
routeKeys := []string{"openai-primary", "openai-backup"}
events := []string{}
strategy := &ax.AxBalancerAdaptiveStrategy{
DeadlineMs: 6_000, BadOutcomeCost: 0.02,
ExpectedTokens: map[string]ax.Value{"promptTokens": 1_200.0, "completionTokens": 300.0},
Namespace: "support-summary-v1", StatsStore: store,
RouteKey: func(_ ax.AxAIService, index int) string { return routeKeys[index] },
Slice: func(context map[string]ax.Value) string {
if options, ok := context["options"].(map[string]ax.Value); ok && options["stream"] == true {
return "streaming"
}
return "interactive"
},
OnRoutingEvent: func(event ax.AxBalancerRoutingEvent) { events = append(events, fmt.Sprint(event["type"])) },
}
balancer, err := ax.NewAxBalancerWithOptions(services, ax.AxBalancerOptions{Strategy: strategy})
if err != nil {
panic(err)
}
response, err := balancer.Chat(context.Background(), map[string]ax.Value{"model": model, "chat_prompt": ax.Array(ax.Object("role", "user", "content", "Summarize why shared routing state matters."))}, nil)
if err != nil {
panic(err)
}
fmt.Println(response)
fmt.Println(events)
}Go AxGen Optimization
Close the loop by measuring examples and applying optimizer artifacts to the program.
Runs a baseline OpenAI prediction and applies an optimizer artifact.
- Level:
beginner - Run:
npm run example -- go src/examples/go/optimization/axgen_optimization.go - Source: src/examples/go/optimization/axgen_optimization.go
- More in this group: Optimization examples
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 Native MCP Tools
Use this runnable example as the next step in the Ax path.
Attaches a live MCP client directly to AxGen without a lossy function adapter.
- Level:
beginner - Run:
npm run example -- go src/examples/go/mcp/native_mcp_tools.go - Source: src/examples/go/mcp/native_mcp_tools.go
- More in this group: MCP examples
package main
import (
"context"
"fmt"
"os"
ax "github.com/ax-llm/ax/packages/go"
)
func main() {
key, endpoint := os.Getenv("OPENAI_API_KEY"), os.Getenv("MCP_URL")
if key == "" {
key = os.Getenv("OPENAI_APIKEY")
}
if key == "" || endpoint == "" {
panic("Set OPENAI_API_KEY and MCP_URL.")
}
transport, err := ax.NewAxMCPStreamableHTTPTransport(endpoint, nil)
if err != nil {
panic(err)
}
mcp := ax.NewAxMCPClient(transport, map[string]ax.Value{"namespace": "inventory"})
defer func() { _ = mcp.Close() }()
catalog, err := mcp.InspectCatalog(false)
if err != nil {
panic(err)
}
fmt.Printf("MCP catalog: %d tools, %d resources, %d templates\n", len(catalog.Tools), len(catalog.Resources), len(catalog.ResourceTemplates))
program := ax.NewAx("request:string -> answer:string", map[string]ax.Value{"mcp": mcp})
llm := ax.NewOpenAICompatibleClient(map[string]ax.Value{"api_key": key, "model": "gpt-5.4-mini"})
output, err := program.Forward(context.Background(), llm, map[string]ax.Value{"request": "Reindex inventory."}, nil)
if err != nil {
panic(err)
}
fmt.Println(output)
}Go MCP Resource Wake
Use this runnable example as the next step in the Ax path.
Subscribes to an MCP resource over real Streamable HTTP and lets AxEventRuntime wake an authenticated Agent automatically.
- Level:
intermediate - Run:
npm run example -- go src/examples/go/mcp/resource_wake_agent.go - Source: src/examples/go/mcp/resource_wake_agent.go
- More in this group: MCP examples
package main
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"time"
ax "github.com/ax-llm/ax/packages/go"
axgoja "github.com/ax-llm/ax/packages/go/runtime/goja"
)
func main() {
key := os.Getenv("OPENAI_API_KEY")
if key == "" {
key = os.Getenv("OPENAI_APIKEY")
}
if key == "" {
panic("Set OPENAI_API_KEY.")
}
endpoint := os.Getenv("AX_MCP_ENDPOINT")
if endpoint == "" {
panic("Set AX_MCP_ENDPOINT to a Streamable HTTP MCP server.")
}
local := strings.HasPrefix(endpoint, "http://127.0.0.1")
transport, err := ax.NewAxMCPStreamableHTTPTransport(endpoint, map[string]ax.Value{"ssrfProtection": map[string]ax.Value{"requireHttps": !local, "allowLocalhost": local, "allowPrivateNetworks": local}})
if err != nil {
panic(err)
}
client := ax.NewAxMCPClient(transport, map[string]ax.Value{"namespace": "inventory"})
source := ax.NewAxMCPEventSourceWithPolicy(client, "inventory", "tenant:demo", "authenticated", ax.AxMCPSubscribeAll())
agent := ax.NewAgent("uri:string -> summary:string", map[string]ax.Value{"runtime": ax.Object("language", "JavaScript")})
llm := ax.NewOpenAICompatibleClient(map[string]ax.Value{"api_key": key, "model": "gpt-5.4-mini"})
done := make(chan struct{}, 1)
runtime, err := ax.NewAxEventRuntime([]ax.AxEventRoute{{ID: "resource-wake", Action: "wake", TargetID: "inventory-agent", RequireAuthenticated: true, Match: map[string]ax.Value{"types": ax.Array("mcp.resource.updated")}}}, nil)
if err != nil {
panic(err)
}
runtime.RegisterTarget(ax.AxEventTarget{ID: "inventory-agent", RetrySafety: "idempotent",
MapInput: func(event ax.AxEventEnvelope, _ *ax.AxEventContinuation) (ax.Value, error) {
return map[string]ax.Value{"uri": event.Data.(map[string]ax.Value)["uri"]}, nil
},
Invoke: func(input ax.Value, _ map[string]ax.Value) (ax.Value, error) {
out, err := agent.Forward(context.Background(), llm, input.(map[string]ax.Value), map[string]ax.Value{"runtime": axgoja.NewRuntime()})
if err == nil {
fmt.Println(out)
select {
case done <- struct{}{}:
default:
}
}
return out, err
},
})
runtime.AddSource(source)
if err := runtime.Start(); err != nil {
panic(err)
}
if os.Getenv("AX_MCP_DEMO_AUTO") == "1" {
response, err := http.Post(strings.TrimSuffix(endpoint, "/mcp")+"/control/resource", "application/json", nil)
if err != nil {
panic(err)
}
response.Body.Close()
}
select {
case <-done:
case <-time.After(60 * time.Second):
panic("Timed out waiting for an MCP resource notification")
}
if err := runtime.Close(); err != nil {
panic(err)
}
if err := client.Close(); err != nil {
panic(err)
}
}Go MCP Task Continuation
Use this runnable example as the next step in the Ax path.
Creates an owned continuation and resumes an AxFlow from real MCP progress and terminal task notifications.
- Level:
advanced - Run:
npm run example -- go src/examples/go/mcp/task_resume_flow.go - Source: src/examples/go/mcp/task_resume_flow.go
- More in this group: MCP examples
package main
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"sync/atomic"
"time"
ax "github.com/ax-llm/ax/packages/go"
)
func main() {
key := os.Getenv("OPENAI_API_KEY")
if key == "" {
key = os.Getenv("OPENAI_APIKEY")
}
if key == "" {
panic("Set OPENAI_API_KEY.")
}
endpoint := os.Getenv("AX_MCP_ENDPOINT")
if endpoint == "" {
panic("Set AX_MCP_ENDPOINT to a Streamable HTTP MCP server.")
}
local := strings.HasPrefix(endpoint, "http://127.0.0.1")
transport, err := ax.NewAxMCPStreamableHTTPTransport(endpoint, map[string]ax.Value{"ssrfProtection": map[string]ax.Value{"requireHttps": !local, "allowLocalhost": local, "allowPrivateNetworks": local}})
if err != nil {
panic(err)
}
client := ax.NewAxMCPClient(transport, map[string]ax.Value{"namespace": "inventory"})
mcp := ax.NewAxMCPEventSource(client, "inventory", "tenant:demo", "authenticated", nil)
started := &ax.AxPushEventSource{ID: "task-started", IdentityScope: "tenant:demo", Trust: "authenticated"}
program := ax.NewFlow(map[string]ax.Value{"id": "reindex-flow"}).Execute("status", ax.NewAx("taskId:string -> status:string", nil), nil).Returns(map[string]ax.Value{"status": "status"})
llm := ax.NewOpenAICompatibleClient(map[string]ax.Value{"api_key": key, "model": "gpt-5.4-mini"})
done := make(chan struct{}, 1)
var calls atomic.Int32
target := ax.AxEventTarget{ID: "reindex-flow", RetrySafety: "idempotent", WaitFor: []map[string]ax.Value{{"kind": "mcp.task", "value": "taskKey", "metadata": map[string]ax.Value{}}},
MapInput: func(event ax.AxEventEnvelope, continuation *ax.AxEventContinuation) (ax.Value, error) {
if continuation != nil {
return map[string]ax.Value{"taskId": continuation.Metadata["taskId"]}, nil
}
return map[string]ax.Value{"taskId": event.Data.(map[string]ax.Value)["taskId"]}, nil
},
Invoke: func(input ax.Value, _ map[string]ax.Value) (ax.Value, error) {
out, err := program.Forward(context.Background(), llm, input.(map[string]ax.Value), nil)
if err == nil {
fmt.Println(out)
if calls.Add(1) >= 2 {
select {
case done <- struct{}{}:
default:
}
}
}
return out, err
},
}
runtime, err := ax.NewAxEventRuntime([]ax.AxEventRoute{
{ID: "task-start", Action: "wake", TargetID: "reindex-flow", Match: map[string]ax.Value{"types": ax.Array("app.task.started")}},
{ID: "task-progress", Action: "observe", Match: map[string]ax.Value{"types": ax.Array("mcp.progress")}},
{ID: "task-resume", Action: "resume", TargetID: "reindex-flow", Match: map[string]ax.Value{"types": ax.Array("mcp.task.status")}},
}, nil)
if err != nil {
panic(err)
}
runtime.RegisterTarget(target)
runtime.AddSource(started)
runtime.AddSource(mcp)
if err := runtime.Start(); err != nil {
panic(err)
}
taskResult, err := client.CallTool("start_reindex", map[string]ax.Value{"scope": "all"})
if err != nil {
panic(err)
}
taskID := taskResult["task"].(map[string]ax.Value)["taskId"].(string)
target.WaitFor[0]["metadata"] = map[string]ax.Value{"taskId": taskID}
if err := started.Publish(ax.AxEventEnvelope{SpecVersion: "1.0", ID: "task-start", Source: "app://tasks", Type: "app.task.started", Data: map[string]ax.Value{"taskId": taskID, "taskKey": "inventory:" + taskID}}); err != nil {
panic(err)
}
fmt.Println("Waiting for terminal MCP task notification", taskID)
if os.Getenv("AX_MCP_DEMO_AUTO") == "1" {
response, err := http.Post(strings.TrimSuffix(endpoint, "/mcp")+"/control/task/complete", "application/json", nil)
if err != nil {
panic(err)
}
response.Body.Close()
}
select {
case <-done:
case <-time.After(60 * time.Second):
panic("Timed out waiting for the MCP task continuation")
}
if err := runtime.Close(); err != nil {
panic(err)
}
if err := client.Close(); err != nil {
panic(err)
}
}