Tin

Examples · agents · 38 of 339

09-code

Code as action: the model answers by writing a program. The model side replays a recorded tape, so it runs offline.

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