---
title: 'Your first agent: a support bot from a tool to Studio'
description: 'Build a support agent step by step: two tools with coded errors, a refund that waits for a person''s approval, every run recorded, and the runs opened in Studio.'
url: https://weftgo.dev/docs/get-started/first-agent/
type: tutorial
sources:
  - weft/examples/approval/main.go (RequireApproval, Pending, resume with Messages + Approve/Deny)
  - 'weft/examples/studio-local/main.go (setup A: otel.Install, studio.New/Handler over otel.LocalDB, mounted under /studio/)'
  - weft/README.md:258-276 (Approval), 319-341 (Recording runs), 343-358 (Inspecting runs)
  - weft/AGENTS.md blocks 1-7 (ToolError, RequireApproval, Approve/Deny, ResumeOf, otel.Install, studio.Handler; setup A's loopback wall); rules 1, 3, 12
  - 'weft/core/tool.go godoc Tool (non-string Out is sent as JSON), ToolError ("<CODE>: <Message>"; Err never shown)'
  - 'weft/core godoc RequireApproval, Approve, Deny ("DENIED: <reason>"), ResumeOf (weft.resumed_from; Studio''s resumed_by), RunResult.Pending, MaxSteps'
  - weft/core/agent.go:24 (defaultParallelism = 4)
  - weft/otel/pipeline.go:223-238 (explicit and environment destinations combine; no destination → Local)
  - weft/otel/pipeline.go:332-351 (Install falls back to Local only with no destinations at all)
  - weft/otel/env.go:11-62 (WEFT_STUDIO_URL, OTEL_EXPORTER_OTLP_ENDPOINT and the discovery file add destinations)
  - weft/obsdb/sqlite/write.go:20-27 (INSERT OR IGNORE on the idempotency keys; migration 0001 unique keys)
  - weft/otel/pipeline.go:229-236 (the discovery file adds its Studio); otel/pipeline.go:276 (INFO joined the running Studio)
  - weft/studio/studio.go:255 (New panics on a nil DB)
  - 'weft/examples/studio-local/main.go:265 (otel.Install(otel.Local(""), …): the sink named explicitly)'
  - weft/otel godoc Install, Local ("" = $WEFT_DB or ./.weft/weft.db), LocalDB; otel/config.go:158-164
  - weft/studio godoc Handler, DB
  - 'weft/cmd/weft (weft studio --help: --db default $WEFT_DB or ./.weft/weft.db; 127.0.0.1:7331)'
  - docs-site/examples/firstagent/main_test.go:TestToolErrorIsData, TestApproval, TestFirstRunParks, TestRunRecordsAndServesStudio
  - 'observed: go run . in a fresh module (output below); weft runs against weft studio over its .weft/weft.db: STOPPED BY parked, then final_answer'
---

# 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](https://weftgo.dev/docs/reference/glossary/#approval-boundary), record every run, and open the runs in Studio. It assumes you have done the [Quickstart](https://weftgo.dev/docs/get-started/quickstart/).

## 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:

```text
refund_order wants to run with {"order_id":"1234","amount":129.99}. Approve? [y/N] y
I 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/
```

![weft Studio's runs list: each run's status, prompt and id, agent, steps, tokens, cost, start and duration, newest first, with a checkbox per row to pick runs to compare](https://weftgo.dev/docs/_astro/studio-runs.light.CFMu-KA1.webp)

*Studio's runs list, newest first. After step 6 yours holds the tutorial's two support-bot runs.*

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`](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/firstagent).

## Before you start

- Go 1.26 or newer
- No API key: the program uses a scripted model unless `ANTHROPIC_API_KEY` is set. A real model chooses its own calls, so its run differs from the one shown here.

## 1. Create the module

```sh
mkdir support-bot && cd support-bot
go mod init example.com/support-bot
go get github.com/weftgo/weft@v0.20.2
```

## 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`:

```go title="firstagent/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
}
```

[firstagent/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main.go)

`lookupOrder` returns an `Order`, and the model reads it as JSON. An unknown id returns a [`*weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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

Turn the handlers into tools, mark the refund as needing approval, and build the agent:

```go title="firstagent/main.go"
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,
)
```

[firstagent/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main.go)

[`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) means a `refund_order` call never runs without a decision. [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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

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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) and no result for it. The run has [parked](https://weftgo.dev/docs/reference/glossary/#park). You resume it with a second run: the transcript plus a decision per call:

```go title="firstagent/main.go"
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
```

[firstagent/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main.go)

[`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) feeds the transcript back. [`weft.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Approve) runs the call through the ordinary tool chain before the next model call. [`weft.Deny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Deny) never runs it: the model reads `DENIED: declined by the operator`. A pending call given neither reads `DENIED: no decision`. [`weft.ResumeOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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

Two lines more: record every run, and mount Studio over the recording:

```go title="firstagent/main.go"
// 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)
```

[firstagent/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main.go)

[`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install)`(`[`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler)`(`[`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB)`(`[`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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](#the-complete-program): `main` passes `run` a function that serves the handler on `127.0.0.1:8080`.

## 6. Run it

Fetch the dependencies the imports need, then run:

```sh
go mod tidy
go run .
```

Answer `y` at the prompt:

```text
refund_order wants to run with {"order_id":"1234","amount":129.99}. Approve? [y/N] y
I 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

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`)

![Studio's run page for the tutorial's first support-bot run: parked, with one call decided and a link to the run that resumed it; step 0 ran two lookup_order calls, one ok and one ORDER_NOT_FOUND, and step 1's refund_order call is pending](https://weftgo.dev/docs/_astro/first-agent-run.light.D8nG2PD5.webp)

*The first run's page: step 0's two lookup_order calls, one ok and one ORDER_NOT_FOUND; step 1's refund_order pending; the header links the run that resumed it.*

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`.

> **Studio without your program running:** After the program exits, `weft studio` run in the same directory serves the same database: it reads `./.weft/weft.db` by default. While it runs, a new `go run .` writes the local sink and also exports to it through its discovery file (one INFO line, `joined the running Studio`). Both copies land in the same `./.weft/weft.db`, which stores each record and span once, so every run still appears once. A `weft studio` serving a different database receives a copy of every run; set `WEFT_DISCOVERY=off` to keep the program to its local sink. Install the command with `go install github.com/weftgo/weft/cmd/weft@v0.20.2` ([Install](https://weftgo.dev/docs/get-started/install/#install-the-weft-command)).

## The complete program

```go title="firstagent/main.go"
// 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)
	}
}
```

[firstagent/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main.go)

Run it with `go run .`; test it, offline, with `go test ./...`. The tests in [`firstagent/main_test.go`](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main_test.go) check the coded error, both decisions, the park, and the two runs Studio lists.

## Best practices & gotchas

- **Give tool failures a code.** `ToolError{Code, Message}` reaches the model as `<CODE>: <Message>`; a plain error reaches it as its `Error()` text. (Source: `weft.ToolError` godoc; `firstagent/main_test.go:TestToolErrorIsData`)
- **A parked run succeeded.** `Generate` returns a nil error and a non-empty `res.Pending`; check `Pending` before reading `res.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.RequireApproval` godoc)
- **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; with `WEFT_STUDIO_URL` or `OTEL_EXPORTER_OTLP_ENDPOINT` set, or a `weft studio` running, `otel.LocalDB()` is nil and `studio.Handler(studio.DB(nil))` panics (in `studio.New`, which `Handler` calls). `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

- Next: [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/)
- [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/)
- [Record every run with otel.Install](https://weftgo.dev/docs/observe/recording/)
- [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/)
- [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/)

Symbols used: [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`Agent.Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) · [`weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) · [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) · [`weft.RunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunOption) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.ResumeOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResumeOf) · [`weft.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Approve) · [`weft.Deny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Deny) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler) · [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB) · [`studio.Token`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Token) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`anthropic.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Model)
