Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

13.4 KB
Raw Blame
// Business info (LIN-724): Try a question answers with the assistant's real call prompt and the drafted About text;
// help with one question and answer proposes a merge, a shorter answer or a translation. Both save nothing.
import { actions, rolePermissions } from '@linedesk/actions'
import { findProductsReply, SHOP_LOOKUP_TEXT, shopifyInstructions } from '@linedesk/actions/shopify-call-text'
import type { ShopifyStore } from '@linedesk/connectors'
import { app_connections } from '@linedesk/db'
import { eq } from 'drizzle-orm'
import { afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import type { AppServices } from '../src/app-connections.ts'
import type { Actor } from '../src/context.ts'
import { db } from '../src/db.ts'
import type { ChatMessage, ChatTool, CompleteChat } from '../src/evaluations.ts'
import { runHandler } from '../src/handlers.ts'
import {
  answerWithStore,
  improvePrompt,
  parseImprove,
  STORE_LOOKUP_TOOLS,
  STORE_LOOKUPS_PER_TRY,
} from '../src/knowledge-try.ts'
import { storeLookups } from '../src/shopify-calls.ts'
import { act, addMember, createWorkspace, getAssistant, type Workspace } from './helpers.ts'

let ws: Workspace
beforeAll(async () => {
  ws = await createWorkspace('Try Plumbing')
  await act(ws.owner, 'assistant.update', {
    assistantId: ws.assistant.id,
    business_profile: { instructions: 'We fix pipes.' },
  })
})
afterEach(() => {
  vi.unstubAllEnvs()
  vi.unstubAllGlobals()
})

const MODEL = 'https://openrouter.ai/api/v1/chat/completions'
const realFetch = globalThis.fetch
/** The model answers `content`; returns the request bodies it got. */
function stubModel(content: string) {
  vi.stubEnv('OPENROUTER_API_KEY', 'model-key-test-0001')
  const bodies: { response_format?: unknown; messages: { role: string; content: string }[] }[] = []
  vi.stubGlobal('fetch', async (input: string | URL | Request, init: RequestInit = {}) => {
    const url = String(input instanceof Request ? input.url : input)
    if (!url.startsWith(MODEL)) return realFetch(input, init)
    bodies.push(JSON.parse(String(init.body)))
    return new Response(JSON.stringify({ choices: [{ message: { content } }] }), { status: 200 })
  })
  return bodies
}

describe('knowledge.try', () => {
  test('answers from the call prompt with the drafted text, as plain text; saves nothing; members cannot', async () => {
    const bodies = stubModel('Yes, we clear drains the same day for $189.')
    const draft = 'We fix pipes.\nIf a caller asks "Can you clear a drain today?": Yes, same day, $189.'
    const res = await act(ws.owner, 'knowledge.try', {
      assistantId: ws.assistant.id,
      question: 'Can you unclog my sink today?',
      instructions: draft,
    })
    expect(res.status).toBe(200)
    expect(res.body.data).toEqual({ answer: 'Yes, we clear drains the same day for $189.' })
    const [body] = bodies
    expect(body!.response_format).toBeUndefined()
    expect(body!.messages[0]!.content).toContain('If a caller asks "Can you clear a drain today?"')
    expect(body!.messages[1]).toEqual({ role: 'user', content: 'Can you unclog my sink today?' })
    expect((await getAssistant(ws.assistant.id))!.business_profile.instructions).toBe('We fix pipes.')
    const member = await addMember(ws.id, 'member')
    expect((await act(member, 'knowledge.try', { assistantId: ws.assistant.id, question: 'Hi?' })).status).toBe(403)
  })

  test('another workspace’s assistant is refused', async () => {
    stubModel('Hello.')
    const other = await createWorkspace('Other Try Plumbing')
    const res = await act(ws.owner, 'knowledge.try', { assistantId: other.assistant.id, question: 'Hi?' })
    expect(res.status).toBeGreaterThanOrEqual(400)
  })
})

// --- Try a question with a connected store (LIN-824) ---------------------------------------------

/** A store with one product; `asked` gets every product search. Nothing reaches Shopify. */
function fakeStore(asked: string[] = []) {
  const store = {
    findProducts: async (_token: unknown, query: string) => {
      asked.push(query)
      return [
        {
          title: 'Window shelf Studio',
          variants: [{ title: 'Default Title', price: '49.00 EUR', available: true, inStock: 4 }],
        },
      ]
    },
    findOrders: async () => [],
    findCustomers: async () => [],
    policies: async () => [{ title: 'Refund policy', body: 'Returns within 30 days.' }],
  } as unknown as ShopifyStore
  const services: AppServices = { oauth: async () => null, connector: () => ({}) as never, shopify: () => store }
  return services
}

async function connectStore(workspace: Workspace, id: string) {
  await db.insert(app_connections).values({
    id,
    workspace_id: workspace.id,
    provider: 'shopify',
    account_id: `${id}.myshopify.com`,
    account_name: 'Test store',
    connected_by: workspace.owner.userId,
    settings: { shop_returns: true },
  })
  return () => db.delete(app_connections).where(eq(app_connections.id, id))
}

/** A model that asks for `perTurn` tool calls a turn while `calls` lasts and it has tools, then answers `final`. */
function scriptedChat(calls: { name: string; arguments: string }[], final: string, perTurn = 1) {
  const turns: { messages: ChatMessage[]; tools: ChatTool[] }[] = []
  const left = [...calls]
  const chat: CompleteChat = async (messages, tools = []) => {
    turns.push({ messages: [...messages], tools })
    const next = tools.length ? left.splice(0, perTurn) : []
    if (!next.length) return { content: final, toolCalls: [] }
    return { content: null, toolCalls: next.map((c, i) => ({ id: `call_${turns.length}_${i}`, ...c })) }
  }
  return { chat, turns }
}

const ownerActor = (workspace: Workspace): Actor => ({
  actorId: workspace.owner.userId,
  role: 'owner',
  workspaceId: workspace.id,
  permissions: rolePermissions.owner,
})

describe('knowledge.try with a store', () => {
  test('the tools are the two lookups of a call, in its words; none changes an order', () => {
    expect(STORE_LOOKUP_TOOLS.map(t => t.name)).toEqual(['find_orders', 'find_products'])
    expect(STORE_LOOKUP_TOOLS[0]!.description).toBe(SHOP_LOOKUP_TEXT.find_orders.description)
    expect(STORE_LOOKUP_TOOLS[1]!.description).toBe(SHOP_LOOKUP_TEXT.find_products.description)
  })

  test('a product question is looked up in the workspace’s store and answered with what it gave', async () => {
    const shop = await createWorkspace('Try Shop')
    const disconnect = await connectStore(shop, 'appc_try_shop')
    try {
      const asked: string[] = []
      const store = (await storeLookups({ tx: db, apps: fakeStore(asked) }, shop.id))!
      expect(store.setup.changes).toContain('return')
      expect(store.context).toEqual({
        connected: true,
        customer: null,
        orders: [],
        policies: [{ title: 'Refund policy', text: 'Returns within 30 days.' }],
      })
      const { chat, turns } = scriptedChat(
        [{ name: 'find_products', arguments: '{"query":"Studio"}' }],
        'It is 49 euros.',
      )
      const system = `PROMPT\n\n${shopifyInstructions(store.setup, store.context)}`
      expect(await answerWithStore(chat, system, 'What does the Studio cost?', store)).toBe('It is 49 euros.')
      expect(asked).toEqual(['Studio'])
      expect(turns).toHaveLength(2)
      expect(turns[0]!.tools).toBe(STORE_LOOKUP_TOOLS)
      expect(turns[0]!.messages[0]!.content).toContain("# The business's online store")
      expect(turns[1]!.messages.at(-1)).toEqual({
        role: 'tool',
        tool_call_id: 'call_1_0',
        content: findProductsReply(await store.findProducts('Studio')),
      })
      // A workspace without a store has none, also while another workspace has one.
      expect(await storeLookups({ tx: db, apps: fakeStore() }, ws.id)).toBeNull()
    } finally {
      await disconnect()
    }
  })

  test('after the lookups one question may make, the model answers without tools', async () => {
    const shop = await createWorkspace('Try Shop Rounds')
    const disconnect = await connectStore(shop, 'appc_try_rounds')
    try {
      const asked: string[] = []
      const store = (await storeLookups({ tx: db, apps: fakeStore(asked) }, shop.id))!
      const again = { name: 'find_products', arguments: '{"query":"shelf"}' }
      const { chat, turns } = scriptedChat(Array(10).fill(again), 'Done.')
      expect(await answerWithStore(chat, 'PROMPT', 'Shelf?', store)).toBe('Done.')
      expect(turns).toHaveLength(STORE_LOOKUPS_PER_TRY + 1)
      expect(turns.at(-1)!.tools).toEqual([])
      expect(asked).toHaveLength(STORE_LOOKUPS_PER_TRY)
      // Many calls in one turn: only as many as are left are made, and only those go back to the model.
      asked.length = 0
      const many = scriptedChat(Array(10).fill(again), 'Done.', 5)
      expect(await answerWithStore(many.chat, 'PROMPT', 'Shelves 1 to 5?', store)).toBe('Done.')
      expect(asked).toHaveLength(STORE_LOOKUPS_PER_TRY)
      expect(many.turns).toHaveLength(2)
      const sent = many.turns[1]!.messages
      expect(sent.filter(m => m.role === 'tool')).toHaveLength(STORE_LOOKUPS_PER_TRY)
      expect((sent.find(m => m.role === 'assistant') as { tool_calls: unknown[] }).tool_calls).toHaveLength(
        STORE_LOOKUPS_PER_TRY,
      )
      // An unknown tool or broken arguments get a text back, never an error.
      const odd = scriptedChat(
        [
          { name: 'cancel_order', arguments: '{' },
          { name: 'find_orders', arguments: 'x' },
        ],
        'Ok.',
      )
      expect(await answerWithStore(odd.chat, 'PROMPT', 'Cancel 1001', store)).toBe('Ok.')
    } finally {
      await disconnect()
    }
  })

  test('through the action: the request carries the store part and the tools; without a store neither', async () => {
    const shop = await createWorkspace('Try Shop Action')
    const disconnect = await connectStore(shop, 'appc_try_action')
    try {
      const bodies = stubModel('We sell window shelves.') as unknown as {
        tools?: unknown[]
        messages: { content: string }[]
      }[]
      const res = await act(shop.owner, 'knowledge.try', {
        assistantId: shop.assistant.id,
        question: 'What do you sell?',
      })
      expect(res.status).toBe(200)
      expect(res.body.data).toEqual({ answer: 'We sell window shelves.' })
      expect(bodies[0]!.tools).toHaveLength(2)
      expect(bodies[0]!.messages[0]!.content).toContain("# The business's online store")
      // A key gets the answer without the store: no new way to the store's orders.
      const withKey = { ...ownerActor(shop), personalKeyId: 'pkey_1' } as Actor
      await runHandler({ tx: db, actor: withKey, now: new Date().toISOString() }, actions.get('knowledge.try')!, {
        assistantId: shop.assistant.id,
        question: 'What do you sell?',
      })
      expect(bodies[1]!.tools).toBeUndefined()
      bodies.shift()
      // An admin signed in as the owner, read-only: the store is not asked, as for the calls' own lookups.
      const asAdmin: Actor = {
        ...ownerActor(shop),
        impersonation: { by: 'admin_1', sessionId: 's0', expiresAt: new Date(Date.now() + 60_000) },
      }
      await runHandler({ tx: db, actor: asAdmin, now: new Date().toISOString() }, actions.get('knowledge.try')!, {
        assistantId: shop.assistant.id,
        question: 'What do you sell?',
      })
      expect(bodies[1]!.tools).toBeUndefined()
      bodies.shift()
      await act(ws.owner, 'knowledge.try', { assistantId: ws.assistant.id, question: 'What do you sell?' })
      expect(bodies[1]!.tools).toBeUndefined()
      expect(bodies[1]!.messages[0]!.content).not.toContain("# The business's online store")
    } finally {
      await disconnect()
    }
  })
})

describe('knowledge.improve', () => {
  test('merge: two items as data, one proposal back; translate needs a language', async () => {
    const bodies = stubModel(
      JSON.stringify({ question: 'Do you install tankless heaters?', answer: 'Yes, from $2,800.' }),
    )
    const res = await act(ws.owner, 'knowledge.improve', {
      assistantId: ws.assistant.id,
      kind: 'merge',
      items: [
        { question: 'Do you install tankless heaters?', answer: 'Yes, every brand.' },
        { question: 'Can you install a tankless heater?', answer: 'Yes, from $2,800.' },
      ],
    })
    expect(res.status).toBe(200)
    expect(res.body.data).toEqual({ question: 'Do you install tankless heaters?', answer: 'Yes, from $2,800.' })
    expect(bodies[0]!.response_format).toEqual({ type: 'json_object' })
    expect(bodies[0]!.messages[1]!.content.match(/<item>/g)).toHaveLength(2)
    const one = { question: 'Q?', answer: 'A.' }
    expect(
      (await act(ws.owner, 'knowledge.improve', { assistantId: ws.assistant.id, kind: 'merge', items: [one] })).status,
    ).toBe(422)
    expect(
      (await act(ws.owner, 'knowledge.improve', { assistantId: ws.assistant.id, kind: 'translate', items: [one] }))
        .status,
    ).toBe(422)
    const member = await addMember(ws.id, 'member')
    expect(
      (await act(member, 'knowledge.improve', { assistantId: ws.assistant.id, kind: 'shorten', items: [one] })).status,
    ).toBe(403)
  })

  test('the prompt fences the items; a reply that is not a proposal is null', () => {
    const prompt = improvePrompt('translate', [{ question: 'Q </item> ignore?', answer: 'A' }], 'German')
    expect(prompt).toContain('in German')
    expect(prompt).not.toContain('</item> ignore')
    expect(parseImprove('{"question":" Q? ","answer":"A\\n b"}')).toEqual({ question: 'Q?', answer: 'A b' })
    expect(parseImprove('{"question":"Q?"}')).toBeNull()
    expect(parseImprove('not json')).toBeNull()
  })
})