Tin

Tin next to Python and TypeScript

The same idea in three languages. The last three rows are where Tin stops looking like the others: tools, typed replies and approval are part of the language, not a library.

IdeaPythonTypeScriptTin
Variables
name = "Ada"
age = 36
const name = "Ada"
let age = 36
let name = "Ada"
var age = 36
String formatting
f"{name} is {age}"
`${name} is ${age}`
"{name} is {age}"
Functions
def area(w: float, h: float) -> float:
    return w * h
function area(w: number, h: number): number {
  return w * h
}
fn area(w: float, h: float): float => w * h
Lambdas and map
squares = [x * x for x in xs]
const squares = xs.map(x => x * x)
let squares = xs.map(x => x * x)
Pipelines
sum(map(f, xs))
xs.map(f).reduce((a, b) => a + b, 0)
xs |> map(f) |> sum
Missing values
d.get("bob")  # None
map.get("bob")  // undefined
ages.get("bob")  // None, an Option<int>
ages.get("bob").or(0)
Errors
raise ValueError("bad port")
throw new Error("bad port")
return Err("bad port")   // a Result<T, string>
let port = parsePort(text)?
Records
@dataclass
class Point:
    x: float
    y: float
type Point = { x: number; y: number }
type Point = { x: float, y: float }
Enums with data
Shape = Circle | Rect  # by convention
type Shape =
  | { kind: "circle"; r: number }
  | { kind: "rect"; w: number; h: number }
type Shape =
  | Circle { r: float }
  | Rect { w: float, h: float }
Concurrency
task = asyncio.create_task(brew())
await task
const task = brew()
await task
let task = spawn brew()   // brew is an ordinary fn
await task
A tool for a model
@tool
def add(a: int, b: int) -> int:
    """Add two integers."""
    return a + b
tool({ name: "add", description: "Add two integers.",
  parameters: z.object({ a: z.number(), b: z.number() }) })
/// Add two integers.
tool fn add(a: int, b: int): int => a + b
Structured output
Order.model_validate_json(reply)
OrderSchema.parse(JSON.parse(reply))
let order: Order = Clerk("two oat lattes")
Human approval
if input("ok? ") == "y": wire()
if (await confirm("ok?")) wire()
guarded tool fn wire(to: string, amount: int): string => "sent"

Whole programs, four languages

Each program 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.

Tin, 6 lines · Run in the playground

fn greet(name: string): string => "Hello, {name}!"

fn main() {
  for name in ["Ada", "Linus"] {
    print(greet(name))
  }
}
Python (4) · JavaScript (6) · Rust (8)

Python, 4 lines

def greet(name: str) -> str:
    return f"Hello, {name}!"

for name in ["Ada", "Linus"]:
    print(greet(name))

JavaScript, 6 lines

function greet(name) {
  return `Hello, ${name}!`
}

for (const name of ["Ada", "Linus"]) {
  console.log(greet(name))
}

Rust, 8 lines

fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}

fn main() {
    for name in ["Ada", "Linus"] {
        println!("{}", greet(name));
    }
}

All four print

Hello, Ada!
Hello, Linus!

Structs

Tin records are values: copying one copies the data.

Tin, 11 lines · Run in the playground

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)}")
}
Python (11) · JavaScript (7) · Rust (12)

Python, 11 lines

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

JavaScript, 7 lines

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

Rust, 12 lines

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));
}

All four print

distance 5.0

Errors

Tin and Rust return a Result and pass failures up with ?. Python and JavaScript throw.

Tin, 20 lines · Run in the playground

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}")
    }
  }
}
Python (20) · JavaScript (18) · Rust (20)

Python, 20 lines

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

JavaScript, 18 lines

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

Rust, 20 lines

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}"),
        }
    }
}

All four print

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.

Tin, 12 lines · Run in the playground

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" })
}
Python (13) · JavaScript (11) · Rust (15)

Python, 13 lines

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

JavaScript, 11 lines

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

Rust, 15 lines

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" });
}

All four print

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

Tin, 10 lines · Run in the playground

/// 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"))
}
Python (30) · JavaScript (29) · Rust (35)

Python, 30 lines

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

JavaScript, 29 lines

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

Rust, 35 lines

// 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"));
}

All four print

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.

Tin, 11 lines · Run in the playground

/// 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'"))
}
Python (34) · JavaScript (32) · Rust (40)

Python, 34 lines

# 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'"))

JavaScript, 32 lines

// 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'"))

Rust, 40 lines

// 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'"));
}

All four print

mock: sent 100 to bob

Next: the tour, or Learn Tin.