Backend/AI models

AI models

Connect the agent chat and AI features to a real model provider, such as Anthropic or OpenAI, through a server route so your API key never reaches the browser.

Where AI is scripted today

FeatureWhere the answer comes from
Agent chat (Rune and your agents)createAssistantReply() in src/lib/chat.ts. Contract summaries, payment reminders and receivables answers are built from your records; other prompts cycle through scripted answers.
Task requests in the chatHandled before the agent: they create a real task in the app
Pipeline questions and adding a leadsrc/lib/lead-ai.ts
People, relationships, overdue and upcoming invoicessrc/lib/network-ai.ts
Payment reminders and receivablessrc/lib/finance-answers.ts
Finding, summarising and drafting emailsrc/lib/email-ai.ts
Making a whiteboard from a templatesrc/lib/board-ai.ts
Write with AI in notessrc/lib/note-ai-draft.ts
New workflow from a descriptionsrc/lib/workflow-draft.ts

createAssistantReply() checks these in order (boards, email, leads, people and invoices, contracts, reminders, receivables) and falls back to the scripted answers. The chat already shows a thinking stage and types each reply out word by word, so it looks the same once real replies arrive.

Add a server route

Create a Route Handler that holds your API key, calls the model and streams the text back. Install the provider's SDK, put the key in .env.local and choose a model from the provider's docs. Two examples:

src/app/api/chat/route.ts (Anthropic)
import Anthropic from "@anthropic-ai/sdk"

const client = new Anthropic() // reads ANTHROPIC_API_KEY

export async function POST(req: Request) {
  // Check who's signed in here before calling the model
  const { messages } = await req.json() // [{ role: "user" | "assistant", content }]
  const stream = client.messages.stream({
    model: process.env.ANTHROPIC_MODEL!,
    max_tokens: 1024,
    system: "You are Rune, a CRM assistant.",
    messages,
  })
  const encoder = new TextEncoder()
  const body = new ReadableStream({
    async start(controller) {
      stream.on("text", (text) => controller.enqueue(encoder.encode(text)))
      await stream.finalMessage()
      controller.close()
    },
  })
  return new Response(body, { headers: { "Content-Type": "text/plain; charset=utf-8" } })
}
src/app/api/chat/route.ts (OpenAI)
import OpenAI from "openai"

const client = new OpenAI() // reads OPENAI_API_KEY

export async function POST(req: Request) {
  // Check who's signed in here before calling the model
  const { messages } = await req.json() // [{ role: "user" | "assistant", content }]
  const stream = await client.responses.create({
    model: process.env.OPENAI_MODEL!,
    instructions: "You are Rune, a CRM assistant.",
    input: messages,
    stream: true,
  })
  const encoder = new TextEncoder()
  const body = new ReadableStream({
    async start(controller) {
      for await (const event of stream)
        if (event.type === "response.output_text.delta")
          controller.enqueue(encoder.encode(event.delta))
      controller.close()
    },
  })
  return new Response(body, { headers: { "Content-Type": "text/plain; charset=utf-8" } })
}

Check the session at the top of the route. Without it, anyone who finds the URL can use your API key.

Connect the chat

  1. In chat-provider.tsx, the reply is created right away and added after a short pause. Instead, add an empty reply, then call /api/chat with the conversation so far.
  2. Read the response as it streams and append each piece of text to that reply, so it fills in live.
  3. Turn off the chat's simulated typing for live replies, since the text now arrives piece by piece.
  4. Keep the task requests and record-based answers if you like them: only send other prompts to the model. To let the model answer from records itself, pass the relevant ones into the conversation.
  5. Show a short error in the chat if the request fails, so people can try again.

Write with AI and workflow drafts follow the same pattern: replace the draft function with a call to a server route.

Give the model tools

Each answer file above shows which facts Rune needs for a kind of question. With a real model, turn each one into a tool: the model decides which to call, your route runs it against your database, and the model writes the reply from what comes back.

ToolReplacesReturns or does
find_leadslead-ai.tsOpen leads filtered by stage, owner, close month or gone quiet
create_leadlead-ai.tsAdds a lead and returns its id
find_peoplenetwork-ai.tsDecision makers, who knows someone best, relationships going cold
list_invoicesnetwork-ai.ts, finance-answers.tsOverdue or upcoming invoices, with the billing contact
search_emailsemail-ai.tsThreads by sender, company, date or topic
draft_emailemail-ai.ts, finance-answers.tsA draft that opens in the composer; never sent by the model
create_boardboard-ai.tsA board from a template, filled in for a customer
Tool definitions (Anthropic)
const tools = [
  {
    name: "find_leads",
    description: "Open sales leads. Use for questions about the pipeline.",
    input_schema: {
      type: "object",
      properties: {
        stage: { type: "string", enum: ["new", "qualified", "proposal", "negotiation"] },
        closingMonth: { type: "string", description: "YYYY-MM" },
        quiet: { type: "boolean", description: "No activity for 7 days or more" },
      },
    },
  },
  // find_people, list_invoices, search_emails, draft_email, create_board…
]

Run the tools on the server with the signed-in person's access, so the model only sees what they could see. Send the ids it used back with the reply in the fields the chat already understands (leads, people, invoices, emails, boards and emailDraft on ChatMessage), and the chat shows the same cards as today.

Keep the demo's rules: when a tool changes something (adding a lead, making a board), the reply shows a card for what it made so the person can check it, and email is only ever drafted. Let the person press Send.

Cost and limits

  • Cap reply length with max_tokens (Anthropic) or max_output_tokens (OpenAI), and send only as much history as you need.
  • Limit use per person, for example a number of messages per minute and per day, checked in the route.
  • Set a spending limit or alert in your provider's dashboard.
  • Handle rate limits. Providers reject requests when you send too many; show a friendly “try again in a moment” message instead of a broken reply.