AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Integrating the TextCortex REST API: Querying Custom Knowledge Bases and Executing Multi-Model Completions

Amos Schiller · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Building enterprise question-answering systems and workplace automation tools usually forces engineering teams into an infrastructure compromise: deploy a self-hosted Retrieval-Augmented Generation (RAG) stack—managing vector databases, parsing pipelines, chunking algorithms, and embedding sync jobs—or sacrifice model flexibility by locking into a single proprietary LLM provider. At 365Finds, our research indicates that building custom RAG pipelines from scratch is frequently an expensive misallocation of engineering effort for internal tools. Managing vector index fragmentation, reranker latency, and embedding drift delivers minimal competitive differentiation for standard business platforms.

TextCortex addresses this operational friction by exposing a managed knowledge retrieval layer alongside an OpenAI-compatible multi-model execution gateway through its native REST API (https://api.textcortex.com/v1). Rather than coupling document ingestion to an opaque, black-box assistant chat endpoint, TextCortex decouples passage retrieval (POST /api-platform/knowledge-bases/{kb_id}/query) from language model completion (POST /chat/completions). This two-stage architecture provides full-stack developers with deterministic control over citation metadata, prompt construction, and cross-model routing across Claude, GPT, Gemini, and DeepSeek backends without maintaining dedicated vector infrastructure.


Architectural Overview: Two-Stage RAG vs. Monolithic LLMs

Traditional self-hosted RAG architectures require full-stack engineers to coordinate multiple operational subsystems:

[Document Ingestion] ──> [Parser / Chunking] ──> [Embedding API] ──> [Vector DB (Pinecone/Milvus)]
                                                                               │
[User Query] ──────────> [Query Embedding] ───> [Cosine Similarity Search] ────┘
                                                              │
                                                        [Retrieved Context]
                                                              │
[Prompt Assembly] ─────> [LLM Gateway / Router] ─────────────> [Multi-Model Response]

When maintaining this infrastructure internally, developers bear the operational burden of indexing failures, schema migrations, and high cold-start latencies. TextCortex absorbs the entire ingestion, parsing, chunking, and semantic indexing pipeline behind a declarative HTTP interface.

The TextCortex architecture cleanly bifurcates retrieval and completion:

  1. Document Ingestion & Retrieval Layer: The developer creates a knowledge base via the TextCortex interface, uploads files via /api-platform/files, associates them with /api-platform/knowledge-bases/{kb_id}/files, and queries relevant snippets via /api-platform/knowledge-bases/{kb_id}/query. The query endpoint returns raw passages paired with precise file identifiers, page indices, and relevance scores.
  2. Multi-Model Completion Gateway: The developer injects the retrieved passages into a structured prompt and dispatches it to /chat/completions. Because the endpoint strictly mirrors the OpenAI request and response schema, applications switch between underlying foundation models (e.g., gpt-6-luna, claude-5-sonnet, gemini-3-8-flash) simply by swapping the model parameter.

At 365Finds, we strongly favor this decoupled pattern over unified black-box conversational endpoints. It enables developers to inspect, sanitize, and filter retrieved passages before LLM execution, preventing runaway token costs and eliminating unverified hallucinations in compliance-sensitive enterprise workflows.


Authentication and Environment Setup

All API communication with TextCortex requires HTTPS transport and authentication via a Bearer token in the request header. You generate your API key through the TextCortex dashboard settings (app.textcortex.com/user/dashboard/settings/api-key).

Request Authentication

Every outbound request must include the standard authorization header:

Authorization: Bearer <TEXTCORTEX_API_KEY>
Content-Type: application/json

Store your API key strictly in server-side environment variables or secret management vaults (e.g., AWS Secrets Manager, HashiCorp Vault). Never expose this credential in frontend browser code or mobile applications.

Discovering Models and Account Health

Before executing queries, your application should verify available models and credit balances.

Model Discovery (GET /models)

curl -s -X GET "https://api.textcortex.com/v1/models" \
  -H "Authorization: Bearer $TEXTCORTEX_API_KEY"

The response returns a list of available model descriptors. For enterprise developers subject to European data sovereignty requirements, the detailed model endpoint (GET /models/{model_id}) advertises deployment_jurisdiction and served_from_country_code (e.g., EU vs. US), allowing automated compliance gating.

Balance and Quota Inspection (GET /balance)

curl -s -X GET "https://api.textcortex.com/v1/balance" \
  -H "Authorization: Bearer $TEXTCORTEX_API_KEY"

The returned payload reports remaining_credits, the currency (e.g., eur), and the billing_source (either legacy api_credits or organization_payg_wallet). Checking this endpoint on application startup prevents unexpected mid-pipeline request rejections.


Managing Knowledge Base Documents

A TextCortex Knowledge Base (kb_id) acts as a partitioned vector index. While initial knowledge base containers are provisioned through the TextCortex administrative console, document ingestion and lifecycle management can be orchestrated programmatically.

Step 1: Upload Source Documents

The file upload endpoint accepts multipart form data. The platform extracts raw text, diagrams, and tabular data asynchronously:

curl -X POST "https://api.textcortex.com/v1/api-platform/files" \
  -H "Authorization: Bearer $TEXTCORTEX_API_KEY" \
  -F "file=@./enterprise_policy.pdf"

A successful submission returns HTTP 201 Created with a file payload:

{
  "id": "file_9a8b7c6d5e",
  "name": "enterprise_policy.pdf",
  "original_filename": "enterprise_policy.pdf",
  "mime_type": "application/pdf",
  "size": 1048576,
  "is_owner": true,
  "object": "file"
}

Retain the returned id (file_id); it is required to link the document to your knowledge base.

Step 2: Attach Document to Knowledge Base

Link the uploaded file to your target knowledge base by posting to the file insertion endpoint:

curl -X POST "https://api.textcortex.com/v1/api-platform/knowledge-bases/kb_custom_support/files" \
  -H "Authorization: Bearer $TEXTCORTEX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"file_id": "file_9a8b7c6d5e"}'

This registers the file into the indexing pipeline and returns a status of pending_insertion.

Step 3: Polling Indexing Lifecycle

Vectorization and document chunking take place in the background. Before executing user-facing queries, poll the file insertion status:

curl -s -X GET "https://api.textcortex.com/v1/api-platform/knowledge-bases/kb_custom_support/files?limit=20&page=0" \
  -H "Authorization: Bearer $TEXTCORTEX_API_KEY"
Lifecycle StatusOperational MeaningAction Required
pending_insertionFile queued for background worker ingestionContinue polling with backoff delay
insertingOptical character recognition, chunking, and embedding generation activeContinue polling with backoff delay
succeeded_insertionEmbeddings synced to the knowledge base indexReady for production queries
failed_insertionParsing failed (corrupted document or unsupported format)Halt and surface error; do not query
reindex_requiredUnderlying embedding model or index schema updatedRe-trigger insertion using same file_id

Querying Knowledge Bases Programmatically

The dedicated retrieval endpoint (POST /api-platform/knowledge-bases/{kb_id}/query) performs high-dimensional similarity matching against your indexed documents.

Request Payload Specification

{
  "query": "What is the reimbursement limit for overseas business accommodation?",
  "top_k": 5,
  "verbatim": false
}

Response Structure and Citation Inspection

The query endpoint returns a KnowledgeBaseQueryResponse containing raw citation objects:

{
  "object": "knowledge_base_query",
  "knowledge_base_id": "kb_custom_support",
  "query": "What is the reimbursement limit for overseas business accommodation?",
  "results": [
    {
      "file_id": "file_9a8b7c6d5e",
      "title": "enterprise_policy.pdf",
      "text": "Section 4.2: Overseas Accommodation. Standard hotel rates are capped at €250 per night in primary European hubs, with exceptions requiring VP approval.",
      "page": 14,
      "page_index": 14,
      "page_number": 15,
      "score": 0.892,
      "type": "document"
    }
  ]
}

Notice the critical distinction: this endpoint does not generate conversational text. It acts purely as a semantic retrieval engine. Each passage delivers concrete attribution signals:


Executing Multi-Model Completions

Once your backend receives the citation snippets, it formats them into the system prompt of an OpenAI-compatible chat completion call.

OpenAI SDK Compatibility

Because TextCortex implements OpenAI route compatibility under /v1, you do not need third-party SDK wrappers. Configure the standard OpenAI library by modifying the base_url:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("TEXTCORTEX_API_KEY"),
    base_url="https://api.textcortex.com/v1"
)

