Your first agent: a support bot from a tool to Studio
This tutorial builds a support bot that looks orders up and refunds them, but never refunds without a person’s yes. Along the way you give a tool a coded error, park a call at the approval boundary, record every run, and open the runs in Studio. It assumes you have done the Quickstart.
What you’ll build
Section titled “What you’ll build”A program that takes one support request, asks you to approve the refund it wants to make, prints the agent’s answer, and serves Studio over the recorded runs:
refund_order wants to run with {"order_id":"1234","amount":129.99}. Approve? [y/N] yI refunded $129.99 on order 1234. I could not find order 5678: check the number and ask again.Studio: http://127.0.0.1:8080/studio/

You will:
- write tools that return a struct and a coded error
- require approval for the tool that changes something
- resume a parked run with your decision
- record every run with one line and serve Studio over them
The finished code: docs-site/examples/firstagent.
Before you start
Section titled “Before you start”- Go 1.26 or newer
- No API key: the program uses a scripted model unless
ANTHROPIC_API_KEYis set. A real model chooses its own calls, so its run differs from the one shown here.
1. Create the module
Section titled “1. Create the module”mkdir support-bot && cd support-botgo mod init example.com/support-botgo get github.com/weftgo/weft@v0.20.22. Write the tools
Section titled “2. Write the tools”The bot has two tools: lookup_order reads an order, refund_order pays money back. Write their inputs, the result type and the handlers in main.go:
// Order is what lookup_order returns; the model reads it as JSON.type Order struct { ID string `json:"id"` Status string `json:"status"` Total float64 `json:"total"`}
type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"`}
type RefundInput struct { OrderID string `json:"order_id" jsonschema:"the order to refund"` Amount float64 `json:"amount" jsonschema:"amount in dollars"`}
var orders = map[string]Order{ "1234": {ID: "1234", Status: "delivered", Total: 129.99},}
func lookupOrder(ctx context.Context, in LookupInput) (Order, error) { o, ok := orders[in.OrderID] if !ok { return Order{}, &weft.ToolError{ Code: "ORDER_NOT_FOUND", Message: "order " + in.OrderID + " does not exist", } } return o, nil}
func refundOrder(ctx context.Context, in RefundInput) (string, error) { return fmt.Sprintf("refunded $%.2f on order %s", in.Amount, in.OrderID), nil}lookupOrder returns an Order, and the model reads it as JSON. An unknown id returns a *weft.ToolError: the model reads ORDER_NOT_FOUND: order 5678 does not exist, a stable code it can branch on. A tool error is data for the model, not a failure of the run. The other calls in the step keep running, and the model decides what to do next. A ToolError’s Err field, when you set it, is the internal cause: middleware and logs see it, the model never does.
3. Build the agent
Section titled “3. Build the agent”Turn the handlers into tools, mark the refund as needing approval, and build the agent:
lookup := weft.Tool("lookup_order", "Look up an order by ID.", lookupOrder)refund := weft.Tool("refund_order", "Refund an order. A person approves every refund.", refundOrder, weft.RequireApproval(),)
return weft.New(model, weft.Name("support-bot"), weft.Instructions("You are a support agent. Look the order up before you refund it."), weft.MaxSteps(8), lookup, refund,)weft.RequireApproval means a refund_order call never runs without a decision. weft.Name is the agent’s name on every recorded run; Studio lists runs by it. weft.MaxSteps(8) caps each run at 8 model calls.
4. Approve the refund
Section titled “4. Approve the refund”When the model calls refund_order, the loop runs the step’s other tools, then ends the run successfully with the call on res.Pending and no result for it. The run has parked. You resume it with a second run: the transcript plus a decision per call:
res, err := agt.Generate(ctx, weft.Prompt(question))if err != nil { return nil, err}for len(res.Pending) > 0 { opts := []weft.RunOption{weft.Messages(res.Messages...), weft.ResumeOf(res.ID)} for _, call := range res.Pending { if approve(call) { opts = append(opts, weft.Approve(call.ID)) } else { opts = append(opts, weft.Deny(call.ID, "declined by the operator")) } } res, err = agt.Generate(ctx, opts...) if err != nil { return nil, err }}return res, nilweft.Messages feeds the transcript back. weft.Approve runs the call through the ordinary tool chain before the next model call. weft.Deny never runs it: the model reads DENIED: declined by the operator. A pending call given neither reads DENIED: no decision. weft.ResumeOf changes nothing the model sees; it links the resume to the parked run, so Studio can show which run decided which park.
The parked call travels in the transcript and the decision in the Approve or Deny run option, so nothing here needs a database: the same two calls work across a queue or an HTTP round trip.
5. Record the runs and serve Studio
Section titled “5. Record the runs and serve Studio”Two lines more: record every run, and mount Studio over the recording:
// The local sink, ./.weft/weft.db, named explicitly: it stays when the// environment adds a Studio (WEFT_STUDIO_URL, or a running weft studio).defer otel.Install(otel.Local(""))()
res, err := converse(ctx, newAgent(model), "Orders 1234 and 5678 arrived broken. Refund them.", approve)if err != nil { return err}fmt.Println(res.Text())
mux := http.NewServeMux()mux.Handle("/studio/", http.StripPrefix("/studio", studio.Handler(studio.DB(otel.LocalDB()))))return serve(mux)otel.Install(otel.Local("")) writes every event, transcript and span to a local database, ./.weft/weft.db (or $WEFT_DB), with content on. When the environment names a destination — WEFT_STUDIO_URL, OTEL_EXPORTER_OTLP_ENDPOINT, or the discovery file a running weft studio writes — the recorder exports there too; naming otel.Local("") keeps the local sink beside it. The function Install returns flushes and shuts the recorder down, hence defer. studio.Handler(studio.DB(otel.LocalDB())) serves Studio over the same database handle. This program records both runs before it serves; an app that serves Studio while it handles requests sees each run live through that shared handle.
Add newModel, askOnStdin and main from the complete program: main passes run a function that serves the handler on 127.0.0.1:8080.
6. Run it
Section titled “6. Run it”Fetch the dependencies the imports need, then run:
go mod tidygo run .Answer y at the prompt:
refund_order wants to run with {"order_id":"1234","amount":129.99}. Approve? [y/N] yI refunded $129.99 on order 1234. I could not find order 5678: check the number and ask again.Studio: http://127.0.0.1:8080/studio/The scripted model looked up both orders in one step — the two calls ran in parallel — and got one order and one ORDER_NOT_FOUND. It then called refund_order, which parked. Your y resumed it, the refund ran, and the model answered. Answer anything else and the model reads DENIED: declined by the operator instead.
7. Open the runs in Studio
Section titled “7. Open the runs in Studio”Open http://127.0.0.1:8080/studio/ while the program runs. The runs list shows two runs of support-bot:
- the first, two steps long: the lookups, then the refund call it parked on (its stop reason is
parked) - the second, its resume: the refund ran, then the reply (stop reason
final_answer)


