Brinpage

Brinpage Platform — Quick Start (Python)

Minimal server-side Python integration calling Brinpage Platform directly via HTTP. No SDK, no special tooling — just env vars + one small client.

Requirements

  • Python 3.10+ (3.11+ recommended)
  • Package: requests
  • A Brinpage Platform account + license key

1) Add environment variables

Set these in your hosting environment (or your framework’s .env system).

.env
# Required (server-side only)
BRINPAGE_LICENSE_KEY="bp_xxxx"

# Optional
BRINPAGE_API_BASE="https://platform.brinpage.com"
BRINPAGE_TIMEOUT_S=30

Don’t have access yet? Create a Platform account and generate your license key.

Get your license key

Important: never expose BRINPAGE_LICENSE_KEY to the browser. Keep it server-side (your Python backend only).

2) Install dependencies

bash
pip install requests

If you run locally and want to load .env files, you can optionally use python-dotenv, but it’s not required in production hosting.

3) Add a tiny Brinpage HTTP client

Create a reusable client (framework-agnostic). Example below assumes a file like brinpage.py.

python
# brinpage.py
from __future__ import annotations

import os
import json
from typing import Any, Dict, Optional

import requests


class Brinpage:
    def __init__(
        self,
        base_url: Optional[str] = None,
        license_key: Optional[str] = None,
        timeout_s: Optional[float] = None,
    ) -> None:
        self.base_url = (base_url or os.getenv("BRINPAGE_API_BASE") or "https://platform.brinpage.com").rstrip("/")
        self.license_key = license_key or os.getenv("BRINPAGE_LICENSE_KEY") or ""
        self.timeout_s = float(timeout_s or os.getenv("BRINPAGE_TIMEOUT_S") or 30)

        if not self.license_key:
            raise RuntimeError("Missing BRINPAGE_LICENSE_KEY")

    def ask(self, question: str, **options: Any) -> Dict[str, Any]:
        question = (question or "").strip()
        if not question:
            raise ValueError("Missing 'question'")

        url = f"{self.base_url}/api/sdk/ask"
        payload: Dict[str, Any] = {
            "question": question,
            # Default to non-streaming JSON response for simplicity
            "stream": False,
            **options,
        }

        res = requests.post(
            url,
            headers={
                "Authorization": f"Bearer {self.license_key}",
                "Content-Type": "application/json",
                "Accept": "application/json",
            },
            data=json.dumps(payload),
            timeout=self.timeout_s,
        )

        # Raise rich error if not ok
        if res.status_code < 200 or res.status_code >= 300:
            try:
                data = res.json()
            except Exception:
                data = {"error": res.text[:500]}
            msg = data.get("error") or f"ask failed ({res.status_code})"
            raise RuntimeError(msg)

        return res.json()

    @staticmethod
    def pick_answer(res: Dict[str, Any]) -> str:
        for k in ("answer", "text", "message", "output"):
            v = res.get(k)
            if isinstance(v, str) and v.strip():
                return v
        return ""

4) Create your own server endpoint

This keeps your license key private and gives your frontend a safe URL to call. Below is a minimal FastAPI example: POST /api/chat.

python
# api.py
from fastapi import FastAPI
from pydantic import BaseModel
from brinpage import Brinpage

app = FastAPI()
bp = Brinpage()

class ChatIn(BaseModel):
    question: str
    tags: list[str] | None = None

@app.post("/api/chat")
def chat(body: ChatIn):
    res = bp.ask(
        body.question,
        tags=body.tags or [],
        k=6,
        minScore=0.18,
        debugEcho=False,
        # You can pass provider/model overrides here if needed
    )
    return {
        "ok": True,
        "answer": Brinpage.pick_answer(res),
        "raw": res,
    }

Run it:

bash
pip install fastapi uvicorn pydantic
uvicorn api:app --host 0.0.0.0 --port 8000

5) Test end-to-end

Once your endpoint is reachable, test it with curl:

bash
curl -X POST http://localhost:8000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"question":"Hello from Python","tags":["docs"]}'

Common /ask options you’ll actually use

  • history: array of chat messages ({ role, content })
  • tags: reduce retrieval scope to specific doc tags
  • k / minScore: retrieval tuning knobs
  • debugEcho: include debug object (retrieval + routing info)
  • provider / model: overrides (optional)
  • stream: SSE mode (advanced; implement when you need token streaming)

Want to switch language/framework? Go back to Installation:

Back to Installation