Tin

Examples · agents · 41 of 339

12-resume

Saving and restoring an agent.

examples/agents/12-resume.tintin run examples/agents/12-resume.tin
// Saving and restoring an agent.
//
// An agent's state is its conversation, and the runtime hands it over as plain text:
// A.save() gives a string, and A.restore(state) puts it back into an agent. Keep it in a
// file or a database, send it to another machine, and pick the conversation up later,
// after a crash or on another device. restore checks what it is given: anything that is
// not a saved agent, or a conversation that calls tools this agent doesn't have, is an Err.
//
//   tin run examples/agents/12-resume.tin

/// Look up how many units of an item are in stock.
tool fn stock(item: string): int => if item == "bolts" { 120 } else { 0 }

agent Clerk {
  model: "mock"
  tools: [stock]
}

fn main() {
  print(Clerk("stock of 'bolts'"))
  let saved = Clerk.save()
  print("saved after {Clerk.turns()} model calls")

  // later, somewhere else: a fresh agent with an empty conversation
  let again = Clerk.fresh()
  match again.restore(saved) {
    Ok(n) => print("restored {n} messages")
    Err(why) => print("could not restore: {why}")
  }
  print(again("stock of 'nuts'"))
  print("{again.turns()} model calls in all")

  print(again.restore("not a saved agent"))
}
mock: 120
saved after 2 model calls
restored 4 messages
mock: 0
4 model calls in all
Err("not a saved agent: the text is not JSON")