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.inbounds | create, list, retrieve, reprocess |
lv.leads | list, retrieve, listEvaluations, recordOutcome, clearOutcome |
lv.contacts | list, retrieve, update, listLeads |
lv.profiles | list, create, retrieve, delete, validate, generate, generateCriterion, saveDraft, updateDraft, discardDraft, publish, activate, listVersions, retrieveVersion |
lv.templates | list, retrieve |
lv.sources | list, create, retrieve, update, delete |
lv.destinations | list, create, retrieve, update, delete, rotateSecret, test, listDeliveries, retryDelivery |
lv.events | list, retrieve |
lv.workspaces | list, create, retrieve, update |
lv.apiKeys | list, create, revoke |
lv.billing | retrieve, checkout, changePlan, portal, setSpendLimit |
lv.usage | retrieve — 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.
| Class | When |
|---|---|
InvalidRequestError | 400 — invalid parameters; err.errors lists every field problem |
AuthenticationError | 401 — missing, invalid or revoked key |
PermissionError | 403 — the key's permission or workspace doesn't allow it |
NotFoundError | 404 |
ConflictError | 409 |
QuotaExceededError | 402 — the plan's leads for this period are used up (Plans and limits); not retried |
RateLimitError | 429, after the automatic retries |
APIError | 5xx |
ConnectionError, TimeoutError | the 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
429is retried for every method, honouringRetry-After.5xxand network errors are retried forGET,PUT,PATCH,DELETE, forevaluateandprofiles.validate, and forinbounds.createwith anexternalId— a repeated ID returns the original inbound. OtherPOSTrequests 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 })
| Option | Default | |
|---|---|---|
apiKey | LEADVEYOR_API_KEY | |
workspace | — | For account-wide keys |
baseUrl | https://core.leadveyor.com | Or LEADVEYOR_BASE_URL |
timeout | 60000 | Milliseconds per attempt |
maxRetries | 2 | |
fetch | global fetch | Custom fetch for proxies and tests |
defaultHeaders | — | Added to every request |
Per request: workspace, timeout, maxRetries, signal (an AbortSignal) and headers.
The SDK is generated from the same OpenAPI spec as this reference, so new endpoints appear in it as soon as they ship. Other languages: use the spec with any OpenAPI generator, or call the REST API directly.