Knowledge bases (RAG)
此内容尚不支持你的语言。
A knowledge base is a named set of documents an llm node can search before it answers (set the node’s knowledgeBaseId). Every operation here takes a dashboard JWT. Text can be added in one call (ingestDocument). A file (PDF, DOCX, Markdown, CSV or XLSX, at most 20 MB) is added in three steps: requestKnowledgeDocumentUpload returns a short-lived upload URL, you PUT the bytes to that URL yourself, then confirmKnowledgeDocumentUpload starts parsing in the background. Poll knowledgeDocuments until the document’s parseStatus is READY (or FAILED with a parseError). Plan quotas limit the number of knowledge bases, chunks and storage.
Every operation is a POST of { "query", "variables" } to https://api.wetel.dev/graphql (sandbox) with the x-huat-platform: customer header and the credential shown. New here? Start with the Quickstart and the Authentication cheat sheet. Errors are listed in Errors; Postman and OpenAPI files are on Downloads.
| Operation | Kind | Credential | What it does |
|---|---|---|---|
createKnowledgeBase | mutation | Dashboard JWT | Create an empty knowledge base. |
knowledgeBases | query | Dashboard JWT | List the workspace’s knowledge bases. |
ingestDocument | mutation | Dashboard JWT | Add pasted text as a document. Chunked and embedded at once; returns the number of chunks. |
requestKnowledgeDocumentUpload | mutation | Dashboard JWT | File upload, step 1: get a short-lived URL to PUT the file to. |
confirmKnowledgeDocumentUpload | mutation | Dashboard JWT | File upload, step 2: confirm the upload finished. Parsing starts in the background. |
knowledgeDocuments | query | Dashboard JWT | List the documents of a knowledge base with their parse status (poll this after an upload). |
knowledgeDocument | query | Dashboard JWT | Read one document with its status and full text. |
resyncKnowledgeDocument | mutation | Dashboard JWT | Retry a FAILED file upload, or re-chunk and re-embed a READY document from its stored text. |
retrieveChunks | query | Dashboard JWT | Search a knowledge base the way an llm node does, and see which chunks come back. |
deleteKnowledgeDocument | mutation | Dashboard JWT | Delete one document and its chunks, releasing its quota. The knowledge base stays. |
deleteKnowledgeBase | mutation | Dashboard JWT | Delete a knowledge base. |
createKnowledgeBase
Section titled “createKnowledgeBase”Create an empty knowledge base.
- Kind: mutation
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
Request
mutation CreateKb($input: CreateKnowledgeBaseInput!) { createKnowledgeBase(input: $input) { id name description }}{ "input": { "name": "IT helpdesk articles", "description": "How-to articles the helpdesk agent may quote." }}Input fields
CreateKnowledgeBaseInput
| Field | Type | Required | Description |
|---|---|---|---|
description | String | no | Optional free-text description. |
name | String! | yes | Display name (at most 120 characters). |
Code samples
#!/usr/bin/env bash# createKnowledgeBase: Create an empty knowledge base.# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "mutation CreateKb($input:CreateKnowledgeBaseInput!){createKnowledgeBase(input:$input){id name description}}", "variables": { "input": { "name": "IT helpdesk articles", "description": "How-to articles the helpdesk agent may quote." } }}JSON// createKnowledgeBase: Create an empty knowledge base.// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `mutation CreateKb($input: CreateKnowledgeBaseInput!) { createKnowledgeBase(input: $input) { id name description }}`;
const variables = { input: { name: "IT helpdesk articles", description: "How-to articles the helpdesk agent may quote.", },};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log(JSON.stringify(body.data?.createKnowledgeBase, null, 2));}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// createKnowledgeBase: Create an empty knowledge base.// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'mutation CreateKb($input: CreateKnowledgeBaseInput!) { createKnowledgeBase(input: $input) { id name description }}GRAPHQL;
$variables = json_decode(<<<'JSON'{ "input": { "name": "IT helpdesk articles", "description": "How-to articles the helpdesk agent may quote." }}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['createKnowledgeBase'], JSON_PRETTY_PRINT), PHP_EOL;// createKnowledgeBase: Create an empty knowledge base.// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ mutation CreateKb($input: CreateKnowledgeBaseInput!) { createKnowledgeBase(input: $input) { id name description } } """;
var variables = JsonNode.Parse(""" { "input": { "name": "IT helpdesk articles", "description": "How-to articles the helpdesk agent may quote." } } """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["createKnowledgeBase"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# createKnowledgeBase: Create an empty knowledge base.# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """mutation CreateKb($input: CreateKnowledgeBaseInput!) { createKnowledgeBase(input: $input) { id name description }}"""
VARIABLES = { "input": { "name": "IT helpdesk articles", "description": "How-to articles the helpdesk agent may quote.", },}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["createKnowledgeBase"], indent=2))Responses
Success (HTTP 200)
{ "data": { "createKnowledgeBase": { "id": 5, "name": "IT helpdesk articles", "description": "How-to articles the helpdesk agent may quote." } }}BAD_REQUEST: Plan limit reached (HTTP 200)
{ "errors": [ { "message": "Creating another knowledge base would exceed your plan's limit of 3. Upgrade your plan or delete an existing knowledge base.", "locations": [ { "line": 2, "column": 3 } ], "path": [ "createKnowledgeBase" ], "extensions": { "code": "BAD_REQUEST", "originalError": { "message": "Creating another knowledge base would exceed your plan's limit of 3. Upgrade your plan or delete an existing knowledge base.", "error": "Bad Request", "statusCode": 400 } } } ], "data": null}knowledgeBases
Section titled “knowledgeBases”List the workspace’s knowledge bases.
- Kind: query
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
Request
query ListKbs { knowledgeBases { id name description createdAt }}{}Code samples
#!/usr/bin/env bash# knowledgeBases: List the workspace's knowledge bases.# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "query ListKbs{knowledgeBases{id name description createdAt}}", "variables": {}}JSON// knowledgeBases: List the workspace's knowledge bases.// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `query ListKbs { knowledgeBases { id name description createdAt }}`;
const variables = {};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log(JSON.stringify(body.data?.knowledgeBases, null, 2));}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// knowledgeBases: List the workspace's knowledge bases.// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'query ListKbs { knowledgeBases { id name description createdAt }}GRAPHQL;
$variables = json_decode(<<<'JSON'{}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['knowledgeBases'], JSON_PRETTY_PRINT), PHP_EOL;// knowledgeBases: List the workspace's knowledge bases.// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ query ListKbs { knowledgeBases { id name description createdAt } } """;
var variables = JsonNode.Parse(""" {} """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["knowledgeBases"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# knowledgeBases: List the workspace's knowledge bases.# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """query ListKbs { knowledgeBases { id name description createdAt }}"""
VARIABLES = {}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["knowledgeBases"], indent=2))Responses
Success (HTTP 200)
{ "data": { "knowledgeBases": [ { "id": 5, "name": "IT helpdesk articles", "description": "How-to articles the helpdesk agent may quote.", "createdAt": "2026-10-12T04:20:00.000Z" } ] }}UNAUTHENTICATED: Called with an API key instead of a JWT (HTTP 200)
{ "errors": [ { "message": "Unauthorized", "locations": [ { "line": 2, "column": 3 } ], "path": [ "knowledgeBases" ], "extensions": { "code": "UNAUTHENTICATED", "originalError": { "message": "Unauthorized", "statusCode": 401 } } } ], "data": null}ingestDocument
Section titled “ingestDocument”Add pasted text as a document. Chunked and embedded at once; returns the number of chunks.
- Kind: mutation
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
- Text only, at most 500 KB. The document is
READYas soon as this returns.
Request
mutation AddText($input: IngestDocumentInput!) { ingestDocument(input: $input)}{ "input": { "knowledgeBaseId": 5, "fileName": "reset-password.md", "text": "To reset your password, open the self-service portal, choose Forgot password and follow the code sent to your work phone. Codes expire after 10 minutes." }}Input fields
IngestDocumentInput
| Field | Type | Required | Description |
|---|---|---|---|
fileName | String! | yes | Label shown as the document name (at most 255 characters); it need not be a real file name. |
knowledgeBaseId | Int! | yes | Id of a knowledge base of your workspace. |
text | String! | yes | The text to store, chunk and embed (at most 500000 characters). Stored as text/plain. |
Code samples
#!/usr/bin/env bash# ingestDocument: Add pasted text as a document. Chunked and embedded at once; returns the number of chunks.# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "mutation AddText($input:IngestDocumentInput!){ingestDocument(input:$input)}", "variables": { "input": { "knowledgeBaseId": 5, "fileName": "reset-password.md", "text": "To reset your password, open the self-service portal, choose Forgot password and follow the code sent to your work phone. Codes expire after 10 minutes." } }}JSON// ingestDocument: Add pasted text as a document. Chunked and embedded at once; returns the number of chunks.// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `mutation AddText($input: IngestDocumentInput!) { ingestDocument(input: $input)}`;
const variables = { input: { knowledgeBaseId: 5, fileName: "reset-password.md", text: "To reset your password, open the self-service portal, choose Forgot password and follow the code sent to your work phone. Codes expire after 10 minutes.", },};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log(JSON.stringify(body.data?.ingestDocument, null, 2));}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// ingestDocument: Add pasted text as a document. Chunked and embedded at once; returns the number of chunks.// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'mutation AddText($input: IngestDocumentInput!) { ingestDocument(input: $input)}GRAPHQL;
$variables = json_decode(<<<'JSON'{ "input": { "knowledgeBaseId": 5, "fileName": "reset-password.md", "text": "To reset your password, open the self-service portal, choose Forgot password and follow the code sent to your work phone. Codes expire after 10 minutes." }}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['ingestDocument'], JSON_PRETTY_PRINT), PHP_EOL;// ingestDocument: Add pasted text as a document. Chunked and embedded at once; returns the number of chunks.// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ mutation AddText($input: IngestDocumentInput!) { ingestDocument(input: $input) } """;
var variables = JsonNode.Parse(""" { "input": { "knowledgeBaseId": 5, "fileName": "reset-password.md", "text": "To reset your password, open the self-service portal, choose Forgot password and follow the code sent to your work phone. Codes expire after 10 minutes." } } """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["ingestDocument"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# ingestDocument: Add pasted text as a document. Chunked and embedded at once; returns the number of chunks.# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """mutation AddText($input: IngestDocumentInput!) { ingestDocument(input: $input)}"""
VARIABLES = { "input": { "knowledgeBaseId": 5, "fileName": "reset-password.md", "text": "To reset your password, open the self-service portal, choose Forgot password and follow the code sent to your work phone. Codes expire after 10 minutes.", },}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["ingestDocument"], indent=2))Responses
Success (number of chunks created) (HTTP 200)
{ "data": { "ingestDocument": 1 }}NOT_FOUND: Knowledge base not in your workspace (HTTP 200)
{ "errors": [ { "message": "Knowledge base 5 not found", "locations": [ { "line": 2, "column": 3 } ], "path": [ "ingestDocument" ], "extensions": { "code": "NOT_FOUND", "status": 404, "originalError": { "message": "Knowledge base 5 not found", "error": "Not Found", "statusCode": 404 } } } ], "data": null}requestKnowledgeDocumentUpload
Section titled “requestKnowledgeDocumentUpload”File upload, step 1: get a short-lived URL to PUT the file to.
- Kind: mutation
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
- Then upload the bytes yourself, with the same
Content-TypeasmimeType:curl -X PUT -H "Content-Type: application/pdf" --data-binary @vpn-guide.pdf "$UPLOAD_URL". The URL expires after 15 minutes. - Allowed
mimeTypevalues:application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document(DOCX),text/markdown,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet(XLSX). At most 20 MB. - Keep
objectStorageKey; step 2 needs it. Limited to 10 calls per minute per client IP.
Request
mutation RequestUpload($input: RequestKnowledgeDocumentUploadInput!) { requestKnowledgeDocumentUpload(input: $input) { uploadUrl objectStorageKey }}{ "input": { "knowledgeBaseId": 5, "fileName": "vpn-guide.pdf", "mimeType": "application/pdf", "declaredSizeBytes": 482113 }}Input fields
RequestKnowledgeDocumentUploadInput
| Field | Type | Required | Description |
|---|---|---|---|
declaredSizeBytes | Int! | yes | File size in bytes as you know it (a positive integer, at most 20971520, 20 MB). Used for an early quota check only; the real size is checked at confirm. |
fileName | String! | yes | Original file name (at most 255 characters). |
knowledgeBaseId | Int! | yes | Id of a knowledge base of your workspace. |
mimeType | String! | yes | MIME type of the file, one of: application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document (DOCX), text/markdown, text/csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (XLSX). Send the same value as Content-Type on the upload. |
Code samples
#!/usr/bin/env bash# requestKnowledgeDocumentUpload: File upload, step 1: get a short-lived URL to PUT the file to.# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "mutation RequestUpload($input:RequestKnowledgeDocumentUploadInput!){requestKnowledgeDocumentUpload(input:$input){uploadUrl objectStorageKey}}", "variables": { "input": { "knowledgeBaseId": 5, "fileName": "vpn-guide.pdf", "mimeType": "application/pdf", "declaredSizeBytes": 482113 } }}JSON// requestKnowledgeDocumentUpload: File upload, step 1: get a short-lived URL to PUT the file to.// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `mutation RequestUpload($input: RequestKnowledgeDocumentUploadInput!) { requestKnowledgeDocumentUpload(input: $input) { uploadUrl objectStorageKey }}`;
const variables = { input: { knowledgeBaseId: 5, fileName: "vpn-guide.pdf", mimeType: "application/pdf", declaredSizeBytes: 482113, },};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log( JSON.stringify(body.data?.requestKnowledgeDocumentUpload, null, 2) );}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// requestKnowledgeDocumentUpload: File upload, step 1: get a short-lived URL to PUT the file to.// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'mutation RequestUpload($input: RequestKnowledgeDocumentUploadInput!) { requestKnowledgeDocumentUpload(input: $input) { uploadUrl objectStorageKey }}GRAPHQL;
$variables = json_decode(<<<'JSON'{ "input": { "knowledgeBaseId": 5, "fileName": "vpn-guide.pdf", "mimeType": "application/pdf", "declaredSizeBytes": 482113 }}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['requestKnowledgeDocumentUpload'], JSON_PRETTY_PRINT), PHP_EOL;// requestKnowledgeDocumentUpload: File upload, step 1: get a short-lived URL to PUT the file to.// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ mutation RequestUpload($input: RequestKnowledgeDocumentUploadInput!) { requestKnowledgeDocumentUpload(input: $input) { uploadUrl objectStorageKey } } """;
var variables = JsonNode.Parse(""" { "input": { "knowledgeBaseId": 5, "fileName": "vpn-guide.pdf", "mimeType": "application/pdf", "declaredSizeBytes": 482113 } } """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["requestKnowledgeDocumentUpload"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# requestKnowledgeDocumentUpload: File upload, step 1: get a short-lived URL to PUT the file to.# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """mutation RequestUpload($input: RequestKnowledgeDocumentUploadInput!) { requestKnowledgeDocumentUpload(input: $input) { uploadUrl objectStorageKey }}"""
VARIABLES = { "input": { "knowledgeBaseId": 5, "fileName": "vpn-guide.pdf", "mimeType": "application/pdf", "declaredSizeBytes": 482113, },}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["requestKnowledgeDocumentUpload"], indent=2))Responses
Success (HTTP 200)
{ "data": { "requestKnowledgeDocumentUpload": { "uploadUrl": "https://storage.example.com/uploads/tenant-3/kb-5/0b7c2f9e-vpn-guide.pdf?X-Signature=example-not-real", "objectStorageKey": "tenant-3/kb-5/0b7c2f9e-vpn-guide.pdf" } }}BAD_REQUEST: File type not supported (HTTP 200)
{ "errors": [ { "message": "mimeType must be one of the following values: application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document, text/markdown, text/csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "locations": [ { "line": 2, "column": 3 } ], "path": [ "requestKnowledgeDocumentUpload" ], "extensions": { "code": "BAD_REQUEST", "originalError": { "message": "mimeType must be one of the following values: application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document, text/markdown, text/csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "error": "Bad Request", "statusCode": 400 } } } ], "data": null}BAD_REQUEST: File too large (HTTP 200)
{ "errors": [ { "message": "File size 31457280 bytes exceeds the maximum upload size of 20971520 bytes.", "locations": [ { "line": 2, "column": 3 } ], "path": [ "requestKnowledgeDocumentUpload" ], "extensions": { "code": "BAD_REQUEST", "originalError": { "message": "File size 31457280 bytes exceeds the maximum upload size of 20971520 bytes.", "error": "Bad Request", "statusCode": 400 } } } ], "data": null}confirmKnowledgeDocumentUpload
Section titled “confirmKnowledgeDocumentUpload”File upload, step 2: confirm the upload finished. Parsing starts in the background.
- Kind: mutation
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
- Call it after your
PUTsucceeded. The document startsPENDING, thenPARSING, thenREADYorFAILED. - Limited to 10 calls per minute per client IP.
Request
mutation ConfirmUpload($input: ConfirmKnowledgeDocumentUploadInput!) { confirmKnowledgeDocumentUpload(input: $input) { documentId parseStatus }}{ "input": { "knowledgeBaseId": 5, "objectStorageKey": "tenant-3/kb-5/0b7c2f9e-vpn-guide.pdf", "fileName": "vpn-guide.pdf", "mimeType": "application/pdf" }}Input fields
ConfirmKnowledgeDocumentUploadInput
| Field | Type | Required | Description |
|---|---|---|---|
fileName | String! | yes | File name, as sent to requestKnowledgeDocumentUpload (at most 255 characters). |
knowledgeBaseId | Int! | yes | Id of the knowledge base, as sent to requestKnowledgeDocumentUpload. |
mimeType | String! | yes | MIME type, as sent to requestKnowledgeDocumentUpload (same allowed values). |
objectStorageKey | String! | yes | The objectStorageKey returned by requestKnowledgeDocumentUpload; a key outside your workspace is refused. |
Code samples
#!/usr/bin/env bash# confirmKnowledgeDocumentUpload: File upload, step 2: confirm the upload finished. Parsing starts in the background.# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "mutation ConfirmUpload($input:ConfirmKnowledgeDocumentUploadInput!){confirmKnowledgeDocumentUpload(input:$input){documentId parseStatus}}", "variables": { "input": { "knowledgeBaseId": 5, "objectStorageKey": "tenant-3/kb-5/0b7c2f9e-vpn-guide.pdf", "fileName": "vpn-guide.pdf", "mimeType": "application/pdf" } }}JSON// confirmKnowledgeDocumentUpload: File upload, step 2: confirm the upload finished. Parsing starts in the background.// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `mutation ConfirmUpload($input: ConfirmKnowledgeDocumentUploadInput!) { confirmKnowledgeDocumentUpload(input: $input) { documentId parseStatus }}`;
const variables = { input: { knowledgeBaseId: 5, objectStorageKey: "tenant-3/kb-5/0b7c2f9e-vpn-guide.pdf", fileName: "vpn-guide.pdf", mimeType: "application/pdf", },};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log( JSON.stringify(body.data?.confirmKnowledgeDocumentUpload, null, 2) );}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// confirmKnowledgeDocumentUpload: File upload, step 2: confirm the upload finished. Parsing starts in the background.// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'mutation ConfirmUpload($input: ConfirmKnowledgeDocumentUploadInput!) { confirmKnowledgeDocumentUpload(input: $input) { documentId parseStatus }}GRAPHQL;
$variables = json_decode(<<<'JSON'{ "input": { "knowledgeBaseId": 5, "objectStorageKey": "tenant-3/kb-5/0b7c2f9e-vpn-guide.pdf", "fileName": "vpn-guide.pdf", "mimeType": "application/pdf" }}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['confirmKnowledgeDocumentUpload'], JSON_PRETTY_PRINT), PHP_EOL;// confirmKnowledgeDocumentUpload: File upload, step 2: confirm the upload finished. Parsing starts in the background.// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ mutation ConfirmUpload($input: ConfirmKnowledgeDocumentUploadInput!) { confirmKnowledgeDocumentUpload(input: $input) { documentId parseStatus } } """;
var variables = JsonNode.Parse(""" { "input": { "knowledgeBaseId": 5, "objectStorageKey": "tenant-3/kb-5/0b7c2f9e-vpn-guide.pdf", "fileName": "vpn-guide.pdf", "mimeType": "application/pdf" } } """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["confirmKnowledgeDocumentUpload"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# confirmKnowledgeDocumentUpload: File upload, step 2: confirm the upload finished. Parsing starts in the background.# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """mutation ConfirmUpload($input: ConfirmKnowledgeDocumentUploadInput!) { confirmKnowledgeDocumentUpload(input: $input) { documentId parseStatus }}"""
VARIABLES = { "input": { "knowledgeBaseId": 5, "objectStorageKey": "tenant-3/kb-5/0b7c2f9e-vpn-guide.pdf", "fileName": "vpn-guide.pdf", "mimeType": "application/pdf", },}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["confirmKnowledgeDocumentUpload"], indent=2))Responses
Success (HTTP 200)
{ "data": { "confirmKnowledgeDocumentUpload": { "documentId": 61, "parseStatus": "PENDING" } }}BAD_REQUEST: The PUT did not complete (HTTP 200)
{ "errors": [ { "message": "No file was found at this upload location — the upload may not have completed. Request a new upload URL and try again.", "locations": [ { "line": 2, "column": 3 } ], "path": [ "confirmKnowledgeDocumentUpload" ], "extensions": { "code": "BAD_REQUEST", "originalError": { "message": "No file was found at this upload location — the upload may not have completed. Request a new upload URL and try again.", "error": "Bad Request", "statusCode": 400 } } } ], "data": null}knowledgeDocuments
Section titled “knowledgeDocuments”List the documents of a knowledge base with their parse status (poll this after an upload).
- Kind: query
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
parseStatusisPENDING,PARSING,READYorFAILED(thenparseErrorsays why). Pasted-text documents areREADYat once.- Do not select
rawTexthere; read one document’s full text withknowledgeDocument(id).
Request
query Documents($knowledgeBaseId: Int!) { knowledgeDocuments(knowledgeBaseId: $knowledgeBaseId) { id fileName mimeType fileSizeBytes parseStatus parseError }}{ "knowledgeBaseId": 5}Code samples
#!/usr/bin/env bash# knowledgeDocuments: List the documents of a knowledge base with their parse status (poll this after an upload).# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "query Documents($knowledgeBaseId:Int!){knowledgeDocuments(knowledgeBaseId:$knowledgeBaseId){id fileName mimeType fileSizeBytes parseStatus parseError}}", "variables": { "knowledgeBaseId": 5 }}JSON// knowledgeDocuments: List the documents of a knowledge base with their parse status (poll this after an upload).// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `query Documents($knowledgeBaseId: Int!) { knowledgeDocuments(knowledgeBaseId: $knowledgeBaseId) { id fileName mimeType fileSizeBytes parseStatus parseError }}`;
const variables = { knowledgeBaseId: 5,};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log(JSON.stringify(body.data?.knowledgeDocuments, null, 2));}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// knowledgeDocuments: List the documents of a knowledge base with their parse status (poll this after an upload).// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'query Documents($knowledgeBaseId: Int!) { knowledgeDocuments(knowledgeBaseId: $knowledgeBaseId) { id fileName mimeType fileSizeBytes parseStatus parseError }}GRAPHQL;
$variables = json_decode(<<<'JSON'{ "knowledgeBaseId": 5}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['knowledgeDocuments'], JSON_PRETTY_PRINT), PHP_EOL;// knowledgeDocuments: List the documents of a knowledge base with their parse status (poll this after an upload).// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ query Documents($knowledgeBaseId: Int!) { knowledgeDocuments(knowledgeBaseId: $knowledgeBaseId) { id fileName mimeType fileSizeBytes parseStatus parseError } } """;
var variables = JsonNode.Parse(""" { "knowledgeBaseId": 5 } """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["knowledgeDocuments"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# knowledgeDocuments: List the documents of a knowledge base with their parse status (poll this after an upload).# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """query Documents($knowledgeBaseId: Int!) { knowledgeDocuments(knowledgeBaseId: $knowledgeBaseId) { id fileName mimeType fileSizeBytes parseStatus parseError }}"""
VARIABLES = { "knowledgeBaseId": 5,}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["knowledgeDocuments"], indent=2))Responses
Success (HTTP 200)
{ "data": { "knowledgeDocuments": [ { "id": 61, "fileName": "vpn-guide.pdf", "mimeType": "application/pdf", "fileSizeBytes": 482113, "parseStatus": "READY", "parseError": null }, { "id": 60, "fileName": "reset-password.md", "mimeType": "text/plain", "fileSizeBytes": 160, "parseStatus": "READY", "parseError": null } ] }}UNAUTHENTICATED: Called with an API key instead of a JWT (HTTP 200)
{ "errors": [ { "message": "Unauthorized", "locations": [ { "line": 2, "column": 3 } ], "path": [ "knowledgeDocuments" ], "extensions": { "code": "UNAUTHENTICATED", "originalError": { "message": "Unauthorized", "statusCode": 401 } } } ], "data": null}knowledgeDocument
Section titled “knowledgeDocument”Read one document with its status and full text.
- Kind: query
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
rawTextis the pasted text or the text extracted from the file. It is empty while the document isPENDINGorPARSING.- Use it to check what the agent can actually quote after a file was parsed (scanned PDFs, for example, can come out empty).
Request
query Document($id: Int!) { knowledgeDocument(id: $id) { id fileName mimeType parseStatus parseError rawText updatedAt }}{ "id": 61}Code samples
#!/usr/bin/env bash# knowledgeDocument: Read one document with its status and full text.# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "query Document($id:Int!){knowledgeDocument(id:$id){id fileName mimeType parseStatus parseError rawText updatedAt}}", "variables": { "id": 61 }}JSON// knowledgeDocument: Read one document with its status and full text.// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `query Document($id: Int!) { knowledgeDocument(id: $id) { id fileName mimeType parseStatus parseError rawText updatedAt }}`;
const variables = { id: 61,};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log(JSON.stringify(body.data?.knowledgeDocument, null, 2));}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// knowledgeDocument: Read one document with its status and full text.// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'query Document($id: Int!) { knowledgeDocument(id: $id) { id fileName mimeType parseStatus parseError rawText updatedAt }}GRAPHQL;
$variables = json_decode(<<<'JSON'{ "id": 61}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['knowledgeDocument'], JSON_PRETTY_PRINT), PHP_EOL;// knowledgeDocument: Read one document with its status and full text.// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ query Document($id: Int!) { knowledgeDocument(id: $id) { id fileName mimeType parseStatus parseError rawText updatedAt } } """;
var variables = JsonNode.Parse(""" { "id": 61 } """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["knowledgeDocument"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# knowledgeDocument: Read one document with its status and full text.# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """query Document($id: Int!) { knowledgeDocument(id: $id) { id fileName mimeType parseStatus parseError rawText updatedAt }}"""
VARIABLES = { "id": 61,}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["knowledgeDocument"], indent=2))Responses
Success (HTTP 200)
{ "data": { "knowledgeDocument": { "id": 61, "fileName": "vpn-guide.pdf", "mimeType": "application/pdf", "parseStatus": "READY", "parseError": null, "rawText": "Connecting to the VPN. Install the VPN client from the self-service portal, sign in with your work account and approve the prompt on your phone.", "updatedAt": "2026-10-12T04:31:09.000Z" } }}NOT_FOUND: Not in your workspace (HTTP 200)
{ "errors": [ { "message": "Knowledge document 61 not found", "locations": [ { "line": 2, "column": 3 } ], "path": [ "knowledgeDocument" ], "extensions": { "code": "NOT_FOUND", "status": 404, "originalError": { "message": "Knowledge document 61 not found", "error": "Not Found", "statusCode": 404 } } } ], "data": null}resyncKnowledgeDocument
Section titled “resyncKnowledgeDocument”Retry a FAILED file upload, or re-chunk and re-embed a READY document from its stored text.
- Kind: mutation
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
- A
FAILEDupload goes back toPENDINGand is parsed again in the background; pollknowledgeDocumentorknowledgeDocuments. AREADYdocument is re-embedded before this returns. - Refused while the document is
PENDINGorPARSING. Re-embedding is a metered model call and counts against your plan’s chunk quota.
Request
mutation Resync($id: Int!) { resyncKnowledgeDocument(id: $id)}{ "id": 61}Code samples
#!/usr/bin/env bash# resyncKnowledgeDocument: Retry a FAILED file upload, or re-chunk and re-embed a READY document from its stored text.# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "mutation Resync($id:Int!){resyncKnowledgeDocument(id:$id)}", "variables": { "id": 61 }}JSON// resyncKnowledgeDocument: Retry a FAILED file upload, or re-chunk and re-embed a READY document from its stored text.// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `mutation Resync($id: Int!) { resyncKnowledgeDocument(id: $id)}`;
const variables = { id: 61,};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log(JSON.stringify(body.data?.resyncKnowledgeDocument, null, 2));}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// resyncKnowledgeDocument: Retry a FAILED file upload, or re-chunk and re-embed a READY document from its stored text.// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'mutation Resync($id: Int!) { resyncKnowledgeDocument(id: $id)}GRAPHQL;
$variables = json_decode(<<<'JSON'{ "id": 61}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['resyncKnowledgeDocument'], JSON_PRETTY_PRINT), PHP_EOL;// resyncKnowledgeDocument: Retry a FAILED file upload, or re-chunk and re-embed a READY document from its stored text.// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ mutation Resync($id: Int!) { resyncKnowledgeDocument(id: $id) } """;
var variables = JsonNode.Parse(""" { "id": 61 } """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["resyncKnowledgeDocument"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# resyncKnowledgeDocument: Retry a FAILED file upload, or re-chunk and re-embed a READY document from its stored text.# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """mutation Resync($id: Int!) { resyncKnowledgeDocument(id: $id)}"""
VARIABLES = { "id": 61,}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["resyncKnowledgeDocument"], indent=2))Responses
Success (HTTP 200)
{ "data": { "resyncKnowledgeDocument": true }}BAD_REQUEST: Still being parsed (HTTP 200)
{ "errors": [ { "message": "Document 61 is already being parsed — wait for it to finish before resyncing.", "locations": [ { "line": 2, "column": 3 } ], "path": [ "resyncKnowledgeDocument" ], "extensions": { "code": "BAD_REQUEST", "originalError": { "message": "Document 61 is already being parsed — wait for it to finish before resyncing.", "error": "Bad Request", "statusCode": 400 } } } ], "data": null}NOT_FOUND: Not in your workspace (HTTP 200)
{ "errors": [ { "message": "Knowledge document 61 not found", "locations": [ { "line": 2, "column": 3 } ], "path": [ "resyncKnowledgeDocument" ], "extensions": { "code": "NOT_FOUND", "status": 404, "originalError": { "message": "Knowledge document 61 not found", "error": "Not Found", "statusCode": 404 } } } ], "data": null}retrieveChunks
Section titled “retrieveChunks”Search a knowledge base the way an llm node does, and see which chunks come back.
- Kind: query
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
- Returns the
topKchunks (default 5, at most 20) most similar toquery, most relevant first.scoreis the cosine similarity (higher is more relevant). - Use it to test whether an article will be found for a typical customer question before you rely on it in a workflow. Embedding the query is a metered model call.
- An unknown knowledge base, or one of another workspace, returns an empty list.
Request
query Search($knowledgeBaseId: Int!, $query: String!, $topK: Int) { retrieveChunks(knowledgeBaseId: $knowledgeBaseId, query: $query, topK: $topK) { chunkId documentId score content }}{ "knowledgeBaseId": 5, "query": "I forgot my password and the code never arrives", "topK": 3}Code samples
#!/usr/bin/env bash# retrieveChunks: Search a knowledge base the way an llm node does, and see which chunks come back.# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "query Search($knowledgeBaseId:Int!$query:String!$topK:Int){retrieveChunks(knowledgeBaseId:$knowledgeBaseId query:$query topK:$topK){chunkId documentId score content}}", "variables": { "knowledgeBaseId": 5, "query": "I forgot my password and the code never arrives", "topK": 3 }}JSON// retrieveChunks: Search a knowledge base the way an llm node does, and see which chunks come back.// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `query Search($knowledgeBaseId: Int!, $query: String!, $topK: Int) { retrieveChunks(knowledgeBaseId: $knowledgeBaseId, query: $query, topK: $topK) { chunkId documentId score content }}`;
const variables = { knowledgeBaseId: 5, query: "I forgot my password and the code never arrives", topK: 3,};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log(JSON.stringify(body.data?.retrieveChunks, null, 2));}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// retrieveChunks: Search a knowledge base the way an llm node does, and see which chunks come back.// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'query Search($knowledgeBaseId: Int!, $query: String!, $topK: Int) { retrieveChunks(knowledgeBaseId: $knowledgeBaseId, query: $query, topK: $topK) { chunkId documentId score content }}GRAPHQL;
$variables = json_decode(<<<'JSON'{ "knowledgeBaseId": 5, "query": "I forgot my password and the code never arrives", "topK": 3}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['retrieveChunks'], JSON_PRETTY_PRINT), PHP_EOL;// retrieveChunks: Search a knowledge base the way an llm node does, and see which chunks come back.// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ query Search($knowledgeBaseId: Int!, $query: String!, $topK: Int) { retrieveChunks(knowledgeBaseId: $knowledgeBaseId, query: $query, topK: $topK) { chunkId documentId score content } } """;
var variables = JsonNode.Parse(""" { "knowledgeBaseId": 5, "query": "I forgot my password and the code never arrives", "topK": 3 } """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["retrieveChunks"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# retrieveChunks: Search a knowledge base the way an llm node does, and see which chunks come back.# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """query Search($knowledgeBaseId: Int!, $query: String!, $topK: Int) { retrieveChunks(knowledgeBaseId: $knowledgeBaseId, query: $query, topK: $topK) { chunkId documentId score content }}"""
VARIABLES = { "knowledgeBaseId": 5, "query": "I forgot my password and the code never arrives", "topK": 3,}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["retrieveChunks"], indent=2))Responses
Success (HTTP 200)
{ "data": { "retrieveChunks": [ { "chunkId": 812, "documentId": 60, "score": 0.8132, "content": "To reset your password, open the self-service portal, choose Forgot password and follow the code sent to your work phone. Codes expire after 10 minutes." }, { "chunkId": 845, "documentId": 61, "score": 0.6017, "content": "Connecting to the VPN. Install the VPN client from the self-service portal, sign in with your work account and approve the prompt on your phone." } ] }}BAD_USER_INPUT: Query missing (HTTP 400)
Sent with variables:
{ "knowledgeBaseId": 5}{ "errors": [ { "message": "Variable \"$query\" of required type \"String!\" was not provided.", "locations": [ { "line": 1, "column": 38 } ], "extensions": { "code": "BAD_USER_INPUT" } } ]}deleteKnowledgeDocument
Section titled “deleteKnowledgeDocument”Delete one document and its chunks, releasing its quota. The knowledge base stays.
- Kind: mutation
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
Request
mutation DeleteDocument($id: Int!) { deleteKnowledgeDocument(id: $id)}{ "id": 61}Code samples
#!/usr/bin/env bash# deleteKnowledgeDocument: Delete one document and its chunks, releasing its quota. The knowledge base stays.# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "mutation DeleteDocument($id:Int!){deleteKnowledgeDocument(id:$id)}", "variables": { "id": 61 }}JSON// deleteKnowledgeDocument: Delete one document and its chunks, releasing its quota. The knowledge base stays.// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `mutation DeleteDocument($id: Int!) { deleteKnowledgeDocument(id: $id)}`;
const variables = { id: 61,};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log(JSON.stringify(body.data?.deleteKnowledgeDocument, null, 2));}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// deleteKnowledgeDocument: Delete one document and its chunks, releasing its quota. The knowledge base stays.// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'mutation DeleteDocument($id: Int!) { deleteKnowledgeDocument(id: $id)}GRAPHQL;
$variables = json_decode(<<<'JSON'{ "id": 61}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['deleteKnowledgeDocument'], JSON_PRETTY_PRINT), PHP_EOL;// deleteKnowledgeDocument: Delete one document and its chunks, releasing its quota. The knowledge base stays.// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ mutation DeleteDocument($id: Int!) { deleteKnowledgeDocument(id: $id) } """;
var variables = JsonNode.Parse(""" { "id": 61 } """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["deleteKnowledgeDocument"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# deleteKnowledgeDocument: Delete one document and its chunks, releasing its quota. The knowledge base stays.# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """mutation DeleteDocument($id: Int!) { deleteKnowledgeDocument(id: $id)}"""
VARIABLES = { "id": 61,}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["deleteKnowledgeDocument"], indent=2))Responses
Success (HTTP 200)
{ "data": { "deleteKnowledgeDocument": true }}NOT_FOUND: Not in your workspace (HTTP 200)
{ "errors": [ { "message": "Knowledge document 61 not found", "locations": [ { "line": 2, "column": 3 } ], "path": [ "deleteKnowledgeDocument" ], "extensions": { "code": "NOT_FOUND", "status": 404, "originalError": { "message": "Knowledge document 61 not found", "error": "Not Found", "statusCode": 404 } } } ], "data": null}deleteKnowledgeBase
Section titled “deleteKnowledgeBase”Delete a knowledge base.
- Kind: mutation
- Credential: Dashboard JWT:
Authorization: Bearer <jwt>, fromlogin(a person or a one-off script) - Available in: sandbox and production
- Delete its documents first with
deleteKnowledgeDocumentif you want their quota back; deleting the knowledge base does not delete them.
Request
mutation DeleteKb($id: Int!) { deleteKnowledgeBase(id: $id)}{ "id": 5}Code samples
#!/usr/bin/env bash# deleteKnowledgeBase: Delete a knowledge base.# Credential: Dashboard JWT (WETEL_JWT).API_URL="${WETEL_API_URL:-https://api.wetel.dev/graphql}"
curl -sS "$API_URL" \ -H "Content-Type: application/json" \ -H "x-huat-platform: customer" \ -H "Authorization: Bearer $WETEL_JWT" \ --data-binary @- <<'JSON'{ "query": "mutation DeleteKb($id:Int!){deleteKnowledgeBase(id:$id)}", "variables": { "id": 5 }}JSON// deleteKnowledgeBase: Delete a knowledge base.// Credential: Dashboard JWT (WETEL_JWT). Node 18+ (built-in fetch).const API_URL = process.env.WETEL_API_URL ?? "https://api.wetel.dev/graphql";
const query = `mutation DeleteKb($id: Int!) { deleteKnowledgeBase(id: $id)}`;
const variables = { id: 5,};
type GraphQLResponse = { data?: Record<string, unknown>; errors?: { message: string; extensions?: { code?: string } }[];};
async function main(): Promise<void> { const res = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-huat-platform": "customer", Authorization: `Bearer ${process.env.WETEL_JWT ?? ""}`, }, body: JSON.stringify({ query, variables }), }); const body = (await res.json()) as GraphQLResponse; if (body.errors?.length) { const error = body.errors[0]; throw new Error(`${error.extensions?.code}: ${error.message}`); } console.log(JSON.stringify(body.data?.deleteKnowledgeBase, null, 2));}
main().catch(err => { console.error(err); process.exit(1);});
export {};<?php// deleteKnowledgeBase: Delete a knowledge base.// Credential: Dashboard JWT (WETEL_JWT). PHP 7.3+ with the curl extension.$apiUrl = getenv('WETEL_API_URL') ?: 'https://api.wetel.dev/graphql';
$query = <<<'GRAPHQL'mutation DeleteKb($id: Int!) { deleteKnowledgeBase(id: $id)}GRAPHQL;
$variables = json_decode(<<<'JSON'{ "id": 5}JSON);
$ch = curl_init($apiUrl);curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-huat-platform: customer', 'Authorization: Bearer ' . getenv('WETEL_JWT'), ], CURLOPT_POSTFIELDS => json_encode(['query' => $query, 'variables' => $variables]),]);$body = json_decode(curl_exec($ch), true);curl_close($ch);
if (!empty($body['errors'])) { $error = $body['errors'][0]; fwrite(STDERR, ($error['extensions']['code'] ?? 'ERROR') . ': ' . $error['message'] . PHP_EOL); exit(1);}echo json_encode($body['data']['deleteKnowledgeBase'], JSON_PRETTY_PRINT), PHP_EOL;// deleteKnowledgeBase: Delete a knowledge base.// Credential: Dashboard JWT (WETEL_JWT). .NET 8: put this in Program.cs of a console app and run "dotnet run".using System.Net.Http.Headers;using System.Net.Http.Json;using System.Text.Json;using System.Text.Json.Nodes;
var apiUrl = Environment.GetEnvironmentVariable("WETEL_API_URL") ?? "https://api.wetel.dev/graphql";
const string query = """ mutation DeleteKb($id: Int!) { deleteKnowledgeBase(id: $id) } """;
var variables = JsonNode.Parse(""" { "id": 5 } """);
using var http = new HttpClient();using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl){ Content = JsonContent.Create(new { query, variables }),};request.Headers.Add("x-huat-platform", "customer");request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WETEL_JWT"));
using var response = await http.SendAsync(request);var body = JsonNode.Parse(await response.Content.ReadAsStringAsync())!;if (body["errors"] is JsonArray errors && errors.Count > 0){ Console.Error.WriteLine($"{errors[0]?["extensions"]?["code"]}: {errors[0]?["message"]}"); return 1;}Console.WriteLine(body["data"]?["deleteKnowledgeBase"]?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));return 0;# deleteKnowledgeBase: Delete a knowledge base.# Credential: Dashboard JWT (WETEL_JWT). Python 3.8+ with "requests".import jsonimport os
import requests
API_URL = os.environ.get("WETEL_API_URL", "https://api.wetel.dev/graphql")
QUERY = """mutation DeleteKb($id: Int!) { deleteKnowledgeBase(id: $id)}"""
VARIABLES = { "id": 5,}
response = requests.post( API_URL, json={"query": QUERY, "variables": VARIABLES}, headers={ "x-huat-platform": "customer", "Authorization": "Bearer " + os.environ["WETEL_JWT"], }, timeout=30,)body = response.json()if body.get("errors"): error = body["errors"][0] raise SystemExit(f"{error.get('extensions', {}).get('code')}: {error['message']}")print(json.dumps(body["data"]["deleteKnowledgeBase"], indent=2))Responses
Success (HTTP 200)
{ "data": { "deleteKnowledgeBase": true }}NOT_FOUND: Not in your workspace (HTTP 200)
{ "errors": [ { "message": "Knowledge base 5 not found", "locations": [ { "line": 2, "column": 3 } ], "path": [ "deleteKnowledgeBase" ], "extensions": { "code": "NOT_FOUND", "status": 404, "originalError": { "message": "Knowledge base 5 not found", "error": "Not Found", "statusCode": 404 } } } ], "data": null}