twilio-enterprise-knowledge
Add knowledge retrieval to AI agents using Twilio's Enterprise Knowledge product. Enterprise Knowledge is a centralized, searchable repository of your organization's documents, websites, and content — FAQs, support policies, warranty terms, product catalogs. Current models don't have access to how you run your business today. Enterprise Knowledge gives agents a way to query this repository during a conversation and ground their responses in your actual approved source material. This skill covers provisioning a Knowledge Base and uploading knowledge sources from web URLs, PDFs, and raw text, and running semantic search to retrieve relevant chunks at runtime. Enterprise Knowledge is shared across your organization — it captures what your organization knows and how it is meant to run. It is distinct from Conversation Memory (twilio-customer-memory), which is scoped to individual end-customers and captures what you know about a specific person. The two are designed to be combined: enterprise content for business practices, customer memory for personalization.
What this skill does
## Overview
Enterprise Knowledge gives AI and human agents access to your organization's actual source material during a conversation — FAQs, warranty policies, support scripts, product catalogs. Models trained on general data don't know how your business operates today; Enterprise Knowledge closes that gap by letting agents query a searchable repository of your approved content and inject accurate, up-to-date answers rather than hallucinated ones.
```
Your content (web/PDF/text) → Knowledge Base → Indexed chunks
Agent query → Search → Ranked chunks → Inject into LLM prompt
```
Enterprise Knowledge is shared across your organization and captures institutional content: how your products work, what your policies say, what your agents are supposed to do. It is distinct from Conversation Memory, which is scoped to individual end-customers. The two are designed to be combined — enterprise content for accuracy and business practices, customer memory for personalization.
**Auth: Basic Auth** — `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN`.
---
## Prerequisites
- Twilio account with Enterprise Knowledge access (requires enablement)
— New to Twilio? See `twilio-account-setup`
- `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` — see `twilio-iam-auth-setup`
---
## Quickstart
### Step 1 — Create a Knowledge Base
Knowledge Bases are containers for knowledge sources. Creation is async — returns 202, poll the `Location` header until `status: ACTIVE`.
**Python**
```python
import os, requests, time
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
res = requests.post(
"https://memory.twilio.com/v1/ControlPlane/KnowledgeBases",
auth=(account_sid, auth_token),
json={
"displayName": "product-docs", # alphanumeric + hyphens only
"description": "Product documentation for customer support agents"
}
)
operation_url = res.headers["Location"]
# Poll until ready
while True:
kb = requests.get(operation_url, auth=(account_sid, auth_token)).json()
if kb.get("status") == "ACTIVE":
kb_id = kb["id"]
break
if kb.get("status") == "FAILED":
raise Exception("Knowledge Base creation failed")
time.sleep(2)
print(kb_id)
```
**Node.js**
```javascript
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const authHeader = "Basic " + btoa(`${accountSid}:${authToken}`);
const res = await fetch("https://memory.twilio.com/v1/ControlPlane/KnowledgeBases", {
method: "POST",
headers: {
"Authorization": authHeader,
"Content-Type": "application/json",
},
body: JSON.stringify({
displayName: "product-docs",
description: "Product documentation for customer support agents",
}),
});
const operationUrl = res.headers.get("Location");
let kbId;
while (true) {
const kb = await fetch(operationUrl, {
headers: { "Authorization": authHeader },
}).then(r => r.json());
if (kb.status === "ACTIVE") { kbId = kb.id; break; }
if (kb.status === "FAILED") throw new Error("Knowledge Base creation failed");
await new Promise(r => setTimeout(r, 2000));
}
```
### Step 2 — Add a Knowledge Source
Three source types: **Web** (crawl a URL), **File** (upload PDF/CSV/Markdown/text), **Text** (inline raw text).
#### Web source
```python
knowledge = requests.post(
f"https://knowledge.twilio.com/v1/KnowledgeBases/{kb_id}/Knowledge",
auth=(account_sid, auth_token),
json={
"name": "Product Documentation",
"description": "Public product docs",
"source": {
"type": "Web",
"url": "https://docs.example.com",
"crawlDepth": 3, # 1–10, default 2
"crawlPeriod": "WEEKLY" # WEEKLY | BIWEEKLY | MONTHLY | NEVER
}
}
).json()
knowledge_id = knowledge["id"]
```
#### File source (PDF, CSV, Markdown, TSV, plain text — max 16MB)
```python
# Step 1: Create the source — returns a presigned upload URL
knowledge = requests.post(
f"https://knowledge.twilio.com/v1/KnowledgeBases/{kb_id}/Knowledge",
auth=(account_sid, auth_token),
json={
"name": "Company Handbook",
"source": {
"type": "File",
"fileName": "handbook.pdf",
"fileSize": 2048576,
"mimeType": "application/pdf"
}
}
).json()
knowledge_id = knowledge["id"]
upload_url = knowledge["source"]["importUrl"] # presigned S3 URL
# Step 2: PUT file to presigned URL — no auth header, URL is already signed
with open("handbook.pdf", "rb") as f:
requests.put(upload_url, data=f, headers={"Content-Type": "application/pdf"})
```
#### Text source (inline content, max 185,000 chars)
```python
knowledge = requests.post(
f"https://knowledge.twilio.com/v1/KnowledgeBases/{kb_id}/Knowledge",
auth=(account_sid, auth_token),
json={
"name": "Refund Policy",
"source": {
"type": "Text",
"content": "Our refund policy: customers may return items within 30 days..."
}
}
).json()
```
### Step 3 — Wait for Processing
Knowledge sources are processed asynchronously. Poll until `status` is `COMPLETED`.
```python
def wait_for_knowledge(kb_id, knowledge_id):
while True:
k = requests.get(
f"https://knowledge.twilio.com/v1/KnowledgeBases/{kb_id}/Knowledge/{knowledge_id}",
auth=(account_sid, auth_token)
).json()
if k["status"] == "COMPLETED":
return k
if k["status"] == "FAILED":
raise Exception(f"Knowledge processing failed: {k}")
time.sleep(3)
wait_for_knowledge(kb_id, knowledge_id)
```
Statuses: `SCHEDULED` → `QUEUED` → `PROCESSING` → `COMPLETED` / `FAILED`
### Step 4 — Search and Inject into LLM
**Python**
```python
results = requests.post(
f"https://knowledge.twilio.com/v1/KnowledgeBases/{kb_id}/Search",
auth=(account_sid, auth_token),
json={
"query": "How do I reset my password?",
"top": 5, # max 20
"knowledgeIds": [knowledge_id] # optional — search specific sources
}
).json()
chunks = "\n\n".join(c["content"] for c in results.get("chunks", []))
system_prompt = f"""You are a helpful support agent.
Relevant knowledge:
{chunks}
Answer the customer's question using only the above content."""
```
**Node.js**
```javascript
const results = await fetch(
`https://knowledge.twilio.com/v1/KnowledgeBases/${kbId}/Search`,
{
method: "POST",
headers: {
"Authorization": authHeader,
"Content-Type": "application/json",
},
body: JSON.stringify({
query: userMessage,
top: 5,
knowledgeIds: [knowledgeId],
}),
}
).then(r => r.json());
const chunks = results.chunks.map(c => c.content).join("\n\n");
const systemPrompt = `You are a helpful support agent.\n\nRelevant knowledge:\n${chunks}`;
```
---
## Key Patterns
### Combine Enterprise Knowledge with Conversation Memory Recall
For the best agent responses, combine both: Enterprise Knowledge for company content, Recall for individual customer history.
**Python**
```python
# Run both in parallel
recall_res = requests.post(
f"https://memory.twilio.com/v1/Services/{MEMORY_STORE_SID}/Profiles/{profile_id}/Recall",
auth=(account_sid, auth_token),
json={"query": user_query, "observationsLimit": 5}
)
search_res = requests.post(
f"https://knowledge.twilio.com/v1/KnowledgeBases/{KB_ID}/Search",
auth=(account_sid, auth_token),
json={"query": user_query, "top": 3}
)
customer_history = "\n".join(o["content"] for o in recall_res.json().get("observations", []))
knowledge_chunks = "\n\n".join(c["content"] for c in search_res.json().get("chunks", []))
system_prompt = f"""Customer history:
{customer_history}
Relevant documentation:
{knowledge_chunks}"""
```
### Refresh Stale WRelated in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.