Skip to content

Quickstart: run an agent in five minutes

View as Markdown

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.

One main.go, under 100 lines, that prints the agent’s answer twice, the second time as the events arrive:

A terminal after go run . in the quickstart module: the answer "Order 1234 has shipped." with "2 steps, 30 tokens", then the streamed run: → lookup_order({"order_id":"1234"}), the same answer and ✓ 2 steps, 30 tokensA terminal after go run . in the quickstart module: the answer "Order 1234 has shipped." with "2 steps, 30 tokens", then the streamed run: → lookup_order({"order_id":"1234"}), the same answer and ✓ 2 steps, 30 tokens
go run . in the finished module: the answer from Generate, then the same run streamed, its tool call first.

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.

  • Go 1.26 or newer (go version)
  • No API key: the program uses a scripted model unless ANTHROPIC_API_KEY is set

Make a directory, start a module and add weft:

Terminal window
mkdir quickstart && cd quickstart
go mod init example.com/quickstart
go get github.com/weftgo/weft@v0.20.2

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:

quickstart/main.go
// 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
})

quickstart/main.go on GitHub

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.

The agent needs a weft.Model. Add a function that returns Anthropic’s when a key is set, and a script otherwise:

quickstart/main.go
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."),
)

quickstart/main.go on GitHub

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.

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:

quickstart/main.go
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())

quickstart/main.go on GitHub

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")).

Generate folds the run’s events away. To show progress, range over them instead:

quickstart/main.go
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())
}
}

quickstart/main.go on GitHub

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.

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:

Terminal window
go mod tidy
go run .
Order 1234 has shipped.
2 steps, 30 tokens
---
→ lookup_order({"order_id":"1234"})
Order 1234 has shipped.
✓ 2 steps, 30 tokens

Two 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 tokens
quickstart/main.go
// 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)
}
}

View quickstart/main.go on GitHub

Run it with go run .; test it, offline, with go test ./.... The page’s own tests are quickstart/main_test.go.

  • A script is consumed as it plays. wefttest.Script hands out its turns in order across every run that uses it, which is why main builds a new model for each run. (Source: wefttest.Script godoc; quickstart/main_test.go:TestMainOutput)
  • Events is single-use. A second call yields only ErrRunConsumed; start another run with Stream instead. (Source: Run.Events godoc)
  • MaxSteps is a budget, not the way to stop. Exceeding it fails the run with a *weft.RunError carrying the partial transcript; the intended end is StopWhen or a text reply. (Source: AGENTS.md rule 13; quickstart/main_test.go:TestMaxSteps)
  • Keep tests off the network. Under WEFT_MODEL_REQUESTS=deny the first-party adapters refuse to call their provider and the run fails with ErrModelRequestsDenied. (Source: AGENTS.md; quickstart/main_test.go:TestRealModelSwap)

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