Skip to Content
AI

Chat

Tool loops with a step cap, and streaming chat for a route handler.

Usage

import { tool } from "ai"
import { z } from "zod"
import { runTools, streamChat } from "@dapplelight/signet-ai/chat"
import { app } from "./app"
import { db } from "./db"
import { model } from "./ai"

const tools = {
  lookupOrder: tool({
    description: "Find an order by id",
    inputSchema: z.object({ orderId: z.string() }),
    execute: async ({ orderId }) => db.orders.find(orderId),
  }),
}

// One-shot tool loop
const r = await runTools({ model, tools, prompt: "Where is order A1042?", maxSteps: 5 })
if (r.capped) {
  // stopped at maxSteps while the model still wanted tools; r.text is often empty
}

// Streaming route (Hono shown; any handler that returns a Response works)
app.post("/api/chat", async (c) => {
  const { messages } = await c.req.json()
  return streamChat({ model, messages, tools, key: c.get("userId"), abortSignal: c.req.raw.signal })
})

Needs ai 7 or later. The client half is useSignetChat in React.

API

ExportWhat it does
runTools(options)Multi-step tool calling with a step cap. Resolves to RunToolsResult
streamChat(options)Streams a reply and returns the Response for useSignetChat
RunToolsOptions, StreamChatOptionsTypes
RunToolsResult{ text, steps, capped, toolCalls, usage, costUsd }
ChatMessage, ChatMetadataTypes: UI message with metadata.usage

runTools / streamChat options

OptionTypeDefault
modelLanguageModelrequiredFrom any AI SDK provider
prompt or messagesstring or ModelMessage[]requiredrunTools only, one of the two. streamChat takes UI messages
systemstringnone
toolsToolSetnone
maxStepsnumber5Each model call is a step
providerstring"ai-sdk"Label in onUsage
pricingPricingnoneperCallUsd is charged once per step
onUsageOnUsagenoneoperation is tools or stream; stream reports when it ends
keystringnoneBudget key, e.g. a user id
abortSignalAbortSignalnone

streamChat treats messages as untrusted. It drops system messages and every tool part, so a browser cannot plant a system prompt or a fake tool result. Authenticate the route and cap the history length yourself.