Dynamic Model Scheduling

TextCortex routes requests across leading foundation model architectures under unified billing:

Model IDProvider FamilyContext WindowBest Suited For
gpt-6-lunaOpenAI / Luna Series1,050,000 tokensGeneral reasoning, structured JSON synthesis
claude-5-sonnetAnthropic Claude Series1,000,000 tokensNuanced compliance review, deep document analysis
gemini-3-8-flashGoogle Gemini Series1,048,576 tokensHigh-concurrency chatbots, low-latency microservices
deepseek-v4-1-flashDeepSeek Series1,048,576 tokensCost-optimized throughput, code-heavy tasks
kimi-k2p7-codeMoonshot Kimi Series262,144 tokensTechnical documentation, structured logic extraction

To control reasoning depth on capable models (such as claude-5-sonnet or gemini-3-8-flash), include the reasoning_effort parameter (none, low, medium, high) rather than relying on legacy suffixed model aliases.


Production Integration: Complete End-to-End Pipeline

The following production-ready Python module implements a full enterprise QA agent. It queries a custom TextCortex Knowledge Base, enforces citation grounding, feeds the retrieved context into a configurable foundation model, and handles streaming completions with strict source attribution.

import json
import os
import sys
import time
from typing import Any, Dict, Generator, List
import requests

