Tin

Examples · agents · 30 of 339

01-tools

Tools and agents are part of the language.

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