tool()

Describe a tool the model can ask your code to run, with its input as a zod schema.

Describes a tool for chat(): what it does, the input it takes as a zod schema, and the function that runs it.

function tool<Schema, Output>(definition: {
  description?: string
  input: Schema
  run?: (input: z.output<Schema>, context: ToolContext) => Output | Promise<Output>
}): Tool

Parameters

definition.descriptionstring

What the tool does and when to use it. The model reads this to choose it.

definition.inputzod schemaRequired

The input the tool takes, usually a z.object. It is sent to the model as JSON Schema, and each call’s input is checked against it before run gets it.

definition.runfunction

Runs the tool with the checked input, and returns what the model should see: a string as it is, anything else as JSON. It can be async. Without it, the call ends when the model asks for the tool, so your code can answer it, such as after asking a person.

Context

run also gets:

context.callIdstring

The call’s ID.

context.messagesMessage[]

The conversation so far, before the answer that asked for the tool.

context.signalAbortSignal or undefined

The call’s signal, to stop work when the call is cancelled.

What happens to a call

  • The tools the model asks for in one answer run at the same time.
  • When the input is not JSON, does not match input, names no tool, or run throws, the model gets the reason as an error and can try again in the next step. The call itself does not fail.
  • The model answers again with the results while maxSteps allows.

Example

order.ts
import { space, tool } from "digitospace"
import { z } from "zod"

const findOrder = tool({
  description: "Find an order by its number",
  input: z.object({ number: z.string().regex(/^\d{6}$/) }),
  run: async ({ number }) => db.orders.find(number),
})

const reply = await space.ai.chat("Where is order 104233?", {
  model: "openai/gpt-oss-120b",
  tools: { findOrder },
  maxSteps: 3,
})

console.log(reply.text)

Last updated