Quickstart: run an agent in five minutes
This quickstart builds a Go program that answers “Where is order 1234?” with an agent that calls one tool, first with Generate and then streamed event by event. It runs offline on a scripted model, so you need Go and nothing else. One if switches it to a real provider: with ANTHROPIC_API_KEY set, the same program asks Claude instead of a script.
What you’ll build
Section titled “What you’ll build”One main.go, under 100 lines, that prints the agent’s answer twice, the second time as the events arrive:


You will:
- define a tool from a Go function, with its schema taken from a struct
- build an agent and run it to the end with
Generate - stream the same run with
Stream(...).Events() - switch the scripted model to a real provider, Anthropic
The finished code: docs-site/examples/quickstart.
Before you start
Section titled “Before you start”- Go 1.26 or newer (
go version) - No API key: the program uses a scripted model unless
ANTHROPIC_API_KEYis set
1. Create the module
Section titled “1. Create the module”Make a directory, start a module and add weft:
mkdir quickstart && cd quickstartgo mod init example.com/quickstartgo get github.com/weftgo/weft@v0.20.22. Write a tool
Section titled “2. Write a tool”A tool is a plain function from an input struct to a result. Create main.go with package main, the imports from the complete program, and the tool:
// LookupInput is the tool's input. Its JSON Schema comes from the struct tags.type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"`}
var lookup = weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + ": shipped", nil })weft.Tool reflects the JSON Schema the model sees from LookupInput: the json tag names the field and the jsonschema tag describes it. The struct is the contract and its documentation. For a one-off tool you can declare the input struct inline in the handler’s signature, as func(ctx context.Context, in struct{ OrderID string `json:"order_id"` }), keeping the tag (without it the schema property is OrderID); a named type reads better and you can reuse it across tools and tests. A string result reaches the model as is; any other result type is sent as JSON.
3. Pick a model
Section titled “3. Pick a model”The agent needs a weft.Model. Add a function that returns Anthropic’s when a key is set, and a script otherwise:
if os.Getenv("ANTHROPIC_API_KEY") != "" { return anthropic.Model("claude-sonnet-5") // reads $ANTHROPIC_API_KEY}return wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."),)wefttest.Script plays its turns in order: first a call to lookup_order, then the reply. Each scripted step reports 10 input and 5 output tokens. anthropic.Model fits the same seam, so nothing else in the program changes.
4. Build and run the agent
Section titled “4. Build and run the agent”An agent is a value: build it once, run it as many times as you like, from as many goroutines as you like. Add the function that builds it and runs one question:
agt := weft.New(model, weft.Instructions("You are a support agent. Use lookup_order for order questions."), weft.MaxSteps(5), lookup,)
res, err := agt.Generate(ctx, weft.Prompt(question))if err != nil { return err}fmt.Println(res.Text())fmt.Printf("%d steps, %d tokens\n", res.NumSteps(), res.Usage.Total())weft.New takes the model, then options; a tool is an option too. weft.Instructions is the system prompt. weft.Prompt is the user’s message. Generate calls the model, runs the tool it asks for, calls the model again with the result, and returns a *weft.RunResult once the model answers in text.
A run ends when the model replies without asking for a tool. weft.MaxSteps is the separate safety budget: past 5 model calls this run fails with weft.ErrMaxSteps (the default is 10). To end a run on purpose — when the model calls a submit_answer tool, say — add weft.StopWhen(weft.HasToolCall("submit_answer")).
5. Stream the events
Section titled “5. Stream the events”Generate folds the run’s events away. To show progress, range over them instead:
for ev, err := range agt.Stream(ctx, weft.Prompt(question)).Events() { if err != nil { return err // at most once, as the last element } switch ev := ev.(type) { case weft.ToolStart: fmt.Printf("→ %s(%s)\n", ev.Name, ev.Args) case weft.TextDelta: fmt.Print(ev.Text) case weft.RunFinish: fmt.Printf("\n✓ %d steps, %d tokens\n", ev.Steps, ev.Usage.Total()) }}Stream returns the run’s handle, and nothing runs until you range over Events. Each event is a typed struct: weft.ToolStart when a tool call begins, weft.TextDelta for each piece of the reply, weft.RunFinish last. A failed run yields its error exactly once, as the last element. Breaking out of the loop, or cancelling ctx, cancels the run.
6. Run it
Section titled “6. Run it”Add main, which asks the question once with ask and once with stream (it is at the end of the complete program). go mod tidy fetches the Anthropic SDK the adapter imports; then run:
go mod tidygo run .Order 1234 has shipped.2 steps, 30 tokens---→ lookup_order({"order_id":"1234"})Order 1234 has shipped.✓ 2 steps, 30 tokensTwo steps: the model’s tool call, then its answer. 30 tokens: two scripted steps of 15. With ANTHROPIC_API_KEY set, the same command asks Claude and prints its own words.
The weft repository ships the same shape as examples/getting-started. In a clone of weft at v0.20.2, go run ./examples/getting-started prints:
→ lookup_order({"order_id":"1234"})Order 1234 shipped and is on its way.✓ 2 steps, 30 tokensThe complete program
Section titled “The complete program”// Command quickstart is the Quickstart's program: one tool, one agent, one// run, then the same question streamed. With ANTHROPIC_API_KEY unset the// model is scripted (wefttest), so it runs offline; with the key set it// calls Anthropic.package main
import ( "context" "fmt" "log" "os"
"github.com/weftgo/weft" "github.com/weftgo/weft/anthropic" "github.com/weftgo/weft/wefttest")
// LookupInput is the tool's input. Its JSON Schema comes from the struct tags.type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"`}
var lookup = weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + ": shipped", nil })
// newModel picks the model: Anthropic when a key is set, else a script.func newModel() weft.Model { if os.Getenv("ANTHROPIC_API_KEY") != "" { return anthropic.Model("claude-sonnet-5") // reads $ANTHROPIC_API_KEY } return wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), )}
// ask runs one question to the end and prints the answer.func ask(ctx context.Context, model weft.Model, question string) error { agt := weft.New(model, weft.Instructions("You are a support agent. Use lookup_order for order questions."), weft.MaxSteps(5), lookup, )
res, err := agt.Generate(ctx, weft.Prompt(question)) if err != nil { return err } fmt.Println(res.Text()) fmt.Printf("%d steps, %d tokens\n", res.NumSteps(), res.Usage.Total()) return nil}
// stream runs the same question and prints its events as they arrive.func stream(ctx context.Context, model weft.Model, question string) error { agt := weft.New(model, weft.Instructions("You are a support agent."), lookup)
for ev, err := range agt.Stream(ctx, weft.Prompt(question)).Events() { if err != nil { return err // at most once, as the last element } switch ev := ev.(type) { case weft.ToolStart: fmt.Printf("→ %s(%s)\n", ev.Name, ev.Args) case weft.TextDelta: fmt.Print(ev.Text) case weft.RunFinish: fmt.Printf("\n✓ %d steps, %d tokens\n", ev.Steps, ev.Usage.Total()) } } return nil}
func main() { ctx := context.Background() if err := ask(ctx, newModel(), "Where is order 1234?"); err != nil { log.Fatal(err) } fmt.Println("---") if err := stream(ctx, newModel(), "Where is order 1234?"); err != nil { log.Fatal(err) }}Run it with go run .; test it, offline, with go test ./.... The page’s own tests are quickstart/main_test.go.
Best practices & gotchas
Section titled “Best practices & gotchas”- A script is consumed as it plays.
wefttest.Scripthands out its turns in order across every run that uses it, which is whymainbuilds a new model for each run. (Source:wefttest.Scriptgodoc;quickstart/main_test.go:TestMainOutput) Eventsis single-use. A second call yields onlyErrRunConsumed; start another run withStreaminstead. (Source:Run.Eventsgodoc)MaxStepsis a budget, not the way to stop. Exceeding it fails the run with a*weft.RunErrorcarrying the partial transcript; the intended end isStopWhenor a text reply. (Source: AGENTS.md rule 13;quickstart/main_test.go:TestMaxSteps)- Keep tests off the network. Under
WEFT_MODEL_REQUESTS=denythe first-party adapters refuse to call their provider and the run fails withErrModelRequestsDenied. (Source: AGENTS.md;quickstart/main_test.go:TestRealModelSwap)
See also
Section titled “See also”- Next tutorial: Your first agent: a support bot from a tool to Studio
- How do tools work?
- Stream a run’s events
- Connect a model provider: OpenAI, Anthropic, Gemini
- Test an agent with a scripted model
Symbols used: weft.Tool · weft.Model · weft.New · weft.Instructions · weft.MaxSteps · weft.ErrMaxSteps · weft.StopWhen · weft.HasToolCall · weft.Prompt · Agent.Generate · Agent.Stream · Run.Events · weft.RunResult · RunResult.Text · RunResult.NumSteps · Usage.Total · weft.ToolStart · weft.TextDelta · weft.RunFinish · weft.ErrRunConsumed · weft.ErrModelRequestsDenied · wefttest.Script · wefttest.ToolCalls · wefttest.Call · wefttest.Say · anthropic.Model