Reproducible CPU Lab · GO

A deterministic Go agent loop

Companion Writing
Inside a Go Agent Loop: Tool Calls, State Transitions, and Failure Recovery →

An agent is a state machine around unreliable boundaries. Build a deterministic loop that makes tool identity, errors, cancellation, and termination inspectable.

Run from the repository root (the directory containing labs). After downloading the archive, extract it and run from the extracted root.

sh
cd labs/go
go test -race ./agent

Go requires 1.24 or newer. Python requires 3.11 or newer. The two LLM labs additionally require CPU-capable PyTorch in labs/.venv; see the collection instructions.

Tests use deterministic substitutes or synthetic tensors. No paid API, cloud service, model-weight download, GPU, or external project checkout is required. A failed test is a correctness issue to investigate; raw timing changes alone do not fail the tests.

Read the source and tests together. The article's code excerpts are extracted from marked regions in these files during the website build.

Source & Verification Files

Primary implementation expanded · Click any file header to toggle
Implementationagent.go
119 lines
/labs/go/agent/agent.goRaw file ↓
go
// Package agent is an original reduced teaching loop informed by pi-go/pi-mono.
// It intentionally does not implement their complete event or wire protocol.
package agent

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
)

type Message struct{ Role, Text, CallID string }
type Call struct {
	ID, Name  string
	Arguments json.RawMessage
}
type Response struct {
	Text string
	Call *Call
}
type Model func(context.Context, []Message) (Response, error)
type Tool func(context.Context, json.RawMessage) (string, error)
type Event struct{ Kind, CallID string }
type Result struct {
	Messages []Message
	Events   []Event
}

var ErrStepLimit = errors.New("model step limit reached")

// region:loop
func Run(ctx context.Context, model Model, tools map[string]Tool, prompt string, maxSteps int) (result Result, err error) {
	result.Messages = []Message{{Role: "user", Text: prompt}}
	result.Events = append(result.Events, Event{Kind: "start"})
	defer func() {
		kind := "complete"
		if err != nil {
			kind = "failed"
		}
		result.Events = append(result.Events, Event{Kind: kind})
	}()
	if maxSteps < 1 || model == nil {
		return result, errors.New("positive step limit and model required")
	}
	seen := make(map[string]bool)
	for range maxSteps {
		if err = ctx.Err(); err != nil {
			return
		}
		var response Response
		response, err = model(ctx, append([]Message(nil), result.Messages...))
		if err != nil {
			return
		}
		if err = ctx.Err(); err != nil {
			return
		}
		if response.Call == nil {
			result.Messages = append(result.Messages, Message{Role: "assistant", Text: response.Text})
			return
		}
		call := response.Call
		if call.ID == "" || call.Name == "" || seen[call.ID] {
			return result, errors.New("empty or duplicate tool call identity")
		}
		seen[call.ID] = true
		result.Messages = append(result.Messages, Message{Role: "assistant", Text: call.Name, CallID: call.ID})
		result.Events = append(result.Events, Event{Kind: "tool_start", CallID: call.ID})
		tool, ok := tools[call.Name]
		var output string
		var toolErr error
		if !ok {
			toolErr = fmt.Errorf("unknown tool: %s", call.Name)
		} else {
			output, toolErr = tool(ctx, call.Arguments)
		}
		if err = ctx.Err(); err != nil {
			return
		}
		if toolErr != nil {
			output = "Tool error: " + toolErr.Error()
		}
		result.Messages = append(result.Messages, Message{Role: "tool", Text: output, CallID: call.ID})
		result.Events = append(result.Events, Event{Kind: "tool_end", CallID: call.ID})
	}
	return result, ErrStepLimit
}

// endregion:loop

// Add is deliberately pure: no filesystem, network, or shell side effects.
func Add(ctx context.Context, raw json.RawMessage) (string, error) {
	if err := ctx.Err(); err != nil {
		return "", err
	}
	var args struct {
		A *int `json:"a"`
		B *int `json:"b"`
	}
	decoder := json.NewDecoder(bytes.NewReader(raw))
	decoder.DisallowUnknownFields()
	if err := decoder.Decode(&args); err != nil {
		return "", err
	}
	if args.A == nil || args.B == nil {
		return "", errors.New("a and b are required integers")
	}
	var extra any
	if decoder.Decode(&extra) != io.EOF {
		return "", errors.New("expected one JSON object")
	}
	// Bound the teaching tool's arithmetic domain to avoid platform overflow.
	if *args.A < -1000000 || *args.A > 1000000 || *args.B < -1000000 || *args.B > 1000000 {
		return "", errors.New("arguments outside teaching range")
	}
	return fmt.Sprint(*args.A + *args.B), nil
}
Verification Suiteagent_test.go
95 lines
/labs/go/agent/agent_test.goRaw file ↓
go
package agent

