<!-- Tin next to Python and TypeScript · Tin · https://tin.ad/docs/from/ · generated from the built page -->

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

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

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

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

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

JavaScript, 6 lines

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

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

Rust, 8 lines

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

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

All four print

<!-- output -->
```text
Hello, Ada!
Hello, Linus!
```

### Structs

Tin records are values: copying one copies the data.

Tin, 11 lines · [Run in the playground](https://tin.ad/docs/play/#code=dHlwZSBQb2ludCA9IHsgeDogZmxvYXQsIHk6IGZsb2F0IH0KCmZuIGRpc3QoYTogUG9pbnQsIGI6IFBvaW50KTogZmxvYXQgewogIGxldCBkeCA9IGEueCAtIGIueAogIGxldCBkeSA9IGEueSAtIGIueQogIHNxcnQoZHggKiBkeCArIGR5ICogZHkpCn0KCmZuIG1haW4oKSB7CiAgbGV0IGEgPSBQb2ludCB7IHg6IDAuMCwgeTogMC4wIH0KICBsZXQgYiA9IFBvaW50IHsgeDogMy4wLCB5OiA0LjAgfQogIHByaW50KCJkaXN0YW5jZSB7ZGlzdChhLCBiKX0iKQp9)

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

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

```tin
// 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

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

<!-- output -->
```text
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](https://tin.ad/docs/play/#code=Zm4gcGFyc2VQb3J0KHRleHQ6IHN0cmluZyk6IFJlc3VsdDxpbnQsIHN0cmluZz4gewogIG1hdGNoIHBhcnNlSW50KHRleHQpIHsKICAgIFNvbWUobikgPT4gaWYgbiA-IDAgJiYgbiA8IDY1NTM2IHsgT2sobikgfSBlbHNlIHsgRXJyKCJwb3J0IHtufSBpcyBvdXQgb2YgcmFuZ2UiKSB9CiAgICBOb25lID0-IEVycigiJ3t0ZXh0fScgaXMgbm90IGEgbnVtYmVyIikKICB9Cn0KCmZuIGFkZHJlc3MobGluZTogc3RyaW5nKTogUmVzdWx0PHN0cmluZywgc3RyaW5nPiB7CiAgbGV0IHBhcnRzID0gbGluZS5zcGxpdCgiOiIpCiAgaWYgcGFydHMubGVuICE9IDIgeyByZXR1cm4gRXJyKCJleHBlY3RlZCBob3N0OnBvcnQiKSB9CiAgbGV0IHBvcnQgPSBwYXJzZVBvcnQocGFydHNbMV0pPwogIE9rKCJ7cGFydHNbMF19IG9uIHtwb3J0fSIpCn0KCmZuIG1haW4oKSB7CiAgZm9yIGxpbmUgaW4gWyJsb2NhbGhvc3Q6ODA4MCIsICJleGFtcGxlLmNvbTpodHRwIiwgIm5vbnNlbnNlIl0gewogICAgbWF0Y2ggYWRkcmVzcyhsaW5lKSB7CiAgICAgIE9rKGEpID0-IHByaW50KCJvayAgICB7YX0iKQogICAgICBFcnIod2h5KSA9PiBwcmludCgiZXJyb3Ige3doeX0iKQogICAgfQogIH0KfQ)

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

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

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

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

<!-- output -->
```text
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](https://tin.ad/docs/play/#code=Zm4gYnJldyhkcmluazogc3RyaW5nLCB3YWl0OiBEdXJhdGlvbik6IHN0cmluZyB7CiAgc2xlZXAod2FpdCkKICAie2RyaW5rfSBpcyByZWFkeSIKfQoKZm4gbWFpbigpIHsKICBsZXQgdDAgPSBub3coKQogIGxldCB0ZWEgPSBzcGF3biBicmV3KCJ0ZWEiLCAyMDBtcykKICBsZXQgY29mZmVlID0gc3Bhd24gYnJldygiY29mZmVlIiwgMzAwbXMpCiAgcHJpbnQoYXdhaXQgdGVhKQogIHByaW50KGF3YWl0IGNvZmZlZSkKICBwcmludChpZiBub3coKSAtIHQwIDwgNTAwbXMgeyAiYm90aCBpbiBwYXJhbGxlbCIgfSBlbHNlIHsgIm9uZSBhZnRlciBhbm90aGVyIiB9KQp9)

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

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

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

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

<!-- output -->
```text
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](https://tin.ad/docs/play/#code=Ly8vIEFkZCB0d28gaW50ZWdlcnMuCnRvb2wgZm4gYWRkKGE6IGludCwgYjogaW50KTogaW50ID0-IGEgKyBiCgphZ2VudCBDYWxjdWxhdG9yIHsKICBtb2RlbDogIm1vY2siCiAgc3lzdGVtOiAiVXNlIHRoZSB0b29scyBmb3IgZXZlcnkgY2FsY3VsYXRpb24uIgogIHRvb2xzOiBbYWRkXQp9CgpmbiBtYWluKCkgewogIHByaW50KENhbGN1bGF0b3IoInBsZWFzZSBhZGQgMTkgYW5kIDIzIikpCn0)

```tin
/// 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

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

```tin
// 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

```tin
// 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

<!-- output -->
```text
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](https://tin.ad/docs/play/#code=Ly8vIFNlbmQgbW9uZXkuIEEgcGVyc29uIGFwcHJvdmVzIGV2ZXJ5IGNhbGwuCmd1YXJkZWQgdG9vbCBmbiB3aXJlKHRvOiBzdHJpbmcsIGFtb3VudDogaW50KTogc3RyaW5nID0-ICJzZW50IHthbW91bnR9IHRvIHt0b30iCgphZ2VudCBUZWxsZXIgewogIG1vZGVsOiAibW9jayIKICB0b29sczogW3dpcmVdCn0KCmZuIG1haW4oKSB7CiAgLy8gVGhlIGxvb3Agc3RvcHMgYW5kIGFza3MgYSBwZXJzb24gYmVmb3JlIHdpcmUgcnVucy4KICAvLyBDYWxsaW5nIHdpcmUoImJvYiIsIDEwMCkgaGVyZSBkaXJlY3RseSB3b3VsZCBub3QgY29tcGlsZS4KICBwcmludChUZWxsZXIoIndpcmUgMTAwIHRvICdib2InIikpCn0)

```tin
/// 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

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

```tin
// 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

```tin
// 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

<!-- output -->
```text
mock: sent 100 to bob
```

Next: [the tour](https://tin.ad/docs/tour/hello/), or [Learn Tin](https://tin.ad/docs/learn/).
