Sn Tin

Chapter 7 of 8

Tools and agents

A tool fn is a function the compiler also describes to a model. An agent is called like a function.

examples/agents/01-tools.tintin run examples/agents/01-tools.tin
// Tools and agents are part of the language.
//
// `tool fn` is an ordinary function the compiler also describes to the model:
// its name, the `///` comments, and a JSON Schema derived from the parameter
// types. See what it generates with:  tin tools examples/agents/01-tools.tin
//
// This file uses `model: "mock"`, a built-in offline stand-in that calls the
// tools a prompt names. Swap in a real model to talk to Claude:
//   model: "claude-opus-5-5"

/// Add two integers.
tool fn add(
  /// The first number
  a: int,
  /// The second number
  b: int,
): int => a + b

/// Divide one integer by another.
tool fn divide(a: int, b: int): Result<int, string> {
  // An Err is not a crash: it goes back to the model as a failed tool call,
  // and the model gets to try something else.
  if b == 0 { return Err("cannot divide by zero") }
  Ok(a / b)
}

agent Calculator {
  model: "mock"
  system: "You are a calculator. Use the tools for every calculation."
  tools: [add, divide]

  // the agent loop is observable: handlers run as it goes
  on toolCall(name, input) => print("  call   {name} {input}")
  on toolResult(name, output, ok) => print("  {if ok { "result" } else { "failed" }} {name}: {output}")
}

fn main() {
  // An agent is called like a function. The loop runs until the model answers:
  // model -> tools -> model -> ... -> text
  print(Calculator("please add 19 and 23"))
  print(Calculator("now divide 10 by 0"))

  // agents remember the conversation; reset() starts a new one (turns() counts every model call the agent has made)
  print("turns so far: {Calculator.turns()}")
  Calculator.reset()
}
  call   add {"a":19,"b":23}
  result add: 42
mock: 42
  call   divide {"a":10,"b":0}
  failed divide: cannot divide by zero
mock: error: cannot divide by zero
turns so far: 4

The tool's name, its /// doc comments and a JSON Schema derived from its parameter types are generated by the compiler, so the description the model sees can't drift from the code. Run tin tools examples/agents/01-tools.tin to see them.

model: "mock" is a built-in offline stand-in that calls the tools a prompt names, so every example here runs without a network. Swap in a real model name to talk to Claude.

Ask for a type and you get that type back. let order: Order = Clerk(…) makes the runtime require an answer in the shape of Order and returns a real Tin value.

examples/agents/02-typed.tintin run examples/agents/02-typed.tin
// A typed call: the type you expect decides the shape of the reply.
//
// `let order: Order = Clerk(...)` makes the compiler generate a JSON Schema for
// Order and the runtime require the model to answer in that shape. What comes
// back is a real Tin value — fields, sum types and all — not a string to parse.

type Size = | Small | Medium | Large

type Order = {
  /// What the customer wants to drink
  drink: string
  size: Size
  /// How many cups
  quantity: int
  /// Extra requests, if any
  notes: Option<string>
}

/// The menu price of one cup, in cents.
tool fn price(drink: string, size: Size): int {
  let base = if drink.lower().contains("latte") { 450 } else { 300 }
  match size {
    Small => base
    Medium => base + 50
    Large => base + 100
  }
}

agent Clerk {
  model: "mock"
  system: "You take coffee orders."
  tools: [price]
}

fn total(o: Order): int => price(o.drink, o.size) * o.quantity

fn main() {
  let order: Order = Clerk("Two cups please: 2 of the 'oat latte', Large")
  print(order)
  print("{order.quantity} x {order.drink}")

  // a tool fn is still a function: call it yourself any time
  print("total: {total(order)} cents")

  // the reply type can be as small as an int or a bool
  let cents: int = Clerk("what is the price of a Medium 'espresso'?")
  print("an espresso costs {cents} cents")
}
Order { drink: "oat latte", size: Large, quantity: 2, notes: None }
2 x oat latte
total: 1100 cents
an espresso costs 350 cents

Some questions take a dozen tool calls. With code: true, the model may answer with a small Tin program that calls the agent's tools instead. The compiler checks that program can reach those tools and nothing else, then it runs in a sandboxed instance with a step budget. This one replays a recorded session.

examples/agents/09-code.tintin run examples/agents/09-code.tin --replay tests/tapes/agents-09-code.json
// Code as action: the model answers by writing a program.
//
// With `code: true`, an agent's model may write a small Tin program that calls
// the agent's tools, instead of calling them one at a time. Before that program
// runs, the compiler checks it: it may compute, print and call these tools, and
// nothing else. No network, no files, no other agents. Then it runs in a
// WebAssembly instance of its own, with a budget of steps.
//
// A question like the one below would take a dozen separate tool calls. As
// code, it is one round trip, and the arithmetic is done by the program, not
// guessed by the model.
//
//   tin run examples/agents/09-code.tin --trace
//   tin run examples/agents/09-code.tin --replay tests/tapes/agents-09-code.json

type Reading = { day: int, celsius: float }

/// The cities that have a weather station.
tool fn cities(): string[] => ["Istanbul", "Oslo", "Cairo", "Lima"]

/// Last week's noon temperatures for a city, one reading per day.
tool fn readings(
  /// A city from cities()
  city: string,
): Result<Reading[], string> {
  let base = match city {
    "Istanbul" => 18.0
    "Oslo" => 6.5
    "Cairo" => 31.0
    "Lima" => 22.0
    _ => return Err("no station in {city}")
  }
  Ok(range(1, 8).map(day => Reading { day, celsius: base + float(day * 7 % 5) - 2.0 }))
}

agent Meteorologist {
  system: "You answer questions about the weather stations. For anything that needs several lookups or arithmetic, write one program with run_code. Be brief."
  tools: [cities, readings]
  code: true
  on toolCall(name, input) => print(if name == "run_code" { "  the model wrote a program" } else { "    program calls {name} {input}" })
}

fn main() {
  print(Meteorologist("Which city had the warmest average last week, and what was each city's average?"))
}
  the model wrote a program
    program calls cities {}
    program calls readings {"city":"Istanbul"}
    program calls readings {"city":"Oslo"}
    program calls readings {"city":"Cairo"}
    program calls readings {"city":"Lima"}
Cairo had the warmest average last week, at about 31.3 °C.

Average noon temperature for each city (7 daily readings each):
- Cairo: 31.3 °C
- Lima: 22.3 °C
- Istanbul: 18.3 °C
- Oslo: 6.8 °C