import (
	"context"
	"encoding/json"
	"errors"
	"testing"
)

func scripted(responses ...Response) Model {
	index := 0
	return func(context.Context, []Message) (Response, error) {
		if index >= len(responses) {
			return Response{}, errors.New("script exhausted")
		}
		r := responses[index]
		index++
		return r, nil
	}
}
func TestToolRoundTrip(t *testing.T) {
	model := scripted(Response{Call: &Call{ID: "1", Name: "add", Arguments: json.RawMessage(`{"a":2,"b":3}`)}}, Response{Text: "5"})
	result, err := Run(context.Background(), model, map[string]Tool{"add": Add}, "add", 3)
	if err != nil {
		t.Fatal(err)
	}
	if len(result.Messages) != 4 || result.Messages[2].Text != "5" || result.Messages[2].CallID != "1" {
		t.Fatalf("wrong transcript %#v", result)
	}
	if len(result.Events) != 4 || result.Events[3].Kind != "complete" {
		t.Fatal(result.Events)
	}
}
func TestInvalidArgumentsBecomeRecoverableResults(t *testing.T) {
	for _, raw := range []string{`{bad`, `{"a":1}`, `{"a":1,"b":2,"extra":3}`, `{"a":1,"b":2} {}`, `{"a":null,"b":2}`} {
		t.Run(raw, func(t *testing.T) {
			model := scripted(Response{Call: &Call{ID: "1", Name: "add", Arguments: json.RawMessage(raw)}}, Response{Text: "corrected explanation"})
			result, err := Run(context.Background(), model, map[string]Tool{"add": Add}, "test", 2)
			if err != nil {
				t.Fatal(err)
			}
			if result.Messages[2].Text[:10] != "Tool error" {
				t.Fatal(result)
			}
		})
	}
}
func TestFailureBoundaries(t *testing.T) {
	t.Run("unknown tool", func(t *testing.T) {
		r, e := Run(context.Background(), scripted(Response{Call: &Call{ID: "1", Name: "missing"}}, Response{Text: "done"}), nil, "", 2)
		if e != nil || r.Messages[2].Role != "tool" {
			t.Fatal(r, e)
		}
	})
	t.Run("model failure", func(t *testing.T) {
		r, e := Run(context.Background(), scripted(), nil, "", 2)
		if e == nil || len(r.Messages) != 1 || r.Events[len(r.Events)-1].Kind != "failed" {
			t.Fatal(r, e)
		}
	})
	t.Run("limit", func(t *testing.T) {
		_, e := Run(context.Background(), scripted(Response{Call: &Call{ID: "1", Name: "missing"}}), nil, "", 1)
		if !errors.Is(e, ErrStepLimit) {
			t.Fatal(e)
		}
	})
	t.Run("duplicate", func(t *testing.T) {
		call := Response{Call: &Call{ID: "1", Name: "missing"}}
		_, e := Run(context.Background(), scripted(call, call), nil, "", 3)
		if e == nil {
			t.Fatal("duplicate accepted")
		}
	})
	t.Run("cancel after model", func(t *testing.T) {
		ctx, cancel := context.WithCancel(context.Background())
		called := false
		model := func(context.Context, []Message) (Response, error) {
			cancel()
			return Response{Call: &Call{ID: "1", Name: "tool"}}, nil
		}
		_, e := Run(ctx, model, map[string]Tool{"tool": func(context.Context, json.RawMessage) (string, error) { called = true; return "", nil }}, "", 3)
		if !errors.Is(e, context.Canceled) || called {
			t.Fatal(e, called)
		}
	})
	t.Run("cancel inside tool", func(t *testing.T) {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
		tool := func(context.Context, json.RawMessage) (string, error) { cancel(); return "late", nil }
		r, e := Run(ctx, scripted(Response{Call: &Call{ID: "1", Name: "tool"}}), map[string]Tool{"tool": tool}, "", 2)
		if !errors.Is(e, context.Canceled) || len(r.Messages) != 2 {
			t.Fatal(r, e)
		}
	})
}