Add AI Chat, Tool Loops and Grounded Answers
A streaming chat route with a React hook, plus tool loops, embeddings search and answers that cite their sources.
Install
npm i @dapplelight/signet-ai zod ai @ai-sdk/reactStream from the server
import { streamChat } from "@dapplelight/signet-ai/chat"
import { requireAuth } from "@dapplelight/signet-server/auth/hono"
import { app } from "../app"
import { model } from "./model"
import { tools } from "./tools"
import { onUsage } from "./ai"
app.post("/api/chat", requireAuth, async (c) => {
const { messages } = await c.req.json()
return streamChat({
model, messages, tools, maxSteps: 5, onUsage,
key: c.get("session").sub,
abortSignal: c.req.raw.signal,
})
})Authenticate the route and cap messages yourself.
Read it in React
import { useSignetChat } from "@dapplelight/signet-ai/react"
const { messages, sendMessage, status, stop, usage } = useSignetChat({ api: "/api/chat" })Run a tool loop
import { runTools } from "@dapplelight/signet-ai/chat"
import { tool } from "ai"
import { z } from "zod"
import { model } from "./model"
import { onUsage } from "./ai"
const inputSchema = z.object({ id: z.string() })
const execute = async ({ id }: { id: string }) => ({ id, status: "shipped" })
const r = await runTools({
model,
tools: { lookupOrder: tool({ description: "Find an order by id", inputSchema, execute }) },
prompt: "Where is order A1?",
maxSteps: 5,
onUsage,
})
if (r.capped) { /* stopped at maxSteps while the model still wanted tools */ }Search your help pages
import { embedDocuments, searchDocuments } from "@dapplelight/signet-ai/ground"
import { embeddingModel } from "./model"
import { docs } from "./docs"
const indexed = await embedDocuments(embeddingModel, docs)
const hits = await searchDocuments(embeddingModel, "how long is delivery", indexed, { topK: 5, minScore: 0.3 })Answer with citations
import { groundedAnswer } from "@dapplelight/signet-ai/ground"
import { model } from "./model"
import { hits } from "./help-search"
export async function answer(question: string) {
const r = await groundedAnswer({ model, question, documents: hits })
if (!r.grounded) return "I couldn't find that in our help pages."
// r.answer, r.citations: [{ id, quote }], r.rejected
}Report cost
import { analyticsUsage } from "@dapplelight/signet-ai"
import { sink } from "./analytics"
export const onUsage = analyticsUsage(sink) // one ai.usage event per call