Examples · agents · 39 of 339
10-try
Handling a failed agent call.
tin run examples/agents/10-try.tin// Handling a failed agent call.
//
// A plain agent call either answers or stops the program: hitting maxTurns, a refusal,
// a used-up maxTokens budget, a reply cut off by the output limit, or a provider error (no key, offline) is a panic.
// `A.try(prompt)` makes the same call but returns Result<T, AgentError>, so the program
// can retry, fall back, or explain. The expected type still decides the reply's shape.
//
// tin run examples/agents/10-try.tin
/// Look up the stock level for an item.
tool fn stock(item: string): int => if item == "tea" { 12 } else { 0 }
// One turn is too few to call a tool and then answer, so this agent always gives up.
agent Hasty {
model: "mock"
tools: [stock]
maxTurns: 1
}
agent Patient {
model: "mock"
tools: [stock]
}
// A token budget: input plus output tokens one question may use. The mock model counts
// 4 characters as a token, so this runs out before the tool result comes back.
agent Frugal {
model: "mock"
tools: [stock]
maxTokens: 50
}
type Order = { item: string, quantity: int }
agent Clerk { model: "mock" }
fn explain(e: AgentError): string => match e {
TurnLimit(n) => "gave up after {n} turn(s)"
OverBudget(n) => "used up its {n}-token budget"
Refused(why) => "the model declined: {why}"
Cut => "the reply was cut off"
NoAnswer => "no answer in the right shape"
Failed(why) => "the call failed: {why}"
}
fn lookup(item: string): string {
match Hasty.try("stock of '{item}'") {
Ok(text) => text
Err(e) => {
print("Hasty {explain(e)}; asking Patient")
Patient("stock of '{item}'")
}
}
}
fn main() {
print(lookup("tea"))
let order: Result<Order, AgentError> = Clerk.try("3 of the 'green tea'")
match order {
Ok(o) => print("{o.quantity} x {o.item}")
Err(e) => print(explain(e))
}
match Frugal.try("stock of 'tea'") {
Ok(text) => print(text)
Err(e) => print("Frugal {explain(e)}")
}
// The agent is still usable after an Err, and tokens and turns are counted as usual.
print(Hasty.try("stock of 'tea'").isErr())
print("Hasty made {Hasty.turns()} model calls")
} Hasty gave up after 1 turn(s); asking Patient
mock: 12
3 x green tea
Frugal used up its 50-token budget
true
Hasty made 2 model calls