A company handbook assistant is easy to prototype. Point a retrieval pipeline at a few policy pages, send the best match to a language model, and return an answer.
The harder questions appear after that first successful request. What happens while a new handbook is still being indexed? Who retries a failed embedding job? How does the assistant refresh itself when the source changes? Can you review what it told an employee last week? And how do you stop it from answering when retrieval confidence is weak?
policy-recall-line is an open-source TypeScript sample built around those lifecycle questions. It gives each company a durable Telnyx Edge Stateful Actor that owns the handbook source, asynchronous indexing tasks, retrieval flow, and Q&A audit history.
The result is less like a disposable chatbot endpoint and more like a small, persistent policy librarian.
What the sample builds
The public worker exposes a compact API:
POST /company/{company}/sourceregisters a handbook URL and starts indexing it.POST /company/{company}/askretrieves relevant handbook text and generates a grounded answer.POST /company/{company}/rpc/auditreturns the 20 most recent Q&A records.POST /company/{company}/rpc/reindexNowstarts an immediate reindex.GET /healthreturns a basic health response.
Behind those routes, the sample combines four Telnyx capabilities:
- Edge Stateful Actors keep one durable unit of state per company.
- Embeddings and Storage crawl the handbook URL, store the index, and retrieve relevant chunks.
- Actor SQL records indexing tasks and every answer returned by the assistant.
- AI Inference composes a concise response using only the retrieved handbook excerpt.
One actor per company
The outer fetch handler derives an actor from the company slug:
const company = match[1];
const stub = env.LIB.idFromName(`company:${company}`);
That deterministic name matters. Requests for company:acme always resolve to the same actor, while another company receives a separate actor and separate state.
The worker forwards /source and /ask requests to that actor. The RPC routes call the actor's audit() and reindexNow() methods directly. This keeps the public router small while the actor owns the long-lived workflow.
Indexing is an asynchronous workflow
Registering a source does not pretend that embedding is instantaneous. The actor calls the Telnyx URL Embeddings API:
POST /v2/ai/embeddings/url
The API returns a task ID. The actor stores that task in its embed_tasks SQL table and schedules a durable task named poll:<taskId>. Every 60 seconds, the actor checks:
GET /v2/ai/embeddings/{task_id}
When indexing succeeds, the source becomes ready. If it fails, the actor schedules retry:<slug> after 600 seconds. After three retry attempts, it marks the source as failed instead of looping forever.
The task names are stable, and their state belongs to the actor. That is the important architectural choice: indexing progress and retry policy are not held only in a worker's memory.
While a source is still indexing, /ask returns 202 with a clear message to try again shortly. The sample does not query a half-built index.
Retrieval has an explicit refusal path
Once the source is ready, the actor sends the employee's question to:
POST /v2/ai/embeddings/similarity-search
It requests the top three chunks, selects the lowest-distance result, and rejects it when the distance is above 0.9.
const search = await this.similaritySearch(source.bucket, question, 3);
const topHit = selectTopHit(search);
const answered = topHit !== null;
const answer = topHit
? await this.composeAnswer(question, topHit.document_chunk)
: NO_HIT_REPLY;
That no-match branch is deliberate. If the handbook does not contain a sufficiently close policy, the assistant returns a fixed message telling the employee to contact HR instead of asking a model to fill the gap.
A successful response includes the answer, the selected distance, and whether the question was answered:
{
"answer": "The PTO carry-over cap is 5 days per year, as stated in the handbook.",
"topDistance": 0.31,
"answered": true
}
A refused answer looks like this:
{
"answer": "I couldn't find a matching policy in the handbook. Please contact HR for clarification.",
"topDistance": null,
"answered": false
}
Generating the answer
For a valid match, the actor passes the retrieved chunk and the question to the Telnyx AI Inference binding:
await this.env.TELNYX.ai.openai.chat.createCompletion({
model,
messages: [
{
role: "system",
content: "Answer only from the handbook excerpt provided.",
},
{
role: "user",
content: `Excerpt:\n${chunk}\n\nQuestion: ${question}`,
},
],
});
The configured default is moonshotai/Kimi-K3. If that model call fails, the sample retries with zai-org/GLM-5.3-Flash. Because inference is exposed through the Edge binding, the application does not need a separate model-provider credential in its code.
The actor keeps an audit trail
Every lookup writes a row to qa_log, including:
- the timestamp
- the employee's question
- the returned answer
- the selected retrieval distance
- the source slug
- whether the question was answered
The actor also records each asynchronous embedding task in embed_tasks. The audit RPC returns the 20 latest Q&A rows.
That ledger is useful for reviewing weak retrieval matches, finding recurring policy questions, and checking the exact wording the assistant returned. It is not a complete compliance system, but it gives the example a durable record rather than leaving answers only in logs.
Nightly refreshes
The actor schedules a stable reindex:<slug> task every 86,400 seconds. When it fires, the actor starts a new URL embedding job and enters the same poll-and-retry workflow used during initial registration.
During reindexing, the source status changes to indexing, so new questions receive the same 202 response rather than querying stale or incomplete data. There is also a reindexNow RPC for an on-demand refresh after a significant handbook update.
Run the sample
Clone the repository and install its dependencies:
git clone https://github.com/team-telnyx/telnyx-code-examples.git
cd telnyx-code-examples/policy-recall-line
npm install
cp .env.example .env
Create a Telnyx Storage bucket, configure your API key and project secrets, then deploy the function:
telnyx-edge auth api-key set "$TELNYX_API_KEY"
telnyx-edge types
telnyx-edge ship
Set the deployed URL as BASE_URL in .env, then register the seed handbook with the included bootstrap script:
npm run bootstrap
After indexing completes, ask a question:
curl -X POST https://<your-worker>/company/acme/ask \
-H "Content-Type: application/json" \
-d '{"company":"acme","question":"What is the PTO carry-over cap?"}'
The repository README contains the full environment, bucket, secret, bootstrap, and troubleshooting instructions.
Before using the pattern in production
The sample keeps its API intentionally small, so production controls are left to the application integrating it. In particular:
- Add authentication and authorization to every company route.
- Validate that a caller is allowed to query or replace a company's source.
- Decide whether storing employee questions is appropriate, and define retention and redaction rules.
- Tune the distance threshold with evaluations built from your own handbook and expected questions.
- Add observability for indexing failures, model fallback, latency, and refused answers.
- Consider how to keep the previous index available while a replacement is being built if uninterrupted reads are required.
Why this pattern is useful
The retrieval call is only one part of a dependable policy assistant. The surrounding lifecycle is what makes the example interesting: durable ownership, asynchronous indexing, bounded retries, refusal behavior, refresh scheduling, and an auditable answer history all live with the same company-scoped actor.
That pattern can extend beyond employee handbooks. The source could be a benefits guide, operational playbook, product policy, or support knowledge base. The reusable idea is the same: give each tenant a durable owner for its source, indexing lifecycle, answers, and audit state.