A programming language
Agents are syntax.
Tin is a small typed language that compiles to WebAssembly. tool, agent and
guarded are keywords: the compiler writes the JSON a model sees from your types, and refuses
any path to a guarded tool that skips a person.
/// Send money. A person approves every call.
guarded tool fn wire(to: string, amount: int): string => "sent {amount} to {to}"
/// Look up a balance.
tool fn balance(account: string): int => 120
agent Teller {
model: "mock"
tools: [balance, wire]
}
fn main() {
print(Teller("wire 100 to 'bob'"))
} a person says yesmock: sent 100 to bob a person says nomock: error: Tool call denied by the user. Do not retry it; continue without it. [
{
"name": "wire",
"description": "Send money. A person approves every call.",
"schema": {
"type": "object",
"properties": {
"to": {
"type": "string"
},
"amount": {
"type": "integer"
}
},
"required": [
"to",
"amount"
],
"additionalProperties": false
}
},
{
"name": "balance",
"description": "Look up a balance.",
"schema": {
"type": "object",
"properties": {
"account": {
"type": "string"
}
},
"required": [
"account"
],
"additionalProperties": false
}
}
] Generated from the signatures and /// docs. You never write this.
fn main() {
print(wire("bob", 100))
} error: 'wire' is a guarded tool, and this call skips approval
--> teller.tin:13:9
|
13 | print(wire("bob", 100))
| ^^^^^^^^^^^^^^^^
= note: path: main → wire
= note: give the tool to an agent (the agent loop asks before it runs), or call it from another guarded tool fn The real compiler's message, produced when this page was built.
Race it here
Press Run. Your browser runs the same program in Tin (compiled to WebAssembly) and in JavaScript, and in Python too if you tick the box. Each runs in its own worker. The times are measured on your machine, now.
Recursive Fibonacci: function-call overhead.
The native numbers for this program, from the table below: . Tin's compile happened when this site was built; JavaScript's parse and JIT are inside its time; Pyodide's download is not.
Show the three sources
// Recursive Fibonacci: function-call overhead.
fn fib(n: int): int => if n < 2 { n } else { fib(n - 1) + fib(n - 2) }
fn main() {
print("fib(36) = {fib(36)}")
}
// Recursive Fibonacci: function-call overhead.
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2)
}
console.log(`fib(36) = ${fib(36)}`)
# Recursive Fibonacci: function-call overhead.
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(f"fib(36) = {fib(36)}")
// Mandelbrot set: floating-point arithmetic in nested loops.
fn escape(cr: float, ci: float, limit: int): int {
var zr = 0.0
var zi = 0.0
var i = 0
while i < limit && zr * zr + zi * zi <= 4.0 {
let next = zr * zr - zi * zi + cr
zi = 2.0 * zr * zi + ci
zr = next
i += 1
}
i
}
fn main() {
let size = 800
var total = 0
var inside = 0
for row in 0..size {
for col in 0..size {
let x = float(col) / float(size) * 3.0 - 2.0
let y = float(row) / float(size) * 3.0 - 1.5
let n = escape(x, y, 200)
total += n
if n == 200 { inside += 1 }
}
}
print("{size}x{size}: {inside} points inside, {total} iterations")
}
// Mandelbrot set: floating-point arithmetic in nested loops.
function escape(cr, ci, limit) {
let zr = 0.0, zi = 0.0, i = 0
while (i < limit && zr * zr + zi * zi <= 4.0) {
const next = zr * zr - zi * zi + cr
zi = 2.0 * zr * zi + ci
zr = next
i++
}
return i
}
const size = 800
let total = 0, inside = 0
for (let row = 0; row < size; row++) {
for (let col = 0; col < size; col++) {
const x = col / size * 3.0 - 2.0
const y = row / size * 3.0 - 1.5
const n = escape(x, y, 200)
total += n
if (n === 200) inside++
}
}
console.log(`${size}x${size}: ${inside} points inside, ${total} iterations`)
# Mandelbrot set: floating-point arithmetic in nested loops.
def escape(cr, ci, limit):
zr = 0.0
zi = 0.0
i = 0
while i < limit and zr * zr + zi * zi <= 4.0:
nxt = zr * zr - zi * zi + cr
zi = 2.0 * zr * zi + ci
zr = nxt
i += 1
return i
size = 800
total = 0
inside = 0
for row in range(size):
for col in range(size):
x = col / size * 3.0 - 2.0
y = row / size * 3.0 - 1.5
n = escape(x, y, 200)
total += n
if n == 200:
inside += 1
print(f"{size}x{size}: {inside} points inside, {total} iterations")
// N-body: the Jovian planets, a float-heavy simulation over arrays.
let SOLAR_MASS = 39.47841760435743 // 4 * pi * pi
let DAYS = 365.24
type Bodies = { x: float[], y: float[], z: float[], vx: float[], vy: float[], vz: float[], m: float[] }
fn bodies(): Bodies {
var b = Bodies {
x: [0.0, 4.84143144246472090e+00, 8.34336671824457987e+00, 1.28943695621391310e+01, 1.53796971148509165e+01],
y: [0.0, -1.16032004402742839e+00, 4.12479856412430479e+00, -1.51111514016986312e+01, -2.59193146099879641e+01],
z: [0.0, -1.03622044471123109e-01, -4.03523417114321381e-01, -2.23307578892655734e-01, 1.79258772950371181e-01],
vx: [0.0, 1.66007664274403694e-03 * DAYS, -2.76742510726862411e-03 * DAYS, 2.96460137564761618e-03 * DAYS, 2.68067772490389322e-03 * DAYS],
vy: [0.0, 7.69901118419740425e-03 * DAYS, 4.99852801234917238e-03 * DAYS, 2.37847173959480950e-03 * DAYS, 1.62824170038242295e-03 * DAYS],
vz: [0.0, -6.90460016972063023e-05 * DAYS, 2.30417297573763929e-05 * DAYS, -2.96589568540237556e-05 * DAYS, -9.51592254519715870e-05 * DAYS],
m: [SOLAR_MASS, 9.54791938424326609e-04 * SOLAR_MASS, 2.85885980666130812e-04 * SOLAR_MASS, 4.36624404335156298e-05 * SOLAR_MASS, 5.15138902046611451e-05 * SOLAR_MASS],
}
// offset the sun's momentum so the system's total is zero
var px = 0.0
var py = 0.0
var pz = 0.0
for i in 0..5 {
px += b.vx[i] * b.m[i]
py += b.vy[i] * b.m[i]
pz += b.vz[i] * b.m[i]
}
b.vx[0] = 0.0 - px / SOLAR_MASS
b.vy[0] = 0.0 - py / SOLAR_MASS
b.vz[0] = 0.0 - pz / SOLAR_MASS
b
}
fn energy(b: Bodies): float {
var e = 0.0
for i in 0..5 {
e += 0.5 * b.m[i] * (b.vx[i] * b.vx[i] + b.vy[i] * b.vy[i] + b.vz[i] * b.vz[i])
for j in i + 1..5 {
let dx = b.x[i] - b.x[j]
let dy = b.y[i] - b.y[j]
let dz = b.z[i] - b.z[j]
e -= b.m[i] * b.m[j] / sqrt(dx * dx + dy * dy + dz * dz)
}
}
e
}
fn advance(b: inout Bodies, dt: float) {
for i in 0..5 {
for j in i + 1..5 {
let dx = b.x[i] - b.x[j]
let dy = b.y[i] - b.y[j]
let dz = b.z[i] - b.z[j]
let d2 = dx * dx + dy * dy + dz * dz
let mag = dt / (d2 * sqrt(d2))
let mi = b.m[i] * mag
let mj = b.m[j] * mag
b.vx[i] -= dx * mj
b.vy[i] -= dy * mj
b.vz[i] -= dz * mj
b.vx[j] += dx * mi
b.vy[j] += dy * mi
b.vz[j] += dz * mi
}
}
for i in 0..5 {
b.x[i] += dt * b.vx[i]
b.y[i] += dt * b.vy[i]
b.z[i] += dt * b.vz[i]
}
}
fn main() {
var b = bodies()
print(energy(b).fixed(9))
for step in 0..500000 { advance(&b, 0.01) }
print(energy(b).fixed(9))
}
// N-body: the Jovian planets, a float-heavy simulation over arrays.
const SOLAR_MASS = 39.47841760435743 // 4 * pi * pi
const DAYS = 365.24
function bodies() {
const b = {
x: [0.0, 4.84143144246472090e+00, 8.34336671824457987e+00, 1.28943695621391310e+01, 1.53796971148509165e+01],
y: [0.0, -1.16032004402742839e+00, 4.12479856412430479e+00, -1.51111514016986312e+01, -2.59193146099879641e+01],
z: [0.0, -1.03622044471123109e-01, -4.03523417114321381e-01, -2.23307578892655734e-01, 1.79258772950371181e-01],
vx: [0.0, 1.66007664274403694e-03 * DAYS, -2.76742510726862411e-03 * DAYS, 2.96460137564761618e-03 * DAYS, 2.68067772490389322e-03 * DAYS],
vy: [0.0, 7.69901118419740425e-03 * DAYS, 4.99852801234917238e-03 * DAYS, 2.37847173959480950e-03 * DAYS, 1.62824170038242295e-03 * DAYS],
vz: [0.0, -6.90460016972063023e-05 * DAYS, 2.30417297573763929e-05 * DAYS, -2.96589568540237556e-05 * DAYS, -9.51592254519715870e-05 * DAYS],
m: [SOLAR_MASS, 9.54791938424326609e-04 * SOLAR_MASS, 2.85885980666130812e-04 * SOLAR_MASS, 4.36624404335156298e-05 * SOLAR_MASS, 5.15138902046611451e-05 * SOLAR_MASS],
}
let px = 0.0, py = 0.0, pz = 0.0
for (let i = 0; i < 5; i++) {
px += b.vx[i] * b.m[i]
py += b.vy[i] * b.m[i]
pz += b.vz[i] * b.m[i]
}
b.vx[0] = 0.0 - px / SOLAR_MASS
b.vy[0] = 0.0 - py / SOLAR_MASS
b.vz[0] = 0.0 - pz / SOLAR_MASS
return b
}
function energy(b) {
let e = 0.0
for (let i = 0; i < 5; i++) {
e += 0.5 * b.m[i] * (b.vx[i] * b.vx[i] + b.vy[i] * b.vy[i] + b.vz[i] * b.vz[i])
for (let j = i + 1; j < 5; j++) {
const dx = b.x[i] - b.x[j], dy = b.y[i] - b.y[j], dz = b.z[i] - b.z[j]
e -= b.m[i] * b.m[j] / Math.sqrt(dx * dx + dy * dy + dz * dz)
}
}
return e
}
function advance(b, dt) {
for (let i = 0; i < 5; i++) {
for (let j = i + 1; j < 5; j++) {
const dx = b.x[i] - b.x[j], dy = b.y[i] - b.y[j], dz = b.z[i] - b.z[j]
const d2 = dx * dx + dy * dy + dz * dz
const mag = dt / (d2 * Math.sqrt(d2))
const mi = b.m[i] * mag, mj = b.m[j] * mag
b.vx[i] -= dx * mj
b.vy[i] -= dy * mj
b.vz[i] -= dz * mj
b.vx[j] += dx * mi
b.vy[j] += dy * mi
b.vz[j] += dz * mi
}
}
for (let i = 0; i < 5; i++) {
b.x[i] += dt * b.vx[i]
b.y[i] += dt * b.vy[i]
b.z[i] += dt * b.vz[i]
}
}
const b = bodies()
console.log(energy(b).toFixed(9))
for (let step = 0; step < 500000; step++) advance(b, 0.01)
console.log(energy(b).toFixed(9))
# N-body: the Jovian planets, a float-heavy simulation over arrays.
import math
SOLAR_MASS = 39.47841760435743 # 4 * pi * pi
DAYS = 365.24
def bodies():
x = [0.0, 4.84143144246472090e+00, 8.34336671824457987e+00, 1.28943695621391310e+01, 1.53796971148509165e+01]
y = [0.0, -1.16032004402742839e+00, 4.12479856412430479e+00, -1.51111514016986312e+01, -2.59193146099879641e+01]
z = [0.0, -1.03622044471123109e-01, -4.03523417114321381e-01, -2.23307578892655734e-01, 1.79258772950371181e-01]
vx = [0.0, 1.66007664274403694e-03 * DAYS, -2.76742510726862411e-03 * DAYS, 2.96460137564761618e-03 * DAYS, 2.68067772490389322e-03 * DAYS]
vy = [0.0, 7.69901118419740425e-03 * DAYS, 4.99852801234917238e-03 * DAYS, 2.37847173959480950e-03 * DAYS, 1.62824170038242295e-03 * DAYS]
vz = [0.0, -6.90460016972063023e-05 * DAYS, 2.30417297573763929e-05 * DAYS, -2.96589568540237556e-05 * DAYS, -9.51592254519715870e-05 * DAYS]
m = [SOLAR_MASS, 9.54791938424326609e-04 * SOLAR_MASS, 2.85885980666130812e-04 * SOLAR_MASS, 4.36624404335156298e-05 * SOLAR_MASS, 5.15138902046611451e-05 * SOLAR_MASS]
px = py = pz = 0.0
for i in range(5):
px += vx[i] * m[i]
py += vy[i] * m[i]
pz += vz[i] * m[i]
vx[0] = 0.0 - px / SOLAR_MASS
vy[0] = 0.0 - py / SOLAR_MASS
vz[0] = 0.0 - pz / SOLAR_MASS
return x, y, z, vx, vy, vz, m
def energy(b):
x, y, z, vx, vy, vz, m = b
e = 0.0
for i in range(5):
e += 0.5 * m[i] * (vx[i] * vx[i] + vy[i] * vy[i] + vz[i] * vz[i])
for j in range(i + 1, 5):
dx = x[i] - x[j]
dy = y[i] - y[j]
dz = z[i] - z[j]
e -= m[i] * m[j] / math.sqrt(dx * dx + dy * dy + dz * dz)
return e
def advance(b, dt):
x, y, z, vx, vy, vz, m = b
for i in range(5):
for j in range(i + 1, 5):
dx = x[i] - x[j]
dy = y[i] - y[j]
dz = z[i] - z[j]
d2 = dx * dx + dy * dy + dz * dz
mag = dt / (d2 * math.sqrt(d2))
mi = m[i] * mag
mj = m[j] * mag
vx[i] -= dx * mj
vy[i] -= dy * mj
vz[i] -= dz * mj
vx[j] += dx * mi
vy[j] += dy * mi
vz[j] += dz * mi
for i in range(5):
x[i] += dt * vx[i]
y[i] += dt * vy[i]
z[i] += dt * vz[i]
b = bodies()
print(f"{energy(b):.9f}")
for step in range(500000):
advance(b, 0.01)
print(f"{energy(b):.9f}")
// Sieve of Eratosthenes: array writes in a tight loop.
fn main() {
let limit = 10000000
var composite = filled(limit, false)
var count = 0
var largest = 0
for n in 2..limit {
if composite[n] { continue }
count += 1
largest = n
if n > limit / n { continue }
var m = n * n
while m < limit {
composite[m] = true
m += n
}
}
print("{count} primes below {limit}, largest {largest}")
}
// Sieve of Eratosthenes: array writes in a tight loop.
const limit = 10000000
const composite = new Array(limit).fill(false)
let count = 0
let largest = 0
for (let n = 2; n < limit; n++) {
if (composite[n]) continue
count++
largest = n
for (let m = n * n; m < limit; m += n) composite[m] = true
}
console.log(`${count} primes below ${limit}, largest ${largest}`)
# Sieve of Eratosthenes: array writes in a tight loop.
limit = 10000000
composite = [False] * limit
count = 0
largest = 0
for n in range(2, limit):
if composite[n]:
continue
count += 1
largest = n
m = n * n
while m < limit:
composite[m] = True
m += n
print(f"{count} primes below {limit}, largest {largest}")
How fast, honestly
The same 9 programs in four languages, on one machine. Rust wins raw compute:
Tin is 2.2× faster (trees) to 4.0× slower (nbody) against it. Against JavaScript, Tin ranges from
5.0× faster (sort) to 1.5× slower (agent), 1.3× faster on the geometric mean of 8.
Against Python, from 20.8× faster (sieve) to 1.6× faster (agent). Every Tin and JavaScript time
includes about 26 ms and 24 ms of process startup (the hello row).
About the agent row
It is Tin's headline feature and its slowest row against JavaScript, so here is what it measures.
50,000 agent runs, each one model call, one tool call and a second model call, against an offline
mock model. In Tin that is the built-in loop: every call is checked against the tool's schema, decoded into
typed values, passed through the capability check and the on handlers, and crosses between
WebAssembly and JavaScript as JSON. In the other languages it is a bare loop written by hand, with none of that.
Measured inside the process, that is 1.7 µs per agent run in Tin, 0.9 µs in JavaScript and 3.4 µs in Python. A real model call takes hundreds of milliseconds, so with a real model this overhead does not show. What you get for it is in Only in Tin.
The same program in four languages
Each snippet runs in its own language when this site is built, and all four print the same output. Line counts skip blank lines.
Hello
String interpolation is the same idea everywhere.
fn greet(name: string): string => "Hello, {name}!"
fn main() {
for name in ["Ada", "Linus"] {
print(greet(name))
}
} def greet(name: str) -> str:
return f"Hello, {name}!"
for name in ["Ada", "Linus"]:
print(greet(name)) function greet(name) {
return `Hello, ${name}!`
}
for (const name of ["Ada", "Linus"]) {
console.log(greet(name))
} fn greet(name: &str) -> String {
format!("Hello, {name}!")
}
fn main() {
for name in ["Ada", "Linus"] {
println!("{}", greet(name));
}
} Hello, Ada!
Hello, Linus! Structs
Tin records are values: copying one copies the data.
type Point = { x: float, y: float }
fn dist(a: Point, b: Point): float {
let dx = a.x - b.x
let dy = a.y - b.y
sqrt(dx * dx + dy * dy)
}
fn main() {
let a = Point { x: 0.0, y: 0.0 }
let b = Point { x: 3.0, y: 4.0 }
print("distance {dist(a, b)}")
} import math
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
def dist(a: Point, b: Point) -> float:
return math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2)
a = Point(0.0, 0.0)
b = Point(3.0, 4.0)
print(f"distance {dist(a, b)}") // plain objects; the shape is a convention (or a TypeScript type)
function dist(a, b) {
return Math.hypot(a.x - b.x, a.y - b.y)
}
const a = { x: 0.0, y: 0.0 }
const b = { x: 3.0, y: 4.0 }
console.log(`distance ${dist(a, b).toFixed(1)}`) struct Point {
x: f64,
y: f64,
}
fn dist(a: &Point, b: &Point) -> f64 {
((a.x - b.x).powi(2) + (a.y - b.y).powi(2)).sqrt()
}
fn main() {
let a = Point { x: 0.0, y: 0.0 };
let b = Point { x: 3.0, y: 4.0 };
println!("distance {:.1}", dist(&a, &b));
} distance 5.0 Errors
Tin and Rust return a Result and pass failures up with ?. Python and JavaScript throw.
fn parsePort(text: string): Result<int, string> {
match parseInt(text) {
Some(n) => if n > 0 && n < 65536 { Ok(n) } else { Err("port {n} is out of range") }
None => Err("'{text}' is not a number")
}
}
fn address(line: string): Result<string, string> {
let parts = line.split(":")
if parts.len != 2 { return Err("expected host:port") }
let port = parsePort(parts[1])?
Ok("{parts[0]} on {port}")
}
fn main() {
for line in ["localhost:8080", "example.com:http", "nonsense"] {
match address(line) {
Ok(a) => print("ok {a}")
Err(why) => print("error {why}")
}
}
} class ConfigError(Exception):
pass
def parse_port(text: str) -> int:
try:
n = int(text)
except ValueError:
raise ConfigError(f"'{text}' is not a number")
if not 0 < n < 65536:
raise ConfigError(f"port {n} is out of range")
return n
def address(line: str) -> str:
parts = line.split(":")
if len(parts) != 2:
raise ConfigError("expected host:port")
return f"{parts[0]} on {parse_port(parts[1])}"
for line in ["localhost:8080", "example.com:http", "nonsense"]:
try:
print(f"ok {address(line)}")
except ConfigError as why:
print(f"error {why}") function parsePort(text) {
const n = Number(text)
if (!Number.isInteger(n)) throw new Error(`'${text}' is not a number`)
if (n <= 0 || n >= 65536) throw new Error(`port ${n} is out of range`)
return n
}
function address(line) {
const parts = line.split(":")
if (parts.length !== 2) throw new Error("expected host:port")
return `${parts[0]} on ${parsePort(parts[1])}`
}
for (const line of ["localhost:8080", "example.com:http", "nonsense"]) {
try {
console.log(`ok ${address(line)}`)
} catch (why) {
console.log(`error ${why.message}`)
}
} fn parse_port(text: &str) -> Result<u16, String> {
let n: i64 = text.parse().map_err(|_| format!("'{text}' is not a number"))?;
if n > 0 && n < 65536 { Ok(n as u16) } else { Err(format!("port {n} is out of range")) }
}
fn address(line: &str) -> Result<String, String> {
let parts: Vec<&str> = line.split(':').collect();
if parts.len() != 2 {
return Err("expected host:port".into());
}
let port = parse_port(parts[1])?;
Ok(format!("{} on {port}", parts[0]))
}
fn main() {
for line in ["localhost:8080", "example.com:http", "nonsense"] {
match address(line) {
Ok(a) => println!("ok {a}"),
Err(why) => println!("error {why}"),
}
}
} ok localhost on 8080
error 'http' is not a number
error expected host:port Concurrency
Tin has no async keyword: any function may suspend, spawn starts a task, await waits for it.
fn brew(drink: string, wait: Duration): string {
sleep(wait)
"{drink} is ready"
}
fn main() {
let t0 = now()
let tea = spawn brew("tea", 200ms)
let coffee = spawn brew("coffee", 300ms)
print(await tea)
print(await coffee)
print(if now() - t0 < 500ms { "both in parallel" } else { "one after another" })
} import asyncio
import time
async def brew(drink: str, wait: float) -> str:
await asyncio.sleep(wait)
return f"{drink} is ready"
async def main():
t0 = time.monotonic()
tea = asyncio.create_task(brew("tea", 0.2))
coffee = asyncio.create_task(brew("coffee", 0.3))
print(await tea)
print(await coffee)
print("both in parallel" if time.monotonic() - t0 < 0.5 else "one after another")
asyncio.run(main()) const sleep = (ms) => new Promise((done) => setTimeout(done, ms))
async function brew(drink, wait) {
await sleep(wait)
return `${drink} is ready`
}
const t0 = performance.now()
const tea = brew("tea", 200)
const coffee = brew("coffee", 300)
console.log(await tea)
console.log(await coffee)
console.log(performance.now() - t0 < 500 ? "both in parallel" : "one after another") use std::thread;
use std::time::{Duration, Instant};
fn brew(drink: &str, wait: Duration) -> String {
thread::sleep(wait);
format!("{drink} is ready")
}
fn main() {
let t0 = Instant::now();
let tea = thread::spawn(|| brew("tea", Duration::from_millis(200)));
let coffee = thread::spawn(|| brew("coffee", Duration::from_millis(300)));
println!("{}", tea.join().unwrap());
println!("{}", coffee.join().unwrap());
let both = t0.elapsed() < Duration::from_millis(500);
println!("{}", if both { "both in parallel" } else { "one after another" });
} tea is ready
coffee is ready
both in parallel Agent with a tool
Tin writes the tool schema from the function's types and runs the loop. Elsewhere you write both. Python, JavaScript and Rust use an offline stand-in for the model client, with the same behaviour as Tin's model: "mock".
/// Add two integers.
tool fn add(a: int, b: int): int => a + b
agent Calculator {
model: "mock"
system: "Use the tools for every calculation."
tools: [add]
}
fn main() {
print(Calculator("please add 19 and 23"))
} import json
# client = anthropic.Anthropic()
def add(a: int, b: int) -> int:
return a + b
TOOLS = [{
"name": "add",
"description": "Add two integers.",
"input_schema": {
"type": "object",
"properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
"required": ["a", "b"],
},
}]
RUN = {"add": add}
def ask(prompt: str) -> str:
messages = [{"role": "user", "content": prompt}]
while True:
reply = client.messages.create(
model="mock", max_tokens=1024, tools=TOOLS, messages=messages,
system="Use the tools for every calculation.")
messages.append({"role": "assistant", "content": reply.content})
if reply.stop_reason != "tool_use":
return "".join(b.text for b in reply.content if b.type == "text")
results = []
for call in reply.content:
if call.type == "tool_use":
out = RUN[call.name](**call.input)
results.append({"type": "tool_result", "tool_use_id": call.id, "content": json.dumps(out)})
messages.append({"role": "user", "content": results})
print(ask("please add 19 and 23")) // const client = new Anthropic()
const tools = [{
name: "add",
description: "Add two integers.",
input_schema: {
type: "object",
properties: { a: { type: "integer" }, b: { type: "integer" } },
required: ["a", "b"],
},
}]
const run = { add: ({ a, b }) => a + b }
async function ask(prompt) {
const messages = [{ role: "user", content: prompt }]
while (true) {
const reply = await client.messages.create({
model: "mock", max_tokens: 1024, tools, messages,
system: "Use the tools for every calculation.",
})
messages.push({ role: "assistant", content: reply.content })
if (reply.stop_reason !== "tool_use") {
return reply.content.filter((b) => b.type === "text").map((b) => b.text).join("")
}
const results = reply.content.filter((b) => b.type === "tool_use").map((call) => ({
type: "tool_result", tool_use_id: call.id, content: JSON.stringify(run[call.name](call.input)),
}))
messages.push({ role: "user", content: results })
}
}
console.log(await ask("please add 19 and 23")) // let client = Client::new(api_key);
fn add(a: i64, b: i64) -> i64 {
a + b
}
const TOOLS: &[Tool] = &[Tool {
name: "add",
description: "Add two integers.",
input_schema: r#"{"type": "object",
"properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
"required": ["a", "b"]}"#,
}];
fn ask(client: &Client, prompt: &str) -> String {
let mut messages = vec![Message { role: "user", content: vec![Block::Text(prompt.into())] }];
loop {
let reply = client.create("mock", TOOLS, &messages);
messages.push(Message { role: "assistant", content: reply.content.clone() });
if reply.stop_reason != "tool_use" {
return reply.content.iter().filter_map(|b| match b { Block::Text(t) => Some(t.clone()), _ => None }).collect();
}
let mut results = vec![];
for block in &reply.content {
if let Block::ToolUse { id, name, input } = block {
let out = match name.as_str() {
"add" => add(input["a"].as_i64().unwrap(), input["b"].as_i64().unwrap()),
other => panic!("unknown tool {other}"),
};
results.push(Block::ToolResult { tool_use_id: id.clone(), content: out.to_string() });
}
}
messages.push(Message { role: "user", content: results });
}
}
fn main() {
println!("{}", ask(&Client, "please add 19 and 23"));
} mock: 42 Guarded tool
In Tin a guarded tool cannot run without a person's yes, and code that calls it directly does not compile. Elsewhere the check is a line you must remember.
/// Send money. A person approves every call.
guarded tool fn wire(to: string, amount: int): string => "sent {amount} to {to}"
agent Teller {
model: "mock"
tools: [wire]
}
fn main() {
// The loop stops and asks a person before wire runs.
// Calling wire("bob", 100) here directly would not compile.
print(Teller("wire 100 to 'bob'"))
} # client = anthropic.Anthropic()
def wire(to: str, amount: int) -> str:
"""Send money. A person approves every call."""
return f"sent {amount} to {to}"
TOOLS = [{
"name": "wire",
"description": "Send money. A person approves every call.",
"input_schema": {
"type": "object",
"properties": {"to": {"type": "string"}, "amount": {"type": "integer"}},
"required": ["to", "amount"],
},
}]
GUARDED = {"wire"}
def ask(prompt: str) -> str:
messages = [{"role": "user", "content": prompt}]
while True:
reply = client.messages.create(model="mock", max_tokens=1024, tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": reply.content})
if reply.stop_reason != "tool_use":
return "".join(b.text for b in reply.content if b.type == "text")
results = []
for call in reply.content:
if call.type != "tool_use":
continue
# approve() is your own UI; forget this check and the tool just runs
if call.name in GUARDED and not approve(call.name, call.input):
out = "a person said no"
else:
out = wire(**call.input)
results.append({"type": "tool_result", "tool_use_id": call.id, "content": out})
messages.append({"role": "user", "content": results})
# nothing stops other code from calling wire("bob", 100) directly
print(ask("wire 100 to 'bob'")) // const client = new Anthropic()
/** Send money. A person approves every call. */
const wire = ({ to, amount }) => `sent ${amount} to ${to}`
const tools = [{
name: "wire",
description: "Send money. A person approves every call.",
input_schema: {
type: "object",
properties: { to: { type: "string" }, amount: { type: "integer" } },
required: ["to", "amount"],
},
}]
const guarded = new Set(["wire"])
async function ask(prompt) {
const messages = [{ role: "user", content: prompt }]
while (true) {
const reply = await client.messages.create({ model: "mock", max_tokens: 1024, tools, messages })
messages.push({ role: "assistant", content: reply.content })
if (reply.stop_reason !== "tool_use") {
return reply.content.filter((b) => b.type === "text").map((b) => b.text).join("")
}
const results = []
for (const call of reply.content.filter((b) => b.type === "tool_use")) {
// approve() is your own UI; forget this check and the tool just runs
const ok = !guarded.has(call.name) || (await approve(call.name, call.input))
results.push({ type: "tool_result", tool_use_id: call.id, content: ok ? wire(call.input) : "a person said no" })
}
messages.push({ role: "user", content: results })
}
}
// nothing stops other code from calling wire({ to: "bob", amount: 100 }) directly
console.log(await ask("wire 100 to 'bob'")) // let client = Client::new(api_key);
/// Send money. A person approves every call.
fn wire(to: &str, amount: i64) -> String {
format!("sent {amount} to {to}")
}
const TOOLS: &[Tool] = &[Tool {
name: "wire",
description: "Send money. A person approves every call.",
input_schema: r#"{"type": "object",
"properties": {"to": {"type": "string"}, "amount": {"type": "integer"}},
"required": ["to", "amount"]}"#,
}];
const GUARDED: &[&str] = &["wire"];
fn ask(client: &Client, prompt: &str) -> String {
let mut messages = vec![Message { role: "user", content: vec![Block::Text(prompt.into())] }];
loop {
let reply = client.create("mock", TOOLS, &messages);
messages.push(Message { role: "assistant", content: reply.content.clone() });
if reply.stop_reason != "tool_use" {
return reply.content.iter().filter_map(|b| match b { Block::Text(t) => Some(t.clone()), _ => None }).collect();
}
let mut results = vec![];
for block in &reply.content {
if let Block::ToolUse { id, name, input } = block {
// approve() is your own UI; forget this check and the tool just runs
let out = if GUARDED.contains(&name.as_str()) && !approve(name, input) {
"a person said no".to_string()
} else {
wire(input["to"].as_str().unwrap(), input["amount"].as_i64().unwrap())
};
results.push(Block::ToolResult { tool_use_id: id.clone(), content: out });
}
}
messages.push(Message { role: "user", content: results });
}
}
fn main() {
// nothing stops other code from calling wire("bob", 100) directly
println!("{}", ask(&Client, "wire 100 to 'bob'"));
} mock: sent 100 to bob Only in Tin
Each of these is produced by the real compiler and runtime while this page is built.
1. The schema comes from your types
The JSON is exactly what the model sees. It is generated from the code, so it can't drift.
type Unit = | Celsius | Fahrenheit
/// Look up the weather for a city.
tool fn weather(
/// City name, for example "Istanbul"
city: string,
unit: Unit,
): string => "sunny in {city}" {
"name": "weather",
"description": "Look up the weather for a city.",
"schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, for example \"Istanbul\""
},
"unit": {
"type": "string",
"enum": [
"Celsius",
"Fahrenheit"
]
}
},
"required": [
"city",
"unit"
],
"additionalProperties": false
}
} 2. Skipping the person does not compile
A guarded tool is reachable only through an agent that was given it, where the loop asks a person first. Any other path is a compile error, and the error shows the path.
/// Move money. A person approves every call.
guarded tool fn wire(to: string, amount: int): string => "sent {amount} to {to}"
fn payday() => wire("bob", 100)
fn main() { print(payday()) } error: 'wire' is a guarded tool, and this call skips approval
--> pay.tin:4:16
|
4 | fn payday() => wire("bob", 100)
| ^^^^^^^^^^^^^^^^
= note: path: main → payday → wire
= note: give the tool to an agent (the agent loop asks before it runs), or call it from another guarded tool fn 3. What each agent can reach, before it runs
The compiler follows every tool, sub-agent and call, and reports what each agent may do on its own and what
needs approval. tin caps prints the same report.
tool fn balance(account: string): int => 120
guarded tool fn wireMoney(to: string, amount: int): string {
// code inside a guarded tool already has approval, so it may call others
audit("wire {amount} to {to}")
}
fn audit(line: string): string {
print(" audit: {line}")
"sent"
}
agent Teller {
model: "mock"
tools: [balance]
}
agent Banker {
model: "mock"
tools: [Teller, wireMoney]
on toolCall(name, input) => print(" {name} {input}")
} agent Teller
tools: balance
can call freely: balance
needs approval: nothing
capabilities: model
agent Banker
tools: Teller (agent), wireMoney (guarded)
can call freely: balance
needs approval: wireMoney
capabilities: model, output
tools
balance free pure
wireMoney guarded output 4. Record a session once, replay it anywhere
tin run --record writes every model reply, fetch, input and random number to a tape;
--replay runs the same program from it with no model and no network. Tests and this page use that.
Below: the first model reply from a session recorded with Claude, and the output of replaying
examples/agents/05-claude.tin from it while this page was built.
{
"agent": "Calculator",
"response": {
"content": [
{
"type": "tool_use",
"name": "add",
"input": {
"a": 17,
"b": 25
}
}
],
"stop": "tool_use",
"inputTokens": 661,
"outputTokens": 66
}
} call add {"a":17,"b":25}
call multiply {"a":42,"b":3}
(17 + 25) * 3 = 126
… Learn it
Learn Tin goes from zero to an agent with tools in small chapters with tasks. The tour is the short version: