Feed knowledge from your website
This guide creates a knowledge base with your website's content. The script reads sitemap.xml, imports each page by its address and uploads the PDFs. At the end it says how many documents it imported and which ones failed.
Before you start
- An API key with the Conhecimento — escrita (
knowledge:write) scope. - The address of your website's
sitemap.xml. - Python 3.11 or later with
requests, or Node.js 18 or later.
The script
import os
import re
import time
from urllib.parse import urlparse
import requests
API = "https://api.diska.ai/v1"
SITEMAP = "https://www.exemplo.ao/sitemap.xml" # your website's sitemap
MAX_PAGES = 100
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['DISKA_API_KEY']}"
def post(path: str, **kwargs) -> requests.Response:
while True:
response = session.post(f"{API}{path}", timeout=60, **kwargs)
if response.status_code == 429: # rate limit: wait as long as the API says
time.sleep(int(response.headers.get("Retry-After", "5")))
continue
return response
# 1. A new base for the website's content.
response = post("/knowledge-bases", json={
"name": "Website",
"instruction": "Use this base to answer questions about the company, its products and prices, with the information on the website.",
})
response.raise_for_status()
base_id = response.json()["id"]
# 2. The sitemap's pages.
sitemap = requests.get(SITEMAP, timeout=30)
sitemap.raise_for_status()
urls = re.findall(r"<loc>\s*([^<\s]+)\s*</loc>", sitemap.text)[:MAX_PAGES]
# 3. Each page as a document: web pages by URL, PDFs by upload.
imported, failed = 0, []
for url in urls:
name = urlparse(url).path.strip("/") or "Home page"
if url.lower().endswith(".pdf"):
pdf = requests.get(url, timeout=60)
result = post(f"/knowledge-bases/{base_id}/documents/pdf",
files={"file": (name, pdf.content, "application/pdf")})
else:
result = post(f"/knowledge-bases/{base_id}/documents/url", json={"name": name[:200], "url": url})
if result.status_code == 201:
imported += 1
else:
failed.append((url, result.json().get("detail")))
time.sleep(0.5) # at most 120 requests per minute per key
print(f"Base {base_id}: {imported} documents imported")
for url, detail in failed:
print("failed:", url, "—", detail)
// Node.js 18 or later, in a .mjs file
import { setTimeout as sleep } from 'node:timers/promises'
const API = 'https://api.diska.ai/v1'
const SITEMAP = 'https://www.exemplo.ao/sitemap.xml' // your website's sitemap
const MAX_PAGES = 100
const auth = { Authorization: `Bearer ${process.env.DISKA_API_KEY}` }
async function post(path, init) {
for (;;) {
const response = await fetch(`${API}${path}`, { method: 'POST', ...init, headers: { ...auth, ...init.headers } })
if (response.status !== 429) return response
await sleep(1000 * Number(response.headers.get('retry-after') || 5)) // rate limit
}
}
const json = body => ({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
// 1. A new base for the website's content.
const created = await post('/knowledge-bases', json({
name: 'Website',
instruction: 'Use this base to answer questions about the company, its products and prices, with the information on the website.'
}))
if (!created.ok) throw new Error(`${created.status} ${await created.text()}`)
const base = await created.json()
// 2. The sitemap's pages.
const xml = await (await fetch(SITEMAP)).text()
const urls = [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map(m => m[1]).slice(0, MAX_PAGES)
// 3. Each page as a document: web pages by URL, PDFs by upload.
let imported = 0
const failed = []
for (const url of urls) {
const name = new URL(url).pathname.replace(/^\/+|\/+$/g, '') || 'Home page'
let result
if (url.toLowerCase().endsWith('.pdf')) {
const form = new FormData()
form.append('file', new Blob([await (await fetch(url)).arrayBuffer()], { type: 'application/pdf' }), name)
result = await post(`/knowledge-bases/${base.id}/documents/pdf`, { body: form })
} else {
result = await post(`/knowledge-bases/${base.id}/documents/url`, json({ name: name.slice(0, 200), url }))
}
if (result.status === 201) imported++
else failed.push([url, (await result.json()).detail])
await sleep(500) // at most 120 requests per minute per key
}
console.log(`Base ${base.id}: ${imported} documents imported`)
for (const [url, detail] of failed) console.log('failed:', url, '—', detail)
- Each page is imported with Import a web page. The page must answer within 15 seconds, be up to 2 MB and be HTML, text or JSON. Private or internal addresses are refused.
- PDFs are downloaded and uploaded with Upload a PDF, up to 25 MB.
- Each document is named after the page's path (
products/phones), so you can recognize it in the backoffice. MAX_PAGEScaps how many pages it imports. Start with a few and check the result.- If your sitemap is an index (it lists other sitemaps instead of pages), run the script for each sitemap in the list.
Pages that fail are listed at the end, with the reason — for example A página não devolveu texto legível. (no readable text) when the page only shows content through JavaScript.
Link the base to the agent
The API creates the base but does not assign it to an agent. In the backoffice:
- Open the base under Conhecimento (Knowledge) and check that the documents were indexed.
- Assign it to the agent, as in Assign bases to an agent.
- Publish the agent, in the backoffice or with Publish an agent. Calls only use a new base after you publish.
Update the content
The DISKA API does not list, change or delete documents yet. To add new pages, import them into the same base: a new document in a base that is already assigned takes effect at once. To redo everything, run the script into a new base, switch the agent's base and publish it, then delete the old base under Conhecimento.

