TypeScript SDK

@leadveyor/sdk is the official client for Node.js, Bun, Deno, Cloudflare Workers and any runtime with fetch. Every method, parameter and response is typed from the API spec; it has no dependencies.

npm install @leadveyor/sdk

Quick start

import Leadveyor from '@leadveyor/sdk'

const lv = new Leadveyor(process.env.LEADVEYOR_API_KEY) // lv_live_… or lv_test_…

const inbound = await lv.inbounds.create(
  { text: 'Hi, we need catering for 80 guests on 12 March in Richmond. Budget around $6k.' },
  { wait: true },
)
const lead = inbound.leads?.[0]
console.log(lead?.evaluation.tier, lead?.evaluation.score)

Create a key in the console or through the API. Without an argument the client reads the LEADVEYOR_API_KEY environment variable.

Resources

Methods follow the API one to one. The last argument of every method takes per-request options.

Methods
lv.inboundscreate, list, retrieve, reprocess
lv.leadslist, retrieve, listEvaluations, recordOutcome, clearOutcome
lv.contactslist, retrieve, update, listLeads
lv.profileslist, create, retrieve, delete, validate, generate, generateCriterion, saveDraft, updateDraft, discardDraft, publish, activate, listVersions, retrieveVersion
lv.templateslist, retrieve
lv.sourceslist, create, retrieve, update, delete
lv.destinationslist, create, retrieve, update, delete, rotateSecret, test, listDeliveries, retryDelivery
lv.eventslist, retrieve
lv.workspaceslist, create, retrieve, update
lv.apiKeyslist, create, revoke
lv.billingretrieve, checkout, changePlan, portal, setSpendLimit
lv.usageretrieve — this period's leads against the plan
lv.evaluate()Score a message without saving anything (Evaluate)

Object types are exported: import type { Lead, Profile, Inbound } from '@leadveyor/sdk'.

// Record what happened to a lead — this is what teaches scoring what "good" means
await lv.leads.recordOutcome('lead_2Ph6Tc9Ks4Wm1Lx7Qv3Nb8Dr', { status: 'won', amount: 6200 })

// Start a profile from a plain-language description
const { profile, assumptions } = await lv.profiles.generate({
  brief: 'Plumbing in Melbourne. Emergencies and bathroom renovations are the best jobs; no commercial work.',
})

Pagination

List methods return a page when awaited and every item when iterated — see Pagination.

const page = await lv.leads.list({ tier: 'hot', limit: 50 }) // { data, has_more, next_cursor }

for await (const lead of lv.leads.list({ outcome: 'none' })) {
  console.log(lead.id, lead.evaluation.score) // next pages are fetched as you go
}

const recent = await lv.events.list({ type: 'lead.*' }).toArray({ limit: 500 })

Webhooks

constructEvent checks the Leadveyor-Signature header and returns the event, typed by event.type. Pass the raw request body — parsed and re-serialised JSON won't match the signature.

Express

import express from 'express'
import Leadveyor, { WebhookSignatureError } from '@leadveyor/sdk'

const app = express()

app.post('/leadveyor-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  let event
  try {
    event = await Leadveyor.webhooks.constructEvent(
      req.body,
      req.headers['leadveyor-signature'],
      process.env.LEADVEYOR_WEBHOOK_SECRET, // whsec_…
    )
  } catch (err) {
    if (err instanceof WebhookSignatureError) return res.sendStatus(400)
    throw err
  }
  if (event.type === 'lead.scored') await saveLead(event.data.object)
  res.sendStatus(200)
})

Next.js

import Leadveyor from '@leadveyor/sdk'

export async function POST(req: Request) {
  const event = await Leadveyor.webhooks.constructEvent(
    await req.text(),
    req.headers.get('leadveyor-signature'),
    process.env.LEADVEYOR_WEBHOOK_SECRET!,
  )
  if (event.type === 'lead.scored') await saveLead(event.data.object)
  return new Response(null, { status: 200 })
}

Leadveyor.webhooks.verify(…) returns true / false instead of throwing. generateTestHeader(payload, secret) signs a payload the way Leadveyor does, for testing your handler. More on events and retries: Webhooks.

Workspaces

A workspace key works in its own workspace. With an account-wide key — an agency serving several businesses — choose the workspace per client or per request:

const acme = lv.withWorkspace('ws_1Bq7Xn4KpRz9Lc2Vt6Hy0Mde')
await acme.leads.list()

await lv.leads.list({}, { workspace: 'ws_1Bq7Xn4KpRz9Lc2Vt6Hy0Mde' })

Errors

Failed calls throw a subclass of LeadveyorError with the fields of the error envelope: type, code, message, param, errors and requestId.

ClassWhen
InvalidRequestError400 — invalid parameters; err.errors lists every field problem
AuthenticationError401 — missing, invalid or revoked key
PermissionError403 — the key's permission or workspace doesn't allow it
NotFoundError404
ConflictError409
QuotaExceededError402 — the plan's leads for this period are used up (Plans and limits); not retried
RateLimitError429, after the automatic retries
APIError5xx
ConnectionError, TimeoutErrorthe API could not be reached, or did not answer in time
import { NotFoundError } from '@leadveyor/sdk'

try {
  await lv.leads.retrieve(id)
} catch (err) {
  if (err instanceof NotFoundError) return null
  throw err
}

Retries and timeouts

  • 429 is retried for every method, honouring Retry-After.
  • 5xx and network errors are retried for GET, PUT, PATCH, DELETE, for evaluate and profiles.validate, and for inbounds.create with an externalId — a repeated ID returns the original inbound. Other POST requests are not repeated, because they may already have been applied.
  • Two retries by default, with exponential backoff.
const lv = new Leadveyor(key, { maxRetries: 4, timeout: 30_000 })
await lv.evaluate({ text }, { timeout: 120_000 })
OptionDefault
apiKeyLEADVEYOR_API_KEY
workspace—For account-wide keys
baseUrlhttps://core.leadveyor.comOr LEADVEYOR_BASE_URL
timeout60000Milliseconds per attempt
maxRetries2
fetchglobal fetchCustom fetch for proxies and tests
defaultHeaders—Added to every request

Per request: workspace, timeout, maxRetries, signal (an AbortSignal) and headers.

Was this page helpful?