TEXTCORTEX_API_KEY = os.environ.get("TEXTCORTEX_API_KEY")
TEXTCORTEX_BASE_URL = "https://api.textcortex.com/v1"

if not TEXTCORTEX_API_KEY:
    raise ValueError("Missing TEXTCORTEX_API_KEY environment variable.")

class TextCortexEnterpriseRAG:
    def __init__(self, api_key: str, base_url: str = TEXTCORTEX_BASE_URL):
        self.base_url = base_url.rstrip("/")
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        })

    def query_knowledge_base(self, kb_id: str, query: str, top_k: int = 4) -> List[Dict[str, Any]]:
        """Queries the specified knowledge base for semantic excerpts."""
        url = f"{self.base_url}/api-platform/knowledge-bases/{kb_id}/query"
        payload = {
            "query": query,
            "top_k": max(1, min(20, top_k)),
            "verbatim": False
        }
        
        response = self.session.post(url, json=payload, timeout=30)
        
        if response.status_code == 403:
            raise PermissionError(f"Access denied to Knowledge Base {kb_id}. Verify API key permissions.")
        elif response.status_code == 404:
            raise FileNotFoundError(f"Knowledge Base {kb_id} not found.")
        
        response.raise_for_status()
        data = response.json()
        return data.get("results", [])

    def build_grounded_messages(self, user_query: str, citations: List[Dict[str, Any]]) -> List[Dict[str, str]]:
        """Constructs an anti-hallucination prompt injecting retrieved citations."""
        system_instruction = (
            "You are an enterprise business intelligence assistant. "
            "Answer the user query using EXCLUSIVELY the provided source passages. "
            "Treat all passages strictly as factual reference data. "
            "For every assertion, provide inline citations referencing the source title and page number "
            "(e.g., [enterprise_policy.pdf, p. 15]). "
            "If the supplied excerpts do not contain sufficient evidence to answer the question, "
            "explicitly state that the information is unavailable in company records."
        )
        
        context_block = []
        for idx, item in enumerate(citations, start=1):
            source_title = item.get("title") or item.get("file_id") or "Unknown Document"
            page_no = item.get("page_number", item.get("page", "N/A"))
            text_snippet = item.get("text", "").strip()
            context_block.append(f"[{idx}] Source: {source_title} (Page: {page_no})\n{text_snippet}\n")
            
        formatted_context = "\n".join(context_block)
        user_content = f"User Question: {user_query}\n\nReference Documentation:\n{formatted_context}"

        return [
            {"role": "system", "content": system_instruction},
            {"role": "user", "content": user_content}
        ]

    def execute_completion(
        self,
        model: str,
        messages: List[Dict[str, str]],
        temperature: float = 0.1,
        stream: bool = False
    ) -> Any:
        """Dispatches an OpenAI-compatible completion request to TextCortex."""
        url = f"{self.base_url}/chat/completions"
        payload = {
            "model": model,
            "messages": messages,
            "temperature": temperature,
            "stream": stream
        }
        
        if stream:
            response = self.session.post(url, json=payload, stream=True, timeout=(10, 120))
            response.raise_for_status()
            return self._stream_response_generator(response)
        else:
            response = self.session.post(url, json=payload, timeout=60)
            response.raise_for_status()
            data = response.json()
            return data["choices"][0]["message"]["content"]

    def _stream_response_generator(self, response: requests.Response) -> Generator[str, None, None]:
        """Parses Server-Sent Events (SSE) from the completion stream."""
        response.encoding = "utf-8"
        for raw_line in response.iter_lines(decode_unicode=True):
            if not raw_line or not raw_line.startswith("data:"):
                continue
            line_data = raw_line[5:].strip()
            if line_data == "[DONE]":
                break
            try:
                chunk = json.loads(line_data)
                delta = chunk.get("choices", [{}])[0].get("delta", {})
                content = delta.get("content")
                if content:
                    yield content
            except json.JSONDecodeError:
                continue