Open a run to see each step’s request, the tool calls with their arguments and results, and the tokens. Press Ctrl+C to stop the program; the recording stays in ./.weft/weft.db.
The complete program
Section titled “The complete program”// Command firstagent is the "Your first agent" tutorial's program: a support// bot with two tools, a refund that waits for a person's approval, every run// recorded, and Studio served over the recording.//// With ANTHROPIC_API_KEY unset the model is scripted (wefttest), so the// program runs offline and prints the same thing every time.package main
import ( "bufio" "context" "fmt" "log" "net/http" "os" "strings"
"github.com/weftgo/weft" "github.com/weftgo/weft/anthropic" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/studio" "github.com/weftgo/weft/wefttest")
// Order is what lookup_order returns; the model reads it as JSON.type Order struct { ID string `json:"id"` Status string `json:"status"` Total float64 `json:"total"`}
type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"`}
type RefundInput struct { OrderID string `json:"order_id" jsonschema:"the order to refund"` Amount float64 `json:"amount" jsonschema:"amount in dollars"`}
var orders = map[string]Order{ "1234": {ID: "1234", Status: "delivered", Total: 129.99},}
func lookupOrder(ctx context.Context, in LookupInput) (Order, error) { o, ok := orders[in.OrderID] if !ok { return Order{}, &weft.ToolError{ Code: "ORDER_NOT_FOUND", Message: "order " + in.OrderID + " does not exist", } } return o, nil}
func refundOrder(ctx context.Context, in RefundInput) (string, error) { return fmt.Sprintf("refunded $%.2f on order %s", in.Amount, in.OrderID), nil}
// newAgent builds the support bot over model.func newAgent(model weft.Model) *weft.Agent { lookup := weft.Tool("lookup_order", "Look up an order by ID.", lookupOrder) refund := weft.Tool("refund_order", "Refund an order. A person approves every refund.", refundOrder, weft.RequireApproval(), )
return weft.New(model, weft.Name("support-bot"), weft.Instructions("You are a support agent. Look the order up before you refund it."), weft.MaxSteps(8), lookup, refund, )}
// converse runs one question to the end, asking approve about every call// that waits for a decision.func converse(ctx context.Context, agt *weft.Agent, question string, approve func(weft.ToolCallPart) bool) (*weft.RunResult, error) { res, err := agt.Generate(ctx, weft.Prompt(question)) if err != nil { return nil, err } for len(res.Pending) > 0 { opts := []weft.RunOption{weft.Messages(res.Messages...), weft.ResumeOf(res.ID)} for _, call := range res.Pending { if approve(call) { opts = append(opts, weft.Approve(call.ID)) } else { opts = append(opts, weft.Deny(call.ID, "declined by the operator")) } } res, err = agt.Generate(ctx, opts...) if err != nil { return nil, err } } return res, nil}
// run records the conversation, then hands serve the handler that shows it// in Studio.func run(ctx context.Context, model weft.Model, approve func(weft.ToolCallPart) bool, serve func(http.Handler) error) error { // The local sink, ./.weft/weft.db, named explicitly: it stays when the // environment adds a Studio (WEFT_STUDIO_URL, or a running weft studio). defer otel.Install(otel.Local(""))()
res, err := converse(ctx, newAgent(model), "Orders 1234 and 5678 arrived broken. Refund them.", approve) if err != nil { return err } fmt.Println(res.Text())
mux := http.NewServeMux() mux.Handle("/studio/", http.StripPrefix("/studio", studio.Handler(studio.DB(otel.LocalDB())))) return serve(mux)}
// newModel picks the model: Anthropic when a key is set, else a script// that makes the same calls on every run.func newModel() weft.Model { if os.Getenv("ANTHROPIC_API_KEY") != "" { return anthropic.Model("claude-sonnet-5") } return wefttest.Script( wefttest.ToolCalls( wefttest.Call{ID: "c1", Name: "lookup_order", Args: `{"order_id":"1234"}`}, wefttest.Call{ID: "c2", Name: "lookup_order", Args: `{"order_id":"5678"}`}, ), wefttest.ToolCalls(wefttest.Call{ID: "c3", Name: "refund_order", Args: `{"order_id":"1234","amount":129.99}`}), wefttest.Say("I refunded $129.99 on order 1234. I could not find order 5678: check the number and ask again."), )}
// askOnStdin asks the operator about one call.func askOnStdin(call weft.ToolCallPart) bool { fmt.Printf("%s wants to run with %s. Approve? [y/N] ", call.Name, call.Args) line, _ := bufio.NewReader(os.Stdin).ReadString('\n') return strings.EqualFold(strings.TrimSpace(line), "y")}
func main() { serve := func(h http.Handler) error { fmt.Println("Studio: http://127.0.0.1:8080/studio/") return http.ListenAndServe("127.0.0.1:8080", h) } if err := run(context.Background(), newModel(), askOnStdin, serve); err != nil { log.Fatal(err) }}Run it with go run .; test it, offline, with go test ./.... The tests in firstagent/main_test.go check the coded error, both decisions, the park, and the two runs Studio lists.
Best practices & gotchas
Section titled “Best practices & gotchas”- Give tool failures a code.
ToolError{Code, Message}reaches the model as<CODE>: <Message>; a plain error reaches it as itsError()text. (Source:weft.ToolErrorgodoc;firstagent/main_test.go:TestToolErrorIsData) - A parked run succeeded.
Generatereturns a nil error and a non-emptyres.Pending; checkPendingbefore readingres.Text(). (Source: AGENTS.md rule 12;firstagent/main_test.go:TestFirstRunParks) - Approval is not a security boundary. It is a policy seam: the transcript that carries decisions is in the caller’s hands. Protect what a tool can do where it runs. (Source: ADR 0007;
weft.RequireApprovalgodoc) - Name the local sink when you serve Studio from it. A bare
otel.Install()adds the local sink only when the environment names no destination; withWEFT_STUDIO_URLorOTEL_EXPORTER_OTLP_ENDPOINTset, or aweft studiorunning,otel.LocalDB()is nil andstudio.Handler(studio.DB(nil))panics (instudio.New, whichHandlercalls).otel.Install(otel.Local(""))keeps it. (Source:otel/pipeline.go:223-238, 332-351;otel/env.go:37-62;studio/studio.go:255;firstagent/main_test.go:TestRunWithStudioInEnvironment) - Embedded Studio trusts loopback only. Without
studio.Token, it answers requests addressed to a loopback host and refuses cross-origin writes; give it a token before it listens anywhere else. (Source: AGENTS.md block 7,Token(tok))
See also
Section titled “See also”- Next: Require human approval for a tool
- Tool errors are data, run errors are yours
- Record every run with otel.Install
- Read a run in Studio
- Approvals in sessions
Symbols used: weft.Tool · weft.ToolError · weft.RequireApproval · weft.New · weft.Name · weft.Instructions · weft.MaxSteps · weft.Prompt · Agent.Generate · weft.RunResult · weft.ToolCallPart · weft.RunOption · weft.Messages · weft.ResumeOf · weft.Approve · weft.Deny · otel.Install · otel.Local · otel.LocalDB · studio.Handler · studio.DB · studio.Token · wefttest.Script · anthropic.Model