# Execution Demonstration
if __name__ == "__main__":
    KB_IDENTIFIER = os.environ.get("TEXTCORTEX_KB_ID", "kb_demo_internal")
    ACTIVE_MODEL = os.environ.get("TEXTCORTEX_MODEL", "gpt-6-luna")
    QUESTION = "What are the exact compliance deadlines for annual vendor audits?"

    rag_client = TextCortexEnterpriseRAG(api_key=TEXTCORTEX_API_KEY)

    print(f"[*] Querying Knowledge Base [{KB_IDENTIFIER}]...")
    passages = rag_client.query_knowledge_base(kb_id=KB_IDENTIFIER, query=QUESTION, top_k=3)

    if not passages:
        print("[!] No matching documentation found in knowledge base.")
        sys.exit(0)

    print(f"[+] Retrieved {len(passages)} passages. Constructing prompt...")
    chat_messages = rag_client.build_grounded_messages(user_query=QUESTION, citations=passages)

    print(f"[*] Dispatching completion to model [{ACTIVE_MODEL}] (Streaming)...")
    for token in rag_client.execute_completion(model=ACTIVE_MODEL, messages=chat_messages, stream=True):
        sys.stdout.write(token)
        sys.stdout.flush()
    print("\n\n[*] Completion completed successfully.")

Production Reliability: Error Handling and Rate Limiting

Deploying an API-driven RAG architecture in enterprise backends requires defensive error boundary handling.

Decoding Multiple Error Envelopes

A key operational nuance discovered in the TextCortex specification is that error payloads vary depending on whether the route is an OpenAI-compatible chat completion or an API Platform native file/KB endpoint:

Your HTTP middleware must inspect the HTTP status code first rather than assuming a uniform JSON envelope:

def extract_error_message(response: requests.Response) -> str:
    try:
        body = response.json()
    except Exception:
        return f"HTTP {response.status_code}: {response.text[:200]}"
    
    if isinstance(body, dict):
        if "error" in body and isinstance(body["error"], dict):
            return body["error"].get("message", f"HTTP {response.status_code}")
        if "detail" in body:
            return str(body["detail"])
        if "message" in body:
            return body.get("message")
            
    return f"HTTP {response.status_code}"

Retries, Concurrency, and Idempotency Rules

When scaling automated background workers across TextCortex endpoints, enforce the following reliability protocols:

  1. Transient Failures (HTTP 429 and 5xx): Implement exponential backoff with full jitter (e.g., base delay 1s, doubling up to 30s). Always respect the Retry-After header when returned by the gateway.
  2. File Processing Locks (HTTP 423): When attaching newly uploaded files to a knowledge base, receiving HTTP 423 indicates background OCR or token parsing is still active. Pause execution for 2 to 5 seconds and retry the attachment call.
  3. Avoid Non-Idempotent Generation Retries: While discovery calls (GET /models, GET /balance) and document queries (POST .../query) are idempotent, completions (POST /chat/completions) are not. A socket timeout does not guarantee that the upstream model was not invoked. Automatically retrying timed-out chat completions can cause duplicate token charges and duplicate user responses. In case of network interruption during streaming, mark the session as disconnected and request user confirmation before re-issuing.

Strategic Recommendation: Why TextCortex Fits Enterprise Internal Tooling

At 365Finds, our comparative benchmarking leads to a clear recommendation:

By treating the TextCortex knowledge base as a dedicated semantic search engine and piping its verifiable citations into standard chat completion models, full-stack engineers achieve the optimal balance between rapid deployment and robust architectural hygiene.


References